Fix "maximum context length" and "prompt is too long" (context_length_exceeded)
This model's maximum context length is 128000 tokens. However, your messages resulted in 135000 tokens. Please reduce the length of the messages.
- This model's maximum context length is 8192 tokens. However, you requested 9000 tokens (7000 in the messages, 2000 in the completion). Please reduce the length of the messages or completion.
- Your input exceeds the context window of this model. Please adjust your input and try again.
- prompt is too long: 215000 tokens > 200000 maximum
- The input token count (1200000) exceeds the maximum number of tokens allowed (1048576).
- Token indices sequence length is longer than the specified maximum sequence length for this model (1024 > 512).
The request sent to the model holds more tokens than its context window accepts. Count tokens before the call, trim the conversation history or split documents, and leave room for the answer (max_tokens).
What this error means
A language model reads tokens, not characters, and can only process a fixed number of them per request: its context window. The system prompt, the whole history, attached documents, tool definitions and tool results all count toward that total. Depending on the provider, the room reserved for the answer (max_tokens) is added too. If the sum goes over the limit, the API rejects the request with a 400: context_length_exceeded at OpenAI, invalid_request_error “prompt is too long” at Anthropic, INVALID_ARGUMENT at Gemini. Nothing is truncated for you: your code has to shrink the input.
Common causes
- Growing chat history: every turn resends the whole conversation, which eventually exceeds the window.
- Whole document or file in the prompt: PDF, logs, a codebase or too many passages retrieved by a RAG pipeline.
max_tokenstoo high: with some providers, input plus maximum output must fit in the window, so a hugemax_tokenstriggers the error.- Large tool results in an agent loop: API JSON responses, web pages or file contents appended at every step.
- Wrong estimate: you count words or characters, while code, JSON and non-English text produce more tokens per word.
Step-by-step fix
-
Count tokens before the call
Use the provider’s own tool:
tiktokenfor OpenAI models, thecount_tokensendpoint for Claude (tokenizers differ, sotiktokenis wrong for Claude), andcount_tokensin thegoogle-genaiSDK for Gemini.# OpenAI models import tiktoken enc = tiktoken.get_encoding("o200k_base") print(len(enc.encode(text))) # Claude import anthropic client = anthropic.Anthropic() count = client.messages.count_tokens( model="claude-opus-5-5", messages=[{"role": "user", "content": text}], ) print(count.input_tokens) -
Reserve room for the answer
Compute an input budget equal to the model’s window minus
max_tokensminus a margin. Setmax_tokensto the answer length you actually expect. -
Trim the history from the oldest end
Keep the system prompt separate and drop the oldest turns, in user/assistant pairs to keep the alternation, until it fits the budget.
def trim_history(messages, count_tokens, budget): """Drop the oldest user/assistant pairs until the history fits.""" kept = list(messages) while len(kept) > 2 and count_tokens(kept) > budget: del kept[:2] return kept -
Summarize older turns
Instead of losing the start of the conversation, replace old turns with a model-written summary. Anthropic also offers server-side compaction (beta) that summarizes history automatically as it nears the limit.
-
Split documents and keep only what matters
Cut long texts into slightly overlapping chunks, index them (embeddings) and send the model only the few passages relevant to the question.
def chunk_text(text, max_chars=8000, overlap=500): chunks, start = [], 0 while start < len(text): end = start + max_chars chunks.append(text[start:end]) start = end - overlap return chunks -
Slim down tool results
In an agent loop, send back only the useful fields of a JSON response, truncate logs and drop old tool results that are no longer needed.
-
Switch to a model with a larger window
If the need is real (a long contract, a code repository), pick a model with a larger context, for example 1 million tokens. Check the exact window in the provider’s docs or Models API.
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Count tokens on every turn and trigger trimming or summarizing before reaching about 80% of the window.
- Cap the number and size of passages your RAG pipeline injects.
- Never cut content silently: tell the user when a document was split or summarized.
Frequently asked questions
How many words is a token?
In English, a token averages about 4 characters, roughly three quarters of a word. French, code and JSON produce more: always measure with the provider’s tokenizer.
Does max_tokens count toward the context limit?
Yes at OpenAI, and at Anthropic on recent models: input plus max_tokens must fit in the window. Lower max_tokens when the input is close to the limit.
Why does the error only appear after several messages?
Because the API is stateless: you resend the whole history every turn, and it grows until it exceeds the window. Trim or summarize the history.
Useful tools for this error
More AI & LLMs errors
- Fix error 429 "Rate limit reached" on OpenAI, Claude and Gemini APIs
- Fix "CUDA out of memory" in PyTorch
- Fix error 401 "Incorrect API key provided" / "invalid x-api-key"
- Fix "Torch not compiled with CUDA enabled" and torch.cuda.is_available() returning False
- Fix "could not connect to ollama" and connection refused on port 11434
- Fix "JSONDecodeError: Expecting value" when parsing an LLM response
- Fix "You are trying to access a gated repo" (401) on Hugging Face