Skip to content

[Bug]: Ollama num_ctx from extra_request_body is never applied (LiteLLM sends it top-level), so extraction prompts are truncated to 2050 tokens #5030

Closed

Description

@qaz2461477-coder

Issue Origin

Observed or reproduced in a real environment

(Diagnosis was done with the help of an AI coding assistant; every number below comes from real Ollama logs and captured HTTP bodies on my machine.)

Bug Description

For ollama/ (and ollama_chat/) routes, LiteLLMVLMProvider._build_kwargs puts num_ctx — both the OLLAMA_DEFAULT_NUM_CTX = 16384 default added in #2992 and any user value from vlm.extra_request_body — into LiteLLM's extra_body:

# openviking/models/vlm/backends/litellm_vlm.py (v0.4.20, unchanged on main)
if self.extra_request_body:
    kwargs["extra_body"] = dict(self.extra_request_body)
if _has_litellm_prefix(model, OLLAMA_LITELLM_PREFIXES):
    extra = kwargs.get("extra_body", {})
    extra.setdefault("num_ctx", OLLAMA_DEFAULT_NUM_CTX)
    extra.setdefault("think", self._effective_thinking(thinking))
    kwargs["extra_body"] = extra

LiteLLM does not map extra_body into Ollama options for these routes; num_ctx is sent as a top-level JSON field. Ollama only reads num_ctx from options, so the model is loaded with its default 4096 context and long prompts are truncated. (think is a valid top-level Ollama field, so only num_ctx is affected.)

Effect on memory extraction: the extraction prompt is truncated to 2050 tokens, the model never sees most of the instructions/conversation, and the commit silently finishes with memories_extracted: {} and an empty memory_diff.json.

This is likely one contributing cause of #4879 (local extraction failing "even after setting num_ctx: 16384"). The reproduction comment there verified num_ctx at the LiteLLM call boundary, but not the outbound HTTP body. #4898 only fixes ollama_chat/ route preservation and does not change this.

Steps to Reproduce

  1. ov.conf:
    "vlm": {
      "provider": "litellm",
      "model": "ollama/qwen3.5:9b",
      "api_key": "no-key",
      "api_base": "http://localhost:11434",
      "temperature": 0.0,
      "extra_request_body": { "num_ctx": 16384, "think": false }
    }
  2. ov session new, ov session add-messages <id> '<6 short user/assistant messages containing a clear preference, a project, and an event>', ov session commit <id>.
  3. Wait for the commit task, then check Ollama server.log and ollama ps.

Expected Behavior

Ollama runs the extraction request with num_ctx 16384 (or the configured value); the prompt is not truncated and memories are extracted.

Actual Behavior

  • ollama ps shows CONTEXT 4096; the llama runner logs llama_context: n_ctx = 4096.
  • Every extraction call is truncated (three commits of the same test session):
    msg="truncating input prompt" limit=2050 prompt=6735 keep=4 new=2050
    msg="truncating input prompt" limit=2050 prompt=7957 keep=4 new=2050
    msg="truncating input prompt" limit=2050 prompt=7957 keep=4 new=2050
    
  • Real Claude Code plugin sessions were also truncated (prompt=17022, prompt=52702 → new=2050).
  • Session llm_token_usage.prompt_tokens stays at exactly 2882 (832 archive summary + 2050 truncated extraction) regardless of extraction_output_format, and memories_extracted is empty.

Minimal Reproducible Example

# Capture what LiteLLM sends to Ollama, using a fake Ollama endpoint.
import json, threading, time
from http.server import BaseHTTPRequestHandler, HTTPServer
import litellm

captured = []

class H(BaseHTTPRequestHandler):
    def log_message(self, *a): pass
    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        captured.append({k: v for k, v in body.items() if k not in ("prompt", "messages")})
        out = json.dumps({"model": "x", "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
                          "response": "ok", "done": True,
                          "prompt_eval_count": 1, "eval_count": 1}).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(out)))
        self.end_headers()
        self.wfile.write(out)

