Skip to content

fix(ollama): apply num_ctx through native chat - #7029

Open
zlg-codes wants to merge 2 commits into
topoteretes:devfrom
zlg-codes:fix/ollama-native-num-ctx
Open

zlg-codes wants to merge 2 commits into
topoteretes:devfrom
zlg-codes:fix/ollama-native-num-ctx

Conversation

@zlg-codes

Copy link
Copy Markdown

Description

Fixes #7014.

LLM_OLLAMA_NUM_CTX was merged into extra_body on the OpenAI-compatible chat path. Ollama ignores that top-level field, so the configured context size never reached the model. The environment variable also was not mapped to the corresponding settings field.

This change maps the setting and, when ollama_num_ctx is explicitly configured, sends chat requests to Ollama's native /api/chat endpoint with options.num_ctx. Plain-text and structured-output requests are both covered. When the setting is unset, the existing OpenAI-compatible path is unchanged.

Acceptance Criteria

  • LLM_OLLAMA_NUM_CTX reaches the Ollama adapter as ollama_num_ctx.
  • An explicitly configured value is sent as options.num_ctx through /api/chat.
  • Plain-text and schema-constrained responses both work through the native endpoint.
  • The unset path retains the existing OpenAI-compatible behavior.
  • Regression tests cover client construction and native request payloads.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Code refactoring
  • Other (please specify):

Screenshots

Validation on the branch rebased onto current dev (b0c6c567):

uv run pytest cognee/tests/unit/infrastructure/llm -q
470 passed, 20 skipped

Ruff check: passed on all changed Python files
Ruff format check: 5 files already formatted
git diff --check: passed

A real local Ollama llama3.2:latest round-trip returned OK for both plain text and structured output. /api/ps reported context_length=4096 for the loaded model.

Pre-submission Checklist

  • I have tested my changes thoroughly before submitting this PR (See CONTRIBUTING.md)
  • This PR contains minimal changes necessary to address the issue/feature
  • My code follows the project's coding standards and style guidelines
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if applicable)
  • All new and existing tests pass
  • I have searched existing PRs to ensure this change hasn't been submitted already
  • I have linked any relevant issues in the description
  • My commits have clear and descriptive messages

DCO Affirmation

I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin.

Signed-off-by: zlg-codes <light131455@gmail.com>
@zlg-codes

Copy link
Copy Markdown
Author

This PR is now marked ready for review. #7018 has been temporarily moved to draft to free a non-draft slot under the repository’s open PR limit; no pull requests were closed. The rebased branch and validation results in the description are current.

@surlymochan surlymochan 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.

Reviewed the diff (not a maintainer approval — just a verification note from reading the code):

What checks out:

  • The native /api/chat payload is built correctly for the covered cases: num_ctx lands in options, temperature/top_p/top_k/seed/stop move into options, max_tokens maps to num_predict, the response schema is passed via format for structured models and omitted for str, and the endpoint rewrite strips a trailing /v1. The cache-key change (explicit value only, None for the default) is covered by a test, including the env-var alias.

Three things worth confirming, because the change is bigger than the title suggests:

  1. This is not just "apply num_ctx" — any user who sets LLM_OLLAMA_NUM_CTX now leaves the instructor/OpenAI-compatible path entirely and goes through native /api/chat, which changes structured-output semantics (native format schema instead of instructor's JSON/tool-call modes). Users who already set num_ctx today will silently switch paths on upgrade. Is that intended, and should it be called out in the docs/release notes?
  2. _acreate_native_output raises ValueError for any llm_args key outside its allow-list (temperature, top_p, top_k, seed, stop, max_tokens, max_completion_tokens). The OpenAI-compatible path previously passed other kwargs through (e.g. frequency_penalty, presence_penalty), so a user with those set plus num_ctx would go from working to a hard error. Is failing loudly the intended contract, or should unknown kwargs be forwarded into options like the extra_body keys are?
  3. The native call uses AsyncClient(timeout=None), so a hung Ollama server would hang this call indefinitely. The OpenAI-compatible path goes through the configured client — should the native call carry a timeout as well?

… chat

Signed-off-by: zlg-codes <light131455@gmail.com>
@zlg-codes

Copy link
Copy Markdown
Author

Thanks for reading through the diff so carefully — #2 and #3 were real gaps.

  1. Switching to /api/chat when LLM_OLLAMA_NUM_CTX is set is intentional, since Ollama's /v1/chat/completions silently drops num_ctx today (and LLM_OLLAMA_NUM_CTX wasn't wired to the config alias before anyway). I expanded the note in docs/runtime-configuration.md so it explicitly calls out that structured outputs use Ollama's native format JSON schema on that path instead of Instructor.
  2. Agreed — raising ValueError on extra llm_args was too strict and would break configs passing things like frequency_penalty or presence_penalty. Remaining kwargs now forward into options (with keep_alive kept top-level if set).
  3. Good catch on timeout=None too. AsyncClient now defaults to self.client.timeout and honors an explicit timeout override in llm_args or call kwargs instead of waiting forever.

Pushed 5984ff6f4 with unit tests covering both.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants