cocodot
← Back to guides
Local card declined for overseas AI? cocodot: one card + one key
TroubleshootingUpdated 2026-10

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.

TL;DR: A context error means everything in the request plus the output you reserved did not fit in the model's window. "Everything" is more than your visible prompt: the system prompt, every earlier turn, tool definitions, tool results, images and documents all count, and so does the output, including any reasoning or thinking tokens. Fix it in this order: (1) measure what you really sent from the `usage` field or a token counter; (2) trim what never needed to be there — stale turns, oversized tool output, whole files where one section would do; (3) split long jobs into pieces; (4) only then move to a model with a larger window. One detail catches people out: on Anthropic's native API, newer Claude models accept a request whose input plus `max_tokens` is over the window and simply stop when the window fills, so the same bug can show up as a silently cut-off answer instead of an error.

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 seeLikely root causeFirst fix to try
Error on a short prompt`max_tokens` set close to the window, or a large hidden historyLower `max_tokens`; log the real input size
Works for a while, then fails mid-conversationHistory grows every turn and is resent in fullSliding window or summary of older turns
Agent fails after a few tool callsTool results (file reads, logs, search dumps) pile upTruncate or summarise tool output before returning it
Fails only after switching modelsSmaller window or a different tokenizerRe-measure on the new model; keep a safety margin
Answer stops abruptly, no errorWindow filled during generationCheck the stop or finish reason; shorten input
Size error with many images or PDFsRequest size limit, not the token limitSend fewer pages per request

FAQ

Am I billed for a request that failed with a context error?

A request rejected up front is generally not processed. A request that was accepted and then stopped when the window filled is a different case: check the `usage` field on that response, because whatever it reports was processed. In a batch, the calls that succeeded are billed normally.

Why do I get maximum context length exceeded with a short prompt?

Usually because `max_tokens` is set close to the window, or because hidden parts of the request — conversation history, tool definitions, tool results, retrieved chunks — are much larger than the prompt you see. Log `usage` on the last successful call to find the real size.

Does prompt caching fix a context length error?

No. Cached tokens still count toward the window; caching changes what you pay for a repeated prefix, not how much space it takes. Solve the fit problem first, then use caching as a cost tool.

What is the difference between context length and context window?

In practice they name the same limit: the maximum number of tokens one request can hold, covering input plus the output it generates. Many vendors also set a separate cap on output length alone, so check both values on the model's documentation page.

Why did my app start failing after I switched models?

The new model may have a smaller window, a lower output cap, or a different tokenizer that turns the same text into more tokens. Re-measure the request on the new model and leave headroom instead of packing the window to the last token.

About cocodot

cocodot is a payment and AI access service for developers and cross-border teams in mainland China. It provides US-BIN virtual cards issued by a licensed institution — used to pay for overseas subscriptions and ad accounts — and an OpenAI-compatible AI API gateway for calling Claude, GPT and Gemini from within mainland China. Both share one wallet, funded by Alipay / WeChat Pay, USDT / USDC and accounted in USD. Fees are listed on the pricing page.

Service scope, pricing and limits →
OpenAI-compatible API, pay in RMBGet API access