400 invalid_request_error: prompt is too long
Cause: The input you sent is already larger than the model's context window, so the Claude API rejects it before generating anything.
Copy-paste fix
Use the token-counting endpoint before you send, and drop the oldest turns until the request fits with room for the reply.
import anthropic
client = anthropic.Anthropic()
def fit_messages(model, system, messages, context_window, max_tokens):
while True:
n = client.messages.count_tokens(
model=model, system=system, messages=messages).input_tokens
if n + max_tokens <= context_window:
return messages
if len(messages) <= 1:
raise ValueError(f"Single message is {n} tokens: summarize it or "
"use a model with a larger context window")
messages = messages[2:] # drop the oldest user/assistant pair
Price a long-context Claude call on TokenCenter and compare it with other models
What the error means
Anthropic's context-window docs say that if the input alone exceeds the window, the API returns a 400 invalid_request_error (“prompt is too long”) on every model.
On Claude 4.5 models and newer, input plus max_tokens may go over the window and the request is still accepted; if generation then hits the limit it stops with stop_reason: "model_context_window_exceeded". Earlier models return a validation error instead.
Checklist
- Get the context window for your exact model from the provider's model page.
- Count input tokens with the token-counting endpoint; it accepts the same system, messages and tools as a real request.
- Keep the conversation starting with a user turn after you trim.
- Keep each tool_use block and its tool_result together when you trim.
- Summarize long documents in chunks instead of sending them whole.
- Check stop_reason on every reply so a window stop is not mistaken for a full answer.
Related
- context_length_exceeded
- finish_reason: "length" (reply cut off)
- Failure mode: Truncation and lost instructions
- Failure mode: Long-chat drift
- Context planner: will your prompt fit the model?
- ModelRaters list: Best for long documents