Skip to content

Commit f48425e

Browse files
smngvlkzsafishamsi
authored andcommitted
send ollama requests to /api/chat so num_ctx actually applies
(cherry picked from commit 5f7b2b4)
1 parent 990ab1b commit f48425e

4 files changed

Lines changed: 428 additions & 74 deletions

File tree

‎graphify/llm.py‎

Lines changed: 149 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1382,6 +1382,123 @@ def _backend_pkg_hint(pkg: str, extra: str) -> str:
13821382
)
13831383

13841384

1385+
def _ollama_request_extras(user_message: str, max_completion_tokens: int) -> dict:
1386+
"""num_ctx/keep_alive for an Ollama request, sized to the prompt."""
1387+
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
1388+
# than that — the symptom is hollow 200 OK responses after the first few
1389+
# chunks (#798). We derive num_ctx from the actual prompt size so we don't
1390+
# over-allocate KV-cache VRAM. Over-allocation (e.g. 128k slots for an 8k
1391+
# prompt on a 31B model) exhausts VRAM by chunk 4 and produces the same
1392+
# hollow-200 symptom — just from a different direction (#798 follow-up).
1393+
# Formula: actual input tokens + output cap + system prompt headroom.
1394+
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
1395+
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
1396+
# Auto-derive num_ctx from actual chunk size regardless — used as the
1397+
# fallback and for the mismatch check below.
1398+
estimated_input = len(user_message) // _CHARS_PER_TOKEN + 400
1399+
auto_num_ctx = min(estimated_input + max_completion_tokens + 2000, 131072)
1400+
auto_num_ctx = max(auto_num_ctx, 8192)
1401+
if num_ctx_raw:
1402+
try:
1403+
num_ctx = int(num_ctx_raw)
1404+
except ValueError:
1405+
# Bad env var: fall through to auto-derivation (not 131072 —
1406+
# hardcoding the cap is what causes OOM on constrained VRAM).
1407+
print(
1408+
f"[graphify] GRAPHIFY_OLLAMA_NUM_CTX={num_ctx_raw!r} is not a valid integer; "
1409+
f"using auto-derived value ({auto_num_ctx}).",
1410+
file=sys.stderr,
1411+
)
1412+
num_ctx = auto_num_ctx
1413+
else:
1414+
# Warn when the pinned value is smaller than the estimated input —
1415+
# Ollama silently truncates the prompt and returns empty responses.
1416+
if num_ctx < estimated_input:
1417+
print(
1418+
f"[graphify] warning: GRAPHIFY_OLLAMA_NUM_CTX={num_ctx} is smaller than "
1419+
f"the estimated chunk input (~{estimated_input} tokens). Ollama will "
1420+
f"silently truncate the prompt and return empty responses. "
1421+
f"Try --token-budget {max(1024, num_ctx // 3)} or increase NUM_CTX.",
1422+
file=sys.stderr,
1423+
)
1424+
else:
1425+
# Estimate input tokens: user_message chars / 4 (standard BPE
1426+
# heuristic) + 400 for the system prompt, then add output headroom.
1427+
num_ctx = auto_num_ctx
1428+
keep_alive = os.environ.get("GRAPHIFY_OLLAMA_KEEP_ALIVE", "30m")
1429+
return {"options": {"num_ctx": num_ctx}, "keep_alive": keep_alive}
1430+
1431+
1432+
# Ollama's OpenAI-compatible /v1 endpoint ignores `options`, so the num_ctx
1433+
# from _ollama_request_extras never reached the server and every prompt was cut
1434+
# to Ollama's default context (4096 on Ollama 0.17.5) — the model lost the JSON
1435+
# instructions and answered in prose (#4413). The native /api/chat endpoint honours it. Servers
1436+
# that only speak /v1 (LM Studio, llama.cpp behind the ollama backend) 404 on
1437+
# /api/chat; remember them so each chunk doesn't pay for a failed request.
1438+
_OLLAMA_NO_NATIVE: set[str] = set()
1439+
1440+
1441+
def _call_ollama_native(
1442+
client,
1443+
base_url: str,
1444+
kwargs: dict,
1445+
user_message: str,
1446+
images: list[_ImageRef],
1447+
) -> tuple[str | None, int, int, str] | None:
1448+
"""Send an ollama request to /api/chat. Returns None when the server has no
1449+
native endpoint, so the caller falls back to /v1."""
1450+
root = base_url.rstrip("/")
1451+
if root.endswith("/v1"):
1452+
root = root[: -len("/v1")]
1453+
if root in _OLLAMA_NO_NATIVE:
1454+
return None
1455+
from openai import APIStatusError
1456+
1457+
extra = kwargs.get("extra_body", {})
1458+
options = dict(extra.get("options", {}))
1459+
options["num_predict"] = kwargs["max_completion_tokens"]
1460+
if "temperature" in kwargs:
1461+
options["temperature"] = kwargs["temperature"]
1462+
if "seed" in kwargs:
1463+
options["seed"] = kwargs["seed"]
1464+
user: dict = {"role": "user", "content": _with_image_notes(user_message, images)}
1465+
pixels = [r.b64 for r in images if r.raw]
1466+
if pixels:
1467+
user["images"] = pixels
1468+
body: dict = {
1469+
"model": kwargs["model"],
1470+
"messages": [*kwargs["messages"][:-1], user],
1471+
"stream": False,
1472+
"options": options,
1473+
"keep_alive": extra.get("keep_alive", "30m"),
1474+
}
1475+
if _thinking_disabled_via_env():
1476+
body["think"] = False
1477+
try:
1478+
data = client.post(f"{root}/api/chat", body=body, cast_to=object)
1479+
except APIStatusError as exc:
1480+
# Ollama also 404s on an unknown model; surface that instead of
1481+
# marking a real Ollama server as non-native.
1482+
if exc.status_code not in (404, 405) or "model" in str(exc).lower():
1483+
raise
1484+
_OLLAMA_NO_NATIVE.add(root)
1485+
print(
1486+
f"[graphify] {root}/api/chat is not available; falling back to the "
1487+
"OpenAI-compatible /v1 endpoint, which ignores num_ctx.",
1488+
file=sys.stderr,
1489+
)
1490+
return None
1491+
data = data or {}
1492+
message = data.get("message") or {}
1493+
finish_reason = "length" if data.get("done_reason") == "length" else "stop"
1494+
return (
1495+
message.get("content"),
1496+
data.get("prompt_eval_count") or 0,
1497+
data.get("eval_count") or 0,
1498+
finish_reason,
1499+
)
1500+
1501+
13851502
def _call_openai_compat(
13861503
base_url: str,
13871504
api_key: str,
@@ -1449,73 +1566,39 @@ def _call_openai_compat(
14491566
# (#1621). Not a default — see _thinking_disabled_via_env for the tradeoff.
14501567
elif _thinking_disabled_via_env():
14511568
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
1452-
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
1453-
# than that — the symptom is hollow 200 OK responses after the first few
1454-
# chunks (#798). We derive num_ctx from the actual prompt size so we don't
1455-
# over-allocate KV-cache VRAM. Over-allocation (e.g. 128k slots for an 8k
1456-
# prompt on a 31B model) exhausts VRAM by chunk 4 and produces the same
1457-
# hollow-200 symptom — just from a different direction (#798 follow-up).
1458-
# Formula: actual input tokens + output cap + system prompt headroom.
1459-
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
14601569
# The ollama num_ctx auto-derive is a default. A custom provider that
14611570
# explicitly sets extra_body has opted out — respect their request shape.
14621571
if backend == "ollama" and extra_body is None:
1463-
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
1464-
# Auto-derive num_ctx from actual chunk size regardless — used as the
1465-
# fallback and for the mismatch check below.
1466-
estimated_input = len(user_message) // _CHARS_PER_TOKEN + 400
1467-
auto_num_ctx = min(estimated_input + max_completion_tokens + 2000, 131072)
1468-
auto_num_ctx = max(auto_num_ctx, 8192)
1469-
if num_ctx_raw:
1470-
try:
1471-
num_ctx = int(num_ctx_raw)
1472-
except ValueError:
1473-
# Bad env var: fall through to auto-derivation (not 131072 —
1474-
# hardcoding the cap is what causes OOM on constrained VRAM).
1475-
print(
1476-
f"[graphify] GRAPHIFY_OLLAMA_NUM_CTX={num_ctx_raw!r} is not a valid integer; "
1477-
f"using auto-derived value ({auto_num_ctx}).",
1478-
file=sys.stderr,
1479-
)
1480-
num_ctx = auto_num_ctx
1481-
else:
1482-
# Warn when the pinned value is smaller than the estimated input —
1483-
# Ollama silently truncates the prompt and returns empty responses.
1484-
if num_ctx < estimated_input:
1485-
print(
1486-
f"[graphify] warning: GRAPHIFY_OLLAMA_NUM_CTX={num_ctx} is smaller than "
1487-
f"the estimated chunk input (~{estimated_input} tokens). Ollama will "
1488-
f"silently truncate the prompt and return empty responses. "
1489-
f"Try --token-budget {max(1024, num_ctx // 3)} or increase NUM_CTX.",
1490-
file=sys.stderr,
1491-
)
1492-
else:
1493-
# Estimate input tokens: user_message chars / 4 (standard BPE
1494-
# heuristic) + 400 for the system prompt, then add output headroom.
1495-
num_ctx = auto_num_ctx
1496-
keep_alive = os.environ.get("GRAPHIFY_OLLAMA_KEEP_ALIVE", "30m")
14971572
# Merge, don't assign: GRAPHIFY_DISABLE_THINKING may have set extra_body
14981573
# above, and replacing it here made the flag silently inert on ollama (#3988).
14991574
kwargs["extra_body"] = {
15001575
**kwargs.get("extra_body", {}),
1501-
"options": {"num_ctx": num_ctx},
1502-
"keep_alive": keep_alive,
1576+
**_ollama_request_extras(user_message, max_completion_tokens),
15031577
}
1504-
resp = client.chat.completions.create(**kwargs)
1505-
if not resp.choices or resp.choices[0].message is None:
1506-
raise ValueError("LLM returned empty or filtered response")
1507-
raw_content = resp.choices[0].message.content
1578+
native = None
1579+
if backend == "ollama" and extra_body is None:
1580+
native = _call_ollama_native(client, base_url, kwargs, user_message, images or [])
1581+
if native is not None:
1582+
raw_content, input_tokens, output_tokens, finish_reason = native
1583+
else:
1584+
resp = client.chat.completions.create(**kwargs)
1585+
if not resp.choices or resp.choices[0].message is None:
1586+
raise ValueError("LLM returned empty or filtered response")
1587+
raw_content = resp.choices[0].message.content
1588+
# Some OpenAI-compatible gateways report null token counts (#4325) — coerce
1589+
# to 0 so the ollama low-token warning and the per-chunk merge below don't
1590+
# crash comparing/adding None.
1591+
input_tokens = (resp.usage.prompt_tokens or 0) if resp.usage else 0
1592+
output_tokens = (resp.usage.completion_tokens or 0) if resp.usage else 0
1593+
finish_reason = resp.choices[0].finish_reason
15081594
result = _parse_llm_json(raw_content or "{}")
1509-
# Some OpenAI-compatible gateways report null token counts (#4325) — coerce
1510-
# to 0 so the ollama low-token warning and the per-chunk merge below don't
1511-
# crash comparing/adding None.
1512-
result["input_tokens"] = (resp.usage.prompt_tokens or 0) if resp.usage else 0
1513-
result["output_tokens"] = (resp.usage.completion_tokens or 0) if resp.usage else 0
1595+
result["input_tokens"] = input_tokens
1596+
result["output_tokens"] = output_tokens
15141597
result["model"] = model
15151598
# `finish_reason == "length"` means the model hit max_completion_tokens
15161599
# mid-generation. The JSON we got back is truncated; callers should
15171600
# treat this as a signal to retry with smaller input.
1518-
result["finish_reason"] = resp.choices[0].finish_reason
1601+
result["finish_reason"] = finish_reason
15191602
# An overwhelmed local model (typically Ollama) can return HTTP 200 with
15201603
# empty / null content or unparseable half-generated JSON. The call looks
15211604
# successful, `finish_reason` is `"stop"`, and the chunk would be silently
@@ -3133,6 +3216,18 @@ def _rec(inp, out) -> None:
31333216
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
31343217
elif _thinking_disabled_via_env():
31353218
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
3219+
# Community-labeling batches are sized for a 16k context, so without this
3220+
# Ollama cut them to its default the same way as extraction chunks (#4413).
3221+
if backend == "ollama" and cfg.get("extra_body") is None:
3222+
kwargs["extra_body"] = {
3223+
**kwargs.get("extra_body", {}),
3224+
**_ollama_request_extras(prompt, max_tokens),
3225+
}
3226+
native = _call_ollama_native(client, cfg["base_url"], kwargs, prompt, [])
3227+
if native is not None:
3228+
content, input_tokens, output_tokens, _finish = native
3229+
_rec(input_tokens, output_tokens)
3230+
return content or ""
31363231
resp = client.chat.completions.create(**kwargs)
31373232
if not resp.choices or resp.choices[0].message is None:
31383233
raise ValueError("LLM returned empty or filtered response")

‎tests/test_llm_backends.py‎

Lines changed: 51 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -545,12 +545,33 @@ def __init__(self, *_, **__):
545545
self.completions = self
546546
def create(self, **__):
547547
return fake_resp
548+
def post(self, *_, **__):
549+
# The ollama backend talks to Ollama's native /api/chat (#4413).
550+
return _native_ollama_reply(fake_resp)
548551

549552
fake_module = types.ModuleType("openai")
550553
fake_module.OpenAI = _FakeOpenAI
554+
fake_module.APIStatusError = _FakeAPIStatusError
551555
monkeypatch.setitem(sys.modules, "openai", fake_module)
552556

553557

558+
class _FakeAPIStatusError(Exception):
559+
def __init__(self, message, status_code):
560+
super().__init__(message)
561+
self.status_code = status_code
562+
563+
564+
def _native_ollama_reply(fake_resp):
565+
"""Re-shape a fake ChatCompletion as Ollama's /api/chat reply."""
566+
choice = fake_resp.choices[0]
567+
return {
568+
"message": {"role": "assistant", "content": choice.message.content},
569+
"done_reason": choice.finish_reason,
570+
"prompt_eval_count": fake_resp.usage.prompt_tokens,
571+
"eval_count": fake_resp.usage.completion_tokens,
572+
}
573+
574+
554575
def test_call_openai_compat_labels_empty_content_hollow(monkeypatch):
555576
# Simulates an overwhelmed Ollama: HTTP 200, empty content, finish_reason
556577
# "stop", zero completion tokens. The chunk must not be dropped silently,
@@ -650,8 +671,20 @@ def create(self, **kwargs):
650671
completion_tokens=100,
651672
)
652673

674+
def post(self, path, *, body, **__):
675+
# Ollama's native /api/chat request (#4413), kept apart from the
676+
# /v1 kwargs so tests can tell which endpoint was used.
677+
captured["native_url"] = path
678+
captured["native"] = body
679+
return _native_ollama_reply(_fake_openai_response(
680+
'{"nodes":[{"id":"x"}],"edges":[],"hyperedges":[]}',
681+
finish_reason="stop",
682+
completion_tokens=100,
683+
))
684+
653685
fake_module = types.ModuleType("openai")
654686
fake_module.OpenAI = _FakeOpenAI
687+
fake_module.APIStatusError = _FakeAPIStatusError
655688
monkeypatch.setitem(sys.modules, "openai", fake_module)
656689
return captured
657690

@@ -742,12 +775,11 @@ def test_ollama_seed_is_top_level_and_preserves_extra_body(monkeypatch, raw, exp
742775
backend="ollama",
743776
)
744777

745-
assert captured["seed"] == expected
746-
assert captured["extra_body"] == {
747-
"thinking": {"type": "disabled"},
748-
"options": {"num_ctx": 65536},
749-
"keep_alive": "30m",
750-
}
778+
native = captured["native"]
779+
assert native["options"]["seed"] == expected
780+
assert native["options"]["num_ctx"] == 65536
781+
assert native["keep_alive"] == "30m"
782+
assert native["think"] is False
751783

752784

753785
@pytest.mark.parametrize("raw", [None, "", " "])
@@ -764,7 +796,7 @@ def test_ollama_seed_disabled_omits_request_key(monkeypatch, raw):
764796
backend="ollama",
765797
)
766798

