On this page
Quickstart Authentication Endpoints Multimodal (Vision/Audio/PDF) Image Generation Web Search & Grounding Streaming Tool Calling Reasoning & Thinking Context & Caching Token Counts & Billing Errors Limits & Retries Key Inspector Models & MIME Types
OpenAI · Anthropic · Gemini compatible

One API for every major AI SDK

Point any OpenAI, Anthropic or Google Gemini SDK at this gateway and keep your code unchanged. Streaming, multi-turn tool loops, vision, audio, PDF documents, image generation, web search and reasoning work seamlessly across all three protocols.

Get started
https://api.zyreca.com

Drop-in compatible

Change base URL and API key. Works with OpenAI, Anthropic, Gemini, Claude Code and Cursor.

Tools & Web Search

Full multi-turn tool loops, parameterless tools and live Google Search grounding.

Vision, Audio & PDF

Upload images, audio recordings and PDF documents in any SDK with instant parsing.

Image Gen & Budgets

Dedicated image generation endpoint with spend caps, concurrency limits and key usage checks.

Quickstart

Base URL https://api.zyreca.com/v1

from openai import OpenAI

client = OpenAI(
    base_url="https://api.zyreca.com/v1",
    api_key="sk-zyreca-xxxxxxxxxxxxxxxx",
)
resp = client.chat.completions.create(
    model="gemini-3.8-flash-high",
    messages=[{"role": "user", "content": "Hello"}],
)
print(resp.choices[0].message.content)

Authentication

Every request requires an API key (sk-zyreca-...). Supply it using whichever convention your client or SDK expects — all forms are accepted across every endpoint:

  • Authorization: Bearer sk-zyreca-... (Standard / OpenAI)
  • x-api-key: sk-zyreca-... (Anthropic)
  • x-goog-api-key: sk-zyreca-... or query parameter ?key=sk-zyreca-... (Google)

Each key includes a spending budget cap, optional expiration date, requests-per-minute rate limit, maximum concurrency limit, and model allow-list. Inspect your key state anytime via GET /v1/usage.

Endpoints

EndpointProtocolDescription
POST/v1/chat/completionsOpenAIChat completions with streaming, tools, vision, audio, PDF files, web search, reasoning.
POST/v1/images/generationsOpenAIGenerate images via Google Imagen (n up to 4, b64_json or url data URI). Flat $0.04/image.
POST/v1/messagesAnthropicAnthropic Messages API: streaming, tools, vision (images), PDF documents (via Gemini), thinking. Also under /anthropic/v1/messages.
POST/v1/messages/count_tokensAnthropicCalculate estimated token consumption for Anthropic message payloads (text and attachment heuristics).
POST/v1beta/models/{model}:generateContentGeminiNative Gemini content generation. Also :streamGenerateContent and :countTokens.
GET/v1/models, /v1/models/{id}UniversalList available models. Returns OpenAI JSON by default, Anthropic JSON if anthropic-version header is sent.
GET/v1/usageZyrecaReal-time remaining balance, amount spent, request counts, rate limits and model allow-list.
GET/healthzSystemLiveness probe returning {"status":"ok"}.

Multimodal Inputs: Vision, Audio, PDF & Files

Send images, audio recordings, PDF documents, spreadsheets and code files directly to multimodal models. Over 50 MIME types are natively processed without external extraction tools.

Supported Modalities by Model Family:

  • Gemini models (gemini-3.8-flash-high, gemini-3.7-flash-medium, gemini-3.6-flash-high): Full multimodal support across Images, Audio (WAV, MP3, AAC, FLAC), Video (MP4, WebM, MOV), PDFs, and Office Documents (DOCX, XLSX, CSV, code files).
  • Claude models (claude-sonnet-4-6, claude-opus-4-6-thinking): Support Images (JPEG, PNG, WebP, HEIC/HEIF). Note: Claude upstream on Google Cloud Code PA only accepts image attachments; for document/audio/video files, specify a Gemini model.

๐Ÿ’ก Agent Optimization Tip (DOCX / XLSX): Uploading raw binary .docx or .xlsx packages tokenizes the underlying XML package structure (~12,000 prompt tokens per 35 KB). For high-volume agent workflows where context window economy is critical, extract raw text or CSV first (e.g. using python-docx or openpyxl) to save up to 70% in token usage.

In OpenAI format, pass base64 data URIs (data:<mime>;base64,<data>) or public HTTPS URLs in image_url or file parts:

