Skip to content

context_length_exceeded

Cause: The prompt, chat history and tool results you sent, plus room for the reply, are bigger than the model's context window.

Copy-paste fix

Keep the system prompt, then add turns from newest to oldest until the token budget is used. The budget leaves room for the reply and a safety margin, because chat formatting adds tokens a plain count misses.

import tiktoken

enc = tiktoken.get_encoding("o200k_base")  # example; use your model's tokenizer or count endpoint

def count(msg):
    return len(enc.encode(msg.get("content") or ""))

def trim_to_budget(messages, context_window, max_output_tokens, margin=0.1):
    budget = int(context_window * (1 - margin)) - max_output_tokens
    system = [m for m in messages if m["role"] == "system"]
    rest = [m for m in messages if m["role"] != "system"]
    used = sum(count(m) for m in system)
    kept = []
    for m in reversed(rest):  # newest first
        c = count(m)
        if used + c > budget:
            break
        kept.append(m)
        used += c
    if not kept:
        raise ValueError("Newest message alone is over budget: "
                         "summarize it or use a longer-context model")
    return system + kept[::-1]

Price a long-context call on TokenCenter before you switch models

What the error means

OpenAI's API spec describes context_length_exceeded as “the request exceeds the model's context window.” The window is shared by everything you send and the answer the model writes.

Fix it before the call: count tokens, keep the system prompt, and drop or summarize the oldest turns until the request fits. If even the newest message is too big, send it to a model with a larger window.

Checklist

  1. Count tokens before every call and log the total next to the model's limit.
  2. Reserve room for the reply: input plus max output tokens must fit.
  3. Never let the system prompt be the message that gets dropped.
  4. Keep tool calls and their results together when you trim, so the history stays valid.
  5. Summarize old turns instead of only deleting them when the facts still matter.
  6. Test with a deliberately long input before you ship.

Related

Sources

All guides · All errors