@@ -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+
13851502def _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" )
0 commit comments