Context length exceeded: what vLLM, SGLang, llama.cpp, Ollama, TGI and Dynamo return, and what openai-python and LiteLLM do with it
Most current engines reject a prompt that does not fit with HTTP 400, which openai-python raises as BadRequestError without retrying. The exceptions are the ones that cause trouble. Ollama and llama.cpp before build b6207 (2025-08-19) cut the prompt and answer 200. vLLM since v0.32.0 shortens an oversized max_tokens without an error. SGLang up to v0.5.9 puts the error inside a 200 stream. TGI answers 422. Any engine that answers 500 makes openai-python send the request three times. LiteLLM raises ContextWindowExceededError only when the message contains one of its known phrases, so several real messages come through as a plain BadRequestError. overflow_check.py sends four over-long requests to your server and shows which case you have.
What does each engine return when the prompt is too long?
The status code and message depend on the engine and its version. The two right-hand columns are measured: each engine's exact response was replayed to the clients (see method).
| Engine, versions | Prompt longer than the context | Prompt fits, prompt + max_tokens does not | openai-python | LiteLLM ContextWindowExceededError? |
|---|---|---|---|---|
| llama.cpp b7481+ (2025-12-19) | 400, type exceed_context_size_error, “request (N tokens) exceeds the available context size (M tokens), try increasing it”, plus n_prompt_tokens and n_ctx. Streaming requests get the same 400. | 200; generation stops at the context with finish_reason: "length" | BadRequestError, 1 request | yes |
| llama.cpp b6380–b7480 | 400, exceed_context_size_error, “the request exceeds the available context size. try increasing the context size or enable context shift” | 200 | BadRequestError | yes |
| llama.cpp b6207–b6379 | 400, invalid_request_error, same message (no token counts) | 200 | BadRequestError | yes |
| llama.cpp up to b6205, default settings | 200. The prompt is cut in half and processed (context shift was on by default). Measured: 2,109 tokens sent, usage.prompt_tokens 1,085. | 200; the context shifts and generation continues | no exception | no error to classify |
| vLLM v0.32.0+ (2026-10-18) | 400, BadRequestError, “This model's maximum context length is M tokens. However, your prompt contains N input tokens, which exceeds this limit even without any output tokens.” | 200; max_tokens is lowered to what fits (PR #57035). Only max_tokens larger than the whole context is a 400. | BadRequestError | yes |
| vLLM v0.18.0–v0.31.0 | 400, “This model's maximum context length is M tokens. However, you requested K output tokens and your prompt contains N input tokens, for a total of T tokens.” | 400, same message | BadRequestError | yes |
| vLLM v0.10.1–v0.17.1 | 400, “This model's maximum context length is M tokens. However, your request has N input tokens.” | 400, “'max_tokens' or 'max_completion_tokens' is too large: K. This model's maximum context length is M tokens and your request has N input tokens (K > M - N).” | BadRequestError | yes |
| vLLM up to v0.10.0 | 400, flat body {"object":"error","message":...}, “This model's maximum context length is M tokens. However, you requested N tokens ...” | 400, “... However, you requested T tokens (N in the messages, K in the completion).” | BadRequestError | yes |
| SGLang v0.5.10+ (2026-04-05) | 400, flat body, “The input (N tokens) is longer than the model's context length (M tokens).” Streaming requests also get 400. | 400, “Requested token count exceeds the model's maximum context length of M tokens.” (since v0.4.1.post7) | BadRequestError | yes |
SGLang up to v0.5.9, stream: true | 200, then one SSE event {"object":"error","message":...} (non-streaming requests get 400) | same | no exception: one chunk with object: "error" and choices: null | no. openai/: MidStreamFallbackError; hosted_vllm/: an empty chunk with finish_reason: "stop" |
Ollama, /v1/chat/completions (all versions) | 200. Oldest messages are dropped (logged only at debug level); a single message still too long is cut in the middle, keeping the first num_keep tokens (default 4) and the end (“truncating input prompt” warning in the server log). | 200 | no exception | no error to classify |
| Ollama v0.30.9+ with context shift off | 400, invalid_request_error, “the prompt is longer than the context length currently available to the model; ...” | — | BadRequestError | no (plain BadRequestError, also with ollama_chat/) |
| TGI 3.x (Text Generation Inference) | 422, body {"error": "Input validation error: `inputs` tokens + `max_new_tokens` must be <= M. ...", "error_type": "validation"} | UnprocessableEntityError with message “Error code: 422” only | only with hosted_vllm/; openai/ gives BadRequestError and loses the text | |
| NVIDIA Dynamo v1.0.0+ frontend | 400, “This model's maximum context length is M tokens. However, your messages resulted in N tokens.” | 400, “... your request would use N prompt tokens plus K ...” | BadRequestError | yes |
Any engine that answers 500 (Dynamo up to v1.6.1 with TensorRT-LLM over max_num_tokens) | 500 | InternalServerError after 3 requests (2 retries, 1.2 s) | no (InternalServerError; with openai/ also 3 requests) | |
“the request exceeds the available context size, try increasing it” (llama.cpp)
The number in the message is the context of one slot, not the -c you passed. llama-server checks the prompt against the slot it runs in. With the default settings (build 12733), all four slots share one unified KV cache and each can use the whole -c. If you pass -np 4 yourself, the cache is split: with -c 2048 -np 4 we got “request (576 tokens) exceeds the available context size (512 tokens)”. Use a larger -c, fewer slots, or --kv-unified.
- The check is
>=: a prompt of exactlyn_ctxtokens is rejected, because no token would be left to generate. - The error has
n_prompt_tokensandn_ctxfields next tomessage(since b6380). A client can read them to trim and retry instead of parsing the text. - Models that cannot split a prompt across batches give a different message: “input (N tokens) is larger than the max context size (M tokens). skipping”. LiteLLM does not recognize that one (plain
BadRequestError). - Up to b6205, context shift was on by default and an over-long prompt was silently truncated (log line
input truncated, n_ctx = 2048, n_keep = 0 ...). From b6207 it is off by default and the request fails; from b6724 (2025-10-09) the prompt is never truncated, even with--context-shift. If an old guide tells you to enable context shift to make long prompts work, that no longer applies. - A prompt that fits with too large a
max_tokensis not an error: generation stops when the context is full, withfinish_reason: "length"(measured: 1,848 prompt tokens + 200 generated = 2,048).
vLLM: “This model's maximum context length is ... tokens” and the v0.32.0 change
Since v0.32.0, vLLM no longer counts max_tokens against the context when it checks the prompt. A request whose prompt fits but whose max_tokens does not is accepted, and the output is cut at the context with finish_reason: "length". Before v0.32.0 the same request was a 400. Code that relied on that 400 to detect “too long” now gets a truncated answer instead (#57035, in v0.32.0).
- vLLM answers 400 with type
BadRequestError. The length check runs while the request is rendered, before the stream starts, sostream: truerequests also get a normal 400 (read in v0.34.0). - v0.10.1 changed the body from
{"object":"error","message":...}to{"error":{"message":...,"type":...,"param":...,"code":400}}. Code that readsbody["message"]broke then. - Since v0.32.0 two other length messages do not contain “maximum context length is” and LiteLLM gives a plain
BadRequestErrorfor them:max_tokens=K cannot be greater than max_model_len=M, and (from the source; not run) a prompt of exactlymax_model_lentokens leaves 0 tokens for output and fails with “max_tokens must be at least 1, got 0.” - Very long text is rejected before tokenizing, by character count: “However, your prompt contains N characters (more than ... characters, which is the upper bound for M input tokens)”. It is still a 400 and LiteLLM still recognizes it.
Ollama: no error, the prompt is cut
On /v1/chat/completions Ollama does not reject an over-long prompt. It drops the oldest messages until the rest fits and, if the last message alone is too long, cuts it in the middle. The answer is a normal 200. This is the usual reason a model “forgets” the start of a long document. The context size is the model's num_ctx or OLLAMA_CONTEXT_LENGTH (default 4k, 32k or 256k depending on VRAM), not the model's maximum.
- The only sign is in the server log: message dropping is logged at debug level, token cutting as a warning “truncating input prompt”. Compare
usage.prompt_tokenswith what you sent; overflow_check.py does that. - A 400 (“the prompt is longer than the context length currently available to the model”) appears only when context shift is off for that request (since v0.30.9). LiteLLM does not classify that message as a context error.
- Raising the context: set
num_ctxin the model options orOLLAMA_CONTEXT_LENGTH; there is no request field on/v1/chat/completionsthat turns the truncation off.
SGLang: the error inside a 200 stream (up to v0.5.9)
Up to v0.5.9, SGLang validated the length after the stream had started, so a streaming request got 200 and then a single event data: {"object":"error","message":"The input (N tokens) is longer than the model's context length (M tokens).", ...}. openai-python does not raise on it: it yields one chunk whose object is "error" and whose choices is None, so code that reads chunk.choices[0] fails with a TypeError far from the cause. v0.5.10 reads the first chunk before sending headers and returns a proper 400. Non-streaming requests got a 400 in both versions. SGLang can truncate instead with --allow-auto-truncate.
What do TGI and Dynamo return?
- TGI answers
422witherroras a string, not an object. openai-python turns it intoUnprocessableEntityErrorwhose message is only “Error code: 422”; the explanation is ine.body. TGI's message checks prompt +max_new_tokensagainst--max-total-tokensand the prompt alone against--max-input-tokens(“`inputs` must have less than M tokens”). - Dynamo's frontend writes its own context message so that clients recognize it: the source says the sentence must contain “maximum context length is” because LiteLLM matches that substring. With the TensorRT-LLM backend, prompts over
max_num_tokenswere reported as a server error until v1.6.2 (2026-11-04) turned them into a 400, so SDKs retried them (#16193).
Does openai-python retry it, and does LiteLLM raise ContextWindowExceededError?
openai-python retries 408, 409, 429 and every 5xx (twice by default, with backoff), or whatever the x-should-retry response header says. It never retries 400 or 422. A context overflow reported as 500 is therefore sent three times and fails three times. LiteLLM decides ContextWindowExceededError by searching the error text for fixed phrases (is_error_str_context_window_exceeded); the status code alone does not make it a context error.
| Phrase in the message (LiteLLM 1.111.0) | Engine that writes it |
|---|---|
this model's maximum context length is | vLLM (all versions), Dynamo |
is longer than the model's context length, requested token count exceeds the model's maximum context length | SGLang |
exceeds the available context size | llama.cpp (both wordings) |
`inputs` tokens + `max_new_tokens` must be | TGI (but see the 422 note: only when the text reaches LiteLLM) |
| not in the list | Ollama “the prompt is longer than the context length”; llama.cpp “is larger than the max context size”; vLLM “cannot be greater than max_model_len”, “max_tokens must be at least 1” |
If you catch overflows yourself, catch openai.BadRequestError and openai.UnprocessableEntityError, and look at the status code and the body (e.body), not only the message. For llama.cpp, e.body["n_ctx"] gives the limit directly.
Check your own server: overflow_check.py
The script reads the context length from the server (vLLM and SGLang /v1/models, llama.cpp /props) or takes --ctx, measures how many tokens a repeated word costs, and sends four requests. For each it prints the status, error type and message, the first SSE event of the streaming request, and for a 200 the usage counts, which reveal silent truncation. It says whether openai-python would retry and whether LiteLLM's phrase check matches. With --clients it also calls the installed openai-python and LiteLLM and prints what they raised.
curl -O https://erimaki-kobo.github.io/en/context-overflow-error-status-check/overflow_check.py
python overflow_check.py --base-url http://localhost:8000/v1 --model MODEL
python overflow_check.py --base-url http://localhost:11434/v1 --model llama3.2 --ctx 4096 # Ollama: pass num_ctx
pip install openai litellm && python overflow_check.py --base-url ... --model ... --clients --json out.json
Output against llama.cpp build b6205 with default settings (CPU, a tiny random-weight model):
context 2048 (/props n_ctx (per slot)); 'the ' = 4.000 tokens, template overhead ~49 tokens
[prompt_over] sent ~2109 prompt tokens, max_tokens=16
verdict accepted with HTTP 200: the prompt was truncated without an error
status 200
prompt_tokens 1085
completion_tokens 16
finish_reason length
clients {'openai_python': 'no exception', 'litellm_openai': 'no exception', 'litellm_hosted_vllm': 'no exception'}
The same request against the current build:
[prompt_over] sent ~2112 prompt tokens, max_tokens=16
verdict HTTP 400
error_type exceed_context_size_error
message request (2112 tokens) exceeds the available context size (2048 tokens), try increasing it
error_extra {'n_prompt_tokens': 2112, 'n_ctx': 2048}
openai_python_retries False
litellm_message_check True
clients {'openai_python': 'BadRequestError', 'litellm_openai': 'ContextWindowExceededError', 'litellm_hosted_vllm': 'ContextWindowExceededError'}
The four requests use a few thousand prompt tokens in total; on a GPU server that takes seconds. Point it at a test instance if a 400 on your production server pages someone.
How this was measured
- Run: llama.cpp llama-server built from source on CPU at build 12733 (commit de30697, 2026-11-25) and at b6205, with a 2-layer random-weight Llama GGUF, through overflow_check.py with
--clients. Settings:-c 2048, default slots;-c 2048 -np 4; b6205 with and without--no-context-shift. - Read, then replayed: for vLLM, SGLang, Ollama, TGI and Dynamo the status, body and message were taken from the source of each release tag (paths in Sources), served by a local mock server, and sent to openai-python 3.59.0 and LiteLLM 1.111.0 (
openai/,hosted_vllm/andollama_chat/providers). The mock counts requests, which is how the retries were measured. The cases and results are in repro/ (cases.json,replay.py,replay_results.json). - Version boundaries were found by scanning every release tag for the code that produces each message.
FAQ
- Should a context overflow be HTTP 400 or 500?
- 400 (or another 4xx). It is a property of the request, so retrying cannot help, and SDKs such as openai-python retry every 5xx automatically. LiteLLM's phrase list also contains OpenAI's own error code
context_length_exceeded. - Why does llama-server say 512 tokens when I started it with -c 2048?
- You set
-np 4, which splits the KV cache into four slots of 512. Without-np(or with--kv-unified) each slot can use the full context. - Why doesn't Ollama return an error for a long prompt?
- It truncates by default: old messages are dropped and an over-long message is cut in the middle. Raise
num_ctxorOLLAMA_CONTEXT_LENGTH, and checkusage.prompt_tokensagainst what you sent. - Why did my vLLM request stop returning 400 after upgrading?
- From v0.32.0 a prompt that fits is accepted even if
max_tokensdoes not; the output stops at the context withfinish_reason: "length". Checkfinish_reasoninstead of waiting for a 400. - Why doesn't LiteLLM raise ContextWindowExceededError for my server?
- LiteLLM looks for fixed phrases in the error text. Ollama's message and some vLLM and llama.cpp messages are not in its list, a 200 with truncation has no error at all, and a 422 through the
openai/provider loses the text.
Limitations
- Only llama.cpp was run. The other engines' rows come from their source and were replayed to the clients; their actual servers were not started here. Middleware such as a proxy or gateway in front of the engine can change the status code.
- Ollama was read on its current code (v0.40.18), whose runner is llama-server; older Ollama runners also truncated (“truncating input prompt”) but were not traced version by version.
- The vLLM boundary case (prompt of exactly
max_model_lentokens) is from the source only. - LiteLLM's phrase list changes between versions; the table is for 1.111.0. overflow_check.py carries a copy of that list and says so.
Sources
- llama.cpp: tools/server/server-context.cpp, server-common.cpp (
format_error_response), server-task.cpp; release tags b3812, b6205, b6207, b6380, b6724, b7481. - vLLM: vllm/renderers/params.py, entrypoints/serve/exception_handling/error_response.py, entrypoints/serve/utils/api_utils.py (
get_max_tokens); PR #57035; tags v0.10.0, v0.10.1, v0.17.1, v0.18.0, v0.31.0, v0.32.0, v0.34.0. - SGLang: srt/managers/tokenizer_manager.py, srt/entrypoints/openai/serving_chat.py, serving_base.py; tags v0.4.1.post7, v0.5.9, v0.5.10.
- Ollama: server/prompt.go, llm/llama_server.go, openai/openai.go, envconfig/config.go; tags v0.30.8, v0.30.9, v0.40.18.
- TGI: router/src/validation.rs, router/src/server.rs.
- Dynamo: lib/llm/src/http/service/error.rs; PR #16193 (cherry-picked to v1.6.2).
- LiteLLM: litellm_core_utils/exception_mapping_utils.py. openai-python: src/openai/_base_client.py (
_should_retry). - Related: llama.cpp arguments removed by build; how many requests fit in vLLM's KV cache; why a model does not stop generating.