How context_length_exceeded Happens Below the Visible Message Token Count
OpenAI enforces the context window across the entire request envelope—not just the raw string length of your visible messages array. When local token counters only measure message text, several hidden or reserved token pools push the total over the model’s limit:
- Reserved completion and reasoning tokens: The context window covers
input_tokens + max_output_tokens(ormax_completion_tokens), including internal reasoning tokens on reasoning models. For example, if a model has a 128k context window and your input is 115k tokens whilemax_completion_tokensis set to 16k, the API reserves115k + 16k = 131ktokens and rejects the request upfront. - Tool definitions and structured output schemas: JSON schemas passed in
toolsandresponse_format(json_schema) are serialized into the model’s prompt context behind the scenes, often adding thousands of tokens that local message counters miss. - Per-message framing, images, and file attachments: Chat message role/header overhead, base64/URL image tiles, and attached files consume additional input tokens beyond plain text tokenization.
- Tokenizer mismatches or rough character heuristics: Estimating with
chars / 4or using an older tokenizer encoding (cl100k_baseinstead ofk_baseor a newer model encoding) undercounts dense JSON, code, and non-English text.
Steps to Prevent Hidden context_length_exceeded Errors
- Budget for both input and output reservations: Check
exactInputTokens + reservedOutputTokens <= modelContextWindow - safetyMarginbefore dispatching the request. - Use OpenAI’s server-side input token count endpoint for exact totals: Call
POST /v1/responses/input_tokens(client.responses.input_tokens.count(...)) when requests include tool schemas, structured output schemas, images, or near-limit histories. - Cap
max_output_tokens/max_completion_tokensrealistically: Avoid reserving huge output budgets (such as 32k–64k tokens) when you only expect a short JSON response or tool call. - Trim tool definitions and bloated tool outputs: Send only the tools relevant to the current step, and truncate large tool return payloads before storing them in conversation history.
TypeScript Example: Preflight Context Budget Guard with Exact Token Counting
import OpenAI from "openai";
const openai = new OpenAI();
interface PreflightBudgetOptions {
model: string;
contextWindow: number;
maxOutputTokens: number;
safetyMarginTokens?: number;
input: OpenAI.Responses.ResponseInput;
tools?: OpenAI.Responses.Tool[];
}
export async function assertRequestFitsContextWindow({
model,
contextWindow,
maxOutputTokens,
safetyMarginTokens = 512,
input,
tools,
}: PreflightBudgetOptions): Promise<{
inputTokens: number;
remainingForOutput: number;
}> {
// Counts exact input tokens including instructions, history, images, and tool schemas
const countResult = await openai.responses.input_tokens.count({
model,
input,
tools,
});
const inputTokens = countResult.input_tokens;
const totalRequested = inputTokens + maxOutputTokens + safetyMarginTokens;
if (totalRequested > contextWindow) {
throw new Error(
`Context budget exceeded for ${model}: input=${inputTokens}, ` +
`reservedOutput=${maxOutputTokens}, margin=${safetyMarginTokens}, ` +
`total=${totalRequested} > limit=${contextWindow}`
);
}
return {
inputTokens,
remainingForOutput: contextWindow - inputTokens,
};
}
Helpful Tips for Context Budgeting
- Dynamically clamp
max_output_tokenswhen near the limit: IfcontextWindow - inputTokensis smaller than your defaultmax_output_tokens, lowermax_output_tokenstoMath.max(minRequiredOutput, contextWindow - inputTokens - safetyMargin)before calling the API. - Leave extra headroom for reasoning models: Reasoning models spend tokens on internal thinking before emitting visible text or tool calls, so setting
max_completion_tokenstoo low causesfinish_reason: "length"with empty visible output. - Watch streaming failure events too: On streaming endpoints, a context limit failure can surface as an error event inside the stream rather than only an initial HTTP 400 exception, so handle error codes in both your
try/catchblock and stream event loop.
You must log in or register to comment.
