Anthropic Context Window Errors Need a Local Admission Policy
Claude context windows include system content, messages, tool results, media, tool definitions, generated output, and extended thinking. A production gateway should resolve the model, count the final request, reserve output headroom, reject oversized payloads before dispatch, and distinguish local admission failures from Anthropic API errors and truncated HTTP 200 responses.

A Claude context window contains the request and the output generated for that turn. System content, conversation messages, tool definitions, tool results, images, documents, plus extended thinking and generated text all consume space. A gateway that checks only the visible user prompt can approve a request whose actual provider payload leaves no room for a valid answer.
The admission policy should run on the final routed request. Resolve the model, estimate input tokens, reserve the enforced output allowance, and return a typed local error before provider dispatch when the route budget cannot fit.
TL;DR
- Calculate context admission against the resolved model and final serialized provider payload.
- Include estimated input tokens plus enforced
max_tokenswith an explicit route margin in the decision. - Keep local preflight rejection separate from Anthropic responses, including HTTP errors and HTTP 200 truncation states.
- Require a new decision after compaction, summarization, model change, or output-budget reduction.
Context includes more than prompt text
Anthropic's context windows guide states that the context window includes all text the model can reference while generating a response, including the response itself. The guide lists system prompts, every message, tool results, images, documents, and tool definitions as request inputs that count. Generated output and extended thinking count too.
Inspect the provider-bound structure after SDK and gateway transformations. The count used for admission should cover the exact system, messages, tool, and media fields that will be dispatched. Bind it to a digest so any later mutation invalidates the decision.
Prompt-cache usage remains in the context calculation. Anthropic splits reported input usage between ordinary tokens and cached usage, with cache reads and cache creation reported separately, and every portion counting toward the window. Cache economics and context capacity therefore need separate fields.
The LLM API parameter allowlisting guide starts with the approved request fields. This article adds the admission rule that follows once the provider payload is fixed.
Admission combines input and output budgets
The model context window must have room for the input and generated output. Use Anthropic's token counting endpoint to estimate the final input, then add the route-enforced output allowance and a documented margin. Compare that total with the current context capacity configured for the resolved model.
max_tokens is an upper bound rather than a prediction, so a request can finish naturally with fewer tokens. Admission still needs to reserve the allowed maximum when the route promises that budget. Otherwise two requests approved against the same remaining capacity can receive inconsistent treatment based on provider behavior.
The Anthropic max_tokens route cap defines how to select and record that output ceiling. Keep estimated_input_tokens, enforced_max_tokens, context_margin, model_context_capacity, and remaining_capacity in separately named fields.
My opinion is that automatic prompt trimming at the gateway is a category error. It turns capacity enforcement into an undocumented conversation editor and can delete the instruction that explains why a tool result exists.
Error channels need separate outcomes
A local admission rejection occurs before the Anthropic request. Return a stable application error with the route decision ID and resolved model, plus budget fields safe for the caller. Avoid copying prompt content into the error. Mark provider dispatch as false.
Anthropic's API errors guide documents HTTP error envelopes and says request sizes above 32 MB produce HTTP 413 request_too_large. That transport-size limit is measured in bytes and differs from a model context limit measured in tokens. Keep those checks and outcomes separate.
A provider can also return invalid_request_error when request data violates the API contract. Preserve the provider status, error type, message, and request ID instead of rewriting every 400 response as a context failure. Classification should follow observed evidence.
Finally, an HTTP 200 can carry a truncated answer. Anthropic's stop-reason documentation includes max_tokens and model_context_window_exceeded as terminal reasons that indicate incomplete output. A status-only success metric misses both.
Correction paths must remain explicit
An over-budget request can be corrected in several ways: reduce conversation input, compact older turns, remove an optional document, lower the output allowance, or select an approved model with a larger context window. Each change produces a new payload or route choice and therefore needs a fresh policy decision.
The gateway should never select a different model merely to make the request fit unless route policy has approved that fallback. A model change can alter cost, behavior, data location, tool support, and output limits. Record the original rejection and the later accepted request as separate attempts under one application operation.
Compaction also changes evidence. Preserve the source conversation reference, compaction method, resulting digest, and count delta. The application decides which information may be summarized or removed. The gateway re-runs allowlisting and context admission on the revised HTTP request.
The safe idempotent LLM retries guide applies when a transport outcome is ambiguous. Deterministic local budget rejection is different: retrying the same bytes under the same model and policy should produce the same denial.
Audit records should preserve the observed boundary
Create one admission record before provider dispatch. Capture authenticated identity, tenant, route, resolved model, policy version, request digest, token-count source, estimated input, enforced output allowance, margin, context capacity, and decision reason.
When dispatch occurs, add the Anthropic request ID and provider response classification. For successful responses, retain actual usage and the stop reason. Calculate estimate drift for operations that have both preflight and actual usage, while preserving the original values.
A local denial has no Anthropic request ID. Leave that field explicitly unobserved. Generating a fake provider ID or copying the gateway decision ID into the provider column makes later incident queries unreliable.
The AI audit log schema can carry the common decision fields. Context-specific values belong in a typed extension rather than one free-form note.
On a review screen, show the budget as a horizontal bar with input and output segments separated by the margin. A thin red segment crossing the model limit gives the engineer a physical view of the exact admission failure.
A boundary fixture needs byte and token failures
Build a fixed test request and send it through the deployed route to a controllable Anthropic stub. Place one case just below the local context threshold and one just above it. The first should reach the stub with the exact approved payload. The second should stop locally and contain no provider request ID.
Mutate the allowed case after counting by adding a tool definition and a long tool result. The request digest check should force another count and decision. Then lower max_tokens under an approved caller action and confirm that the revised request receives a new record.
Test HTTP 413 separately with a payload over Anthropic's documented request-size boundary. Test a provider 400 invalid_request_error that names an unrelated field. Neither should be relabeled as local context rejection.
Return HTTP 200 responses with end_turn and two incomplete stop reasons, max_tokens and model_context_window_exceeded. The consumer should classify one completed response and two incomplete responses, preserving output and stop reason under the route's handling policy.
DeepInspect
DeepInspect can enforce context-admission policy on authenticated user or agent HTTP traffic deliberately routed through its proxy to Anthropic. It can bind identity, route, model, request digest, token estimate, output allowance, policy version, and allow or deny outcome before provider dispatch, then record response stop reasons on the routed return path.
The application owns conversation compaction, summarization, fallback selection, tool-state preservation, and user-facing correction. DeepInspect cannot govern direct Anthropic calls or payload changes made after traffic leaves its HTTP boundary.
Book a demo today.
Frequently asked questions
- Does prompt caching remove tokens from the context window?
Anthropic's context guide says cached input usage still counts toward the window through ordinary
input_tokenspluscache_read_input_tokensandcache_creation_input_tokens. Caching changes reuse and billing behavior, not the amount of context available to the model.- Is HTTP 413 an Anthropic context-window error?
Anthropic documents 413
request_too_largefor requests above 32 MB. That is a byte-size transport limit. Context admission uses model capacity and token accounting, so record the two failures separately.- Should the gateway retry a local context rejection?
The same payload under the same model and policy should receive the same denial. A valid correction changes the request settings or routing through the payload, output allowance, or approved model, then enters a fresh count and policy decision.
- Can HTTP 200 still mean the answer is incomplete?
Yes. Anthropic documents stop reasons including
max_tokensandmodel_context_window_exceeded. Inspect the terminal stop reason and actual usage before treating a response as complete.