Setting context length in Ollama

Ollama's context window decides how much text a model can hold at once, and its VRAM-based defaults often fall short for agents and coding tools. This page explains how to set context length server-wide or per request and what the memory cost is.

On this page

Setting context length in Ollama: when the default is too small

The context length is the number of tokens a model can hold in one request, covering the system prompt, conversation history, tool definitions, retrieved documents and the reply. When a team runs Ollama for chat, agents or coding tools and sees answers cut off mid-thought, forgotten instructions or a server that slows and runs out of memory, the context window is the first setting to check. Ollama picks a default from the VRAM it detects, so two servers running the same model can behave differently. The default works for short chats on a small GPU, but it is rarely enough for agents or coding tools. Ollama's context length documentation describes three tiers: a 4k default with under 24 GiB of VRAM, 32k with 24 to 48 GiB and 256k with 48 GiB or more. The same documentation recommends at least 64000 tokens for web search, agents and coding tools.

A larger window is not free. The key and value cache for the context is held in memory alongside the model weights, so a bigger context can push a model partly onto the CPU or force a smaller number of loaded models. The memory cost depends on the model architecture and on how many requests run in parallel, so the only reliable way to size it is to measure it on your hardware. Treat the change as configuration plus measurement. Decide who sets the value: the server-wide OLLAMA_CONTEXT_LENGTH variable, a per-request num_ctx option, or both. Decide which models need the larger window and which workloads can stay small. Then run ollama ps under realistic load to confirm the allocated context and the CPU and GPU split, and adjust before the setting goes into production.

Context length settings and when each fits

This table compares the three ways to set context length in Ollama: the VRAM-based default, the server-wide OLLAMA_CONTEXT_LENGTH variable and the per-request num_ctx parameter. Read each row for scope, who controls the value and the workload it suits. The main takeaway is that num_ctx lets one application use a larger window without changing the whole server.

SettingScope and controlWhen it fits
VRAM-based defaultChosen by Ollama from detected VRAM (4k under 24 GiB, 32k at 24 to 48 GiB, 256k at 48 GiB or more). Applies when nothing else is set.A single developer trying a model who has not tuned anything. Confirm the default on your hardware with ollama ps before relying on it.
OLLAMA_CONTEXT_LENGTHServer-wide. Set once in the service environment and applies to every model and every client of that server.A shared server running one tool or one team workload, where every request needs the same window and the operator controls the memory budget.
num_ctx request parameterPer request. Set by the calling application in the options of each API call, and it overrides the server-wide value for that call.Mixed workloads on one server: a coding agent needing a large window next to a short chat app that should stay small. Only the calling application changes.
Memory cost of a larger windowApplies to whichever value wins. A larger context reserves more memory for the model's working state, which can push layers from GPU to CPU.Set the smallest window the workload needs. Check the CPU/GPU split in ollama ps after each change, since a larger window can slow responses.
Agents and coding toolsOllama's documentation recommends at least 64000 tokens for web search, agents and coding tools.Usually set through num_ctx or OLLAMA_CONTEXT_LENGTH on a server with enough VRAM for that window. Confirm the tool's own context setting does not override yours.
Verification with ollama psShows the allocated context and CPU/GPU split for loaded models, so the effective value is visible.Use after every change to confirm the value a request actually received, rather than assuming the environment variable or request option took effect.

How to set and verify context length

This sequence confirms the GPU memory and current default, sets a context length that fits the workload, applies it, and proves with ollama ps that the model loaded with the intended context and a GPU-heavy CPU/GPU split. The result is a context setting you can show a reviewer, not a guess.

  1. Confirm GPU memory and the current default

    The server administrator checks how much VRAM each GPU has and which total memory is available, using the vendor tool for the GPU (for example, nvidia-smi on NVIDIA hardware) and the Ollama context length documentation. Ollama picks a default context from the VRAM tier: 4k under 24 GiB, 32k at 24 to 48 GiB and 256k at 48 GiB or more. Write down the tier and the default that applies to this machine. The step is done when you can state the VRAM figure and the default context length in one sentence.

  2. Choose a target context for the workload

    The platform owner decides how much context the workload needs, based on the longest prompt, retrieved documents and conversation history the application sends. Ollama recommends at least 64000 tokens for web search, agents and coding tools, so treat that as a floor for those workloads and test whether your hardware can hold it. Longer context increases the memory the model needs for its key-value cache, so a larger target may move the model partly onto the CPU. The step is done when you have one agreed number and the workload it serves.

  3. Set the context in server or client configuration

    The administrator sets OLLAMA_CONTEXT_LENGTH in the Ollama server environment to apply the value to every model, or the client sets num_ctx on individual requests when only one application needs a different size. Confirm where your installation reads these settings: for a Linux systemd service, this is usually an override file for the ollama service, and for containers it is the environment block in the compose file or run command. Those locations depend on your install method, so check them in your own environment. The step is done when the value appears in the file or request you control and nothing else overrides it.

  4. Restart the service and reload the model

    The administrator restarts the Ollama service so the new environment value takes effect, or the client sends a new request after changing num_ctx. Unload the model if it was already loaded with a different context, so the next request allocates memory with the new setting. The step is done when the service is running again and the next request to the model completes without a startup error in the logs.

  5. Confirm the allocated context with ollama ps

    Run ollama ps on the server after the model has handled a request. The output shows the loaded model, the allocated context and the split between CPU and GPU. Compare the context value with the target from the second step. If the value differs, check whether the setting was overridden at the request level or the service did not restart. The step is done when the allocated context matches the target.

  6. Check the CPU and GPU split

    In the same ollama ps output, confirm that the model is still mostly on the GPU. A split that moves fully to CPU usually means the context is too large for the available VRAM, and responses will be much slower. Note the split at your target context and at the default, so you can compare them. If the model has moved to CPU, lower the target or move to a GPU with more memory. The step is done when the split is recorded and the model is on the GPU at the chosen setting.

  7. Test a long prompt against the target

    Send a prompt close to the target context size from the application or a test script, using realistic content from your workload. Confirm the response is coherent, that information placed near the start of the prompt is used correctly, and that the request does not fail or truncate silently. Then run ollama ps again during the request and after it to confirm the split held under load. Record the result with the test date and the Ollama version reported by the server. The step is done when a long prompt completes correctly and the split still shows the model on the GPU.

