Repository navigation
fix(server): define tools only when the request sends them - #1598
Merged
Merged
Conversation
`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
`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
7 of 12 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
build_template_contextinserted thetoolskey into the minijinja context unconditionally, and both render paths substituted an emptyVec<Tool>when the request carried no tools. Every template that selects its tool branch withtools is definedortools is not nonetherefore took that branch on a plain chat request and rendered a tool-calling preamble with an empty function list. transformers passestools=Noneand 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 notoolskey:models/mlx/youtu-llm-2b-4bittools is defined and tools is not none<|begin_of_tool_description|>blockmodels/mlx/llama-3.2-1b-4bitset tools = nonedefault, thentools is not noneEnvironment: ipythonplus the functions preambleWhat changed
src/server/chat_template.rs:build_template_contexttakestools: Option<minijinja::Value>and inserts the key only forSome.apply_raw_innerandapply_innerbuild that value astools.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, bothinput_tokensroutes, the Muse ATEM stream path, the prompt cache's history-boundary render, and the offlinegenerateandchatCLI commands. No caller was patched, no standalone helper was introduced, andeffective_toolsinsrc/server/chat_request.rsis untouched (it already mapstool_choice: "none"toNone), so this PR does not overlap #1581.Undefined rather than
noneis the required value, not a stylistic choice. minijinja 2.24'siterabletest isValue::try_iter().is_ok(), which succeeds fornone, while| lengthofnoneerrors; the Nemotron / MiMo guardtools is iterable and tools | length > 0would therefore abort the render and degrade the prompt to the simple fallback. That family defaults an undefinedtoolsto[]itself, so an absent key is the one value all three shipped guard shapes agree on.toolsstays inRESERVED_KEYS, so achat_template_kwargsentry 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/lengthfacts and a pointer to this issue.docs/llama-server-compat.mdgains a subsection under "Chat templates, reasoning, and output parsing" stating that llama-server definestoolsonly for a non-null tool array, that mlxcel now matches, that transformers'tools=Nonerenders 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_contextinserts exactly these keys:messages,bos_token,eos_token,add_generation_prompt: stay unconditional. Templates read them for their value and never test them withis defined; a missing one would change the rendered conversation rather than select a branch.enable_thinking: stays unconditional and stays defined. It is the tested per-request override point from bug(gemma4): dense gemma-4 text modeling is catastrophically degraded (ppl ~12k vs gemma-3's 15 on the same corpus); likely root of the temp-0 pad-collapse #686 and fix(cli): the "not a model" error omits the bare-name form the resolver accepts #1114, and changing its definedness would change that contract. No shipped template was found whereenable_thinking is definedalone flips a branch; if one turns up it is a follow-up issue, not a widening of this fix.tools: now conditional. This is the key the invariant was written for.thinking(feat(server): map enable_thinking -> thinking_mode for the DeepSeek-V3.2 chat template #512) andthinking_mode(feat(server): derive the thinking_mode chat-template kwarg when the template supports it #775, fix(server): DeepSeek-V4 thinking requests silently render the non-thinking branch (thinking_mode sentinel mismatch) #819): already conditional before this PR.tool_choiceanddocuments: never inserted anywhere (ctx.insert/owned.insertinchat_template.rs), so there is nothing to audit.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_detectionandtest_supports_tools_cachingpass unchanged.cargo test --profile test-fast --features metal,accelerate --lib server::chat_request(104 passed), plusserver::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: rendersmodels/mlx/youtu-llm-2b-4bitandmodels/mlx/llama-3.2-1b-4bitthroughfrom_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 unlessenable_thinkingis true, whichserver::startupderives from the tokenizer's think markers.cargo test --profile test-fast --features metal,accelerate --test apply_template_tools_paritycompiles and registers the gated HTTP test.cargo clippy --profile test-fast --lib --tests --features metal,accelerate -- -D warningscargo fmt --all -- --checkpython3 scripts/ci/check_cross_repo_refs.pymodels/: every one of the 8 that computestools | lengthguards it with a definedness or none test first, so no local template can error under an undefinedtools.models/mlx/youtu-llm-2b-4bitandmodels/mlx/llama-3.2-1b-4bit(cargo test --test apply_template_tools_parity --release -- --ignored, or the/apply-templateandinput_tokenscurls in the issue). Run centrally; this PR did not start a server.Closes #1597