Maximum Context Length Exceeded or "Prompt Is Too Long": Find What Overflowed, Then Fix It
context_length_exceeded and "prompt is too long" mean your input plus the output you reserved overflowed the model's window. Measure first, then trim, split, and only then upgrade.
1. Read the error: which limit did you actually hit?
The wording varies by provider and by gateway. OpenAI-compatible endpoints usually return an error code such as `context_length_exceeded`, often with two numbers in the message: the model's limit and the size of what you asked for. On Anthropic's native API, an input that is already larger than the window returns a 400 `invalid_request_error` with the message "prompt is too long". Before changing anything, copy those numbers down. The gap between them tells you how much to cut: a few hundred tokens over means one setting is wrong; double the limit means your design is sending far more than it should. Also check that it is really a token problem. Anthropic's documentation notes that requests with many images or large documents can hit request size limits before the token limit, and that is a different fix — fewer pages per call, not a shorter prompt.
2. The budget equation: what counts toward the window
Think of the window as one budget shared by input and output. According to Anthropic's context window documentation, everything in the request counts: the system prompt, every message (including tool results, images and documents) and your tool definitions, plus the output generated for that turn, including extended thinking. Other vendors describe it differently but the arithmetic is the same: input + reserved output must fit. This explains most surprises. A tool schema with dozens of functions can be thousands of tokens you never see in your own code. A retrieval step that pastes ten chunks instead of three quietly triples your input. And a generous `max_tokens` reserves space whether or not the model ends up using it. Write the equation down for your own app, with a rough number next to each part, and the biggest term is usually obvious.
3. Measure instead of estimating
Word-count conversions are fine for order of magnitude, but they break on code, JSON, logs and non-English text, which tend to use more tokens per character than plain English prose. Use real numbers instead. Every successful response reports what it consumed in its `usage` field; log it on every call, together with the model name, so you can see the growth curve before it hits the ceiling. Anthropic also offers a token counting API that estimates a request before you send it, and most vendors publish a tokenizer you can run locally. A practical rule: alert yourself at a fixed share of the window, not at the limit, for example when input passes three quarters of it. That turns a hard failure in production into a warning in your logs, and it gives you time to trim before users notice.
No overseas card needed: cocodot's OpenAI-compatible API — switch your base_url to call the models on sale.
Top up via Alipay / WeChat Pay, USDT / USDC · billed per token · switch your base_url to connect
4. max_tokens, reasoning, and the silent cut-off
`max_tokens` is a reservation, not a prediction. Setting it to the model's maximum "just in case" eats the space your input needs. With reasoning or thinking enabled the reservation matters even more: Anthropic's documentation states that thinking tokens are a subset of `max_tokens` and count toward the window. Then there is the behaviour difference that trips up error handling. On Anthropic's native API, if the input alone is too large, every model returns the "prompt is too long" error; but on Claude 4.5 and newer models, if input plus `max_tokens` is over the window, the request is accepted and generation stops with `stop_reason: "model_context_window_exceeded"` when the window fills. Older models reject the request instead. So check the stop or finish reason on every response, not just the HTTP status. An answer that ends mid-sentence with no error is the same overflow showing up later.
5. Long conversations: decide what to keep
Chat apps resend the whole history by default, so every turn is more expensive than the last and eventually the request no longer fits. A sliding window (keep the last N turns plus the system prompt) is the simplest fix. A rolling summary keeps more meaning: summarise older turns into a short note and keep recent turns verbatim. Whichever you choose, pin the things the user will expect you to remember — names, numbers, decisions, constraints — in a small structured block rather than trusting a free-form summary to keep them. One detail for reasoning models: Anthropic documents that on its newer Opus, Sonnet and Fable models, thinking blocks from earlier assistant turns are kept by default and count as input like any other history, while some earlier models strip them automatically. If your history grows faster than the visible text suggests, that is a place to look.
6. Agents and tools: the growth you do not see
In agent loops, your own prompt is rarely the problem. The window fills with tool results — a full file read, a search dump, a stack trace, a page of HTML — and with the record of every previous step. Cap tool output at the source: return the matching lines instead of the whole file, the first and last parts of a log instead of all of it, and identifiers instead of full documents when the model only needs to refer to them. Drop finished sub-tasks from the working context and keep a short progress note instead. Trim the tool list too: definitions count toward the window on every call. Anthropic documents server-side compaction and context editing (such as clearing old tool results) for this situation; check its documentation for which models support them. Coding assistants that say the conversation is too long or cannot be compacted further are hitting the same wall — start a fresh session with a short summary of where you are.
7. Long documents: split and retrieve before you upgrade
Sending a whole manual or contract in one call means paying for every page on every request, even when the answer depends on two paragraphs. Split the document into sections, retrieve only the passages relevant to the question, and send those. For tasks that genuinely need the whole document — a summary, a consistency check — process it in segments and combine the partial results in a final call. Several smaller calls are usually cheaper than one enormous call, and easier to retry: if one segment fails you re-run that segment, not the whole job. Bigger is not automatically better either. Anthropic's documentation notes that as token count grows, accuracy and recall degrade, which it calls context rot; curating what goes into the window matters as much as how large it is. Prompt caching does not help with fit: cached prefixes still occupy the window and only change what you pay for them.
8. When a bigger window is the answer, and how to test it
Some workloads really do need it: reasoning across an entire codebase, or comparing long documents side by side where splitting would lose the connections. Window sizes differ by model and change between releases, so read the current value on each vendor's model comparison page rather than relying on an old blog post, and remember that the same text can be a different token count on another vendor's tokenizer. Re-measure after switching and keep a margin. To compare candidates quickly, an OpenAI-compatible endpoint lets you swap models by changing one string. cocodot exposes Claude, GPT, Gemini and other models through one such endpoint; each model's context limit and current rate are listed at cocodot.co/pricing#models. Listed Claude / GPT / Gemini rates are at or below the official list price; check the pricing page for each model's current rate. Run the same trimmed request on two or three models and compare quality and `usage`, not just whether it fits.
Symptom → root cause → fix
| What you see | Likely root cause | First fix to try |
|---|---|---|
| Error on a short prompt | `max_tokens` set close to the window, or a large hidden history | Lower `max_tokens`; log the real input size |
| Works for a while, then fails mid-conversation | History grows every turn and is resent in full | Sliding window or summary of older turns |
| Agent fails after a few tool calls | Tool results (file reads, logs, search dumps) pile up | Truncate or summarise tool output before returning it |
| Fails only after switching models | Smaller window or a different tokenizer | Re-measure on the new model; keep a safety margin |
| Answer stops abruptly, no error | Window filled during generation | Check the stop or finish reason; shorten input |
| Size error with many images or PDFs | Request size limit, not the token limit | Send fewer pages per request |