Skip to content

Protected budget and TPM profiles

Last updated: 2026-11-27T12:13:34-03:00 (UTC-3)

A budget is only reliable if the gateway can measure what the call consumed. That is why each type of call has a profile: what the request must carry for the reservation to be calculated, and what the response must carry for the usage to be proven. A call under a policy that does not fit any profile is refused before it goes to the provider.

Rules common to all profiles:

  • a single target, with no retry and no cache (realtime uses only the first target, with no fallback);
  • under a USD budget, an approved rate for the exact connection and upstream model; input images require an approved rate with an image ceiling even under a token-only policy;
  • an explicit output limit when the call generates tokens;
  • measuring does not rewrite requests, stream events or media bytes; an explicitly configured protocol adapter still performs its normal translation, and an alias with stream_usage: inject asks a chat stream for the usage its client left out and keeps it out of the client’s stream.
Profile Flag What the request needs What the response needs
Chat, JSON tpm_limits/budget_limits An output limit; text, function tools and agent parameters (below) Approved model, one final choice (text, refusal or function tool calls) and complete counters
Chat, stream quota_streaming + stream_usage On the openai protocol, stream_options.include_usage: true, or on an alias with stream_usage: inject stream_options absent, null, or with only include_usage (true, false or null) and include_obfuscation; on a translated provider, nothing more Stable model and ID, a finish, the final usage (on the usage-only chunk or the finishing one; a repeat must match) and [DONE] (a repeated [DONE] is ignored); on a translated provider, the native terminal usage
Responses API (native, api: responses or auto target) tpm_limits/budget_limits; stream also the stream flags max_output_tokens; text or stateless tool-loop input items; function tools, alone or grouped in a namespace; client_metadata (Codex CLI) completed (or incomplete for the output limit or a content filter), only messages, reasoning and function calls in the output, the default tier and the usage
Anthropic Messages, JSON or stream quota_native_protocols (stream also requires the stream flags) Text, client tools and their results, 5m/1h cache breakpoints; max_tokens Approved model; message_start → final message_delta → message_stop
Gemini Interactions, JSON or stream quota_native_protocols (stream also requires the stream flags); background needs quota_background_responses Text input, function tools and results, an inline PDF with a closed page_image range; generation_config.max_output_tokens; no continuation, agent or hosted tool (file inputs) Approved model, status completed or incomplete, steps of text, thoughts and function calls; thoughts count as output
Gemini, JSON or stream quota_native_protocols (same) Text, function declarations, calls and responses; a thinkingConfig (Gemini CLI); with gemini_file_inputs, an inline PDF with a closed page range whose layers name page_image alone, each page reserved like an image (file inputs); generationConfig.maxOutputTokens Approved modelVersion, one final candidate and counters; thoughts count as output
Embeddings quota_embeddings Input texts (input_type on a translated provider) On the openai protocol: approved model, indexed data and consistent usage. On Bedrock (Titan text, Cohere families), Cohere v2 and Vertex AI: every provider call’s own count (the X-Amzn-Bedrock-Input-Token-Count header, Cohere’s meta.billed_units.input_tokens, Vertex’s statistics.token_count of an untruncated prediction); one call without it keeps the reservation
DALL-E images quota_media Explicit n, size and quality Complete list of images; per-image rate for the variant
GPT Image generations and edits (OpenAI, gpt-image-*) quota_media + quota_image_tokens Prompt (reserved by its UTF-8 bytes), optional n (1-10, default 1) and the documented image options; not streamed, no partial images, no svg or gif output; input images at the rate’s image_input_tokens; see GPT Image budgets The usage after the images, read whole: text and image input, image and text output, each at its approved price
Whisper transcription (WAV PCM) quota_media Valid WAV PCM, up to 8 MiB; response_format: verbose_json usage.type: duration and usage.seconds
Rerank (Cohere) quota_media Query and documents Valid results and meta.billed_units.search_units
Video (Runway) quota_video See asynchronous video —
Realtime, per response tpm_limits/budget_limits Under a budget, an approved rate with audio prices; output from max_output_tokens or realtime.default_max_output_tokens response.done with consistent totals and text/audio details; see realtime

The Messages, Responses and GenerateContent routes translated to another provider (protocol translation) are measured as chat: the canonical request must fit the chat profile, and the answer is measured as below.

An agent loop fits the chat profile. Each of these changes how many tokens the answer has, never what a token costs:

  • tools with type: function only, tool_choice (none, auto, required or a named function), parallel_tool_calls;
  • assistant messages with tool_calls (and content: null), tool messages with their tool_call_id, and name on any message;
  • content as a string or a list of text parts;
  • response_format (text, json_object or json_schema);
  • reasoning_effort (none, minimal, low, medium, high, xhigh, max): reasoning is billed as output, inside the output limit, and the answer must still prove it is part of the output (see below). On an api: auto target the profile follows the API the attempt uses: on Responses, the output limit bounds reasoning, every stream ends with usage, and a policy object effort ({effort, summary}) counts as its effort;
  • up to 1,024 messages and 128 tools per request, and 128 parts per message, by default: the quota settings change these limits.

A function tool call in the answer is output text the client runs itself, counted in the output tokens; the finish reason tool_calls ends the answer like stop. The reservation bounds the tool and output schemas too: they count twice, since chat templates re-serialize them, and each tool and tool call gets the same 1,024-token template allowance as a message (see budgets and TPM).

Still refused, with the reason in the 422:

Request Why
Hosted tools (web search, file search, code interpreter, MCP, custom tools) Billed per call or per session, which no token rate prices
Images in the input without an approved image_input_tokens on the rate An image’s tokens depend on the model’s own tiling (one provider bills the same picture at 85 base tokens on one model and 2,833 on another of the same family), and a remote image’s size is unknown before the provider fetches it: only the operator’s per-model ceiling bounds it. With the ceiling, image_url parts, Messages image blocks, Gemini image inlineData and Responses input_image (not a stored file_id) are reserved at it, or at the provider’s documented tokens for the image when larger (image sizes), and the answer’s image token details count as input
Audio, video and files in the input Billed by their own rules (seconds, pages), which no token rate prices
n above 1, logprobs, modalities with audio, prediction, web_search_options, service_tier More answers, priced categories or tiers the rate does not cover
Responses previous_response_id, conversation, item_reference, a reasoning item without its encrypted_content, background, prompt, truncation: auto The provider bills stored turns (and stored reasoning loaded by ID) again as input, which this request’s bytes do not bound; background work has no terminal answer in the call
reasoning_effort with max_tokens only, on an OpenAI-compatible chat target (or any call to a rate marked reasoning: true without max_completion_tokens) A third-party model may reason past max_tokens; max_completion_tokens bounds reasoning and output by the OpenAI contract. Anthropic, Claude on Bedrock, Gemini, Converse and the Responses API count reasoning in their own limit; on Cohere the reservation adds the thinking budget the adapter asks for (up to 16,384)
Anthropic-defined tool types; a Messages thinking setting other than adaptive, enabled with budget_tokens, or disabled (each with an optional display); in output_config, a task_budget or any field other than effort and format; in context_management, any edit other than clear_thinking_20251015 with keep: "all" (an edit that clears turns or tool results changes what the prompt cache holds, and compaction runs a second generation billed apart); a tool call whose caller is not the model itself (direct); a tool_reference to a tool the request does not declare; Gemini googleSearch, codeExecution and other built-in tools, and any thinkingConfig field other than includeThoughts, thinkingLevel and thinkingBudget Billed per use, outside the output limit, or not a field the profile knows. Claude’s thinking itself is admitted on /v1/messages: it is output inside max_tokens, billed as output tokens, so the reservation bounds it; thinking blocks of an answer, of a stream (thinking_delta, signature_delta) and of an earlier turn sent back are measured like text, and usage.output_tokens_details.thinking_tokens is read as a part of output_tokens, never added to it. Claude Code’s requests are inside the profile, measured field by field: output_config.effort (low to max) changes how much the model writes, inside max_tokens; output_config.format of type json_schema is input, counted like one client tool with its schema bytes (measured: a 133-byte schema added 207 input tokens, well inside that bound); context_management with clear_thinking_20251015 keeping all thinking changes nothing in the request; a tool’s defer_loading flag and a system turn inside messages (text only) are input the request’s bytes bound; a tool’s eager_input_streaming flag and thinking.block_binding (OpenCode) change nothing the bytes do not bound; the estimated_tokens beside a thinking delta is a display estimate, never the measurement. A recorded Claude Code task (two calls, thinking, a tool call, cache writes and reads) is admitted and measured at the tokens the valuation prices

