OpenAI Context Length Exceeded
Your messages tokens plus max_tokens (or max_completion_tokens on o-series) exceeds the model's context window. Fix by trimming history, summarizing older turns, chunking documents, or moving to a model with a larger window.
Count your prompt tokens with tiktoken. Ensure input_tokens + max_tokens ≤ model_context. GPT-5: 400K context. GPT-4o: 128K. o3: 200K. If over, trim old conversation turns, summarize with a cheaper model, or split documents into chunks.
The Error Message You're Seeing
HTTP/1.1 400 Bad Request
{
"error": {
"message": "This model's maximum context length is 128000
tokens. However, your messages resulted in 132000 tokens
(128500 in the messages, 3500 in the completion).
Please reduce the length of the messages or completion.",
"type": "invalid_request_error",
"code": "context_length_exceeded"
}
}Model Context Windows Reference
| Model | Context window | Max output |
|---|---|---|
| gpt-5 | 400,000 | 128,000 |
| gpt-5-mini | 400,000 | 128,000 |
| gpt-4o | 128,000 | 16,384 |
| gpt-4o-mini | 128,000 | 16,384 |
| o3 | 200,000 | 100,000 |
| o3-mini | 200,000 | 100,000 |
| o1 | 200,000 | 100,000 |
What Actually Causes This Error
Fixes That Work (Tested Nov 2026)
1Count Tokens Before Sending
2Trim Old Turns with Priority
3Summarize Old Context
Summarizing older turns with a cheap model (gpt-4o-mini) reduces context by 80%+ while keeping semantic memory. Refresh summary every N turns or when hitting 70% of context budget.
Preventing This Error Going Forward
- Always count tokens before sending. tiktoken is fast and free.
- Enforce budget: input + max_tokens ≤ ctx − 2K safety.
- Trim conversations proactively. Don't wait for overflow.
- Summarize instead of dropping. Cheaper model, preserves memory.
- Choose model by context need. GPT-5 (400K) > o3 (200K) > GPT-4o (128K).
- Vision: use low detail unless zoom needed. 85 vs 1600 tokens per image.
Researcher · AI Error Hub
Frequently Asked Questions
Yes — output tokens must fit inside the total window alongside prompt. If prompt is 120K and window is 128K, max_tokens can't exceed 8K.
Yes. o-series uses max_completion_tokens covering both reasoning tokens AND visible output. Prompt + max_completion_tokens ≤ context. Reasoning tokens can be 5-20K on hard problems.
Yes. Function schemas, descriptions, and past tool_calls in history all count. Large tool arrays (20+ tools) can consume 5-15K tokens before you even start.
Low detail: 85 tokens fixed. High detail: 85 + 170 per 512×512 tile. A 2048×2048 image at high detail = ~1,530 tokens.
No — cost scales with input tokens. Use the smallest model that fits your context. GPT-4o-mini at 128K is far cheaper than GPT-5 at 400K for the same content.
Related Errors
Stop Context Overflow Errors
Weekly deep dives on token counting, RAG optimization, and context strategies. 12,000+ developers subscribe.
Subscribe Free →