767-
assert "seed" not in captured
799+
assert "seed" not in captured["native"]["options"]
768800

769801

770802
def test_call_llm_ollama_forwards_seed(monkeypatch):
@@ -774,7 +806,7 @@ def test_call_llm_ollama_forwards_seed(monkeypatch):
774806

775807
llm._call_llm("label this", backend="ollama")
776808

777-
assert captured["seed"] == 7
809+
assert captured["native"]["options"]["seed"] == 7
778810

779811

780812
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):
840872
"user msg", temperature=0, max_completion_tokens=8192, backend="ollama",
841873
)
842874

843-
assert "extra_body" in captured, "extra_body must be sent to Ollama"
844-
eb = captured["extra_body"]
875+
assert "native" in captured, "options must be sent to Ollama's /api/chat"
876+
native = captured["native"]
845877
# num_ctx is now dynamic: derived from message size, not hardcoded 131072
846-
assert "num_ctx" in eb.get("options", {}), "num_ctx must be present"
847-
assert eb["options"]["num_ctx"] >= 8192, "num_ctx must be at least the floor value"
848-
assert eb.get("keep_alive") == "30m", "default keep_alive must be 30m"
878+
assert "num_ctx" in native["options"], "num_ctx must be present"
879+
assert native["options"]["num_ctx"] >= 8192, "num_ctx must be at least the floor value"
880+
assert native.get("keep_alive") == "30m", "default keep_alive must be 30m"
849881