How a context setting reaches the loaded model

The flow starts with a client request. If the request sets num_ctx, that value is used for the model load. If it does not, the server checks OLLAMA_CONTEXT_LENGTH, and if that is also unset, Ollama picks a default from the GPU memory it detects. The chosen context is then applied when the model loads. Run ollama ps afterward to confirm the allocated context and the CPU/GPU split, because the value you configured is not the only input that shapes what the server actually loads.

Context value resolution from request to verification with ollama ps.

Context settings for agents, coding tools and chat

Chat assistants usually carry a system prompt, the visible conversation history and any uploaded text in each request, so context grows with every turn. For short, single-question use, the default for your VRAM tier may be enough. Long working sessions, pasted documents and multi-turn analysis push the total up quickly, and when the history exceeds the allocated window, older content is dropped from what the model sees.

  • Typical consumption: Short exchanges often fit well inside the default window, while long sessions with pasted documents grow steadily.
  • Starting point: Ollama recommends at least 64000 tokens for web search, agents and coding tools, so treat that figure as a floor for any workload that keeps large inputs.
  • Measure first: Track how many turns a typical user reaches before answers degrade or earlier content is ignored.
  • Memory cost: A larger window costs more memory, so raise it only where session length demands it.
  • Per-user variation: Some users run long sessions and others do not, so consider separate settings for different groups.

Before raising the value for chat, confirm the setting in your chat front end, since some interfaces send their own options and may override the server default.

Security and operational risks of larger context windows

A larger context window raises memory use, response time and the amount of prompt data a server holds. The risks below share one root: each request can change how much of the shared server it consumes. Check each one before you raise the default or let a client set num_ctx.

Out-of-memory failures and unloading

The context window's memory cost is paid in VRAM or system memory when the model loads and while requests run. A larger window on a busy server can push a model out of memory or force Ollama to unload and reload models that other users need. Test your planned window with the concurrency you expect, then watch ollama ps for the allocated context and the CPU/GPU split. The memory headroom you need depends on how many requests run at once, which is set by OLLAMA_NUM_PARALLEL.

Default under 24 GiB VRAM
4k
Context length docs

Slower responses and client timeouts

Longer prompts take longer to process before the first token appears, so a window that works in a quick test can exceed the timeout of a web app, gateway or agent. Measure time to first token with realistic prompt sizes, not short samples. Set client timeouts that match the window you allow, and confirm that any reverse proxy in front of Ollama does not cut long requests first.

One user's window affects everyone

On a shared server, a single client that sets a large num_ctx in its request can consume memory that other users' requests depend on. Because Ollama's local API does not require authentication, any client that can reach the port can set this value. Decide who may set per-request context sizes, and enforce that through the gateway or application layer rather than trusting each client to behave.

Prompt data kept in logs

Verbose server logging can record request content, and larger windows mean more prompt text per request. Check what your Ollama service writes to its logs, who can read them and how long they are kept. Ollama states that local runs do not send your prompts to it, but that statement does not cover logs, caches or files on your own host. Set log retention and access rules before the service handles regulated data.

Ollama FAQ

Behavior drift after upgrades

Default context sizes depend on detected VRAM and on Ollama's own defaults, and both can change between releases. An upgrade can therefore change how much text the model sees, which can alter answers, truncate documents or change memory use without any change to your configuration. Pin the window explicitly with OLLAMA_CONTEXT_LENGTH or a Modelfile, and re-test key workloads after each version change.

Ollama releases

Questions teams ask before changing context length

What does raising the context length cost in memory and response speed?