import base64
from openai import OpenAI

client = OpenAI(base_url="https://api.zyreca.com/v1", api_key="sk-zyreca-...")

# Example 1: PDF Document Input (Gemini)
with open("invoice.pdf", "rb") as f:
    pdf_b64 = base64.b64encode(f.read()).decode()

resp = client.chat.completions.create(
    model="gemini-3.8-flash-high",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "Extract line items and total amount from this invoice:"},
            {"type": "image_url", "image_url": {"url": f"data:application/pdf;base64,{pdf_b64}"}}
        ]
    }]
)
print(resp.choices[0].message.content)

# Example 2: Audio File Input (WAV, MP3, AAC, FLAC)
with open("voice_memo.mp3", "rb") as f:
    audio_b64 = base64.b64encode(f.read()).decode()

audio_resp = client.chat.completions.create(
    model="gemini-3.8-flash-high",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "Transcribe and extract action items from this audio:"},
            {"type": "image_url", "image_url": {"url": f"data:audio/mp3;base64,{audio_b64}"}}
        ]
    }]
)
print(audio_resp.choices[0].message.content)

Image Generation (Imagen 3)

Generate high-fidelity, photorealistic or artistic images via POST /v1/images/generations powered by Google Imagen 3 (model: gemini-3.1-flash-image). Generates up to 4 images per call with customizable aspect ratios.

ParameterTypeDefaultDescription
promptstringRequiredA text description of the desired image.
modelstring"gemini-3.1-flash-image"Optional model identifier (also aliased from dall-e-3).
ninteger1The number of images to generate (1 to 4).
sizestring"1024x1024"Controls the image aspect ratio for Google Imagen 3. Imagen 3 always renders at its native high-resolution standard: 1024x1024 / 512x512 / 256x256 (1:1 square, native output: 1024×1024), 1792x1024 (16:9 widescreen, native output: 1376×768), 1024x1792 (9:16 portrait, native output: 768×1376), 1536x1024 (3:2 landscape, native output: 1264×848), 1024x1536 (2:3 portrait, native output: 848×1264). (Note: Imagen 3 does not generate low-resolution 512×512 images; selecting 512x512 outputs a full 1024×1024 high-definition square image).
response_formatstring"b64_json""b64_json" (raw base64 string) or "url" (returns a data:image/jpeg;base64,... data URI).
from openai import OpenAI
import base64

client = OpenAI(base_url="https://api.zyreca.com/v1", api_key="sk-zyreca-...")

response = client.images.generate(
    model="gemini-3.1-flash-image",
    prompt="A cute small origami fox sitting on a polished oak desk, soft cinematic lighting, 8k",
    n=1,
    size="1792x1024",     # 16:9 widescreen
    response_format="b64_json"
)

# Save the generated JPEG to disk
image_bytes = base64.b64decode(response.data[0].b64_json)
with open("origami_fox.jpg", "wb") as f:
    f.write(image_bytes)

print("Saved to origami_fox.jpg")

Raw Response Payload

{
  "created": 1790392846,
  "data": [
    {
      "revised_prompt": "A cute small origami fox sitting on a polished oak desk, soft cinematic lighting, 8k",
      "b64_json": "/9j/4AAQSkZJRgABAQEBLAEsAAD/6xeGSlAAAQAAAAEAABd8anVtYgAAAB5q..."
    }
  ],
  "usage": {
    "images_generated": 1,
    "cost_usd": 0.04,
    "prompt_tokens": 8,
    "total_tokens": 8
  }
}

Pricing & Tokens: Image generation is billed at a flat $0.04 per generated image (or per your reseller pricing). Every response includes a top-level usage object detailing images_generated and cost_usd. Requests blocked by safety filters or resulting in errors are never charged.

Web Search & Grounding

Ground your model responses with real-time web retrieval powered by Google Search. Enables models to access current stock prices, breaking news, sports scores, and real-time world events beyond training cutoffs.

Set "web_search": true in the request body for POST /v1/chat/completions:

from openai import OpenAI

client = OpenAI(base_url="https://api.zyreca.com/v1", api_key="sk-zyreca-...")

resp = client.chat.completions.create(
    model="gemini-3.8-flash-high",
    messages=[{"role": "user", "content": "What is the stock price and market cap of Alphabet (GOOGL) today?"}],
    extra_body={"web_search": True}
)
print(resp.choices[0].message.content)

