Skip to content

fix: send ollama requests to /api/chat so the context size is used - #4414

Closed
smngvlkz wants to merge 1 commit into
Graphify-Labs:v8from
smngvlkz:fix/ollama-native-num-ctx
Closed

smngvlkz wants to merge 1 commit into
Graphify-Labs:v8from
smngvlkz:fix/ollama-native-num-ctx

Conversation

@smngvlkz

Copy link
Copy Markdown
Contributor

Fixes #4413.

What this fixes

graphify works out a context size for each Ollama request, but it sends it to Ollama's /v1 address, which ignores it. So Ollama cut every prompt at its default (4096 for me), the model lost the part asking for JSON, and docs came back empty.

What changed

  • Ollama requests now go to Ollama's own /api/chat, which actually uses the context size. Same for the output limit, seed and the disable thinking setting.
  • This covers both places graphify talks to Ollama: reading files and naming communities.
  • If a server doesn't have /api/chat (like LM Studio or llama.cpp behind the ollama backend), graphify says so once and goes back to /v1 like before.
  • If you set your own extra_body in providers.json, nothing changes, it still goes through /v1.
  • Timeouts and retries work the same, it uses the same client as before.

How I tested it

With my local qwen2.5:14b, nothing else changed:

  • reading the same 2 docs: before, cut at 4,096 tokens and an empty graph after about 12 minutes. After, all 6,316 tokens read, JSON first try, about 4 minutes.
  • naming communities on rich (312 communities): before, the first batch was cut at 4,096 tokens and it took 8 requests. After, the full 7,468 tokens went through and it took 4 requests. All communities got names both times, the old code just needed extra retries to get there.

I also checked against my real Ollama:

  • a server with only /v1 is tried once, then graphify sticks to /v1
  • a model that doesn't exist still gives a clear "not found" error
  • disable thinking works on qwen2.5 and qwen3.5
  • works with openai 1.x and 3.x

Tests:

  • added tests for all of the above. They fail on current v8 and pass with this change, apart from the ones checking that other setups aren't affected
  • updated the existing Ollama tests to check the /api/chat request instead of the /v1 one
  • full test suite passes

Heads up

graphify's 30 min keep alive now actually reaches Ollama too. Before it was ignored and Ollama's own setting applied, so now the model unloads after 30 min idle unless you set GRAPHIFY_OLLAMA_KEEP_ALIVE.

@smngvlkz
smngvlkz requested a review from safishamsi as a code owner October 13, 2026 13:08
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @smngvlkz. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, and that the change keeps extraction deterministic.

@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Oct 13, 2026

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify reviewed this change.

Worth a look — the grounded gate found no coupling regressions or blocking issues, but 1 advisory finding(s) below merit a look before merge.

Not checked: tests were not run; formal verification proved 0 of 2 changed function(s) (2 not verified).

Formal verification. PR-changed functions: 0/2 verified (0 proven, 0 may-equivalent, 0 distinguished) · 2 not verified (1 vacuous, 1 error).

Not verified on this run: \_call\_llm (vacuous: never exercised), \_call\_openai\_compat (error).


Graphify review — findings

Sends Ollama extraction requests to the native /api/chat endpoint via _call_ollama_native, so the prompt-sized num_ctx reaches the server instead of being dropped by the OpenAI-compatible /v1 endpoint. If a server 404s or 405s on /api/chat for a reason other than an unknown model (LM Studio, llama.cpp), it falls back to /v1 and remembers that root so later chunks skip the probe, at the cost of num_ctx being ignored again. The sizing logic now lives in _ollama_request_extras, which also applies num_ctx and keep_alive to _call_llm so community-labeling batches aren't cut to Ollama's default context either.

Worth a look

  • Ollama _call_llm path still sends num_ctx only to /v1 — graphify/llm.py:3206 · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 1057 functions depend on the 361 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: _call_llm() — 17 callers, 21 callees
  • worse: _call_openai_compat() — 32 callers, 11 callees

Verification — 1057 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 631 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