A longer context consumes more memory, and the extra memory has to fit alongside the model weights. Ollama allocates the context window when a model loads, so a larger value can push part of the model off the GPU and onto the CPU. The cost shows up in three places:

  • GPU memory: the context window needs space in VRAM on top of the weights, so a larger window can leave less room for the model itself.
  • CPU and GPU split: when memory runs short, ollama ps shows a higher CPU share, which slows token generation.
  • Concurrency: each parallel request uses context memory, so a shared server may need fewer parallel slots.

The exact figure depends on the model, quantization and hardware. Ask the vendor or your team to measure it on your own GPUs with your real prompt sizes before you settle on a value.

How long does a context length tuning exercise take?

The duration depends on how many models, hardware types and workloads are in scope, and on how much the team already knows about its prompts. The main drivers are:

  • the number of models and the context sizes each workload needs
  • whether the GPUs are already inventoried and their VRAM is known
  • how many representative workloads exist for testing, such as chat, retrieval and agent runs
  • how many test cycles are needed to confirm the split between CPU and GPU stays acceptable under concurrent load

A quote should state the models, hardware, workloads and the number of verification rounds it covers, so the duration can be checked against that written scope.

Can our team change the context length without outside help?

Yes, a capable platform or infrastructure team can change the setting alone, because the mechanics are simple. Set OLLAMA_CONTEXT_LENGTH on the server for a default, or pass num_ctx in a request for a specific call. The harder part is deciding the right value. That requires knowing the VRAM on each host, the models in use, the concurrency settings and the prompt sizes users send. Teams that lack GPU measurement experience, or that run several hosts with different hardware, often find a short external review useful. DeployOpen works on this as a fixed-scope engagement with written deliverables.

What do you need from us to tune context length?

The work needs access and information that only your organization holds. Typically, a tuning engagement needs:

  • an inventory of GPU hosts, including model, VRAM and whether the hosts are shared
  • the list of models in use and any custom or fine-tuned weights
  • representative sample workloads, such as typical prompts, document sizes and agent or coding tool sessions
  • access to the Ollama servers, their service configuration and logs, in a test or staging environment where possible
  • a named contact who can approve changes to shared servers

Ask for this list in writing as part of the scope so that gaps are visible before work starts.

Does changing the context length require re-pulling the model?

No, the context length is a runtime setting, so changing it does not require pulling the model again. The value is applied when Ollama loads the model. After you change OLLAMA_CONTEXT_LENGTH on the server, restart the service so the new default applies. A num_ctx value in a request overrides the server default for that call. Models that are already loaded may keep their earlier allocation until they unload, so confirm the change with ollama ps after reloading. Model re-pulls matter only when you change the model itself, which is a separate decision.

How do we verify that the context setting actually holds?

Run ollama ps after a model loads and check the allocated context and the CPU/GPU split shown for that model. Then send a request with a long prompt and confirm the split stays the same under concurrent load. Repeat the check after server restarts, after model updates and after changes to OLLAMA_NUM_PARALLEL or OLLAMA_MAX_LOADED_MODELS, because each can change the memory allocation. Record the results in your change log so that a later complaint about truncated answers can be traced to a specific setting. Ask any vendor to provide a written verification procedure as a deliverable.

Which context length should coding tools and agents use?

Ollama recommends at least 64000 tokens for web search, agents and coding tools. Its default context depends on VRAM: 4k with under 24 GiB, 32k with 24 to 48 GiB and 256k with 48 GiB or more. Those defaults are too small for many agent sessions, so teams running coding tools often need to raise the value on the server or per request. Larger values cost memory, so the right choice depends on whether the hardware can hold the window at the concurrency you need. Test the target tool with a real session before you roll it out to the team.

How DeployOpen works on this

DeployOpen plans and implements context length settings for Ollama inside your own infrastructure, starting from the workloads you need to run and the memory each one can afford. Every engagement is fixed-scope, with the context targets, configuration and checks agreed in writing before work starts.

How we scope

  • Inventory which applications, agents and coding tools will send prompts, and how long those prompts typically run.
  • Record the GPUs, VRAM and host memory each Ollama server has, so context targets match real hardware.
  • Agree in writing whether context is set server-wide, per request or in model packaging, with the reasons for each.

How we build

  • Configure OLLAMA_CONTEXT_LENGTH on each server and confirm the value a client request actually receives.
  • Test the allocated context and the CPU/GPU split with ollama ps under realistic load, not only at idle.
  • Set num_ctx defaults for agent and coding tool clients, and check memory headroom when several models are loaded.

How we hand over

  • Document the chosen context values, the reason for each, and the memory cost measured during testing.
  • Provide a runbook for changing context length, including the steps to restart and re-verify the server.
  • Deliver a short checklist for reviewing a new model or client so context settings are revisited before rollout.

How we support

  • Offer ongoing support, upgrades and continuous testing as a retainer after handover.
  • Re-check context behavior when Ollama releases change defaults or configuration handling, with release notes reviewed first.
  • Revisit context targets when hardware, models or user workloads change, through a scoped change request.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.