Symptoms
- Requests fail with HTTP 400. Typical messages (wording varies by provider and version):
- OpenAI / Azure OpenAI:
"code": "context_length_exceeded", "This model's maximum context length is N tokens. However, your messages resulted in M tokens". - Amazon Bedrock:
ValidationExceptionsaying the input is too long for the requested model. - vLLM:
400 Bad Request, "This model's maximum context length is N tokens. However, you requested M tokens".
- OpenAI / Azure OpenAI:
- It started after a release or config change, or failures grow through the day for long chat sessions.
- Short questions work; long conversations, large documents or agent runs fail.
The context window counts input tokens plus the output tokens you reserve with max_tokens (or max_completion_tokens / max_output_tokens). Anything that grows the prompt or raises the output reservation can push requests over.
1. Confirm scope and impact
Find out what share of calls fail and since when. If you log the provider error code:
AppTraces
| where TimeGenerated > ago(6h)
| where Message has_any ("context_length_exceeded", "maximum context length", "Input is too long")
| summarize failures = count() by bin(TimeGenerated, 10m), tostring(Properties.feature)
| order by TimeGenerated asc
Match the start time against deploys and config changes. Then measure a failing request. Count tokens of the exact payload you sent:
import json, tiktoken
enc = tiktoken.get_encoding("o200k_base") # GPT-4o family; other models use other tokenizers
def count_tokens(messages: list[dict]) -> int:
# Approximate: content tokens plus a few per message for role/formatting
return sum(len(enc.encode(m.get("content") or "")) + 4 for m in messages)
payload = json.load(open("failed_request.json"))
print("input tokens ~", count_tokens(payload["messages"]))
print("max_tokens ", payload.get("max_tokens") or payload.get("max_completion_tokens"))
for m in payload["messages"]:
print(m["role"], len(enc.encode(m.get("content") or "")))
For non-OpenAI models, the count is approximate; use the model's own tokenizer or the usage fields from successful calls for exact numbers.
The per-message breakdown usually shows the culprit straight away:
| Biggest part of the prompt | Cause | Fix |
|---|---|---|
Many user/assistant turns | History not trimmed | Trim history (step 3) |
One huge tool message | Tool returned raw JSON or a full log file | Truncate or summarise tool output |
| Retrieved context block | top_k or chunk size raised in the release | Roll back retrieval settings |
| System prompt | New instructions or examples pasted in | Roll back the prompt version |
Input fine, max_tokens large | Output reservation raised | Lower max_tokens |
| Same payload worked last week | Model switched to one with a smaller window, or vLLM --max-model-len lowered | Restore the model or setting |
2. Fastest mitigation: roll back
If a release or config change lines up with the start time, roll it back first and investigate afterwards. Typical knobs to revert:
- Prompt version,
top_k, chunk size, number of few-shot examples. max_tokens(a raise from 1,000 to 16,000 consumes that budget on every call).- Model or deployment name (a fallback model with a smaller window).
- For self-hosted vLLM, the
--max-model-lenvalue in the deployment:
kubectl -n ai get deploy vllm -o jsonpath='{.spec.template.spec.containers[0].args}' | tr ',' '\n' | grep -A1 max-model-len
curl -s http://vllm.ai.svc:8000/v1/models | jq '.data[] | {id, max_model_len}'
Warning
Do not raise vLLM's
--max-model-lenas a quick fix without checking GPU memory. A longer maximum length needs more KV cache; the server may fail to start or serve far fewer concurrent requests. Change it in a canary first.
If there was no release (failures grow over the day), the cause is usually unbounded history or tool output. Go to step 3.
3. Enforce a token budget in code
Put a budget in front of every model call. Keep the system prompt and the latest user message, add retrieved context up to a cap, then fill the rest with the most recent history.
MODEL_WINDOW = 128_000 # check the current limit for your model and deployment
MAX_OUTPUT = 2_000
SAFETY = 1_000
TOOL_OUTPUT_CAP = 4_000
def tok(text: str) -> int:
return len(enc.encode(text or ""))
def truncate(text: str, limit: int) -> str:
ids = enc.encode(text or "")
return text if len(ids) <= limit else enc.decode(ids[:limit]) + "\n[truncated]"
def build_messages(system, history, context_chunks, user_msg):
budget = MODEL_WINDOW - MAX_OUTPUT - SAFETY
msgs_head = [{"role": "system", "content": system}]
budget -= tok(system) + tok(user_msg) + 8
ctx, used = [], 0
for c in context_chunks: # already ranked best-first
t = tok(c)
if used + t > budget * 0.5: # context gets at most half
break
ctx.append(c); used += t
if ctx:
msgs_head.append({"role": "system", "content": "Context:\n" + "\n---\n".join(ctx)})
budget -= used
kept = []
for m in reversed(history): # newest first
content = m["content"]
if m["role"] == "tool":
content = truncate(content, TOOL_OUTPUT_CAP)
t = tok(content) + 4
if t > budget:
break
kept.append({**m, "content": content}); budget -= t
return msgs_head + list(reversed(kept)) + [{"role": "user", "content": user_msg}]
Notes:
- Dropping old turns can orphan a
toolmessage from itsassistanttool call; drop them as a pair, or the API rejects the request with a different 400. - For long sessions, summarise the dropped turns into one short message instead of losing them.
- Cap tool output at the source too: return the first N rows or a summary, not a full log file.
Ship this behind a feature flag so you can turn it on per feature.
4. Verify recovery
- Replay the saved failing payloads through
build_messages; all succeed. - 400 rate for context errors back to zero in the query from step 1.
- Answer quality spot check on long conversations: trimming should not drop the facts the user is asking about. Run your evaluation set if you have one.
usage.prompt_tokensp95 well below the window.
Tell users
"Since
Prevent it next time
- Every call goes through one function that applies the token budget; no direct SDK calls in feature code.
- Log
usage.prompt_tokensandusage.completion_tokensper feature and alert when p95 reaches 70% of the model window. - CI test that builds the prompt with the largest realistic inputs (longest history, max chunks, largest tool output) and asserts it fits.
- Treat
top_k, chunk size,max_tokens, prompt version and model name as configuration with a review, not code tweaks. - When switching to a fallback model, check its context window and output limit first; record them next to the model name in config.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get