50 of 413 test file(s) selected (12%) via static blast radius.

  • tests/test_backend_env_isolation.py — impact
  • tests/test_backend_extras.py — impact
  • tests/test_build.py — impact
  • tests/test_build_located_semantic_identity.py — impact
  • tests/test_build_merge_dedup_scope.py — impact
  • tests/test_build_merge_hyperedges_and_prune.py — impact
  • tests/test_build_merge_shrink_guard.py — impact
  • tests/test_c_include_resolution.py — impact
  • tests/test_carried_hyperedge_remap.py — impact
  • tests/test_charmap_encoding.py — impact
  • tests/test_chunking.py — impact
  • tests/test_claude_cli_backend.py — impact
  • tests/test_corrupt_graph_json.py — impact
  • tests/test_cross_extension_reexport_self_cycle.py — impact
  • tests/test_dedup.py — impact
  • tests/test_dedup_remaps_hyperedges.py — impact
  • tests/test_dedup_shrink_refuses_force_write.py — impact
  • tests/test_dedup_survivor_richness.py — impact
  • tests/test_evidence_binding.py — impact
  • tests/test_file_slice.py — impact
  • tests/test_file_truncation_warning.py — impact
  • tests/test_global_graph.py — impact
  • tests/test_go_qualified_resolution.py — impact
  • tests/test_hyperedge_member_shapes.py — impact
  • tests/test_image_vision.py — impact
  • tests/test_injection_sentinel_coverage.py — impact
  • tests/test_issue_3472_source_file_collision.py — impact
  • tests/test_label_retry.py — impact
  • tests/test_labeling.py — impact
  • tests/test_llm_backends.py — impact, changed-test
  • tests/test_llm_null_token_counts.py — impact
  • tests/test_llm_parser.py — impact
  • tests/test_llm_parser_reasoning.py — impact
  • tests/test_no_dedup_flag.py — impact
  • tests/test_non_string_node_ids.py — impact
  • tests/test_ollama.py — impact
  • tests/test_ollama_native_chat.py — impact, changed-test
  • tests/test_ollama_retry_cap.py — impact, changed-test
  • tests/test_oversized_document_slicing.py — impact
  • tests/test_partial_cache.py — impact
  • tests/test_pdf_slicing.py — impact
  • tests/test_pdf_token_estimate.py — impact
  • tests/test_provider_registry.py — impact
  • tests/test_prs.py — impact
  • tests/test_prune_sweeps_orphans.py — impact
  • tests/test_r_extractor.py — impact
  • tests/test_semantic_fragment_sanitize.py — impact
  • tests/test_semantic_origin_stamp.py — impact
  • tests/test_source_file_encoding.py — impact
  • tests/test_unverified_semantic_shrink.py — impact

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Docs that may be stale (advisory)

…and 10 more.

Formal verification

Could not verify: Could not verify \_call\_llm.

The verifier did not have enough to check \_call\_llm, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 40 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly TypeError — names the real obstacle, not a sampling gap)

Verification did not run: Verification did not run for \_call\_openai\_compat.

The verification could not execute (an environment/toolchain issue, not a statement about the code).

Guarantee: No guarantee, the check itself did not complete.

Note: Detail: harness produced no verdict (rc=124): timeout after 30s

· 1 grounded finding(s) anchored inline below; 1 more finding(s) on lines outside this diff (see the check run).

Comment thread graphify/llm.py
)


def _call_openai_compat(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — _call_openai_compat()

fans out to 11 callees (efferent coupling); 32 callers depend on it (afferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

safishamsi added a commit that referenced this pull request Oct 14, 2026
Eight community PRs: Windows MCP-stdio hang (#4441), Rust use->declaration
(#4443), JS/TS file-scope callback param shadowing (#4457), sibling-file-id
symbol retention (#4452), TS class-field receiver scoping (#4297), Ollama
/api/chat num_ctx (#4414), cluster label retention on majority overlap (#4451),
and an ingest symlink test fix (#4442). AST cache schema bumped to 16.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Landed in 0.9.91 as f48425e (cherry-picked with your authorship preserved, so it shows on your contributions). Thanks @smngvlkz! Released to PyPI: https://pypi.org/project/graphifyy/0.9.91/

@safishamsi safishamsi closed this Oct 14, 2026

@nothariharan nothariharan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

I verified this against a live Ollama server rather than only the suite. Setup: Ollama 0.32.13, qwen2.5:3b-instruct, Windows, graphify at base v8 and at this branch.

The premise holds, and it bites earlier than the issue suggests

Pinning options.num_ctx at three values and sending the same prompt to both endpoints:

endpoint no options num_ctx=512 num_ctx=16384
/api/chat 2050 258 8194
/v1/chat/completions 2050 2050 2050

/v1 is completely indifferent to options. Note that the practical cutoff on default settings is 2048 tokens, not 4096: Ollama only gives a prompt half of num_ctx, so the bug fires on shorter prompts than reported.

Base vs this branch, same chunk

A single 74,619-char extraction chunk through _call_openai_compat with backend="ollama":

  • base v8: input_tokens: 0, elapsed 195.4s, empty extraction
  • this branch: input_tokens: 14625, elapsed 27.0s

Same for the community-labeling path via _call_llm: base reported no usage at all, this branch reported {'input': 16386, 'output': 64}. The 195s on base is the retry layer re-running a hollow chunk, which matches the "empty graph after 12 minutes" symptom.

Full suite on this branch: 7640 passed, 10 failed. All 10 fail identically on unmodified base v8 (Windows path and symlink tests in test_hooks, test_ingest_url_type, test_install_references, test_resolve_memoization, test_source_key_memoization, test_unmapped_at_alias_resolution). No regressions.

The unknown-model guard is correct. Ollama returns 404 with {"error":"model 'nope:9b' not found"} from /api/chat, which contains "model", so _call_ollama_native re-raises instead of poisoning _OLLAMA_NO_NATIVE. Good instinct handling that.

The one thing I would change before merge

num_ctx needs to be roughly 2x the prompt, and the formula does not do that. Ollama allocates num_ctx / 2 to the prompt and reserves the rest, independent of num_predict. Measured with num_predict at 8, 4096 and -1:

num_ctx prompt tokens accepted
2048 1026
4096 2050
8192 4098
16384 8194
32768 16386

_ollama_request_extras at llm.py:1398 builds estimated_input + max_completion_tokens + 2000, which assumes the prompt can use essentially all of num_ctx. Only half is available, so the effective input budget is (estimated_input + max_completion_tokens + 2000) / 2. The max_completion_tokens term happens to carry half the load, which is why it mostly works in practice, but the explicit +2000 headroom is about half of what the formula implies.

Concretely, with max_completion_tokens=16384 (the ollama default) and the system prompt measuring 769 real tokens, a chunk is still truncated when:

  • code: estimated_input > ~10,300 tokens, about 41k chars
  • devanagari: estimated_input > ~2,500 tokens, about 10k chars

Computing num_ctx as 2 * (estimated_input + system_headroom) + max_completion_tokens closes it. My 74k-char chunk landed at 14,625 real tokens against a 14,623 budget, truncated by 2: right on the line.

Related: _CHARS_PER_TOKEN = 4 under-estimates by script. Measured real tokenization:

script len/4 estimate real ratio
english prose 7900 6430 0.81x
code 9700 12829 1.32x
chinese 3400 9628 2.83x
devanagari 6500 25229 3.88x

This never mattered before because num_ctx was discarded. Now that it lands, a Devanagari-heavy repo gets a context a quarter of the size it needs. llm.py:2230 already has a real tokenizer path, so routing the estimate through it (or widening headroom for non-Latin scripts) fixes both at once.

The +400 system-prompt headroom is short too. _extraction_system() is 769 real tokens, 823 in deep mode.

Smaller notes

  • Every new test monkeypatches the openai module, so the real SDK's client.post(path, body=..., cast_to=object) at llm.py:1478 is the single line no test touches. A signature change or a non-dict response there only fails at runtime. An opt-in integration test against a live Ollama, or a stub that asserts the constructed call instead of replacing the client, would close it.
  • The 404 fallback keys on "model" in str(exc).lower(). That reads correctly for Ollama, but a gateway returning a 404 body that mentions a routing "model" would raise instead of falling back to /v1. Checking that exc.body is Ollama's {"error": ...} shape would be tighter.
  • graphify/prs.py:683 builds its own streaming OpenAI client for triage and stays on /v1. It sends no num_ctx, so this PR does not regress it, but it will hit the same truncation on large PR lists. Separate follow-up.
  • The keep_alive change is accurate. I confirmed the value lands as a top-level keep_alive in the request body at llm.py:1473, which Ollama honors. Good that you called it out.

Verdict

The mechanism is right, the fallback is sound, and both the suite and a live server back it. The num_ctx sizing is the only thing I would want addressed, and it is a formula change rather than a rethink. Happy to approve once that lands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor Pull request from a returning community contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Ollama ignores graphify's context size, so docs come back empty

3 participants