A coding agent sends fields an ordinary application does not, and a budget refuses what it cannot bound. Each client below was run through the gateway on a real task with a budget on its key, and its requests were recorded with every text blanked; the recordings are the fixtures of the gateway’s own tests (internal/gateway/testdata/*_shape.jsonl). For each one: what to configure, what is admitted and by which rule, and what stays refused. A refusal answers 422 quota_profile_unsupported with the reason, before any provider call.

How each client is recognized from its requests is in agent recognition.

Measured twice: the Claude Agent SDK 0.2.189 (claude_code_messages_shape.jsonl, the fields in the Messages row of the refused table) and the Claude Code CLI 2.1.330 with tool search on, 2026-11-27 (claude_code_tool_search_shape.jsonl: two calls, a tool search and its result).

Nothing to configure. The CLI asks for max_tokens: 128000 on the current models, and the reservation holds that limit as asked: 128,000 output tokens at the output price, settled at what the answer used. To reserve less per call, lower the limit on the target with max_output_tokens (request parameter policy) or in the client with CLAUDE_CODE_MAX_OUTPUT_TOKENS.

What the CLI sends beyond the SDK recording Rule
A tool_reference block inside a tool result ({"type": "tool_reference", "tool_name": ...}), which the client’s tool search answers with Admitted when it names a tool the same request declares, with those two fields only. The provider loads that tool’s definition into the context, so each reference is reserved as another copy of the definition (one item and its schema bytes). A reference to a tool the request does not declare is refused (client_tools_only): its definition is not in the request
output_config: {effort} on a system turn inside messages (the effort for the turns after it) Admitted on a system turn with effort alone, also on a turn with no text. A format or a task budget there, or the field on another role, is refused

Before the reference was admitted, the CLI recovered by itself: after three refusals it resent the turn with the reference replaced by text. Each refusal answered before any provider call, so nothing was held.

Measured with codex-cli 0.163.0 over the Responses API, 2026-11-27 (codex_responses_shape.jsonl: two calls, a tool step, reasoning handed back encrypted, a cache read).

Configure two things.

  1. An output limit on the alias. Codex sends no max_output_tokens, and a budget cannot reserve an answer without one: the request is refused with output_limit_required. Give the target a ceiling with the request parameter policy (request_parameter_policy on, max_output_tokens on the target): a request without a limit then goes out with that limit, and the reservation is computed from it.
  2. Web search off in the client. Codex declares the provider’s hosted web_search tool on every call, even for cached results (external_web_access: false). A hosted tool bills per call, which no token rate prices, so the request is refused with function_tools_only. In Codex’s config.toml: web_search = "disabled".
features:
request_parameter_policy: true
models:
- id: gpt-5.4-mini
capabilities: [responses]
targets:
- provider: openai
model: gpt-5.4-mini
max_output_tokens: 4096 # the limit Codex does not send
~/.codex/config.toml
model = "gpt-5.4-mini"
model_provider = "gateway"
web_search = "disabled"
[model_providers.gateway]
name = "gateway"
base_url = "https://gateway.example.com/v1"
env_key = "GATEWAY_KEY"
wire_api = "responses"
What Codex sends Rule
client_metadata (session, thread, turn and window IDs) Admitted: a flat object of at most 64 string values. They label the request and are not model input
A namespace tool (Codex groups its agent tools under one) Admitted: a name, an optional description and 1 or more function tools. Each member is framed and counted like a top-level function tool; a namespace or a hosted tool inside one is refused
phase on an assistant message handed back (commentary, final_answer) Admitted on an assistant message with one of those two values
logprobs: [] on an output_text part handed back Admitted when the list is empty; log probabilities themselves stay refused
reasoning: {effort, summary}, include: ["reasoning.encrypted_content"], reasoning items with their encrypted content, prompt_cache_key, store: false Already in the Responses profile
web_search Refused (hosted tool); turn it off in the client
No max_output_tokens Refused as sent; the target’s max_output_tokens supplies it

The cost ledger values the same calls: a Responses request’s reasoning setting (an effort and a summary) is not a price category, and the answer’s echoes of this turn’s reasoning (context: "current_turn", mode: "standard"), of the cache key and of the default 24-hour cache retention bill nothing. Cache writes a provider bills are reported in the usage (cache_write_tokens); a nonzero count there keeps the answer unresolved, as does any other retention, context or mode.

Measured with @google/gemini-cli 0.71.1 in API key mode against gemini-3.5-flash-lite on Vertex AI, 2026-11-27 (gemini_cli_generate_shape.jsonl: two streamed calls, thoughts shown, a tool step, a context-cache read).

Configure one thing: an output limit in the client. Gemini CLI sends no generationConfig.maxOutputTokens, and the request is refused with output_limit_required. The request parameter policy does not apply to the native generateContent route, which passes the request through unchanged, so the limit is set in the client’s settings.json:

{
"modelConfigs": {
"customOverrides": [
{"match": {"model": "gemini-3.5-flash-lite"},
"modelConfig": {"generateContentConfig": {"maxOutputTokens": 4096}}}
]
}
}

Point the client at the gateway with GOOGLE_GEMINI_BASE_URL and a gateway key in GEMINI_API_KEY.

What Gemini CLI sends Rule
generationConfig.thinkingConfig with includeThoughts and thinkingLevel Admitted: includeThoughts (a flag), thinkingLevel (minimal, low, medium or high, any case) and thinkingBudget (a whole number, or -1). Thoughts are output inside maxOutputTokens and bill at the output price. Measured: with maxOutputTokens: 64, a 4,096-token thinking budget stopped at 58 thought and 2 answer tokens, and thinkingLevel: HIGH at 60. Any other field of the setting is refused
Answer parts marked thought: true (shown because of includeThoughts) Measured like text; their tokens are in thoughtsTokenCount, counted as output. A request may not carry the mark
functionDeclarations with parametersJsonSchema, function calls with their thoughtSignature, function responses, temperature, topP, topK, a systemInstruction Already in the Gemini profile
No maxOutputTokens Refused as sent; set it in the client

Vertex AI streams are now measured. On Vertex AI every chunk before the last carries usageMetadata: {"trafficType": "ON_DEMAND"} and no count. That was read as a broken count, so a streamed Gemini call on Vertex AI kept its whole reservation (unknown) and its cost stayed unknown. A chunk before the finish that names only the tier is now a tier report: the tier must agree with the other chunks, and the counts are still required on the finishing chunk.

Measured with opencode-ai 1.19.6, 2026-11-27, on both of its paths: its Anthropic provider on /v1/messages (opencode_messages_shape.jsonl: the title call and two calls of the task, cache writes and a read) and its OpenAI-compatible provider on /v1/chat/completions (opencode_chat_shape.jsonl: the title call and two calls).

On Messages there is nothing to configure. OpenCode sends max_tokens on every call.

What OpenCode sends on Messages Rule
thinking.block_binding: {prefix_mismatch_behavior: "drop_block"} Admitted: block_binding with that one field, error or drop_block. It says what the provider does with a thinking block handed back from another conversation: refuse the request, or leave the block out unbilled. Neither adds input the request’s bytes do not bound
eager_input_streaming: true on a tool Admitted as a flag: the tool call’s input is streamed as it is generated, which changes how the answer is delivered, not what it holds
thinking: {type: "adaptive"} with an optional display, cache_control marks, tool_choice: {type: "auto"} Already in the Messages profile

On Chat Completions, configure the alias. OpenCode sends max_tokens together with reasoning_effort. Under a budget that pair is refused on an OpenAI-compatible target with reasoning_requires_max_completion_tokens, because a model may reason past max_tokens; and the current OpenAI models refuse max_tokens themselves, and refuse function tools with a reasoning effort on Chat Completions. One target setting answers each (request parameter policy, api: auto):

features:
request_parameter_policy: true
models:
- id: gpt-5.4-mini-chat
capabilities: [chat]
targets:
- provider: openai
model: gpt-5.4-mini
api: auto # tools with an effort go to the Responses API
request_overrides: {max_completion_tokens: 4096} # replaces the client's max_tokens
max_output_tokens: 4096

Nothing in OpenCode’s chat requests needed a new rule: the limit, the effort, stream_options.include_usage, function tools and tool_choice are in the chat profile.

Configure the alias before pointing the client at it: a request the provider refuses after it was sent (as the current OpenAI models do with max_tokens) leaves that call’s reservation held as unknown: see what is left out and financial reconciliation.

Measured with @mariozechner/pi-coding-agent 0.73.1, 2026-11-27, on its three APIs, one task of two calls each: anthropic-messages (pi_messages_shape.jsonl), openai-responses (pi_responses_shape.jsonl) and openai-completions (pi_chat_shape.jsonl).

Nothing to configure for the budget. pi sends an output limit on every call (max_tokens, max_output_tokens or max_completion_tokens, from the model’s maxTokens in its models.json).

What pi sends Rule
Messages: eager_input_streaming: true on every tool Admitted as a flag, as for OpenCode
Responses: the answer’s reasoning item handed back with content: [] beside its encrypted_content Admitted when the list is empty. Reasoning text in it, or the item by its ID alone, stays refused (stored_state_not_bounded)
Responses: reasoning: {effort, summary}, include, prompt_cache_key, store: false; chat: max_completion_tokens with reasoning_effort, a developer message, stream_options.include_usage, store: false Already in the profiles

Two things outside the budget, seen on the same run:

  • Thinking with a budget. pi 0.73.1 asks a model it marks reasoning: true for thinking: {type: "enabled", budget_tokens}, which the current Claude models refuse with a 400 after the call was sent, leaving its reservation held. Declare the target thinking_mode: adaptive: the gateway then refuses that request itself with 422 unsupported_on_provider before anything is sent, and nothing is held. In pi, mark the model reasoning: false, or use a model that takes a thinking budget.
  • Tools with an effort. On Chat Completions the current OpenAI models refuse function tools with a reasoning effort, so the chat alias needs api: auto as for OpenCode.

Measured with the Grok CLI 1.0.92 (@xai-official/grok) and custom models, 2026-11-27, on its three backends: messages (grok_cli_messages_shape.jsonl: the title call and two calls of the task), responses (grok_cli_responses_shape.jsonl) and chat_completions (grok_cli_chat_shape.jsonl), two calls each.

Nothing to configure for the budget. Without max_completion_tokens on its custom model the client asks for 128,000 output tokens on every call, and the reservation holds that limit as asked. To reserve less per call, set max_completion_tokens on the model (the recordings used 8,192), or lower the limit in the gateway with the target’s max_output_tokens (request parameter policy):

~/.grok/config.toml
[model.gateway]
model = "claude-haiku-5-5"
base_url = "https://gateway.example.com/v1"
name = "Gateway"
env_key = "GATEWAY_KEY"
api_backend = "messages" # or "responses", "chat_completions"
max_completion_tokens = 8192
What the Grok CLI sends Rule
Chat: model_id on an assistant message handed back (the model that wrote it) Admitted as a string on an assistant message, like name; on any other role it is refused
Messages: cache marks, a forced tool_choice on the title call; Responses: reasoning: {summary}, include, prompt_cache_key, store: false, function tools; chat: max_tokens, stream_options.include_usage, function tools Already in the profiles
max_tokens: 128000 (the client’s default) Reserved as asked (output limit)

Two things to expect:

  • Helper calls use the client’s own model name. The session title goes to grok-4.6 on the same endpoint. Without an alias of that name the call is refused (model_forbidden or capability_unsupported) and the task still runs; with one, it is budgeted like any call.
  • A headless run can leave one held reservation. grok -p starts a turn summary as it exits and closes the connection a few milliseconds later. If the call had already gone out to the provider, it is cut before its answer ended and keeps its reservation, because the provider may have charged for it. Turn on stream_settle_on_disconnect and the gateway reads that answer to its end and settles it (measured on 2026-11-27: the summary settled at 478 input and 11 to 14 output tokens).

Neither can be run under a budget on a gateway that only your own machine or network reaches, and the gateway ships no recognition rule for them. Checked on 2026-11-27:

Client Custom model endpoint What the vendor’s documentation and the client itself show
Cursor editor Only one that Cursor’s own servers can reach, and only on a paid Cursor plan The API keys page says a custom key is “sent to our backend with every request” and that all requests are routed through Cursor’s servers for the final prompt. The model call is made from Cursor’s servers, not from the editor: a gateway on localhost or a private network never receives it. Custom keys work with chat models only; Tab keeps Cursor’s models. On the Free plan the editor (3.32.4, 2026-11-27) sends nothing to a custom endpoint: with a key, the base URL override and a custom model set, it answers “Cursor Subscription Required: Agent and Edit rely on custom models that require a paid subscription” before any request
Cursor command-line agent (agent, cursor-agent), version 2026.11.22 None It refuses to run without a Cursor account (Authentication required). Its one endpoint option (--endpoint, CURSOR_API_ENDPOINT) defaults to Cursor’s own API, and the model is chosen by Cursor’s model names. The package carries hidden options for a provider base URL, and the released build refuses them (--base-url can only be used with agent-cli-local)
Antigravity (editor and CLI) None The plans page lists “Bring-your-own-key (BYOK) or bring-your-own-endpoint” under what is not supported. Model traffic goes to Google’s own hosts after a Google sign-in (enterprise deployments lists them for firewall allowlists)

On a paid plan the Cursor editor can be pointed at a gateway that is published on the internet (Settings → Models → Override OpenAI Base URL). What it then sends was not measured here (the test account was on the Free plan): the requests would come from Cursor’s servers, with a prompt Cursor builds, so the rules above for other clients do not describe them. Put a budget on such a key only after reading the refusals its first requests produce.

Behind the chat route (and every translated route), Bedrock, Anthropic, Gemini, Cohere and an openai target with api: responses (or api: auto, when the request goes to Responses) answer in their own format, which the adapter translates. The translated body names the public alias and folds cache reads into prompt_tokens, so it cannot prove the billed model or price the cache. The adapter reads the native answer anyway; under a budget it hands what that answer proves to the settlement, and the bytes the client receives do not change.

Provider Model proven Terminal answer Counters Kept reservation
Bedrock Converse The model in the request path (Converse names none, and the call cannot change it) stopReason (end_turn, tool_use, max_tokens, stop_sequence, content_filtered); in a stream, messageStop then metadata inputTokens plus cacheReadInputTokens and cacheWriteInputTokens (one-hour writes from cacheDetails); outputTokens; totalTokens consistent Guardrail intervention or trace, latency-optimized or non-default service tier, unknown categories
Anthropic Messages model stop_reason; in a stream, message_start → message_delta → message_stop input_tokens plus cache read and creation tokens (one-hour writes from cache_creation); output_tokens (thinking included) Server tool use, cited (searched) text, a tier other than standard, a regional inference surcharge
Gemini modelVersion One candidate with a final finishReason promptTokenCount (cached part included), candidatesTokenCount plus thoughtsTokenCount; serviceTier only standard Flex or priority tier, grounding, tool-use prompt tokens, provisioned throughput, non-text modalities, a blocked prompt
Cohere v2 The requested model (the answer names none) finish_reason; in a stream, message-end billed_units (the raw counts include Cohere’s own template) Search units or other billed units
OpenAI Responses (api: responses) model response.completed / response.incomplete input_tokens (cache reads in the details), output_tokens (reasoning inside) Hosted tool calls, citations, a non-default tier, failed or cancelled responses

Vertex AI’s text-embedding-*, text-multilingual-embedding-* and textembedding-gecko* models are priced per 1,000 characters, not per token, so they are refused under a budget or a token ceiling and no token rate can be approved for them; the token-priced gemini-embedding-* models are measured.

Refused: SageMaker bills endpoint instance time, not tokens, and its container’s usage has no contract; OCI bills several on-demand models per character, and its stream has no terminal event to prove the end of an answer.

A stream the provider cuts, an error event, a second proof or a measurement that arrives after the request ended keeps the reservation.

  • Guardrails: with input guardrails on, the reservation is estimated from the request as they left it: a mask can turn a short match into a longer [REDACTED:<name>] placeholder, and the provider bills what it receives.
  • Usage over the bound: if a provider still bills more than the reservation, in tokens or in money (a budget without a token ceiling can overrun only in USD, when more output than estimated costs more than the input it replaced), the settlement debits the full amount (never truncated), the measurement proof and the ledger record overrun_tokens and overrun_usd, and the gateway logs quota_reservation_overrun, and the settlement writes the alert event of the same name in its own transaction, so no overrun settles without its alert, however many settle at once.
  • Cache write split: a cache write settles only with a time-to-live breakdown that accounts for every write (Anthropic’s cache_creation, Bedrock’s cacheDetails, their five-minute and one-hour parts adding up to the total); absent, empty or short, the writes may be one-hour writes, so the reservation stays.
  • Images the gateway can inspect: an inline image (a chat or Responses data URL, a Messages base64 source, a Gemini inlineData part) counts only when its leading bytes are the PNG, JPEG, GIF or WebP its MIME type declares. A URL counts only over https, in fields that take images alone (chat image_url, Messages url sources, Responses input_image), and only where the provider documents that it fetches such a URL as an image and bills it by the image rules: the OpenAI API (chat and Responses) and Claude Messages on the Anthropic API. Anywhere else (a third-party OpenAI-compatible or Anthropic-compatible host, a translated route) a URL needs image_urls: true on the approved rate; the translating adapters take data URLs only. A Gemini fileData URI is refused: its MIME type is the client’s claim, and Gemini bills the file by its real type.
  • Running counts: a Gemini stream reports usage on many chunks; only the usage on the finishing chunk or after it settles.

A per-image ceiling alone ignores size, and providers bill a large image more than a small one. For each inline image the gateway reads the width and height from the PNG, JPEG, GIF or WebP header (a JPEG’s largest frame before its first scan; a GIF’s logical screen or its first frame, whichever reaches further, since decoders grow the image to cover the frame: Nova Lite billed a 2000×2000 frame behind a 16×16 screen exactly like a 2000×2000 GIF, 2,621 tokens against 541) and computes the provider’s documented formula for the connection; the reservation takes the larger of that and the rate’s image_input_tokens. A URL’s size is unknown before the provider fetches it, so it is reserved at the provider’s documented maximum per image. An inline image whose header does not give a size is treated the same way, and refused where no maximum is documented.

Connection/profile Reservation formula used by the gateway Unknown-size reference Source
OpenAI API (api.openai.com), patch-based models ceil(multiplier × patches), 32×32 patches, at most 30,000 (larger images are rejected); multiplier 1.2 to 2.46 by model multiplier × 30,000 OpenAI images and vision, calculating costs
OpenAI API, tile-based models base + tile tokens × 512-px tiles, after fitting in 2048×2048 and the shortest side in 768 (gpt-4o 85 + 170, gpt-4o-mini 2,833 + 5,667) base + 8 tiles Same page
OpenAI API, a model the tables do not name The largest of the implemented published-family formulas 73,800 from those known families; not a guarantee for future models Same page
Claude: Anthropic API, Claude on Bedrock, Anthropic-compatible connections ceil(width/28) × ceil(height/28), at most 4,784 4,784 (high-resolution tier; the standard tier stops at 1,568) Claude vision, resolution and token cost
Gemini 3 and later 1,120 at the default and high media resolution (the 2,240 ultra-high level is set per part, which the profile refuses) 1,120 Gemini media resolution
Earlier Gemini models 258 up to 384×384; above, 258 per tile, counting tiles of the shortest side over 1.5, kept between 256 and 768 px (never fewer tiles than the documented 768-px tiling) None: an image of unknown size is refused Gemini token counting
Gemini models matching neither The larger of both rules None Both pages
Amazon Nova 2 on Bedrock 230, flat 230 Amazon Nova 2 multimodal understanding
Any other connection (Amazon Nova 1, third-party OpenAI-compatible hosts, Cohere) No published formula: Nova 1 documents approximate counts only, up to about 2,600 for a 1.3K×1.3K image (Amazon Nova image understanding) None The approved image_input_tokens is the bound

These are the gateway’s implemented reservation references, not a promise that an unlisted or future model shares another model’s billing rules. Approve image_input_tokens against the selected model and endpoint; review it when the provider changes its contract.

Setting a ceiling where no formula is published. On such a connection the rate’s image_input_tokens is the operator’s bound. The following are historical Amazon Nova Lite v1 samples through Converse (us-east-1, October 2026), not fresh certification or a maximum for every input. One PNG with a one-line prompt billed:

Image Input tokens billed (image and prompt)
32×32 535
64×64 541
1000×3000 1,085
4000×1000 1,303
4000×3000 1,677
900×600 1,831
1800×900 2,349
2000×2000 2,615
1500×1500 2,621

In those samples, the highest counts occurred near 1,500 to 2,000 pixels a side; a ceiling of 3,000 covered the measured sizes, and 2,000 did not. These observations do not prove that 3,000 bounds every possible request. The console warns beside a rate whose image ceiling is below the documented maximum of its model family (Claude 4,784, Gemini 3 1,120, Nova 2 230, each OpenAI model’s maximum) or the measured one (Nova v1, 2,621); it does not refuse it.

The OpenAI-compatible endpoints of Anthropic and Gemini use their provider’s rule. For known OpenAI families, the reservation uses the conservative formula above rather than estimating a discount from detail; model-specific sizing rules still apply upstream. A model is matched by its documented name or a dated snapshot of it (gpt-4o-2024-08-06); any other suffix is a different model.

Answers report the tokens read from (and on some providers written to) the provider’s prompt cache. These are input tokens at another price, never plain input:

  • OpenAI shape: prompt_tokens_details.cached_tokens (and the write as cache_write_tokens, cache_creation_tokens or created_cache_tokens) inside prompt_tokens; DeepSeek’s prompt_cache_hit_tokens and prompt_cache_miss_tokens must add up to prompt_tokens;
  • Anthropic and Bedrock: the cache read and write counts beside the input count;
  • Gemini: cachedContentTokenCount inside promptTokenCount;
  • Responses: input_tokens_details.cached_tokens inside input_tokens.

With cache_read_usd_per_million, cache_write_usd_per_million and cache_write_1h_usd_per_million on the approved rate, each category settles at its own price (one-hour writes are read from Anthropic’s cache_creation and Bedrock’s cacheDetails; an OpenAI-shaped write has no time to live and is a five-minute write). Messages accepts cache_control with ttl 5m or 1h, and so does the chat profile (T115) on a Claude target (Anthropic or Claude on Bedrock): on a content part, a message or a function tool, the marks a Chat Completions client sends and the canonical form of a translated Messages request (prompt caching). On any other target the marks are removed before the call, except on an OpenAI Chat Completions passthrough, where a marked request stays outside the profile (text_messages_only): its writes carry no time to live. Automatic points a target adds (prompt_cache) are not in the request the reservation reads; the reservation already prices every input token at the highest input-side price the rate approves, one-hour writes included. Without the matching price, the reservation stays: the gateway does not guess a discount, nor charge cached tokens as plain input. The measurement records the cache categories (cache_read_tokens, cache_write_tokens, cache_write_1h_tokens) as part of the input; token ceilings count every input token.

A rate’s long_context tier (threshold and higher prices, see budgets and TPM) settles a request whose measured input (cache included) exceeds the threshold entirely at the tier’s prices, and a cache category the tier does not price keeps the reservation. The reservation takes the highest prices of both tiers whenever the input estimate exceeds the threshold.

To avoid applying the wrong price, these cases keep the reservation (or are refused) instead of using the text rate:

  • prompt caching without an approved cache price, server tools, service tiers and unrecognized usage categories;
  • reasoning, unless the provider proves it is part of the output: completion_tokens_details.reasoning_tokens no larger than completion_tokens, and total_tokens equal to input plus output. Then the reasoning text (reasoning or reasoning_content) is ordinary output at the output rate; a provider that bills reasoning on top of the output reports a larger total and keeps the reservation;
  • media in Gemini: only TEXT modality details count;
  • GPT Image streams, partial images, SVG and GIF output, and any GPT Image answer whose usage is not proven (GPT Image budgets);
  • audio in a compressed format: duration is read only from WAV PCM, with no guessing;
  • TPM for images, audio and rerank: these units are not tokens, and the gateway does not convert seconds into tokens to get around the policy. Use a budget policy for these profiles.

With quota_image_tokens (off by default; requires quota_media), budgets and token limits admit /v1/images/generations and /v1/images/edits requests to a GPT Image model (gpt-image-* on the openai protocol). Before the flag, and for any other image model without a per-image profile, they are refused with image_token_pricing_requires_separate_profile.

The approved rate prices text and image tokens apart and bounds what one generated image can bill:

quotas:
rates:
- provider_id: openai
model: gpt-image-2.6-flare
connection: <connection fingerprint>
input_usd_per_million: "5" # text input
output_usd_per_million: "30" # text output; see below
image_input_usd_per_million: "8"
image_output_usd_per_million: "30"
image_input_tokens: 1000 # ceiling per input image (edits)
image_output_tokens: 6000 # ceiling per generated image
revision: gpt_image_2026_11
Field Default Bounds Meaning
image_input_usd_per_million, image_output_usd_per_million none decimal USD, up to 6 places, at most 10000; both or neither The image token prices. Not combinable with long_context or service_tiers: the Images API documents neither.
image_output_tokens none 1-1,000,000, beside the image prices Your ceiling of output tokens per generated image. The profile does not restrict size, quality or complexity, so set it for the largest the provider accepts: a request above it bills past the reservation (debited in full and flagged as an overrun). Without it a GPT Image request is refused (422 quota_profile_unsupported), under a budget or a token ceiling alone.
image_input_tokens none 1-1,000,000 The existing per-image input ceiling: each input image of an edit, and its mask or markup, is reserved at it. image_urls: true is needed for https image URLs.

The reservation is the prompt’s UTF-8 bytes (no prompt token is shorter than a byte; text tokens the provider adds around the prompt bill past it as an overrun) plus image_input_tokens per input image, priced at the higher of the text and image input prices, and n × image_output_tokens, priced at the higher of the text and image output prices. OpenAI publishes per-size and per-quality output token counts only for the models before gpt-image-2 (272 to 6,240 tokens for low to high); for newer models it points to its calculator, so the ceiling is yours to approve and review when the provider changes its rules. An answer that bills more is debited in full and flagged as an overrun, like any other profile.

What a request may carry: model, prompt (1-32,000 characters), n (1-10, default 1), size, quality, background, output_format (png, jpeg or webp), output_compression, moderation, complexity, input_fidelity, user, safety_identifier, stream: false and partial_images: 0; an edit also its images, mask or markup. A stream, partial images (each adds 100 image output tokens and needs a stream), svg (its authoring model bills apart in svg_usage), gif, service_tier or any other field is refused before the provider.

The answer settles from the usage the gateway reads after the images (the same scanner as usage valuation): text input at input_usd_per_million, image input at image_input_usd_per_million, image output at image_output_usd_per_million and, when the answer splits its output, text output at output_usd_per_million. An answer that does not split its output is all image output only when output_usd_per_million equals the image output price; otherwise which part was text is unproven and the reservation is held. OpenAI publishes no text output price for gpt-image-2.6-flare, so approve its image output price there. The measurement proof keeps the image split (image_input_tokens, image_output_tokens), so a later reconciliation prices it the same way. An answer the scanner cannot prove (malformed, cut short, with an error or svg_usage, counts that do not add up) keeps its reservation.

This profile is qualified on PostgreSQL.

Many APIs accept an alias (gpt-4o-mini) and respond with the dated snapshot (gpt-4o-mini-2024-07-18). By default, the gateway requires the response to carry the exact model requested. To accept snapshots, declare them in the approved rate:

quotas:
rates:
- provider_id: openai
model: gpt-4o-mini
response_models: [gpt-4o-mini-2024-07-18]
# ...
  • Up to eight literal IDs, with no wildcard or prefix; allowed characters: letters, digits and ._:/+-, starting with a letter or digit.
  • Omitting the field or using [] keeps exact matching; null is invalid.
  • The list does not change routing, credentials, capability or price: it only says which response names prove the same rate.
  • Changing the list requires a new review of the rate. In a stream, the first model observed stays fixed until the end.
  • It does not apply to per-unit rates (image, audio, rerank).

Images, seconds of audio and search units use a per-unit rate: unit, variant (for example 1024x1024_standard, whisper_duration, cohere_v2) and unit_usd, with up to six decimal places. The console shows the human unit separately from tokens.

Anthropic usage accepts the documented standard speed (speed: standard, or an absent/null field). Fast mode, an unknown speed, nonstandard service tiers and regional usage not covered by the protected profile retain the reservation. The legacy inference_geo: not_available denotes an unset geo, like an absent/null field; it does not authorize US regional pricing. Optional null response metadata does not create a billed category. See the official Messages usage contract, speed reporting and data residency pricing and legacy geo reporting.

Each eligible response generates an immutable measurement (with no payload) containing the model, connection, categories, counts and checksum. The measurement is written before settlement; if settlement fails later, it lets you reconcile the reservation in financial reconciliation.

Read limits for measuring:

  • streams: 256 KiB per event, 32 MiB and 100,000 events;
  • JSON: 4 MiB. A larger response is delivered normally, but without complete proof the reservation stays;
  • requests: 64 levels of JSON nesting (tool schemas nest deeply) and a parser budget of 262,144 JSON values.

An error, a limit being reached, an end without termination, cancellation, a model change mid-stream or partial usage do not release the reservation. The gateway never repeats a call to recover the usage.

Validate selected profiles against a real provider

Section titled “Validate selected profiles against a real provider”

For contributors with local Docker/OrbStack and the pinned integration images already loaded, scripts/verify-quota-live.py runs selected profiles through a temporary production gateway binary, isolated PostgreSQL and two synthetic billing owners. It approves the plan’s exact prices through the admin API, sends inference through the public API and compares reservations, immutable measurements, ledger settlement and request/trace IDs. Existing installations and operator configuration are not changed.

Create a private JSON plan in the ignored test-results/ directory. This minimal compatibility example uses a model exercised in November 2026, not a recommendation to deploy that deprecated model:

{
"providers": [{
"provider": "openai",
"model": "gpt-4.1-mini",
"response_models": ["gpt-4.1-mini-2025-04-14"],
"rates": {
"input_usd_per_million": "0.40",
"output_usd_per_million": "1.60",
"cache_read_usd_per_million": "0.10"
},
"profiles": ["chat_json"]
}],
"max_requests": 1,
"max_output_tokens": 64,
"budget_usd": "0.25"
}

Check the model, capability, snapshot IDs and every price against the provider’s current official documentation before executing. Rates are operator approvals, never automatically inferred from catalog prices. budget_usd is a test-owner enforcement ceiling, not a guarantee of an external provider charge. Bound the combined attempt allowance across every author/reviewer run separately; a failed or timed-out send still consumes an attempt.

First exercise setup without credentials or inference:

Terminal window
python3 scripts/with-test-services.py -- \
python3 scripts/verify-quota-live.py \
--plan test-results/quota-plan.json --prepare-only \
--report test-results/quota-prepare.json

After explicit authorization for the selected providers and spend, run outside the quality gate:

Terminal window
GATEWAY_TEST_REAL_QUOTAS=1 python3 scripts/with-test-services.py -- \
python3 scripts/verify-quota-live.py \
--plan test-results/quota-plan.json \
--credentials /absolute/path/to/private-provider.env \
--report test-results/quota-live.json

Only the selected OPENAI_API_KEY, ANTHROPIC_API_KEY or GEMINI_API_KEY variables are parsed as data; the credential file is never shell-sourced. No real credential is copied into configuration, reports or fixtures. Keep reports private even though they contain only bounded metadata, counters and checksums. A report path must be new. Owned processes, configuration and services are removed on success or failure.

Supported selections are OpenAI chat_json, chat_stream, responses_json, responses_stream; Anthropic messages_json, messages_stream, messages_cache_write, messages_cache_read; Gemini generate_json, generate_stream. Cache profiles must be a write/read pair in that order with explicit read and one-hour-write prices; the helper creates a unique synthetic prefix. Anthropic connections requiring a workspace accept a non-secret workspace_id in the private plan, passed through the existing operator header policy. The selected 2026-11-01 acceptance resolved that workspace requirement and covered real native Messages image/one-hour-cache write/read and SSE. Historical account access is not current quota proof; the translated Chat regression replay used a synthetic provider and is not live translation certification. json_image: true requires an approved single-image ceiling; the helper sends only a small synthetic inline PNG, including in both JSON calls of a selected cache write/read pair; the shared system-cache prefix remains identical. stream_tool: true exercises OpenAI client function output, not a hosted provider tool. The helper validates official endpoints, refuses redirects and never retries inference.

A provider’s HTTP 200 alone is not success: an unknown reservation or absent complete measurement fails the run. The successful result proves usage settlement at the approved rate; it does not reconcile an invoice, certify every model or change production flags. The quality gate runs only the helper’s deterministic guard/privacy tests and recorded response regressions; it refuses real-provider opt-ins.

m7gtwcontact@m7gtw.com