Supported Models: All Gemini 3.8 and 3.7 variants (e.g. gemini-3.8-flash-high, gemini-3.8-flash-medium, gemini-pro-agent). Token usage includes retrieved search snippets in prompt tokens and synthesis in completion/reasoning tokens at standard per-token pricing.

Streaming

Set "stream": true. OpenAI streams deliver a role chunk, content and reasoning_content deltas, a final chunk with finish_reason, then [DONE]. Add "stream_options": {"include_usage": true} to receive token usage in the final chunk. Anthropic streams use standard message_start … message_stop SSE events. Requests are billed strictly for tokens actually generated, even if disconnected early.

Tool Calling & AI Agents

Support for OpenAI tools / tool_choice and Anthropic tools / tool_use / tool_result across all models. The gateway transparently handles:

  • Multi-turn tool loops: Preserves upstream tool call IDs (toolu_vrtx_...) so agent loops never drop state.
  • Parameterless tools: Tools taking zero arguments (e.g., get_time with empty properties) automatically map to valid input schemas for both Gemini and Claude models.
  • Schema Normalization: Automatically translates unsupported JSON Schema keywords ($ref, additionalProperties, complex nullable unions) into strict engine-compatible representations.
resp = client.chat.completions.create(
    model="claude-sonnet-4-6",
    messages=[{"role": "user", "content": "What is the current time? Call the get_time tool."}],
    tools=[{"type": "function", "function": {
        "name": "get_time",
        "description": "Get current server time",
        "parameters": {"type": "object", "properties": {}}
    }}],
    tool_choice="required"
)
call = resp.choices[0].message.tool_calls[0]

# Follow-up turn: return the tool result back to the model
followup = client.chat.completions.create(
    model="claude-sonnet-4-6",
    messages=[
        {"role": "user", "content": "What is the current time? Call the get_time tool."},
        {"role": "assistant", "content": None, "tool_calls": [call]},
        {"role": "tool", "tool_call_id": call.id, "content": "10:30 AM"}
    ]
)
print(followup.choices[0].message.content)

Reasoning & Extended Thinking

Thinking models (e.g. claude-opus-4-6-thinking, claude-sonnet-4-6, gemini-3.8-flash-high, gemini-pro-agent) produce deep reasoning before answering:

  • Claude thinking models (claude-opus-4-6-thinking, claude-sonnet-4-6):
    • Anthropic protocol (POST /v1/messages): Pass "thinking": {"type": "enabled", "budget_tokens": 1024} (ensure max_tokens exceeds budget_tokens). The full reasoning process is returned in dedicated thinking blocks (and streamed via thinking_delta).
    • OpenAI protocol (POST /v1/chat/completions): Full reasoning text is returned in message.reasoning_content (and streamed in deltas via reasoning_content). You can specify thinking effort via "reasoning_effort": "low" | "medium" | "high" or "thinking": {"budget_tokens": 1024}. Thinking compute is billed under usage.completion_tokens_details.reasoning_tokens.
  • Gemini thinking models (gemini-3.8-flash-high, gemini-3.7-flash-medium): Google Cloud Code PA cryptographically protects the raw thought monologue via an encrypted thoughtSignature. The internal reasoning tokens are fully accounted for and billed in usage.completion_tokens_details.reasoning_tokens.

AI Agent Context & Prompt Caching Optimization

Building long-running AI agents requires balancing rich context (instructions, tools, documents, generated images) with low latency and cost. Zyreca Gateway natively supports provider KV prompt caching on both OpenAI and Anthropic routes, enabling up to 75%โ€“90% cost savings and 2โ€“4x faster time-to-first-token on recurring context.

Image & Multimodal Ingestion in Multi-Turn Context:

When passing a base64 image (e.g. data:image/png;base64,...) into a multi-turn conversation, the gateway and model never tokenize raw base64 characters as text. The image is decoded into raw pixels and passed directly to the Vision Transformer (ViT):

  • Gemini models: An image costs a flat ~258 tokens (standard resolution) or ~1,100 tokens (high-res tiled), whether the file is 100 KB or 5 MB.
  • Claude models: An image costs ~1,400 to 1,500 tokens for a 1024×1024 image (based on pixel resolution: (width × height) / 750).

๐Ÿ’ก Agent Tip: Sending a 2 MB base64 PNG image does not cost 500,000 text tokens โ€” it only costs ~258 tokens on Gemini!

