send ollama requests to /api/chat so num_ctx actually applies

(cherry picked from commit 5f7b2b4dc8)
This commit is contained in:
smngvlkz authored and safishamsi committed 2026-10-14 22:53:26 +01:00
1 parent 990ab1b75c
commit f48425e6e0
4 files changed
+428 -74

No files matched your search

+149 -54
View File
@@ -1382,6 +1382,123 @@ def _backend_pkg_hint(pkg: str, extra: str) -> str:
)
def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dict:
"""num_ctx/keep_alive for an Ollama request, sized to the prompt."""
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
# than that — the symptom is hollow 200 OK responses after the first few
# chunks (#798). We derive num_ctx from the actual prompt size so we don't
# over-allocate KV-cache VRAM. Over-allocation (e.g. 128k slots for an 8k
# prompt on a 31B model) exhausts VRAM by chunk 4 and produces the same
# hollow-200 symptom — just from a different direction (#798 follow-up).
# Formula: actual input tokens + output cap + system prompt headroom.
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
# Auto-derive num_ctx from actual chunk size regardless — used as the
# fallback and for the mismatch check below.
estimated_input = len(user_message) // _CHARS_PER_TOKEN + 400
auto_num_ctx = min(estimated_input + max_completion_tokens + 2000, 131072)
auto_num_ctx = max(auto_num_ctx, 8192)
if num_ctx_raw:
try:
num_ctx = int(num_ctx_raw)
except ValueError:
# Bad env var: fall through to auto-derivation (not 131072 —
# hardcoding the cap is what causes OOM on constrained VRAM).
print(
f"[graphify] GRAPHIFY_OLLAMA_NUM_CTX={num_ctx_raw!r} is not a valid integer; "
f"using auto-derived value ({auto_num_ctx}).",
file=sys.stderr,
)
num_ctx = auto_num_ctx
else:
# Warn when the pinned value is smaller than the estimated input —
# Ollama silently truncates the prompt and returns empty responses.
if num_ctx < estimated_input:
print(
f"[graphify] warning: GRAPHIFY_OLLAMA_NUM_CTX={num_ctx} is smaller than "
f"the estimated chunk input (~{estimated_input} tokens). Ollama will "
f"silently truncate the prompt and return empty responses. "
f"Try --token-budget {max(1024, num_ctx // 3)} or increase NUM_CTX.",
file=sys.stderr,
)
else:
# Estimate input tokens: user_message chars / 4 (standard BPE
# heuristic) + 400 for the system prompt, then add output headroom.
num_ctx = auto_num_ctx
keep_alive = os.environ.get("GRAPHIFY_OLLAMA_KEEP_ALIVE", "30m")
return {"options": {"num_ctx": num_ctx}, "keep_alive": keep_alive}
# Ollama's OpenAI-compatible /v1 endpoint ignores `options`, so the num_ctx
# from _ollama_request_extras never reached the server and every prompt was cut
# to Ollama's default context (4096 on Ollama 0.17.5) — the model lost the JSON
# instructions and answered in prose (#4413). The native /api/chat endpoint honours it. Servers
# that only speak /v1 (LM Studio, llama.cpp behind the ollama backend) 404 on
# /api/chat; remember them so each chunk doesn't pay for a failed request.
_OLLAMA_NO_NATIVE: set[str] = set()
def _call_ollama_native(
client,
base_url: str,
kwargs: dict,
user_message: str,
images: list[_ImageRef],
) -> tuple[str | None, int, int, str] | None:
"""Send an ollama request to /api/chat. Returns None when the server has no
native endpoint, so the caller falls back to /v1."""
root = base_url.rstrip("/")
if root.endswith("/v1"):
root = root[: -len("/v1")]
if root in _OLLAMA_NO_NATIVE:
return None
from openai import APIStatusError
extra = kwargs.get("extra_body", {})
options = dict(extra.get("options", {}))
options["num_predict"] = kwargs["max_completion_tokens"]
if "temperature" in kwargs:
options["temperature"] = kwargs["temperature"]
if "seed" in kwargs:
options["seed"] = kwargs["seed"]
user: dict = {"role": "user", "content": _with_image_notes(user_message, images)}
pixels = [r.b64 for r in images if r.raw]
if pixels:
user["images"] = pixels
body: dict = {
"model": kwargs["model"],
"messages": [*kwargs["messages"][:-1], user],
"stream": False,
"options": options,
"keep_alive": extra.get("keep_alive", "30m"),
}
if _thinking_disabled_via_env():
body["think"] = False
try:
data = client.post(f"{root}/api/chat", body=body, cast_to=object)
except APIStatusError as exc:
# Ollama also 404s on an unknown model; surface that instead of
# marking a real Ollama server as non-native.
if exc.status_code not in (404, 405) or "model" in str(exc).lower():
raise
_OLLAMA_NO_NATIVE.add(root)
print(
f"[graphify] {root}/api/chat is not available; falling back to the "
"OpenAI-compatible /v1 endpoint, which ignores num_ctx.",
file=sys.stderr,
)
return None
data = data or {}
message = data.get("message") or {}
finish_reason = "length" if data.get("done_reason") == "length" else "stop"
return (
message.get("content"),
data.get("prompt_eval_count") or 0,
data.get("eval_count") or 0,
finish_reason,
)
def _call_openai_compat(
base_url: str,
api_key: str,
@@ -1449,73 +1566,39 @@ def _call_openai_compat(
# (#1621). Not a default — see _thinking_disabled_via_env for the tradeoff.
elif _thinking_disabled_via_env():
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
# than that — the symptom is hollow 200 OK responses after the first few
# chunks (#798). We derive num_ctx from the actual prompt size so we don't
# over-allocate KV-cache VRAM. Over-allocation (e.g. 128k slots for an 8k
# prompt on a 31B model) exhausts VRAM by chunk 4 and produces the same
# hollow-200 symptom — just from a different direction (#798 follow-up).
# Formula: actual input tokens + output cap + system prompt headroom.
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
# The ollama num_ctx auto-derive is a default. A custom provider that
# explicitly sets extra_body has opted out — respect their request shape.
if backend == "ollama" and extra_body is None:
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
# Auto-derive num_ctx from actual chunk size regardless — used as the
# fallback and for the mismatch check below.
estimated_input = len(user_message) // _CHARS_PER_TOKEN + 400
auto_num_ctx = min(estimated_input + max_completion_tokens + 2000, 131072)
auto_num_ctx = max(auto_num_ctx, 8192)
if num_ctx_raw:
try:
num_ctx = int(num_ctx_raw)
except ValueError:
# Bad env var: fall through to auto-derivation (not 131072 —
# hardcoding the cap is what causes OOM on constrained VRAM).
print(
f"[graphify] GRAPHIFY_OLLAMA_NUM_CTX={num_ctx_raw!r} is not a valid integer; "
f"using auto-derived value ({auto_num_ctx}).",
file=sys.stderr,
)
num_ctx = auto_num_ctx
else:
# Warn when the pinned value is smaller than the estimated input —
# Ollama silently truncates the prompt and returns empty responses.
if num_ctx < estimated_input:
print(
f"[graphify] warning: GRAPHIFY_OLLAMA_NUM_CTX={num_ctx} is smaller than "
f"the estimated chunk input (~{estimated_input} tokens). Ollama will "
f"silently truncate the prompt and return empty responses. "
f"Try --token-budget {max(1024, num_ctx // 3)} or increase NUM_CTX.",
file=sys.stderr,
)
else:
# Estimate input tokens: user_message chars / 4 (standard BPE
# heuristic) + 400 for the system prompt, then add output headroom.
num_ctx = auto_num_ctx
keep_alive = os.environ.get("GRAPHIFY_OLLAMA_KEEP_ALIVE", "30m")
# Merge, don't assign: GRAPHIFY_DISABLE_THINKING may have set extra_body
# above, and replacing it here made the flag silently inert on ollama (#3988).
kwargs["extra_body"] = {
**kwargs.get("extra_body", {}),
"options": {"num_ctx": num_ctx},
"keep_alive": keep_alive,
**_ollama_request_extras(user_message, max_completion_tokens),
}
resp = client.chat.completions.create(**kwargs)
if not resp.choices or resp.choices[0].message is None:
raise ValueError("LLM returned empty or filtered response")
raw_content = resp.choices[0].message.content
native = None
if backend == "ollama" and extra_body is None:
native = _call_ollama_native(client, base_url, kwargs, user_message, images or [])
if native is not None:
raw_content, input_tokens, output_tokens, finish_reason = native
else:
resp = client.chat.completions.create(**kwargs)
if not resp.choices or resp.choices[0].message is None:
raise ValueError("LLM returned empty or filtered response")
raw_content = resp.choices[0].message.content
# Some OpenAI-compatible gateways report null token counts (#4325) — coerce
# to 0 so the ollama low-token warning and the per-chunk merge below don't
# crash comparing/adding None.
input_tokens = (resp.usage.prompt_tokens or 0) if resp.usage else 0
output_tokens = (resp.usage.completion_tokens or 0) if resp.usage else 0
finish_reason = resp.choices[0].finish_reason
result = _parse_llm_json(raw_content or "{}")
# Some OpenAI-compatible gateways report null token counts (#4325) — coerce
# to 0 so the ollama low-token warning and the per-chunk merge below don't
# crash comparing/adding None.
result["input_tokens"] = (resp.usage.prompt_tokens or 0) if resp.usage else 0
result["output_tokens"] = (resp.usage.completion_tokens or 0) if resp.usage else 0
result["input_tokens"] = input_tokens
result["output_tokens"] = output_tokens
result["model"] = model
# `finish_reason == "length"` means the model hit max_completion_tokens
# mid-generation. The JSON we got back is truncated; callers should
# treat this as a signal to retry with smaller input.
result["finish_reason"] = resp.choices[0].finish_reason
result["finish_reason"] = finish_reason
# An overwhelmed local model (typically Ollama) can return HTTP 200 with
# empty / null content or unparseable half-generated JSON. The call looks
# successful, `finish_reason` is `"stop"`, and the chunk would be silently
@@ -3133,6 +3216,18 @@ def _call_llm(
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
elif _thinking_disabled_via_env():
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
# Community-labeling batches are sized for a 16k context, so without this
# Ollama cut them to its default the same way as extraction chunks (#4413).
if backend == "ollama" and cfg.get("extra_body") is None:
kwargs["extra_body"] = {
**kwargs.get("extra_body", {}),
**_ollama_request_extras(prompt, max_tokens),
}
native = _call_ollama_native(client, cfg["base_url"], kwargs, prompt, [])
if native is not None:
content, input_tokens, output_tokens, _finish = native
_rec(input_tokens, output_tokens)
return content or ""
resp = client.chat.completions.create(**kwargs)
if not resp.choices or resp.choices[0].message is None:
raise ValueError("LLM returned empty or filtered response")
+51 -20
View File
@@ -545,12 +545,33 @@ def _install_fake_openai(monkeypatch, fake_resp):
self.completions = self
def create(self, **__):
return fake_resp
def post(self, *_, **__):
# The ollama backend talks to Ollama's native /api/chat (#4413).
return _native_ollama_reply(fake_resp)
fake_module = types.ModuleType("openai")
fake_module.OpenAI = _FakeOpenAI
fake_module.APIStatusError = _FakeAPIStatusError
monkeypatch.setitem(sys.modules, "openai", fake_module)
class _FakeAPIStatusError(Exception):
def __init__(self, message, status_code):
super().__init__(message)
self.status_code = status_code
def _native_ollama_reply(fake_resp):
"""Re-shape a fake ChatCompletion as Ollama's /api/chat reply."""
choice = fake_resp.choices[0]
return {
"message": {"role": "assistant", "content": choice.message.content},
"done_reason": choice.finish_reason,
"prompt_eval_count": fake_resp.usage.prompt_tokens,
"eval_count": fake_resp.usage.completion_tokens,
}
def test_call_openai_compat_labels_empty_content_hollow(monkeypatch):
# Simulates an overwhelmed Ollama: HTTP 200, empty content, finish_reason
# "stop", zero completion tokens. The chunk must not be dropped silently,
@@ -650,8 +671,20 @@ def _install_capturing_openai(monkeypatch):
completion_tokens=100,
)
def post(self, path, *, body, **__):
# Ollama's native /api/chat request (#4413), kept apart from the
# /v1 kwargs so tests can tell which endpoint was used.
captured["native_url"] = path
captured["native"] = body
return _native_ollama_reply(_fake_openai_response(
'{"nodes":[{"id":"x"}],"edges":[],"hyperedges":[]}',
finish_reason="stop",
completion_tokens=100,
))
fake_module = types.ModuleType("openai")
fake_module.OpenAI = _FakeOpenAI
fake_module.APIStatusError = _FakeAPIStatusError
monkeypatch.setitem(sys.modules, "openai", fake_module)
return captured
@@ -742,12 +775,11 @@ def test_ollama_seed_is_top_level_and_preserves_extra_body(monkeypatch, raw, exp
backend="ollama",
)
assert captured["seed"] == expected
assert captured["extra_body"] == {
"thinking": {"type": "disabled"},
"options": {"num_ctx": 65536},
"keep_alive": "30m",
}
native = captured["native"]
assert native["options"]["seed"] == expected
assert native["options"]["num_ctx"] == 65536
assert native["keep_alive"] == "30m"
assert native["think"] is False
@pytest.mark.parametrize("raw", [None, "", " "])
@@ -764,7 +796,7 @@ def test_ollama_seed_disabled_omits_request_key(monkeypatch, raw):
backend="ollama",
)
assert "seed" not in captured
assert "seed" not in captured["native"]["options"]
def test_call_llm_ollama_forwards_seed(monkeypatch):
@@ -774,7 +806,7 @@ def test_call_llm_ollama_forwards_seed(monkeypatch):
llm._call_llm("label this", backend="ollama")
assert captured["seed"] == 7
assert captured["native"]["options"]["seed"] == 7
def test_call_llm_invalid_ollama_seed_fails_before_api_key_lookup(monkeypatch):
@@ -840,12 +872,12 @@ def test_ollama_extra_body_sets_num_ctx_and_keep_alive(monkeypatch):
"user msg", temperature=0, max_completion_tokens=8192, backend="ollama",
)
assert "extra_body" in captured, "extra_body must be sent to Ollama"
eb = captured["extra_body"]
assert "native" in captured, "options must be sent to Ollama's /api/chat"
native = captured["native"]
# num_ctx is now dynamic: derived from message size, not hardcoded 131072
assert "num_ctx" in eb.get("options", {}), "num_ctx must be present"
assert eb["options"]["num_ctx"] >= 8192, "num_ctx must be at least the floor value"
assert eb.get("keep_alive") == "30m", "default keep_alive must be 30m"
assert "num_ctx" in native["options"], "num_ctx must be present"
assert native["options"]["num_ctx"] >= 8192, "num_ctx must be at least the floor value"
assert native.get("keep_alive") == "30m", "default keep_alive must be 30m"
def test_ollama_num_ctx_scales_with_small_token_budget(monkeypatch):
@@ -864,7 +896,7 @@ def test_ollama_num_ctx_scales_with_small_token_budget(monkeypatch):
small_chunk_msg, temperature=0, max_completion_tokens=16384, backend="ollama",
)
num_ctx = captured["extra_body"]["options"]["num_ctx"]
num_ctx = captured["native"]["options"]["num_ctx"]
# Should be far less than 131072 for an 8k input — VRAM-friendly
assert num_ctx < 131072, (
f"num_ctx={num_ctx} is too large for a small chunk; "
@@ -884,7 +916,7 @@ def test_ollama_num_ctx_env_override(monkeypatch):
"u", temperature=0, max_completion_tokens=8192, backend="ollama",
)
assert captured["extra_body"]["options"]["num_ctx"] == 65536
assert captured["native"]["options"]["num_ctx"] == 65536
def test_non_ollama_backend_gets_no_num_ctx_extra_body(monkeypatch):
@@ -1004,11 +1036,10 @@ def test_ollama_thinking_disabled_via_env_survives_num_ctx(monkeypatch):
"u", temperature=0, max_completion_tokens=8192, backend="ollama",
)
assert captured["extra_body"] == {
"thinking": {"type": "disabled"},
"options": {"num_ctx": 65536},
"keep_alive": "30m",
}
native = captured["native"]
assert native["think"] is False
assert native["options"]["num_ctx"] == 65536
assert native["keep_alive"] == "30m"
def test_call_openai_compat_explicit_extra_body_skips_ollama_auto_derive(monkeypatch):
+221
View File
@@ -0,0 +1,221 @@
"""#4413 - Ollama's OpenAI-compatible /v1 endpoint ignores `options`, so the
derived num_ctx never reached the server and prompts were cut to Ollama's
default context. The ollama backend now uses the native /api/chat endpoint,
and falls back to /v1 for servers that don't have it.
"""
from __future__ import annotations
import sys
import types
import pytest
from graphify import llm
class _StatusError(Exception):
def __init__(self, message, status_code):
super().__init__(message)
self.status_code = status_code
def _reply(content='{"nodes":[{"id":"x"}],"edges":[],"hyperedges":[]}', done_reason="stop"):
return {
"message": {"role": "assistant", "content": content},
"done_reason": done_reason,
"prompt_eval_count": 6316,
"eval_count": 901,
}
def _install(monkeypatch, *, post_error=None, reply=None):
calls = {"post": [], "create": []}
class _Resp:
class _Choice:
class message:
content = '{"nodes":[{"id":"v1"}],"edges":[],"hyperedges":[]}'
finish_reason = "stop"
class usage:
prompt_tokens = 4096
completion_tokens = 50
choices = [_Choice()]
class _FakeOpenAI:
def __init__(self, *_, **__):
self.chat = self
self.completions = self
def create(self, **kwargs):
calls["create"].append(kwargs)
return _Resp()
def post(self, path, *, body, cast_to):
calls["post"].append((path, body))
if post_error is not None:
raise post_error
return reply if reply is not None else _reply()
mod = types.ModuleType("openai")
mod.OpenAI = _FakeOpenAI
mod.APIStatusError = _StatusError
monkeypatch.setitem(sys.modules, "openai", mod)
monkeypatch.setattr(llm, "_OLLAMA_NO_NATIVE", set(), raising=False)
monkeypatch.delenv("GRAPHIFY_OLLAMA_NUM_CTX", raising=False)
monkeypatch.delenv("GRAPHIFY_OLLAMA_KEEP_ALIVE", raising=False)
monkeypatch.delenv("GRAPHIFY_DISABLE_THINKING", raising=False)
return calls
def _call(base_url="http://localhost:11434/v1", **kwargs):
return llm._call_openai_compat(
base_url, "ollama", "qwen2.5:14b", "x" * 40_000,
temperature=0, max_completion_tokens=8192, backend="ollama", **kwargs,
)
def test_ollama_uses_native_chat_with_num_ctx(monkeypatch):
calls = _install(monkeypatch)
result = _call()
assert calls["create"] == []
path, body = calls["post"][0]
assert path == "http://localhost:11434/api/chat"
assert body["model"] == "qwen2.5:14b"
assert body["stream"] is False
assert [m["role"] for m in body["messages"]] == ["system", "user"]
assert body["messages"][1]["content"].endswith("x" * 100)
# 40k chars is ~10k tokens; num_ctx must cover it plus the output cap.
assert body["options"]["num_ctx"] > 10_000 + 8192
assert body["options"]["num_predict"] == 8192
assert body["options"]["temperature"] == 0
assert body["keep_alive"] == "30m"
assert "think" not in body
assert result["nodes"] == [{"id": "x"}]
assert result["input_tokens"] == 6316
assert result["output_tokens"] == 901
assert result["finish_reason"] == "stop"
@pytest.mark.parametrize("base_url", [
"http://localhost:11434/v1",
"http://localhost:11434/v1/",
"http://localhost:11434",
])
def test_native_url_drops_the_v1_suffix(monkeypatch, base_url):
calls = _install(monkeypatch)
_call(base_url)
assert calls["post"][0][0] == "http://localhost:11434/api/chat"
def test_native_length_maps_to_length(monkeypatch):
_install(monkeypatch, reply=_reply('{"nodes": [{"id":', done_reason="length"))
assert _call()["finish_reason"] == "length"
def test_native_empty_reply_is_hollow(monkeypatch):
_install(monkeypatch, reply=_reply(""))
assert _call()["finish_reason"] == "hollow"
def test_native_sends_images(monkeypatch, tmp_path):
calls = _install(monkeypatch)
ref = llm._ImageRef(path=tmp_path / "a.png", rel="a.png", media_type="image/png", raw=b"\x89PNG")
_call(images=[ref])
user = calls["post"][0][1]["messages"][1]
assert user["images"] == [ref.b64]
assert "a.png" in user["content"]
def test_server_without_native_chat_falls_back_to_v1_once(monkeypatch, capsys):
calls = _install(monkeypatch, post_error=_StatusError("Unexpected endpoint or method.", 404))
first = _call("http://127.0.0.1:1234/v1")
second = _call("http://127.0.0.1:1234/v1")
assert len(calls["post"]) == 1, "a /v1-only server must not be probed on every chunk"
assert len(calls["create"]) == 2
assert first["nodes"] == [{"id": "v1"}]
assert second["input_tokens"] == 4096
assert "falling back" in capsys.readouterr().err
def test_unknown_model_is_raised_not_treated_as_missing_endpoint(monkeypatch):
calls = _install(
monkeypatch,
post_error=_StatusError("Error code: 404 - {'error': \"model 'nope' not found\"}", 404),
)
with pytest.raises(_StatusError):
_call()
assert calls["create"] == []
assert llm._OLLAMA_NO_NATIVE == set()
def test_other_server_errors_are_raised(monkeypatch):
calls = _install(monkeypatch, post_error=_StatusError("internal error", 500))
with pytest.raises(_StatusError):
_call()
assert calls["create"] == []
def test_explicit_extra_body_keeps_v1(monkeypatch):
calls = _install(monkeypatch)
_call(extra_body={"options": {"num_ctx": 4096}})
assert calls["post"] == []
assert calls["create"][0]["extra_body"] == {"options": {"num_ctx": 4096}}
def test_other_backends_never_use_native_chat(monkeypatch):
calls = _install(monkeypatch)
llm._call_openai_compat(
"https://api.openai.com/v1", "sk-test", "gpt-4.1-mini", "u",
temperature=0, max_completion_tokens=8192, backend="openai",
)
assert calls["post"] == []
assert len(calls["create"]) == 1
def test_call_llm_ollama_uses_native_chat(monkeypatch):
# Community labeling goes through _call_llm; its batches are sized for a
# 16k context and were cut to Ollama's default the same way (#4413).
calls = _install(monkeypatch, reply=_reply("Console Rendering"))
monkeypatch.setattr(llm, "_get_backend_api_key", lambda _backend: "ollama")
usage: dict = {}
out = llm._call_llm("y" * 40_000, backend="ollama", max_tokens=1024, usage_out=usage)
assert out == "Console Rendering"
assert calls["create"] == []
path, body = calls["post"][0]
assert path.endswith("/api/chat")
assert [m["role"] for m in body["messages"]] == ["user"]
assert body["options"]["num_ctx"] > 10_000
assert body["options"]["num_predict"] == 1024
assert usage == {"input": 6316, "output": 901}
def test_call_llm_ollama_falls_back_to_v1(monkeypatch):
calls = _install(monkeypatch, post_error=_StatusError("Unexpected endpoint or method.", 404))
monkeypatch.setattr(llm, "_get_backend_api_key", lambda _backend: "ollama")
out = llm._call_llm("label this", backend="ollama")
assert len(calls["create"]) == 1
assert out.startswith('{"nodes"')
+7
View File
@@ -27,6 +27,13 @@ def _capture_client_kwargs(monkeypatch):
resp.usage.prompt_tokens = 1
resp.usage.completion_tokens = 1
client.chat.completions.create.return_value = resp
# The ollama backend goes through Ollama's native /api/chat (#4413).
client.post.return_value = {
"message": {"content": '{"nodes": [], "edges": [], "hyperedges": []}'},
"done_reason": "stop",
"prompt_eval_count": 1,
"eval_count": 1,
}
return client
monkeypatch.setattr("openai.OpenAI", _factory)