# HTTP 400 `context_length_exceeded` — API Store Hub

> VI: HTTP 400 `context_length_exceeded` xảy ra khi tổng số token đầu vào (`messages` + `tools` + ảnh/tệp) cộng với `max_tokens` đầu ra vượt cửa sổ ngữ cảnh của model.
> EN: HTTP 400 `context_length_exceeded` triggers when prompt tokens (messages, tool definitions, images) plus `max_tokens` exceed the model's context window.

- Canonical VI: https://apistorehub.com/vi/loi-api/400-context-length-exceeded
- Canonical EN: https://apistorehub.com/en/loi-api/400-context-length-exceeded
- Retry Policy: Do not retry identical overflowing payloads; trim history or switch to a larger-context model first.

## Root Causes
- Sending entire multi-hundred-turn chat histories without windowing or summarization.
- Setting `max_tokens` too high so `input_tokens + max_tokens` overflows the window.
- Pasting raw multi-hundred-KB HTML, PDF, or JSON tool outputs directly into messages.

## Step-by-Step Resolution
1. Estimate token counts before sending and reserve headroom for output tokens.
2. Keep the system prompt fixed, summarize older turns, and send only the latest 8–12 turns.
3. Cap `max_tokens` to realistic response sizes (2048–4096) instead of maximum model output.
4. Route massive documents to long-context models like `gemini-4-neon` or a RAG index.

## Diagnostic cURL
```bash
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."}]}'
```

## Production Fix (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))
```

## FAQ
- **Do tool schemas count toward the context window?**: Yes. Every tool definition and parameter description counts as input tokens on every turn.
- **How much safety headroom should I keep for multilingual text?**: Leave at least 20% headroom because non-ASCII scripts tokenize at higher token-per-word ratios.
- **Which models on API Store Hub offer the largest context windows?**: `gemini-4-neon`, `claude-sonnet-5-5`, `claude-opus-5-5`, and `kimi-k3-1-pro` support 200K–1M context.
