Learning objectives
After reading this article you will be able to:
- Understand what goes into the context window of a request
- Count tokens before sending and reserve room for the answer
- Trim, summarize or replace with RAG whatever does not fit
Your chatbot runs fine for days, and then one long-time user stops getting answers. The logs show a 400 error saying the request is too large for the model. Nothing changed in the code: that user's conversation simply grew until it no longer fit.
This error is predictable and avoidable. It happens because every model has a ceiling on tokens per request, and your app is sending more than that. Knowing what fills that space shows you where to cut.
What does the error look like?#
On OpenAI, the error comes back with status 400 and type invalid_request_error, and the message follows a pattern that barely changes between models: the model's limit, how much you asked for and how much of that came from the prompt and the completion. In OpenAI-format APIs, the context_length_exceeded code goes in the code field of the error object, but not every response fills it in. In this OpenAI cookbook example, on an embeddings model, the field is empty:
Error code: 400 - {'error': {'message': "This model's maximum context length is 8192 tokens, however you requested 10001 tokens (10001 in your prompt; 0 for the completion). Please reduce your prompt; or completion length.", 'type': 'invalid_request_error', 'param': None, 'code': None}}On Anthropic, the documentation says an input larger than the window comes back as a 400 invalid_request_error with the message "prompt is too long", on every model.
Sending the same request again does not help: it is still too big. Unlike a 429 error, which clears with waiting, this one only clears when you send fewer tokens.
What is the context window and what goes into it?#
The context window is the maximum number of tokens the model uses in a single request. OpenAI counts input, output and reasoning tokens in it. Anthropic spells out what counts: the system prompt, every message in the history (including tool results, images and documents), the tool definitions and the turn's output, reasoning included. For tokens themselves, see what is an LLM.
The size varies a lot, from a few thousand to a million tokens or more, depending on the model. Check the number on your provider's models page and treat it as a ceiling, not a target. Anthropic warns that as context grows, accuracy and recall degrade, an effect it calls context rot. A full window costs more and answers worse.
The output limit takes up the window too. On OpenAI it shows in the error message ("for the completion"). On Anthropic, recent models accept a request whose input plus max_tokens goes past the window and stop generating with stop_reason: "model_context_window_exceeded"; older ones return a validation error.
Why do long conversations and tools blow the window?#
The API is stateless. For the model to "remember" the conversation, your app resends the whole history on every call. Request number 40 carries the 39 before it.
Tools weigh in two ways. Their definitions, with the name, description and JSON schema of every parameter, ride along on every request. And their results land in the history: a search that returns a whole HTML page, a file read end to end or a query that brings back a thousand rows turns into thousands of tokens at once. An agent that calls tools in a loop piles all of that up.
Run the numbers with hypothetical values. A 1,500-token system prompt, 10 tools at 300 tokens each (3,000 in total) and question-and-answer exchanges of 600 tokens. In a 32,000-token window, with 2,000 reserved for the answer:
(32,000 - 2,000 - 1,500 - 3,000) / 600 = 42 exchangesOn exchange 43, the request fails. If a single tool returns 20,000 tokens, the count drops below 10 exchanges.
How do you count tokens before sending?#
There are three ways, from most accurate to most practical:
| Method | When to use it | Accuracy |
|---|---|---|
The response's usage field (usage.prompt_tokens in chat completions) |
After each call, to log and calibrate your estimate | Exact: the model's own count |
A counting endpoint: OpenAI's, for the Responses API, or Anthropic's messages.count_tokens |
Before sending, without generating an answer | The provider's estimate; Anthropic's is free and has its own request limit |
| A local tokenizer, such as tiktoken | Before sending, in your own process, with no network call | Good for text on OpenAI's models; approximate on others |
Each model uses its own tokenizer, and counts shift even within one provider: Anthropic warns that a newer generation of its models has a tokenizer that produces noticeably more tokens for the same text, and asks you to recount prompts against the model you plan to use. So leave headroom and double-check against usage.
How do you fix it: trim, summarize or retrieve?#
In order of effort:
- Trim the history. Keep the system prompt and the most recent messages that fit. Cut at whole turns: each tool result stays with the assistant message that asked for it, in the format the API expects.
- Summarize what you drop. Replace the old messages with a short summary that keeps names, numbers and decisions. The user does not lose the thread.
- Retrieve instead of pasting. Instead of putting a whole manual in the prompt, split the document into chunks and send only the ones relevant to the question. That is what RAG does, walked through step by step in how to build a RAG chatbot.
- Slim down tool results. Return only the fields the model needs, paginate long lists and cut large texts before they go into the history.
- Reserve the output. Set
max_completion_tokensand size the history as window minus output minus headroom.
The code below combines steps 1, 2 and 5 with OpenAI's Python SDK. Set the environment variables first (the model ID and its window come from the provider's models page):
# .env
OPENAI_API_KEY=your-key
OPENAI_MODEL=model-id
CONTEXT_WINDOW=32000import os
import tiktoken
from openai import APIStatusError, OpenAI
client = OpenAI()
MODEL = os.environ["OPENAI_MODEL"]
WINDOW = int(os.environ["CONTEXT_WINDOW"])
OUTPUT = 1_000 # tokens reserved for the answer
HEADROOM = 1_000 # margin for message structure and estimation errors
enc = tiktoken.get_encoding("o200k_base") # an approximation for other providers' models
def tokens(msg: dict) -> int:
return len(enc.encode(msg.get("content") or "")) + 4
def summarize(old: list[dict], limit: int) -> dict:
text = "\n".join(f"{m['role']}: {m.get('content') or ''}" for m in old)
text = enc.decode(enc.encode(text)[-limit:]) # the summary request has to fit too
r = client.chat.completions.create(
model=MODEL,
max_completion_tokens=500,
messages=[{
"role": "user",
"content": "Summarize this conversation in up to 10 short bullet points. "
"Keep names, numbers and decisions.\n\n" + text,
}],
)
return {"role": "system", "content": "Summary of the earlier conversation:\n" + r.choices[0].message.content}
def fit(messages: list[dict], budget: int) -> list[dict]:
if sum(map(tokens, messages)) <= budget:
return messages
system, rest = messages[0], messages[1:]
used, recent = tokens(system), []
for msg in reversed(rest): # newest to oldest
if used + tokens(msg) > budget * 0.7: # 30% is left for the summary
break
recent.insert(0, msg)
used += tokens(msg)
while recent and recent[0]["role"] == "tool": # keep a tool result with its caller
recent.pop(0)
old = rest[: len(rest) - len(recent)]
return [system, summarize(old, budget // 2), *recent]
def ask(messages: list[dict]):
budget = WINDOW - OUTPUT - HEADROOM
try:
return client.chat.completions.create(
model=MODEL, messages=fit(messages, budget), max_completion_tokens=OUTPUT
)
except APIStatusError as err: # any status: the code is what decides
if err.code != "context_length_exceeded":
raise
# the estimate came in under the real count: try once with half the budget
return client.chat.completions.create(
model=MODEL, messages=fit(messages, budget // 2), max_completion_tokens=OUTPUT
)
history = [{"role": "system", "content": "You are the support assistant for an online store."}]
history.append({"role": "user", "content": "My order never arrived. What should I do?"})
response = ask(history)
history.append({"role": "assistant", "content": response.choices[0].message.content})
print(response.choices[0].message.content)
print("input tokens:", response.usage.prompt_tokens)In production, store the summary with the conversation and only redo it when the history grows again, so you do not pay for an extra call on every message; how to add memory to a chatbot covers where to keep it. Providers also offer server-side compaction: OpenAI in the Responses API, and Anthropic on some of its models. They write the summary for you, but tie your code to that API.
How do you keep it from coming back?#
- Watch
usage. Logprompt_tokensper conversation and alert when it passes 80% of the window. The error stops being a surprise. - Cap the number of messages too. A fixed ceiling, like the last 20 exchanges, is easy to explain and to test.
- Mind the output limit on reasoning models. On OpenAI,
max_completion_tokensincludes reasoning tokens. A value set too low can end generation before the visible answer. - Keep documents out of the prompt. A search index, in a vector database or in the application's memory, returns only what matters for each question.
- A bigger window is not the fix. It postpones the error, bills every resent token and hurts accuracy. The math on resending is in how much an LLM API costs.
How to do this on Square Cloud#
On Square Cloud, from the Standard plan (R$44.99 a month), the AI Gateway is an OpenAI-compatible API for using the cubic model in your own products. Each request holds a context of up to 64k tokens on Standard, up to 128k on Pro and up to 256k on Enterprise. As with OpenAI's chat completions, the gateway is stateless: you send the history with every request, up to 500 messages.
The code above works with three changes: the base URL https://api.squarecloud.app/v2/ai on the client, an account API key with the ai:chat scope and OPENAI_MODEL=cubic, with CONTEXT_WINDOW set to your plan's value. The gateway returns the error in the OpenAI format with the context_length_exceeded code, the same one the code above checks for. Since tiktoken only estimates cubic's tokens, keep the headroom and check usage. Smaller requests answer faster and use less of the plan's limits.
To store the conversation and its summary between calls, database hosting starts on the same plan, with Redis, PostgreSQL, MySQL and MongoDB. For RAG, the index can live in PostgreSQL, which comes with the pgvector extension; embeddings come from another provider, because the gateway does not generate them. See the limits per plan on the AI Gateway page.
AI
Host AI apps in always-on containers
FAQs
What is an LLM's context window?
It is the maximum number of tokens the model takes in one request: system prompt, history, tool definitions, tool results and the generated answer. Anything beyond that is rejected or cut off.
Why does the error only show up after many messages?
Because the API is stateless: your app resends the whole conversation on every call. Each new message adds tokens until the request no longer fits the window.
Does max_tokens count toward the context window?
Yes, because the answer takes up the same window. With some providers and models, input plus the output limit above the window is already an error; with others the request goes through and generation stops when the window fills up.
Does switching to a model with a bigger window fix it?
It postpones the problem. The conversation keeps growing, each call costs more and accuracy drops with long contexts. Trimming and summarizing the history fixes it for good.
More in AI
See all 31 articles- How much does an AI chatbot cost to build and run?Running an AI chatbot costs model tokens, hosting, a database and, with RAG, extra context per message. See how to estimate the cost per conversation.
- How much does a RAG system cost? Embeddings, database and LLMA RAG system has three costs: embeddings, a vector database and the LLM. See the math for 1,000 questions a day, with hypothetical prices, and where the bill grows.
- RAG vs fine-tuning: which to useRAG puts your data in the prompt at question time; fine-tuning changes the model's weights with examples. Compare cost, updates, latency and when to use each.
- pgvector vs a dedicated vector database: which to usepgvector stores vectors in PostgreSQL, next to your data; a dedicated vector database focuses on scale and filtering. Compare indexes, operations and migration.