Skip to content

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

  1. Get the context window for your exact model from the provider's model page.
  2. Count input tokens with the token-counting endpoint; it accepts the same system, messages and tools as a real request.
  3. Keep the conversation starting with a user turn after you trim.
  4. Keep each tool_use block and its tool_result together when you trim.
  5. Summarize long documents in chunks instead of sending them whole.
  6. Check stop_reason on every reply so a window stop is not mistaken for a full answer.

Related

Sources

All guides · All errors