Ollama "truncating input prompt": the RAG that silently ignored half its context

A RAG prompt longer than Ollama's context window gets cut from the front, the API still answers 200, and the only trace is one WARN line in the server log. A measured repro on Ollama 0.40.18 and 0.12.10, the three fixes, why /v1 ignores num_ctx, and the flag that makes it fail loudly.

Simone Negro, Backend & AI Developer
12 min read

TL;DR. If Ollama logs msg="truncating input prompt", your prompt was longer than the model’s context window (num_ctx) and Ollama dropped tokens from the front before the model saw it. The request still returns 200. In a RAG prompt the front is where the system prompt and your best-ranked chunks live. On a machine without a big GPU the default window is 4096 tokens, and on Ollama 0.40.18 an oversized prompt is cut to about half of that (2050 tokens), not to 4096. Fix it with one of:

  • "options": {"num_ctx": 16384} in the body of /api/chat or /api/generate;
  • OLLAMA_CONTEXT_LENGTH=16384 on the server;
  • a Modelfile with PARAMETER num_ctx 16384, then call the new model name.

Only the last two work through the OpenAI-compatible /v1/chat/completions, which ignores num_ctx in any form. Check the result with ollama ps (the CONTEXT column), and send "truncate": false on /api/chat so an oversized prompt becomes a 400 instead of a wrong answer.

The rest of this post is the repro behind each of those sentences.

What the log line means

I wanted to see what a RAG backend actually gets back when the retrieved context is bigger than the window. So I set up two Ollama servers in Docker on a shared 12-core x86_64 Linux box, CPU only, with qwen2.5:1.5b: the current release, 0.40.18, and a 0.12.10 image from November 2025 that was already on the machine. Then I sent them prompts of known length.

This is the line 0.40.18 printed for a 7226-token prompt with the default settings:

time=2026-11-24T13:24:40.678Z level=WARN source=llama_server.go:350 msg="truncating input prompt" limit=2050 prompt=7226 keep=4 new=2050

And this is 0.12.10 on a prompt of the same shape (7205 tokens there, because that request came in through /v1, which rendered it slightly differently on the old version):

time=2026-11-24T13:15:30.439Z level=WARN source=runner.go:136 msg="truncating input prompt" limit=4096 prompt=7205 keep=4 new=4096

Reading the fields:

  • prompt is how many tokens your rendered prompt had.
  • keep is how many tokens at the very start are protected (num_keep, plus one if the tokenizer adds a BOS token). Here 4.
  • limit and new are how many tokens the model actually received.

Everything between the first keep tokens and the last limit - keep tokens is gone. The source for 0.40.18 makes the order explicit:

truncated = append(truncated, tokens[:nKeep]...)
truncated = append(truncated, tokens[nKeep+discard:]...)

So the tail survives, which is why the model still sees the question and still answers it. What it loses is the head: the system message (chat templates put it first) and the first chunks of context. Most RAG code concatenates chunks in ranking order, so the chunk your retriever liked most is the first one deleted.

The part that changed between versions is limit. In 0.40.18 it comes from this function:

func contextShiftPromptLimit(numCtx, numKeep int) int {
	[...]
	// Match the old runners' first context shift: preserve num_keep, then free
	// roughly half of the remaining context before generation needs the slot.
	return numCtx - max((numCtx-numKeep)/2, 1)
}

With num_ctx 4096 and keep 4 that is 4096 minus 2046, which is the 2050 in the log. The function first appears in the v0.30.11 tag, after the pull request titled “llm: preserve generation headroom for shifted prompts”. The older runner kept the full 4096. I’m not going to argue with the reasoning (the model does need room to generate), but the effect is that a prompt that goes over the window by 10 tokens now loses about half its content, not 10 tokens.

Where the default 4096 comes from

The 0.40.18 server says it at startup:

time=2026-11-24T13:24:32.830Z level=INFO source=routes.go:2596 msg="vram-based default context" total_vram="0 B" default_num_ctx=4096

The current context-length docs list the rule: 4k below 24 GiB of VRAM, 32k between 24 and 48 GiB, 256k at 48 GiB and above. The FAQ page still says the default is 4096 flat. On a CPU-only server there is no VRAM, so you get 4096 regardless of how much RAM the box has (this one has 62 GiB). I only tested CPU, so I can’t show the 32k tier, but the rule has an uncomfortable implication: a workstation with a 24 GB GPU gets a 32k default, and the same code on a CPU server in staging gets 4k. The bug shows up on the machine you deploy to, not the one you developed on.

0.12.10 printed OLLAMA_CONTEXT_LENGTH:4096 in its server config line. Same number, no VRAM rule.

The repro: a needle in the first chunk