850882

851883
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):
864896
small_chunk_msg, temperature=0, max_completion_tokens=16384, backend="ollama",
865897
)
866898

867-
num_ctx = captured["extra_body"]["options"]["num_ctx"]
899+
num_ctx = captured["native"]["options"]["num_ctx"]
868900
# Should be far less than 131072 for an 8k input — VRAM-friendly
869901
assert num_ctx < 131072, (
870902
f"num_ctx={num_ctx} is too large for a small chunk; "
@@ -884,7 +916,7 @@ def test_ollama_num_ctx_env_override(monkeypatch):
884916
"u", temperature=0, max_completion_tokens=8192, backend="ollama",
885917
)
886918

887-
assert captured["extra_body"]["options"]["num_ctx"] == 65536
919+
assert captured["native"]["options"]["num_ctx"] == 65536
888920

889921

890922
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):
10041036
"u", temperature=0, max_completion_tokens=8192, backend="ollama",
10051037
)
10061038

1007-
assert captured["extra_body"] == {
1008-
"thinking": {"type": "disabled"},
1009-
"options": {"num_ctx": 65536},
1010-
"keep_alive": "30m",
1011-
}
1039+
native = captured["native"]
1040+
assert native["think"] is False
1041+
assert native["options"]["num_ctx"] == 65536
1042+
assert native["keep_alive"] == "30m"
10121043

10131044

10141045
def test_call_openai_compat_explicit_extra_body_skips_ollama_auto_derive(monkeypatch):

0 commit comments

Comments
 (0)