The Golden Rule of Prompt Caching: Prefix Invariance

KV-cache algorithms match tokens strictly from the very first token (character 0) forward. Any modification to a token in the prefix breaks cache matching for every token that follows. To maximize cache hits:

Context LayerStabilityRecommended PlacementBest Practice
1. System InstructionsStaticTop of promptKeep system prompts completely static across all turns. Never inject dynamic timestamps (e.g. Current Time: 2026-09-26 09:50:00) into the system prompt; pass timestamps in the user message or via a tool.
2. Tool / Function SchemasStaticAfter system promptKeep tool definitions in the exact same order. Do not dynamically add or remove tools mid-session.
3. Knowledge / Reference DocsStaticBefore conversation historyInject large reference manuals, PDF contents, or company guidelines once at the start of context.
4. Dynamic Chat TurnsAppendedTail of messages listAppend turns strictly to the end: [User 1, Assistant 1, User 2, Assistant 2, ...]. Modifying previous assistant answers busts the cache.

Minimum Caching Thresholds & Automatic Billing Discounts:

  • Claude models (Deterministic Caching): Activates reliably when the static prefix reaches 1,024 tokens or more. Cache reads receive an automatic 90% discount on input prompt billing.
  • Gemini models (Implicit Context Caching): Google's upstream implicit cache threshold is 32,768 tokens on Gemini Flash (with opportunistic cache affinity across identical GPU replicas for repeated prompts ≥ 2,048 tokens). Cache reads receive a 75% discount.

When cache hits occur, they are reported in usage.prompt_tokens_details.cached_tokens (OpenAI route) and usage.cache_read_input_tokens (Anthropic route) and billed at discounted rates automatically.

Complete Python Agent Example (Multi-Turn Chat with Image Generation & Caching)

import base64
from openai import OpenAI

client = OpenAI(base_url="https://api.zyreca.com/v1", api_key="sk-zyreca-...")

# 1. Static System Prompt (will be cached across turns)
SYSTEM_PROMPT = """You are a senior UI/UX design assistant at an agency.
Analyze user requests, generate design concepts, critique visual assets,
and provide concrete CSS/color recommendations. Always stay structured and precise."""

# 2. Generate an asset via Imagen 3 (Fixed flat rate: $0.04)
img_resp = client.images.generate(
    model="gemini-3.1-flash-image",
    prompt="Clean modern SaaS dashboard landing page mockup, dark violet and obsidian theme",
    size="1024x1024",
    response_format="b64_json"
)
image_b64 = img_resp.data[0].b64_json

# 3. Initialize Multi-Turn Context (Static Prefix + Image)
messages = [
    {"role": "system", "content": SYSTEM_PROMPT},
    {
        "role": "user",
        "content": [
            {"type": "text", "text": "Here is our newly generated dashboard concept. Critique the visual hierarchy:"},
            {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_b64}"}}
        ]
    }
]

# Turn 1: Analyze Image (~258 vision tokens on Gemini)
turn1 = client.chat.completions.create(
    model="gemini-3.8-flash-high",
    messages=messages
)
assistant_critique = turn1.choices[0].message.content
print("Turn 1 Response:", assistant_critique)

# Turn 2: Follow-up (Prefix is preserved -> Cache Hit!)
messages.append({"role": "assistant", "content": assistant_critique})
messages.append({"role": "user", "content": "Suggest 3 accessible color pairings for call-to-action buttons."})

turn2 = client.chat.completions.create(
    model="gemini-3.8-flash-high",
    messages=messages
)
print("Turn 2 Response:", turn2.choices[0].message.content)
print("Turn 2 Cached Tokens:", turn2.usage.prompt_tokens_details.cached_tokens)

Token Counts & Multimodal Billing

Billing is strictly usage-based with second-by-second atomicity. How tokens are calculated:

ModalityInput UnitsApproximate Token CountBilling Rate
Text & CodeCharacters / words~1 token per 4 English characters (~0.75 words)Per-model prompt / completion rate
Vision (Images)PNG / JPEG / WebP image~258 tokens (square) to ~1,100 tokens (high resolution)Billed as prompt tokens at model rates
AudioWAV / MP3 / AAC audio~25 to 32 prompt tokens per 1 second of audio (~1,500 to 1,920 tokens/min)Billed as prompt tokens at model rates
PDF DocumentsDocument pages~250 to 550 prompt tokens per pageBilled as prompt tokens at model rates
VideoVideo clips (1 fps)~80 to 258 tokens per second (depending on resolution and motion)Billed as prompt tokens at model rates
Image Generation1 generated imageFixed flat charge ($0.04 / image)Flat rate, zero token charges
Reasoning TokensThinking processCounted 1:1 with generated tokensBilled at model completion rate