The test script builds a RAG-shaped prompt: [doc 0] holds the fact the question asks about, followed by N filler chunks about warehouses, then the question at the end. Each run gets a different random door code, so a correct answer can’t be a lucky guess.

def build(seed):
    rng = random.Random(seed)
    code = f"{rng.choice(['ORCHID', 'FALCON', 'MAPLE', 'COBALT'])}-{rng.randint(1000, 9999)}"
    needle = f"[doc 0] The door code for the Kestrel server room is {code}."
    body = "\n".join([needle] + [chunk(rng, i) for i in range(1, N)])
    user = (f"Answer using only the context below.\n\nContext:\n{body}\n\n"
            "Question: What is the door code for the Kestrel server room? Reply with the code only.")
    return code, user

The same prompt goes to /api/chat and to /v1/chat/completions with temperature 0, and the script prints the token count the server reports (prompt_eval_count on the native API, usage.prompt_tokens on /v1) and whether the code appears in the answer. Three runs per size. Token counts are the ones the server reported, so they come from the model’s own tokenizer.

ChunksPrompt tokens0.12.10: tokens kept0.12.10: needle found0.40.18: tokens kept0.40.18: needle found
401908 to 1931all3/3all3/3
803826 to 3838all3/3all3/3
864090 to 4124not run2050 (2 of 3 runs)0/3
1205708 to 574740960/320500/3
1708161 to 8210not run20500/3

/api/chat and /v1/chat/completions gave the same verdict on every row, because with default settings they hit the same 4096 window. Two things in that table were not what I expected.

The 86-chunk row has a run that wasn’t truncated at all. The prompt was 4090 tokens, under the 4095 the code allows, so it went in whole. The answer was 'COBALT-32': the right code, cut off, because only 6 tokens of the window were left for the reply. A prompt that fits is not the same as a request that fits.

The other is what the model said when the needle was gone. It didn’t say “I don’t know”. Across the truncated runs on 0.40.18 the answers were '123456' most of the time, plus '827', '829', '2022', '20220510' and '825-987-1234'. On 0.12.10 one run produced 'The door code for the Kestrel server room is "1234".' A small model, sure. But the instruction “answer using only the context below” was in the part of the prompt that got deleted, so the model never received it.

Fix 1: options.num_ctx on the native API

The per-request fix is a field in options:

curl -s localhost:11434/api/chat -d '{
  "model": "qwen2.5:1.5b",
  "stream": false,
  "options": { "num_ctx": 16384, "temperature": 0 },
  "messages": [{ "role": "user", "content": "..." }]
}'

With the official Python client it’s ollama.chat(model=..., messages=..., options={"num_ctx": 16384}). The generation step in my privacy-first local RAG guide calls ollama.chat with no options at all, so it inherits whatever default the server has. That is the most common shape of this bug: nothing is misconfigured, nothing is configured.

There is a cost I only noticed in the server log. num_ctx is a load-time setting, so when two clients ask for different values, Ollama restarts the runner. My script alternated a 16384 request on /api/chat with a default request on /v1, and every switch started a new llama-server, once at n_ctx = 16384 and once at n_ctx = 4096. If several services share one Ollama, pick one context length for all of them.

Fix 2 and 3: the server default, or a Modelfile

OLLAMA_CONTEXT_LENGTH changes the default for every request that doesn’t set its own:

docker run -d -p 11434:11434 -e OLLAMA_CONTEXT_LENGTH=16384 \
  -v ollama:/root/.ollama ollama/ollama

A Modelfile bakes it into a model name, which is the option I’d pick when the value belongs to the application rather than to the server:

FROM qwen2.5:1.5b
PARAMETER num_ctx 16384
ollama create qwen2.5-16k -f Modelfile

Why /v1/chat/completions ignores num_ctx

This is the part that catches people using LangChain, LlamaIndex, the OpenAI SDK, or anything else that talks to Ollama through its OpenAI-compatible endpoint. The OpenAI API has no field for context size, and Ollama’s translation layer only maps the fields that exist: in openai/openai.go at v0.40.18 the options it fills are stop, num_predict (from max_tokens), temperature, seed, frequency_penalty, presence_penalty and top_p. Anything else you send is dropped. The docs say it directly: “The OpenAI API does not have a way of setting the context size for a model.”

I tested it anyway, sending both a top-level "num_ctx": 16384 and "options": {"num_ctx": 16384} in the /v1 body, which is what extra_body in the OpenAI SDK produces. Same 7.2k-token prompt, three runs per cell:

How the context was set/api/chat/v1/chat/completions
Nothing (default 4096)2050 tokens kept, 0/12050 tokens kept, 0/1
num_ctx 16384 in the request7213 to 7230 tokens, 3/32050 tokens kept, 0/3
OLLAMA_CONTEXT_LENGTH=163847213 to 7230 tokens, 3/37213 to 7230 tokens, 3/3
Modelfile PARAMETER num_ctx 163847213 to 7230 tokens, 3/37213 to 7230 tokens, 3/3

The second row is the one to remember. The request carried num_ctx and the /v1 call still came back with prompt_tokens: 2050 and the answer '123456'. An issue asking for this was opened in June 2024 and closed in April 2025, with the server-side environment variable as the answer instead of a request field. A pull request to forward num_ctx on the OpenAI endpoints (#16825) was open when I checked. Until something like it ships, if your client speaks OpenAI, the context length has to live on the server or in the model name.

Verify with ollama ps, not with your config

ollama ps shows the context the loaded model is actually running with. After the default request:

NAME            ID              SIZE      PROCESSOR    CONTEXT    RUNNER      UNTIL
qwen2.5:1.5b    65ec06548149    1.2 GB    100% CPU     4096       llamacpp    4 minutes from now

And on the server started with OLLAMA_CONTEXT_LENGTH=16384:

qwen2.5:1.5b    65ec06548149    1.6 GB    100% CPU     16384      llamacpp    4 minutes from now

0.12.10 already had the CONTEXT column. It’s the fastest way to check what you’re getting, because it reflects the last load, not the value you think you set.

From the client side there is a cheaper signal: compare the prompt token count in the response with num_ctx. On 0.40.18, a prompt_eval_count of exactly num_ctx - (num_ctx - keep) / 2 (2050 for a 4096 window) on a prompt you know is longer means it was cut. On 0.12.10 the tell was a count of exactly 4096.

Make it fail loudly

A truncated prompt is a wrong answer with a 200 status. I would much rather have an error. The native API has two request fields for that, truncate and shift, and both work on 0.40.18. Same 7226-token prompt, default window:

{'truncate': False} -> 400 {"error":"request (7226 tokens) exceeds the available context size (4096 tokens), try increasing it"}
{'shift': False} -> 400 {"error":"the prompt is longer than the context length currently available to the model; shorten the prompt, adjust the context length in settings, or use a model with a longer context length"}

"truncate": false gives the more useful message, because it carries both numbers. In a RAG backend that 400 is something you can handle: drop the lowest-ranked chunks and retry, or return a clear error to the caller. You can’t do either with an answer that looks fine. Like num_ctx, these fields only exist on the native API, so a /v1 client can’t ask for them. I didn’t test them on 0.12.10.

What a bigger window costs

A larger num_ctx reserves a larger KV cache when the model loads, whether or not the prompts use it. I loaded the model at each size and read three numbers: the KV buffer llama-server logged, the size ollama ps reported, and the container’s memory from docker stats.

num_ctxKV cache (log)ollama ps SIZEdocker stats
204856 MiB1.1 GB1.092 GiB
4096112 MiB1.2 GB1.152 GiB
8192224 MiB1.4 GB1.257 GiB
16384448 MiB1.6 GB1.48 GiB
32768896 MiB2.1 GB1.92 GiB

I ran the full sweep two more times and the docker stats values moved by 0.004 GiB at most, so the table shows the first pass.

The KV cache is linear: 28 KiB per token for this model (28 layers, 2 KV heads of 128 dimensions, keys and values in f16). Qwen2.5 1.5B is small and uses grouped-query attention, so even 32k costs under 1 GiB. Bigger models pay much more per token, and the arithmetic in the log line llama_kv_cache: size = ... is the place to read it for yours. If you’re sizing hardware for this, I went through the cost side of running RAG locally versus on cloud GPUs in a separate post.

The point for this bug: on a CPU box with tens of GB of RAM, going from 4096 to 16384 cost this model 336 MiB of KV cache. The 4096 default is a conservative choice for GPUs with little VRAM, and it’s applied to servers where it isn’t needed.

What I’d do in a RAG backend

Count before you send. The retriever knows how many tokens it is about to put in the prompt, or can find out from prompt_eval_count on the first call, and the budget is num_ctx minus the reply length minus the template. Set num_ctx explicitly in the one place your client honours it: in options on the native API, in a Modelfile if you go through /v1. Send "truncate": false when you can, check ollama ps once after every deploy, and grep the server logs for truncating input prompt. In the ASP.NET Core chatbot with tool calling the retrieved context was small enough that none of this came up, which is exactly why it’s easy to miss until the corpus grows.

My position: silent truncation is the wrong default for an API. Chat apps can live with it, because forgetting the start of a long conversation is often fine. A RAG prompt is not a conversation, and the front is the part you care about most. If I were writing Ollama’s defaults, /api/chat would return the 400 unless the client opted into truncation. Since I’m not, I treat truncate: false as part of every RAG request, and I’m still not sure there is a clean equivalent for clients stuck on /v1 other than putting the context length in the model name and keeping prompts well under it.

References