A Claude API 400 invalid_request_error that says prompt is too long means the input you sent is bigger than the model's context window. A public bug report quotes the full message as prompt is too long: 218556 tokens > 200000 maximum: the first number is what you sent, the second is the limit. Anthropic's context windows docs say that if the input alone exceeds the window, the API returns this error "on every model." Retrying the same request can't help. The fix is to send less: count tokens before each turn, shorten large tool results, drop the oldest turns in a way that keeps the history valid, or let the API compact the history for you.
This post covers what counts toward the limit, how to catch the error in Python, a trimmer you can drop into an agent loop, and the server-side options that make most trimming code unnecessary. The code was run with the anthropic Python package, version 2.14.0, on Python 3.13, against a fake HTTP transport that counts tokens roughly and returns this 400 when a request is over a small limit. No request went to the real API.
What counts toward the limit
The context windows docs are direct: "Everything in the request counts toward the context window: the system prompt, every message in messages (including tool results, images, and documents), and your tool definitions." The output the model generates for the turn, thinking included, counts too.
The window depends on the model. The docs list a 1M-token window for current models, including Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5, and say "other Claude models have a 200k-token context window." On models with a 1M window, 1M is the default and needs no beta header.
In an agent loop, the usual cause is not a long user message. It is growth. Every turn adds an assistant message with tool_use blocks and a user message with their tool_result blocks, and nothing ever leaves. One file read or search that returns a few hundred kilobytes is enough to push a long run over the edge. Two more things grow quietly:
- Thinking blocks. On Claude Opus 4.5 and later Opus models, Sonnet 4.6 and later Sonnet models and the other current models, the docs say the API keeps previous thinking blocks by default, and they count toward the window.
- Cached input. Prompt caching lowers what you pay for repeated input, not how much room it takes. The previous post on budgeting the context window shows why
usage.input_tokensalone can look small while the window is nearly full.
Too long is not too large, and not max_tokens
Three errors look alike:
- 400
prompt is too long: too many tokens for the model's window. - 413
request_too_large: too many bytes. The errors page lists a 128 MB maximum for the Messages API and says that on the first-party API, Cloudflare returns this error "before the request reaches the API servers." Large base64 images or PDFs trigger this one. max_tokenspushes past the window. On Claude 4.5 models and newer, the docs say a request whose input plusmax_tokensexceeds the window is accepted, and if generation reaches the limit it stops withstop_reason: "model_context_window_exceeded". On earlier models the API returns a validation error instead. That one is fixed by loweringmax_tokens, not by trimming.
So prompt is too long is only about the input. If the input fits but leaves little room, you get a cut-off response, which your loop should treat like any other stop it has to handle, as in agent infinite loops.
Catch it in Python
In the Python SDK a 400 raises anthropic.BadRequestError. The SDK does not retry 400s; in the test, the failing request was sent once. Check the message text so you only trim on this error and not on every 400:
import re
import anthropic
TOO_LONG = re.compile(r"prompt is too long: (\d+) tokens > (\d+) maximum")
def is_prompt_too_long(err: Exception) -> bool:
text = str(err).lower()
return isinstance(err, anthropic.BadRequestError) and (
"prompt is too long" in text or "input is too long" in text
)
def too_long_numbers(err: Exception):
"""(actual, maximum) if the message includes them, else None."""
m = TOO_LONG.search(str(err))
return (int(m.group(1)), int(m.group(2))) if m else None
str(err) includes the response body, and err.body["error"]["message"] holds the message alone. The second check covers a wording that Claude Code's error reference lists next to this one, Input is too long for requested model. Don't depend on the numbers being there; use them for logs. With a fake 400, the test printed:
A BadRequestError 400 True (1918, 1800) requests: 1
body message: prompt is too long: 1918 tokens > 1800 maximum
Count before you send
Catching the error means one wasted request per overflow. Counting first avoids it. The token counting endpoint, client.messages.count_tokens(), takes the same model, system, tools and messages as a normal request and returns input_tokens. The docs say it is "free to use" with its own requests-per-minute limits, separate from message creation.
Two cautions from the same page. The count "is an estimate," so leave a margin. And Claude 4.7 and later models use a newer tokenizer that produces "approximately 30 percent more tokens" for the same text, so a count against an older model can say a prompt fits when it doesn't. Count against the model you will call. The endpoint also returns invalid_request_error for server tools such as web search and for the MCP connector; for those requests, read usage from the last response instead.
A reasonable budget is the window minus your max_tokens minus a margin. For a 200k model with max_tokens=16000, a budget around 180,000 leaves room for both the answer and the estimate's error.
Trim in two steps
Trimming has one hard rule: every tool_use block in an assistant message needs its tool_result in the next user message. Cut in the wrong place and you swap this error for the one in tool_use ids without tool_result blocks. So never remove a single message. Remove an assistant message together with the user message that answers it.
Step one is to shorten oversized tool results, which keeps the structure of the history and usually frees the most space:
def cap_tool_results(messages, max_chars=20_000):
"""Shorten long string tool results. Returns a new list; ids stay untouched."""
out = []
for msg in messages:
if msg["role"] != "user" or isinstance(msg["content"], str):
out.append(msg)
continue
blocks = []
for block in msg["content"]:
content = block.get("content") if block.get("type") == "tool_result" else None
if isinstance(content, str) and len(content) > max_chars:
cut = len(content) - max_chars
block = {**block, "content": content[:max_chars] + f"\n[truncated {cut} characters]"}
blocks.append(block)
out.append({**msg, "content": blocks})
return out
This only handles tool results whose content is a string. If your tools return lists of content blocks, apply the same idea to their text blocks.
Step two drops the oldest turns after the first message, which holds the task, until the count fits:
def drop_oldest_turns(client, model, messages, budget, system=None, tools=None):
"""Drop the oldest assistant/user pairs after the first message until the count fits."""
extra = {}
if system is not None:
extra["system"] = system
if tools is not None:
extra["tools"] = tools
msgs = list(messages)
while True:
n = client.messages.count_tokens(model=model, messages=msgs, **extra).input_tokens
if n <= budget:
return msgs, n
if len(msgs) < 5:
raise ValueError(f"{n} tokens even after trimming; shorten the first message or tools")
# msgs[1] is an assistant turn, msgs[2] the user turn that answers it.
# Dropping both keeps every tool_use paired with its tool_result.
msgs = [msgs[0]] + msgs[3:]
It assumes the usual agent shape: a user message first, then strict assistant and user turns. Each step removes one pair, so the roles still alternate and the conversation still ends on a user message. On a test history of 17 messages (a task plus 8 tool calls, one with a large result):
B after cap: 1301 was 1918
C fit: 17 -> 13 messages, 990 tokens; first tool id kept: toolu_2
pairs intact: True roles: uauauauauauau
D create after fit: end_turn 990
E 182 tokens even after trimming; shorten the first message or tools
Capping the large result took the count from 1,918 to 1,301. Dropping the two oldest pairs brought it under the 1,000 budget, every remaining tool_use still had its result, and the resent request succeeded. In E, with a budget too small for even the task and the last turns, the function raises instead of looping forever.
Wire both into the call that runs each turn, and keep the trimmed list, or the next turn overflows again:
def create_fitting(client, budget, **kwargs):
"""Send a turn. On 'prompt is too long', trim once and resend.
Returns (response, messages) so the caller keeps the trimmed history.
"""
try:
return client.messages.create(**kwargs), kwargs["messages"]
except anthropic.BadRequestError as err:
if not is_prompt_too_long(err):
raise
messages = cap_tool_results(kwargs["messages"])
messages, _ = drop_oldest_turns(
client, kwargs["model"], messages, budget,
system=kwargs.get("system"), tools=kwargs.get("tools"),
)
return client.messages.create(**{**kwargs, "messages": messages}), messages
In the test, this made two message requests: the one that failed and the resend.
Dropped turns are gone for good, so the agent can repeat work it no longer remembers. Before you drop, it helps to have the agent write its progress to notes outside the window, as in AI agent memory. Two more side effects: any change to early history breaks the prompt cache from that point on, and with thinking enabled, the errors page lists a 400 for a thinking block whose signature is "bound to a different conversation." Its suggested fixes are to remove the block or set thinking.block_binding.prefix_mismatch_behavior to "drop_block".
Or let the API do it
The Claude API can shrink history on the server, which avoids most of the code above.
- Context editing (beta header
context-management-2025-06-27) clears old tool results with theclear_tool_uses_20250919strategy. The defaults are a trigger at 100,000 input tokens and keeping the 3 most recent tool uses;exclude_toolsprotects results you need, andclear_at_leastskips a clear that wouldn't free enough to be worth the cache write. The response'scontext_management.applied_editsreports what was cleared. - Threshold compaction (beta header
compact-2026-01-12, edit typecompact_20260112) summarizes older turns when input reaches a trigger, 150,000 tokens by default and at least 50,000. The response starts with acompactionblock, and the API ignores everything before it on later requests, so append the wholeresponse.contentto your history.
response = client.beta.messages.create(
betas=["compact-2026-01-12"],
model="claude-opus-5-5",
max_tokens=4096,
messages=messages,
tools=tools,
context_management={
"edits": [
{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": 150000},
"instructions": (
"Summarize the transcript inside <summary></summary> tags. "
"Include relevant information in the summary for continuing the task "
"in the next context window. Do not call any tools while writing this "
"summary; respond with text only."
),
}
]
},
)
messages.append({"role": "assistant", "content": response.content})
The instructions here come from the docs' own fix for a known failure: with tools defined, the model sometimes calls a tool during summarization and returns a compaction block with content: null. Custom instructions replace the default prompt completely. The summary is written by the model in your request, and its tokens are reported in usage.iterations, not the top-level usage.
Set the trigger well below the window. The compaction docs say it runs inside the request that reaches the threshold, so plan for it to keep you under the limit, not to rescue a request that is already over it. Keep the trimmer as a fallback for that case.
Checklist
- Read both numbers in the message; log them with the
request_id. - Rule out 413 (bytes) and
max_tokensbefore trimming. - Count tokens before each turn, against the model you will call.
- Budget the window minus
max_tokensminus a margin. - Cap large tool results first.
- Drop whole assistant and user pairs, never single messages.
- Keep the trimmed history for the next turn.
- Save progress to notes before dropping turns.
- Prefer context editing or compaction for long runs, with the trimmer as a fallback.
FAQ
What does "prompt is too long" mean on the Claude API?
The input of your request has more tokens than the model's context window. The system prompt, tool definitions and every message, tool results included, all count. It is a 400 invalid_request_error, and resending the same request fails the same way.
How do I check token count before sending to Claude?
Call client.messages.count_tokens() with the same model, system prompt, tools and messages. It returns input_tokens, is free within its own rate limits, and is an estimate, so leave a margin.
Does the Anthropic SDK retry prompt is too long errors?
No. The SDK source retries 408, 409, 429 and 5xx responses (plus connection errors and timeouts), not 400s, unless the response's x-should-retry header says to. In the test above, the failing request was sent once.
What is the context window for current Claude models?
Anthropic's docs list 1M tokens for current models such as Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5, and 200k for other Claude models. Check the context windows page for the model you use.
Can compaction fix prompt is too long?
It is a way to avoid it. Compaction runs when a request crosses its trigger, so set the trigger well below the window, and keep a trimmer as a fallback for a request that is already over the limit.
Sources
- Anthropic, Context windows (documentation: window sizes, what counts, overflow behavior, thinking blocks)
- Anthropic, Claude API errors (documentation: 400 and 413 errors, request size limits, retries, thinking signature error)
- Anthropic, Token counting (documentation:
count_tokens, pricing, estimates, tokenizer change, unsupported features) - Anthropic, Context editing (documentation:
clear_tool_uses_20250919, defaults, caching) - Anthropic, Compaction at a token threshold (documentation:
compact_20260112, trigger, instructions, usage) - Anthropic, Compaction (documentation: overview)
- Anthropic, Claude Code errors (documentation: error message reference)
- Google AI Developers Forum, Frequent "prompt is too long" (200k token limit) after longer agent sessions (bug report quoting the full error message)
- Anthropic, anthropic-sdk-python (SDK source, version 2.14.0)