Failed requests (HTTP 4xx / 5xx) and requests blocked by upstream safety filters are never charged. Your current balance and token spend are queryable in real-time at GET /v1/usage.

Errors

Errors use the format of the protocol you called (OpenAI {"error":{...}}, Anthropic {"type":"error",...}, Google {"error":{"status":...}}), so SDK error handling and automatic retries work unchanged. Every response carries an X-Request-Id header.

StatusMeaningAction
400Invalid request (bad JSON, unsupported parameter, blocked by safety filters).Inspect error message; do not retry unchanged.
401Missing or invalid API key.Verify sk-zyreca-... key.
403Key disabled, expired, or model not in key's allow-list.Check GET /v1/usage.
404Unknown model or endpoint.Check GET /v1/models.
413Request body exceeds upload limit (20 MB).Compress or split media.
429Rate limit (RPM), concurrency limit, or key budget exhausted (insufficient_quota).Honour Retry-After; top up if quota exhausted.
502 / 503Upstream provider temporarily busy.Retry with exponential backoff.

Limits & Retries

  • Responses include X-RateLimit-Limit-Requests and X-RateLimit-Remaining-Requests.
  • The gateway automatically load balances and fails over across accounts on upstream rate limits. You only receive a 429 when every upstream pool account is temporarily constrained.
  • Recommended Retry Policy: Retry status codes 429, 502, 503 with exponential backoff and jitter (e.g. 1s, 2s, 4s, 8s). Never retry 400, 401, 403, 404.

API Key Inspector

Check live balance, remaining budget, concurrency limits, and request volume for any key:

Models, Pricing & MIME Types

The authoritative, live catalog is always available via GET /v1/models. Standard prices in USD per 1M tokens:

Model IDFamilyContextMax OutputCapabilitiesPrompt/1MOutput/1M
gemini-3.8-flash-high Gemini 3.8 1,048,576 65,536 Vision Audio PDF Search Tools $0.15 $0.60
gemini-3.8-flash-medium Gemini 3.8 1,048,576 65,536 Vision Audio PDF Search Tools $0.12 $0.45
gemini-3.8-flash-low Gemini 3.8 1,048,576 65,536 Vision Audio PDF Search Tools $0.10 $0.35
claude-opus-4-6-thinking Claude 4.6 250,000 64,000 Vision PDF Tools Thinking $5.00 $25.00
claude-sonnet-4-6 Claude 4.6 250,000 64,000 Vision PDF Tools Thinking $3.00 $15.00
gemini-pro-agent Gemini Pro 1,048,576 65,535 Vision Audio PDF Search Tools $1.25 $5.00
gemini-3.1-flash-image Image Gen - - Imagen 3 - $0.04 / img
gemini-3.7-flash-high Gemini 3.7 1,048,576 65,536 Vision Audio PDF Search Tools $0.15 $0.60
gemini-3.6-flash-high Gemini 3.6 1,048,576 65,536 Vision Audio PDF Search Tools $0.15 $0.60

Supported MIME Types Reference (from models.json)

The gateway accepts 51 distinct media and document MIME types directly in prompts:

CategorySupported MIME FormatsSupported Models
Images image/png, image/jpeg, image/webp, image/heic, image/heif All Gemini & Claude models
Audio audio/wav, audio/mp3, audio/mpeg, audio/aac, audio/flac, audio/ogg, audio/opus, audio/webm, audio/m4a, audio/vnd.wave Gemini models (3.8, 3.7, 3.6, Pro)
PDF & Documents application/pdf, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/rtf Gemini models & Claude models
Data & Spreadsheets text/csv, application/json, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet Gemini models
Code & Markup text/plain, text/markdown, text/html, text/css, text/javascript, text/x-python, text/x-typescript, application/x-ipynb+json, text/xml Gemini models
Video video/mp4, video/webm, video/quicktime, video/jpeg2000 Gemini models

All Claude aliases (e.g. claude-3-5-sonnet-20241022, claude-opus-4-1) are automatically mapped to the closest high-tier Claude models.