HTTP 400 Context Length Exceeded — Prompt Window Overflow Fix
Total tokens across system prompt, message history, tool definitions, and max_tokens exceeded the model window. Apply sliding-window trimming or switch to a long-context model.
Need resilient routing with automatic multi-upstream failover and full request telemetry on API Store Hub?
Error runbook
| HTTP Status | 400 |
|---|---|
| Error type | context_length_exceeded |
| Retry policy | Fix request first |
Total tokens across system prompt, message history, tool definitions, and max_tokens exceeded the model window. Apply sliding-window trimming or switch to a long-context model.
Metadata & root causes
- Appending unbounded chat turns or pasting entire raw PDFs/logs into a single prompt.
- Attaching dozens of verbose tool schemas that silently consume tens of thousands of tokens.
- Combined input_tokens + max_tokens exceeds the model limit even when input alone fits.
3 steps to resolve
- Immediate diagnosis: Estimate input token count before dispatch and clamp max_tokens to the remaining context budget.
- Apply standard fix: Use sliding-window truncation (keep system prompt + newest turns) or periodic conversation summarization.
- Prevent recurrence in production: For large corpora, switch to RAG retrieval or route to a long-context model like Gemini or Claude on API Store Hub.
Production retry & recovery snippet
cURL
curl https://apistorehub.com/v1/chat/completions \
-H "Authorization: Bearer sk-ash-your_key" \
-H "Content-Type: application/json" \
-d '{"model":"gemini-4-neon","max_tokens":1024,"messages":[{"role":"user","content":"Summarize the attached report."}]}'Python
def trim_messages(messages: list[dict], max_chars: int = 48000) -> list[dict]:
system = [m for m in messages if m.get("role") == "system"]
convo = [m for m in messages if m.get("role") != "system"]
kept, total = [], sum(len(str(m.get("content", ""))) for m in system)
for msg in reversed(convo):
size = len(str(msg.get("content", "")))
if kept and total + size > max_chars:
break
kept.append(msg)
total += size
return system + list(reversed(kept))Frequently asked questions
- Am I billed on API Store Hub when an HTTP 400 (context_length_exceeded) error occurs?
- No. Atomic pre-hold settlement on API Store Hub automatically releases any reserved amount for failed requests that return no valid completion.
- How do I tell whether the error originated from my client or upstream?
- 4xx codes (except 429) usually point to auth headers, wallet quota, or request payload formatting; 429/502/504/529 indicate load or transient upstream conditions visible on /status.
- Can I fall back to another model without changing SDKs?
- Yes. Pass the fallback model ID (e.g. across Claude, GPT, DeepSeek, or Gemini) inside your retry catch block using your existing sk-ash- API key.