srv = HTTPServer(("127.0.0.1", 11555), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
base = dict(messages=[{"role": "user", "content": "hi"}],
            api_base="http://127.0.0.1:11555", temperature=0.0, api_key="no-key")

# A: what OpenViking does today
litellm.completion(model="ollama/qwen3.5:9b", extra_body={"num_ctx": 16384, "think": False}, **base)
# B: num_ctx as a LiteLLM kwarg
litellm.completion(model="ollama/qwen3.5:9b", num_ctx=16384, **base)
for c in captured:
    print(c)

Output (litellm 1.91.1; the middle line is LiteLLM's follow-up /api/show request after call A):

{'model': 'qwen3.5:9b', 'options': {'temperature': 0.0}, 'stream': False, 'images': [], 'num_ctx': 16384, 'think': False}
{'name': 'qwen3.5:9b'}
{'model': 'qwen3.5:9b', 'options': {'temperature': 0.0, 'num_ctx': 16384}, 'stream': False, 'images': []}

Call A (OpenViking today) sends num_ctx at the top level; call B puts it in options.num_ctx.

ollama_chat/ + extra_body behaves like A (num_ctx top-level on /api/chat).

Error Logs

llama_context: n_ctx                 = 4096
slot   operator(): id  0 | task 645 | new prompt, n_ctx_slot = 4096, n_keep = 4, task.n_tokens = 2050
time=2026-09-15T01:45:02.478+08:00 level=WARN source=llama_server.go:317 msg="truncating input prompt" limit=2050 prompt=6735 keep=4 new=2050

No error or warning is emitted by OpenViking; the commit task completes with error: null.

OpenViking Version

0.4.20 (PyPI); code is unchanged on current main

Python Version

3.11.9

Operating System

Windows

Model Backend

Other (LiteLLM → local Ollama)

Additional Context

  • Environment: litellm 1.91.1 (within the >=1.83.7,<1.91.2 pin), Ollama 0.34.0, model qwen3.5:9b (Q4_K_M, context length 262144).
  • Suggested fix: for Ollama routes, pass num_ctx (and other Ollama options) as LiteLLM kwargs instead of via extra_body — variant B above is verified to land in options.num_ctx. A regression test should assert on the outbound Ollama request body, not only on the kwargs given to litellm.completion.
  • Workaround that I verified: an Ollama Modelfile variant (FROM qwen3.5:9b + PARAMETER num_ctx 32768) used as vlm.model. With it, the Ollama log shows no truncation and the full 6,735-token extraction prompt is delivered.
  • Related observation for the "which local models work" discussion in Self-hosting experience report: memory extraction effectively Doubao/cloud-only; local OSS models (Ollama) cannot drive it + MCP/temp_upload gotchas #4879: with the context fixed, qwen3.5:9b under the default Python DSL still produced 0 operations. Captured responses show it wrote correct sdk.create_preferences / create_entities / create_events calls plus one invalid identity_1.content.update(...) (identity has no content field). The whole program was rejected ("No changes from the invalid program were applied"); 3 format retries repeated the mistake. With memory.extraction_output_format: "json", the same session extracted 3 correct memories in a single call.

Activity

  1. moved this from Backlog to In progress in OpenViking projecton Sep 15, 2026
  2. CryoThrust commented on Sep 15, 2026

    @CryoThrust
    Contributor

    Confirmed, and the LiteLLM-side diagnosis is exactly right. I verified it at the wire level rather than by reading the transformation: with litellm 1.91.1 and a local HTTP server as api_base, the body OV currently sends for ollama/qwen3.5:4b is

    {"options": {}, "num_ctx": 16384, "think": false}
    

    i.e. num_ctx top-level, options empty — so the server never sees it. Passing num_ctx as a top-level argument instead gives

    {"options": {"num_ctx": 16384}, "think": false}
    

    which is the field Ollama reads. think is valid top-level either way, so only num_ctx needs to move.

    Opened #5033 with the change plus a wire-level test that runs the built kwargs through OllamaChatConfig.transform_request and asserts options.num_ctx — asserting the built kwargs alone would only pin where OV puts the value, not the field that matters, which is part of why this slipped through.

    One thing worth flagging for the related issues: this makes the plumbing correct, but it won't by itself guarantee extraction succeeds on a small local model. num_ctx 16384 is the OV default, and if the configured VLM can't handle it or the extraction prompt is still oversized, the commit will fail for a different reason. Worth re-testing #4879 with ollama ps confirming CONTEXT 16384 after this lands, so the remaining cause (if any) is separable from this one.

  3. moved this from In progress to Done in OpenViking projecton Sep 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions