Skip to content

fix(server): define tools only when the request sends them - #1598

Merged
inureyes merged 3 commits into
mainfrom
fix/issue-1597-undefined-tools-context
Sep 2, 2026
Merged

inureyes merged 3 commits into
mainfrom
fix/issue-1597-undefined-tools-context

Conversation

@inureyes

@inureyes inureyes commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Summary

build_template_context inserted the tools key into the minijinja context unconditionally, and both render paths substituted an empty Vec<Tool> when the request carried no tools. Every template that selects its tool branch with tools is defined or tools is not none therefore took that branch on a plain chat request and rendered a tool-calling preamble with an empty function list. transformers passes tools=None and llama-server leaves the key unset, so neither of them does this. The key is now absent unless the request carries at least one tool.

Measured on the two shipped families, for {"messages":[{"role":"user","content":"The Fibonacci sequence begins with"}]} with no tools key:

Checkpoint Guard Before Oracle
models/mlx/youtu-llm-2b-4bit tools is defined and tools is not none 76 tokens, empty <|begin_of_tool_description|> block 8 tokens
models/mlx/llama-3.2-1b-4bit set tools = none default, then tools is not none 97 tokens, Environment: ipython plus the functions preamble 40 tokens

What changed

src/server/chat_template.rs: build_template_context takes tools: Option<minijinja::Value> and inserts the key only for Some. apply_raw_inner and apply_inner build that value as tools.filter(|t| !t.is_empty()).map(minijinja::Value::from_serialize), so a request with no tools and a request with an explicit "tools": [] both leave the key undefined. The tests-module render helper mirrors the same expression so it keeps reproducing what the server renders.

Normalizing inside the two inner functions covers every render in the tree at once: /v1/chat/completions, /v1/messages, /v1/responses, /apply-template, both input_tokens routes, the Muse ATEM stream path, the prompt cache's history-boundary render, and the offline generate and chat CLI commands. No caller was patched, no standalone helper was introduced, and effective_tools in src/server/chat_request.rs is untouched (it already maps tool_choice: "none" to None), so this PR does not overlap #1581.

Undefined rather than none is the required value, not a stylistic choice. minijinja 2.24's iterable test is Value::try_iter().is_ok(), which succeeds for none, while | length of none errors; the Nemotron / MiMo guard tools is iterable and tools | length > 0 would therefore abort the render and degrade the prompt to the simple fallback. That family defaults an undefined tools to [] itself, so an absent key is the one value all three shipped guard shapes agree on. tools stays in RESERVED_KEYS, so a chat_template_kwargs entry still cannot fill the slot the request left empty.

The two stale comments that attributed the old empty-list workaround to minijinja short-circuiting are replaced with the actual iterable / length facts and a pointer to this issue.

docs/llama-server-compat.md gains a subsection under "Chat templates, reasoning, and output parsing" stating that llama-server defines tools only for a non-null tool array, that mlxcel now matches, that transformers' tools=None renders identically for every guard shape shipped, and that upgrading costs one cold prompt-cache miss per affected model.

Context-key audit

Requested by the issue; also recorded as a comment on the insert block so the invariant travels with the code. build_template_context inserts exactly these keys:

Prompt cache

The change alters tokens[..prefix_len] and the history-boundary render for affected models, so the first request per model after upgrading misses once and rebuilds. That is a one-time cold miss, not a compatibility break: no key digest version changes and no migration is needed.

Test plan

  • cargo test --profile test-fast --features metal,accelerate --lib server::chat_template (154 passed), including four new tests: the DeepSeek/Youtu guard, the Llama guard, the Nemotron guard rendering without error, and the history-boundary render. test_apply_with_tools_none_still_works, test_kwargs_cannot_override_reserved_tools_key, test_supports_tools_detection and test_supports_tools_caching pass unchanged.
  • cargo test --profile test-fast --features metal,accelerate --lib server::chat_request (104 passed), plus server::routes (387), server::tool (384), server::prompt_cache (173), server::reasoning_effort_tests (28), server::anthropic_translator (33), server::muse_atem_roundtrip_tests (5), server::muse_glimmer_template_tests (6).
  • cargo test --profile test-fast --features metal,accelerate --lib server::chat_template::tests::local_checkpoint_templates_render -- --ignored: renders models/mlx/youtu-llm-2b-4bit and models/mlx/llama-3.2-1b-4bit through from_model_path, which reads only the template files, and both match the transformers oracle string exactly. This is the weight-free half of the gate and it runs in milliseconds; it caught that the Youtu template primes an empty <think></think> block unless enable_thinking is true, which server::startup derives from the tokenizer's think markers.
  • cargo test --profile test-fast --features metal,accelerate --test apply_template_tools_parity compiles and registers the gated HTTP test.
  • cargo clippy --profile test-fast --lib --tests --features metal,accelerate -- -D warnings
  • cargo fmt --all -- --check
  • python3 scripts/ci/check_cross_repo_refs.py
  • Static audit of the 196 chat templates under models/: every one of the 8 that computes tools | length guards it with a definedness or none test first, so no local template can error under an undefined tools.
  • Real-checkpoint gate on models/mlx/youtu-llm-2b-4bit and models/mlx/llama-3.2-1b-4bit (cargo test --test apply_template_tools_parity --release -- --ignored, or the /apply-template and input_tokens curls in the issue). Run centrally; this PR did not start a server.

Closes #1597

`build_template_context` inserted the `tools` key unconditionally and both render paths substituted an empty `Vec<Tool>` when the request carried no tools, so every template that selects its tool branch with `tools is defined` or `tools is not none` took that branch on plain chat requests and rendered a tool-calling preamble with an empty function list. transformers passes `tools=None` and llama-server leaves the key unset, so neither does this. Measured on the two shipped families: a one-line user message rendered 76 tokens instead of 8 on Youtu-LLM-2B-4bit, with an empty `<|begin_of_tool_description|>` block, and 97 instead of 40 on Llama-3.2-1B-Instruct-4bit, with `Environment: ipython` and the "Given the following functions" preamble.

`build_template_context` now takes `tools: Option<minijinja::Value>` and inserts the key only for `Some`, and `apply_raw_inner` / `apply_inner` build that value as `tools.filter(|t| !t.is_empty()).map(Value::from_serialize)`, so a request with no tools and a request with an explicit `"tools": []` both leave the key absent. Normalizing inside the two inner functions covers every render in the tree at once: the chat, messages, responses, apply-template and input_tokens routes, the Muse ATEM stream path, the prompt cache's history-boundary render, and the offline CLI. No caller was patched and `effective_tools` is unchanged.

Undefined rather than `none` is the required value. minijinja 2.24's `iterable` test is `Value::try_iter().is_ok()`, which succeeds for `none`, while `| length` of `none` errors, so the Nemotron / MiMo guard `tools is iterable and tools | length > 0` would abort the render and fall back to the plain prompt. That family defaults an undefined `tools` to `[]` itself, so absence satisfies all three shipped guard shapes. `tools` stays in `RESERVED_KEYS` so a `chat_template_kwargs` entry still cannot fill the slot the request left empty.

Audit of the other unconditional context keys, recorded as a comment on the insert block: `messages`, `bos_token`, `eos_token` and `add_generation_prompt` are read for their value and never tested with `is defined`; `enable_thinking` stays unconditional by contract (#686, #1114); `thinking` (#512) and `thinking_mode` (#775, #819) were already conditional; `tool_choice` and `documents` are never inserted.

Tests: four checkpoint-free unit tests over the three guard shapes plus the history-boundary render, and `tests/apply_template_tools_parity.rs`, which asserts the exact Youtu and Llama 3.2 prompts against the transformers oracle on real checkpoints and that a request carrying one tool still renders its tool block. A static audit of the 196 local templates found no `tools | length` without a preceding definedness guard.

Prompt cache: the rendered prefix changes for affected models, so the first request per model after upgrading misses once and rebuilds. That is a cold miss, not a compatibility break, and no key digest version changes.

Closes #1597
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:inference Generation, sampling, decoding (incl. speculative, DRY) status:review Under review labels Sep 2, 2026
`from_model_path` reads only the template files, so the two shipped checkpoints can be rendered and compared against the transformers oracle with no weights, no GPU and no server. That makes the exact prompt strings a local gate rather than something only the real-checkpoint HTTP test can catch, and it caught the first version of this test asserting a prompt the server does not produce: the Youtu template primes an empty `<think></think>` block when `enable_thinking` is defined and false, and `server::startup` sets that default to true from the tokenizer's think markers, so the test has to set it too.

Gated on the local `models/` tree with the same `#[ignore]` convention as `test_all_local_model_templates_render`, and it skips a checkpoint that is not present.

Refs #1597
@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 2, 2026
@inureyes
inureyes merged commit 81ccb75 into main Sep 2, 2026
12 checks passed
@inureyes
inureyes deleted the fix/issue-1597-undefined-tools-context branch September 2, 2026 18:43
@inureyes inureyes added this to the 0.7 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(server): chat template context always defines tools, so tool-guarded templates emit a phantom tool preamble

1 participant