Skip to content

Context window check before dispatch

Last updated: 2026-11-27T02:00:32-03:00 (UTC-3)

A prompt longer than a model’s context window is refused by the provider, but only after the gateway has sent it: the request travels, the provider answers 400, and only then can a semantic fallback send it to a model with a larger window. When you declare a target’s maximum input, the gateway estimates the request’s input tokens before calling it and skips a target whose window the request clearly exceeds. No provider call is made for that target; the request goes to the next target, to the alias’s context_window_fallback, or back to the client with the same context-length error a provider gives.

The provider’s own refusal stays in place as the backstop: anything the estimate cannot see, or does not count, is still caught there, exactly as before.

Declare max_input_tokens on each target whose window you know. The flag context_window_check is on in the bundled configuration; it acts only on targets that declare a limit.

features:
context_window_check: true # shipped on; acts only on targets with max_input_tokens
semantic_fallbacks: true # for context_window_fallback
models:
- id: chat
context_window_fallback: chat-long
targets:
- provider: groq
model: llama-3.1-8b-instant
max_input_tokens: 131072
- provider: openai
model: gpt-4o-mini
max_input_tokens: 128000
max_input_tokens_margin_percent: 5
- id: chat-long
targets:
- {provider: openai, model: gpt-4.1-mini, max_input_tokens: 1047576}

A request of about 300,000 tokens of English text to chat skips both targets without calling them and is answered by chat-long, with X-Gateway-Fallback: context_window:chat-long. A request only slightly above a window (say 135,000 tokens) is not clearly too large for the estimate, so it is sent as before; the provider refuses it and the semantic fallback takes over, exactly as without this check.

In the console, the model editor shows a Context window block on each target of a text-generation alias: Maximum input tokens and, once a limit is set, Margin above the limit (%). Clearing the limit removes the margin too. With the flag off the block says that the limit is saved but not applied.

Field Values Default Applied
features.context_window_check true, false true in the bundled config/gateway.yaml and Helm chart; false when a configuration file leaves it out Runtime flag: YAML, the features API and the console Features page; next request
models[].targets[].max_input_tokens 1–100,000,000 unset: no check, the target is called as before YAML, PUT /api/v1/admin/models/{id}, console model editor; next request
models[].targets[].max_input_tokens_margin_percent 0–100 10 Same; requires max_input_tokens
  • The target is skipped when the estimate is greater than max_input_tokens × (100 + margin) / 100. With the default margin and a limit of 128,000, an estimate of 140,800 tokens is still sent and one of 140,801 is not.
  • max_input_tokens is compared with the input alone. A provider that counts the requested output inside the same window (input plus max_tokens) refuses earlier than that; for such a model, set the limit to the window minus the output you reserve, or rely on the provider’s refusal for the last few percent.
  • The fields are accepted only on aliases whose capabilities are all text generation: chat (the default), messages, responses and generate_content. Any other value is refused at load and by the model API: max_input_tokens must be from 1 to 100000000, max_input_tokens_margin_percent must be from 0 to 100, max_input_tokens_margin_percent requires max_input_tokens, max_input_tokens applies only to chat, messages, responses and generate_content aliases.
  • The flag is an operator control, not a plan right: plan entitlements do not switch it per team.
Route Too-small target with another target left No target left
POST /v1/chat/completions Skipped; the next target in the alias’s order is tried context_window_fallback when configured and semantic_fallbacks is on; otherwise 400
POST /v1/messages, POST /v1/responses, generateContent translated to another protocol Same (they run through the chat pipeline) Same, and the error is re-encoded in the route’s own dialect
Native POST /v1/messages (Anthropic target) Skipped 400 in the Messages error shape
Native POST /v1/responses (OpenAI Responses target) Skipped, when the request may fall back (stateless) 400 in the Responses error shape
Native generateContent / streamGenerateContent (Gemini target) Skipped 400 in the Gemini error shape

On the chat pipeline, when a target was skipped for its window and a later target then fails (destination admission or circuit breaker refusal, a transport failure, a translation refusal, or a 429 or 5xx answer from the last target), the request is offered to context_window_fallback before that failure is returned: without the check, the skipped target’s provider would have refused the request for context and the fallback would have answered it. Without a fallback, or when the fallback alias refuses, the client gets the later target’s failure as before (with X-Gateway-Fallback-Refused when the fallback refused).

The native routes have no semantic fallback today, with or without this check. A stateful Responses request (previous_response_id, conversation, containers) stays on the target holding its state: if that target’s window is clearly too small, the client gets the 400 without a call. Token counting endpoints, embeddings and the other operations are not checked.

The check runs per target, at the moment the target would be called: after guardrails, quota admission and the cache lookup, before the request is translated, before destination admission and the circuit breaker. A target skipped this way does not count as a send: attempts, retries and fallbacks in request events and X-Gateway-Attempts count only real sends, and a budget reservation of a request that made no send is released. A semantic fallback triggered this way is the same second request as after a provider’s refusal, admitted in full against the fallback alias, with the request ID <request id>.fallback.

The body imitates a provider’s context-length refusal, so a client, an SDK or an agent that already handles that error (for example by compacting its conversation) handles this one too. It names the estimate and the largest limit among the skipped targets; it never names a provider.

Chat Completions (and the semantic fallback’s reading of it):

HTTP/1.1 400 Bad Request
Content-Type: application/json
{"error":{"code":"context_length_exceeded","message":"prompt is too long: the input has at least 140902 tokens by the gateway's estimate, above this model's maximum context length of 128000 tokens; reduce the length of the messages","param":"messages","type":"invalid_request_error"}}

Messages (native, or translated to another protocol):

{"error":{"message":"prompt is too long: the input has at least 140902 tokens by the gateway's estimate, above this model's maximum context length of 128000 tokens; reduce the length of the messages","type":"invalid_request_error"},"type":"error"}

Responses: {"error":{"code":"context_length_exceeded","message":"...","param":null,"type":"invalid_request_error"}}. GenerateContent: {"error":{"code":400,"message":"...","status":"INVALID_ARGUMENT"}}.

When context_window_fallback is configured but its alias refuses before any provider answers (the key may not call it, a budget, a rate limit, or its own targets’ windows are too small), the client gets this error with X-Gateway-Fallback-Refused: context_window:<code>, for example context_window:context_length_exceeded or context_window:model_forbidden, exactly as after a provider’s refusal.

Each skipped target writes two log records and one trace span, with counts only, never request text (abridged: the records also carry time, correlation_id, trace_id and the span IDs):

{"level":"INFO","msg":"upstream_attempt_skipped","request_id":"9f0c...","provider":"groq","model":"chat","capability":"chat","reason":"context_window_exceeded","field":""}
{"level":"INFO","msg":"context_window_exceeded","request_id":"9f0c...","provider":"groq","model":"chat","capability":"chat","estimated_input_tokens":140902,"max_input_tokens":131072,"margin_percent":10}

The span is provider.<capability>.skipped. A request answered with the 400 has error_code: "context_length_exceeded", provider: null and attempts: null in its request event; one answered by another target or by the fallback alias records that answer as usual.

How the estimate works, and how far it can be off

Section titled “How the estimate works, and how far it can be off”

Without the provider’s tokenizer the count is estimated, and the estimate is built to stay at or below the real count, so a skipped target is one the provider would have refused anyway:

  • Only text the model reads is counted: message and system text, tool call arguments and tool results, tool names, descriptions, parameter names, types and enum values. Images, audio, files, documents, base64 data, opaque reasoning state (Anthropic thinking, Responses reasoning items, Gemini parts marked thought), signatures, IDs, roles, schema titles and the chat template’s own tokens count zero. A request whose size comes from media is therefore never skipped by this check; the provider still refuses it if it does not fit.
  • A top-level member listed in the target’s drop_parameters (request parameter policy), such as tools, is not counted for that target, since it never receives it. Neither is what a path or a preset removes: with tools[*].description dropped, the descriptions are left out of that target’s estimate and the rest of tools is counted.
  • Text is split the way byte-pair tokenizers split it before merging: a word, a run of digits, a run of other symbols. Each piece is at least one real token in the common tokenizer families, so counting pieces gives a floor. Whitespace counts zero; a single symbol before a word counts with the word; a run of digits counts once, whatever its length. Scripts written without spaces (Chinese, Japanese, Thai…) count one piece per 20 characters, the longest such run one token of the measured vocabularies holds, which makes the estimate very low for those languages: the check rarely acts on them.
  • Stored state the request only points to (previous_response_id, conversation) is not read, so it is not counted.

Measured error. The estimate was compared with the real token counts of seven public tokenizers (OpenAI o200k_base and cl100k_base through tiktoken 0.14.0; Qwen2.5, DeepSeek-V3, Llama 2 and Gemma through tokenizers 0.23.3; and the legacy public Claude tokenizer) on 229 text samples and 60 conversations with tools. The figure is the estimate divided by the real count, median / largest; 1.00 would be exact. No sample had an estimate above its real count with any tokenizer. Every entry of the seven vocabularies (about 927,000) was also checked against the segmentation: apart from three (a special-token fragment, a piece that only occurs inside a contraction the estimate counts as one word, and one kaomoji in Gemma), none counts as more than one piece.

Content Samples o200k cl100k Qwen2.5 DeepSeek-V3 Llama 2 Gemma legacy Claude
English technical Markdown 73 0.88 / 0.97 0.88 / 0.98 0.86 / 0.98 0.85 / 0.94 0.72 / 0.85 0.81 / 0.95 0.81 / 0.92
Portuguese Markdown 30 0.77 / 0.95 0.71 / 0.92 0.70 / 0.92 0.71 / 0.93 0.59 / 0.86 0.73 / 0.93 0.64 / 0.91
Go source 46 0.76 / 0.80 0.77 / 0.81 0.75 / 0.80 0.71 / 0.74 0.56 / 0.61 0.62 / 0.67 0.63 / 0.68
TypeScript source 59 0.72 / 0.79 0.73 / 0.80 0.73 / 0.78 0.69 / 0.76 0.55 / 0.62 0.61 / 0.68 0.66 / 0.73
JSON data 3 0.66 / 0.75 0.67 / 0.75 0.56 / 0.65 0.63 / 0.73 0.47 / 0.50 0.51 / 0.51 0.61 / 0.70
YAML (OpenAPI) 3 0.72 / 0.75 0.72 / 0.74 0.68 / 0.72 0.71 / 0.73 0.58 / 0.62 0.62 / 0.68 0.75 / 0.77
CSV numbers, log lines 2 0.84–0.85 0.84–0.85 0.49–0.56 0.83–0.85 0.49–0.54 0.49–0.55 0.79–0.83
Russian, Arabic, Hindi, Korean 4 0.52–0.68 0.22–0.41 0.24–0.52 0.40–0.58 0.17–0.41 0.45–0.62 0.19–0.32
Chinese, Japanese, Thai 3 0.10–0.15 0.06–0.07 0.11–0.12 0.10–0.16 0.05–0.06 0.12–0.17 0.03–0.08
Base64 text 1 0.43 0.41 0.40 0.42 0.36 0.43 0.42
Conversations with tools (OpenAI accounting: content, 3 tokens per message, tools as the model reads them) 60 0.77 / 0.83 0.77 / 0.83

The remaining samples (hex, emoji and accented text, whitespace-heavy code, repeated symbols and letters) stayed between 0.01 and 0.82. Read it this way: on English prose the estimate is typically 12% below the real count and was never above it; on code about 25% below; on unspaced scripts it is a small fraction. A provider also adds its chat template’s tokens, so its count is higher still. The current Claude, Gemini and Mistral tokenizers are not public and were not measured: the margin is what covers a tokenizer that splits text more coarsely than these seven. With the default 10%, a target is skipped only when even an estimate inflated by a tenth would not fit. Set the margin to 0 for a target whose tokenizer is one of the measured families, or raise it if you see a provider accept a request the check refused (the logs give the estimate and the limit of every skip).

  • New flag context_window_check, shipped true in config/gateway.yaml and the Helm chart’s files/gateway.yaml. A deployment that uses its own configuration file without the key has the check off, which changes nothing either way until a target declares max_input_tokens.
  • New optional target fields, stored with the model: no migration. A target without max_input_tokens is called exactly as before, on every route.
  • Turning the flag off restores the previous behavior immediately; the declared limits stay saved.

An alias can opt in to truncating the oldest turns or summarizing them with another alias when no target fits, behind the flag context_overflow: see context overflow.

m7gtw[email protected]