Repository navigation
feat(server): enforce required and named tool_choice on chat (#1319) - #1581
Conversation
`/v1/chat/completions` accepted `tool_choice: "required"` and the named-function object but only `none` changed behaviour: `required` was validated and then ignored, and a named function still rendered every declared tool and only filtered the parsed calls afterwards, so a model that picked another tool answered with an empty `tool_calls` array and `finish_reason: "stop"`.
Both forms now steer generation. `ToolChoice::validate` rejects the unsatisfiable shapes with 400 (`required` without tools, a named function that is undeclared, malformed, or empty) and is shared by the chat route, the Responses and Anthropic Messages routes, and the disaggregated router front. `effective_tools` narrows the template's tool list to the named function, and `prepare_chat_request_with_cache` renders from a cloned message list carrying the forced-choice instruction (first system message, else last user message, else a new leading system message), so the history-boundary render and the next-turn warm-up see the same prompt while the request itself stays untouched.
On templates whose tool-call wire shape is a JSON object in a fixed wrapper, the call is grammar-forced through the existing llguidance path: `ChatTemplateProcessor::forced_tool_call_format` reads Hermes (`<tool_call>`), Mistral Nemo (`[TOOL_CALLS]`) and Llama 3 (`<|python_tag|>` / `"parameters":`) off the template text at construction, excluding the XML-body dialects that reuse those tags; `tool_calls::tool_choice_grammar_with` spells the wrapper around `%json` schemas built from the tool definitions (`anyOf` for `required`, the single schema for a named function); and `structured::build_lark_constraint` compiles it with the same limits and tokenizer cache as the schema path. Wrapper markers the tokenizer carries as special tokens are referenced by id (`<[151657]>`) because the trie hides those behind a marker byte and a byte literal would mask out the very token the model emits. A forced choice combined with a constraining `response_format` is a 400, and a forced choice that finishes without a call is logged at `warn`; the streaming path now reports `tool_calls` only when at least one delta actually reached the client.
Validation: `cargo fmt --all -- --check`, `cargo check` and `cargo clippy --lib --tests -- -D warnings` under `--profile test-fast --features metal,accelerate`, plus the unit tests for `server::chat_request`, `server::types`, `server::tool_calls`, `server::chat_template`, `server::structured`, `server::anthropic_translator` and `server::routes::chat`. On `mlx-community/Qwen3-4B-4bit` (Hermes), `required` returned a `get_time` call with `finish_reason: "tool_calls"` on 5 of 5 runs at temperature 0.7, the named form returned `get_weather` and never `get_time` on 5 of 5 runs, the three 400 cases were rejected, the streaming form carried tool-call deltas and a `tool_calls` finish chunk, and the Anthropic `{"type": "any"}` mapping ended with `stop_reason: "tool_use"`.
Refs #1319
The forced-call grammar embedded each tool's `parameters` schema verbatim under `properties/arguments` of a synthesized wrapper object. A tool schema written as its own document then lost its own definitions: `{"$defs": {"Addr": ...}, "properties": {"to": {"$ref": "#/$defs/Addr"}}}`, which is exactly what Pydantic, the OpenAI SDK and LangChain emit for a nested model, resolves `#/$defs/Addr` against the wrapper's root, finds nothing, and fails to compile. Because a compile failure was returned to the client, `tool_choice: "required"` with any such tool answered HTTP 400 on a request that returned 200 before the choice was enforced at all.
`relocate_root_refs` now re-points a tool schema's root-relative pointers at the place the schema comes to rest, `#/properties/arguments/...` for a named choice and `#/anyOf/<i>/properties/arguments/...` for `required`, before the schema is embedded. Per-branch relocation also keeps two tools' identically-named definitions apart, since each branch's pointers stay inside that branch.
A grammar that still does not compile no longer fails the request. The client asked for a tool call, not for a grammar, and the grammar is only how the server delivers one; a schema past llguidance's reach, a nesting depth past its limits or a tool set whose combined grammar exceeds the size cap now falls back to the instruction-only enforcement every non-grammar-capable template already gets, logged at `warn`. A `response_format` schema, which the client did ask for explicitly, still turns a compile failure into a 400.
Verified on `mlx-community/Qwen3-4B-4bit` under `--profile test-fast --features metal,accelerate`: the nested `$defs` tool with `tool_choice: "required"` returns `finish_reason: "tool_calls"` with `book_trip({"to":{"city":"Seoul"}})` on 3 of 3 runs and over SSE, an unresolvable external `$ref` degrades to instruction-only with the fallback warning and still returns 200, and the existing acceptance cases are unchanged (required to get_time 3/3, named get_weather 3/3, and the three 400 cases). `cargo fmt --all -- --check`, `cargo clippy --lib --tests -- -D warnings` and the `server::chat_request server::types server::tool_calls server::chat_template server::structured server::anthropic_translator server::routes::chat server::request_options server::responses_translator server::routes::anthropic server::routes::responses server::router_front server::prompt_cache` filter (1139 passing) are clean.
Refs #1319
Claude-Session: https://claude.ai/code/session_01FXxGfASHG7ju369cFEpHjS
Implementation Review SummaryIntentMake The implementation matches the issue's specification closely. All eight deliverables are present and wired into the request path, all sixteen mandated unit tests exist under the names the issue gives, Findings addressed
Remaining items (reported, not changed)
Verification
Not verified on this host: the ATEM instruction-only checkpoint ( |
`ToolChoice::validate` compared a trimmed choice name against the declared tools, while `effective_tools`, the grammar builder and the response filter all compare the raw string. A padded name such as `" get_weather "` therefore passed validation and then rendered no tool, forced no grammar and filtered every parsed call, answering 200 with an empty `tool_calls` array instead of the 400 the named form promises. The declared-tool check now uses the name exactly as sent; blank names are still rejected on the trimmed form. Validation: `cargo fmt --all -- --check` and `cargo test --profile test-fast --features metal,accelerate --lib -- server::types::request server::routes::chat::tests` (68 passing, including the new padded-name case). Refs #1319
`forced_tool_choice_grammar` runs on the caller's thread, which for every HTTP route is a Tokio runtime worker: `build_chat_constraint` computes the Lark text before it enters `spawn_blocking`, and the Messages and Responses routes call it the same way. `tool_choice_grammar_with` then deep-clones every selected tool's `parameters`, walks the clone recursively to relocate its root-relative `$ref`s, and re-serializes the result. All of that is proportional to the tool schemas the request declared, and none of it was bounded: `tools` is capped by count (`MAX_TOOLS`) and not by size, and `build_lark_constraint`'s `MAX_SCHEMA_BYTES` cap only sees the finished text, on the blocking pool, after the work is already done and about to be discarded. The JSON body limit is sized for base64 image payloads (roughly 1.3 GB at the default image knobs), so a single `tool_choice: "required"` request could buy a long stall on a runtime worker plus a multiple of the body size in transient allocation, for a grammar that was never going to compile. Measured on an M-series host, a 36 MB `tools` array cost 352 ms and about 72 MB of transient allocation inside the builder, scaling linearly with the body; Tokio's worker count is the core count, so a handful of concurrent requests stalls the HTTP surface, `/health` and in-flight SSE included. Measure the selected tools' names and `parameters` against a `MAX_SCHEMA_BYTES` budget first, using a counting sink that fails once the budget is exhausted. `serde_json::to_writer` stops at the first writer error, so an oversized schema costs the budget rather than its own size, and the same 36 MB array now leaves the builder in 133 us. Exceeding the budget returns `None`, which is the instruction-only fallback a grammar that fails to compile already takes, so no request that worked before is newly refused. The pre-flight is a lower bound on the finished text and does not replace the cap; `build_lark_constraint` stays the authority on the final size. Verified with `cargo fmt --all -- --check`, `cargo clippy --lib --tests -- -D warnings`, and the chat / tool-call / structured-output / translator / route test filters (967 passed, 0 failed). Refs #1319
Security and performance reviewScope: the changed surface of this PR, with attention on the request-controlled JSON schemas that now flow from Fixed in 4933f6fHIGH -- unbounded reactor-thread work and transient allocation in the forced-grammar build. Reported, not changedMEDIUM -- MEDIUM -- the disaggregated router front silently drops the forced grammar. MEDIUM -- the named LOW -- LOW -- LOW -- Checked and clear
Validation
|
The `response_format` path guards a schema with three pre-compilation limits (size, nesting depth, `$ref` count) because each `$ref` expands into its own sub-grammar and a small schema that references itself many times buys compile time out of proportion to its size. The forced tool-call grammar enforced the size cap only, so 1000 references inside a 49 KB tool schema still cost about 100 ms of grammar compilation on the blocking pool. `tool_choice_grammar_with` now counts `$ref` entries across the selected tools' `parameters` the same way `validate_schema_bounds` does and takes the instruction-only fallback past `MAX_SCHEMA_REFS`, with a `warn` naming the reason. Depth needs no separate guard: serde_json's recursion limit rejects deeper documents at parse time. The disaggregated router front cannot carry a compiled constraint to the decode node, so a forced choice there is enforced through the narrowed tool list and the injected instruction only. It keeps accepting those requests, as it did before the choice was enforced at all, and logs the limitation at `warn` once per request instead of silently dropping the grammar. Validation: `cargo fmt --all`, `cargo test --profile test-fast --features metal,accelerate --lib -- server::tool_calls server::router_front server::structured` (435 passing, including the new ref-cap case), and `cargo clippy --profile test-fast --features metal,accelerate --lib --tests -- -D warnings`. Refs #1319
The streaming finish path's `emitted > 0` gate, which decides whether `finish_reason` may claim `"tool_calls"`, lived only inside `stream_chat_completion`'s `spawn_blocking` closure, so it had no unit coverage of its own; extract `tool_call_matches_choice` and `count_tool_calls_reaching_client` as plain functions that the emission loop now calls through the same predicate, without touching the SSE emission flow itself, and add tests pinning the `"required"`, named-match, and named-miss cases so a future change to the filter cannot silently let `finish_reason` claim a call the client never received. Validation: - cargo test --profile test-fast --features metal,accelerate --lib -- server::routes::chat (52 passed) - cargo fmt --all -- --check and cargo clippy --profile test-fast --features metal,accelerate --lib --tests -- -D warnings both clean Refs #1319
`route_chat` gained a branch (#1319) that lets a forced `tool_choice` ("required" or a named function) proceed past validation on the disaggregated router instead of being rejected the way `response_format` is, since the narrowed tool list and the injected prompt instruction still reach the rendered prompt even without a grammar constraint; nothing exercised that branch, so a future regression that turned it back into a 400 would have gone unnoticed by every existing router test. Add a test that posts a "required" tool_choice with a declared tool through a template that raises once rendering is reached, so getting the template's own rejection (not the tool_choice/response_format guard's 400) proves the request passed the new branch. Validation: - cargo test --profile test-fast --features metal,accelerate --lib server::router_front (27 passed) - cargo fmt --all -- --check and cargo clippy --profile test-fast --features metal,accelerate --lib --tests -- -D warnings both clean Refs #1319
…ion-only The disaggregated-serving scope-and-limitations list already documents that `response_format` is rejected with 400 because the wire protocol cannot carry a compiled structured-output constraint to the decode node, but said nothing about the new forced `tool_choice` handling (#1319) added right next to it in `route_chat`, which takes the opposite path: it is accepted and enforced through the narrowed tool list and injected prompt instruction alone, logged once at `warn` instead of failing the request, since the grammar constraint has the same wire-protocol limitation but a forced tool_choice is still meaningfully served without one. Refs #1319
## 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:
- `messages`, `bos_token`, `eos_token`, `add_generation_prompt`: stay unconditional. Templates read them for their value and never test them with `is 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 #686 and #1114, and changing its definedness would change that contract. No shipped template was found where `enable_thinking is defined` alone 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` (#512) and `thinking_mode` (#775, #819): already conditional before this PR.
- `tool_choice` and `documents`: never inserted anywhere (`ctx.insert` / `owned.insert` in `chat_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
- [x] `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.
- [x] `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).
- [x] `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.
- [x] `cargo test --profile test-fast --features metal,accelerate --test apply_template_tools_parity` compiles and registers the gated HTTP test.
- [x] `cargo clippy --profile test-fast --lib --tests --features metal,accelerate -- -D warnings`
- [x] `cargo fmt --all -- --check`
- [x] `python3 scripts/ci/check_cross_repo_refs.py`
- [x] 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
Summary
/v1/chat/completionsacceptedtool_choicein all four OpenAI shapes but onlynonechanged behaviour:requiredwas validated and then ignored, and a named function still rendered every declared tool and only filtered the parsed calls afterwards, so a model that picked another tool returned an emptytool_callsarray withfinish_reason: "stop". This PR makesrequiredand the named form steer generation: the tool list handed to the template is narrowed, an instruction is injected into the rendered prompt, unsatisfiable requests are rejected with 400, and on tool-call formats whose wire shape is a JSON object in a fixed wrapper the call is grammar-forced through the existing structured-output constraint.Closes #1319
Semantics
tool_choice"auto""none""required"toolsabsent or empty{"type":"function","function":{"name":"f"}}ffon grammar-capable formatsfundeclared (matched exactly as sent),typenotfunction, empty nameThe instruction is appended to the first system message as
"\n\n" + instruction, otherwise to the last user message (a content-parts message gets a trailing text part), otherwise inserted as a new leading system message. The injection happens on the message list handed to the renderer; the request object is never mutated. A forced choice combined with a constrainingresponse_formatis rejected with 400.Grammar forcing is best effort on top of the prompt enforcement: when the loaded template's tool format has no fixed JSON wrapper, when the declared tool schemas exceed the grammar size or
$refbudgets, when the grammar does not compile, or on the disaggregated router (whose prefill frame cannot carry a constraint to the decode node), the request proceeds with the narrowed tool list and the injected instruction only and the server logs the reason atwarn. A forced choice that finishes without a parsed call is logged atwarnas well, andfinish_reasonstays what the model produced.Changes
src/server/types/request.rs:ToolChoice::is_required,ToolChoice::is_forced, andToolChoice::validate(tools)carrying the 400 rules, shared byroutes/chat.rs,routes/responses.rs,routes/anthropic.rs, and the disaggregatedrouter_front.rsthroughvalidate_chat_tool_inputs. The named function is matched exactly as sent, because the renderer, the grammar builder and the response filter compare the raw string; a padded name is a 400 rather than a 200 with an emptytool_callsarray.src/server/chat_request.rs:effective_toolsnarrows to the named tool;tool_choice_instruction,inject_tool_choice_instruction, andwith_tool_choice_instruction(aCowclone only when a choice is forced).prepare_chat_request_with_cacheandrender_next_turn_historyrender from that list, sohistory_promptstays a prefix of the prompt and the next-turn warm-up matches what a follow-up turn with the sametool_choicerenders.request_options.rsdocuments that one narrowed tool still counts as tools rendered for the loop-detection gate.src/server/chat_template.rs:forced_tool_call_format()cached at construction from template markers: Hermes on<tool_call>(excluding the XML-body dialects Qwen3-Coder<function=, GLM<arg_key>, and<function_name>), Mistral Nemo on[TOOL_CALLS](excluding bracketed[ARGS]), Llama 3 on<|python_tag|>or"parameters":; ATEM templates returnNone.src/server/tool_calls/mod.rs:tool_choice_grammarandtool_choice_grammar_withbuild the Lark grammar (start: <wrapper> %json { schema } <wrapper>) from per-tool schemas (namepinned byconst,argumentsorparameterstyped by the tool's own schema,additionalProperties: false;anyOfover all tools forrequired).relocate_root_refsre-points a tool schema's root-relative$refs (#/$defs/..., the shape Pydantic, the OpenAI SDK and LangChain emit for nested models) at the place the schema comes to rest inside the wrapper, so those schemas compile and two tools' identically named definitions stay apart.special_token_idresolves wrapper markers that the llguidance trie treats as special tokens (an added token that is flagged special or wrapped in<...>, which is how Qwen ships<tool_call>) so they are referenced by id (<[151657]>); a byte literal there masks out the model's own token, which is exactly what the first real-model run showed. Before anything is cloned,tool_schemas_fitmeasures the selected tools' names and schemas againstMAX_SCHEMA_BYTESwith a counting sink andcount_refsappliesMAX_SCHEMA_REFS, so a request cannot buy runtime-worker time or transient allocation proportional to a body sized for base64 images; either budget exceeded is the instruction-only fallback.src/server/structured.rs:build_lark_constraint(tokenizer, lark)next tobuild_json_schema_constraint, sharingTOK_ENV_CACHE, the tightenedParserLimits, and theMAX_SCHEMA_BYTEScap applied to the grammar text. Nothing else in the file changes (issue perf(server): apply structured-output token masks as a packed u32 bitmask instead of a full f32 bias #1316 owns the rest).src/server/routes/chat.rs:build_chat_constraintbuilds either theresponse_formatconstraint or the forced tool-call grammar on the blocking pool and is shared by the chat, Responses, and Anthropic routes;forced_constraint_or_instruction_onlyturns a grammar compile failure into the instruction-only fallback with awarn(aresponse_formatthe client asked for explicitly still yields a 400);validate_chat_tool_inputsdelegates toToolChoice::validateand rejectsresponse_formatplus a forced choice; both finish paths log atwarnwhen a forced choice ends without a call (format name included), and the streaming path setsfinish_reason: "tool_calls"only when at least one tool-call delta reached the client (previously it claimedtool_callseven when the named-function filter had dropped every call). The name filter for the named form stays as the last line of defence.src/server/routes/responses.rsandsrc/server/routes/anthropic.rs: run the shared validation and constraint build, sotext.formatplus a forced choice is a 400 on Responses and the Anthropic{"type": "any"}/{"type": "tool"}mappings (already present inanthropic_translator.rs) get the same enforcement; the constraint is threaded into both Anthropic generation paths.src/server/router_front.rs: a forced choice is accepted as before and enforced through the prompt only, with awarnsaying the grammar cannot travel to the decode node;router_front_tests.rspins that the router forwards such a request instead of rejecting it the way it rejectsresponse_format.src/server/routes/chat.rsstreaming finish gate:tool_call_matches_choiceandcount_tool_calls_reaching_clientare extracted from thespawn_blockingclosure so thefinish_reason: "tool_calls"gate has unit coverage for therequired, named-match, and named-miss cases; the SSE emission flow is unchanged.docs/responses-api.md(tool_choicerow plus a "Tool choice enforcement" section),docs/server-features.md("Tool calling andtool_choice"), anddocs/CONTINUOUS_BATCHING.md(the disaggregated router's instruction-only behaviour next to its existingresponse_formatlimitation); the repository has nosrc/server/README, so the server feature doc is the closest equivalent to the README section the issue names.Validation
All commands ran under
DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developerwith--profile test-fast --features metal,accelerateon Apple Silicon (M1, Metal + Accelerate).cargo fmt --all -- --check: clean.cargo check --lib --tests: clean, no warnings.cargo clippy --lib --tests -- -D warnings: clean.cargo test --lib -- server::chat_request server::types server::tool_calls server::chat_template server::structured server::anthropic_translator server::routes::chat server::request_options server::responses_translator server::routes::anthropic server::routes::responses server::router_front: all passing, including the new testseffective_tools_narrows_to_named_function,tool_choice_instruction_appends_to_system_message,tool_choice_instruction_appends_to_last_text_user_message,tool_choice_instruction_inserts_system_when_no_system_and_no_text_user,named_tool_choice_changes_rendered_prompt_and_template_sig,tool_choice_required_without_tools_is_rejected,tool_choice_unknown_function_is_rejected,tool_choice_object_without_function_type_is_rejected,tool_choice_grammar_hermes_required_is_anyof_over_all_tools,tool_choice_grammar_named_pins_name_const,tool_choice_grammar_is_none_for_atem_and_gemma4,tool_choice_grammar_references_special_wrapper_tokens_by_id,tool_choice_grammar_is_none_when_the_declared_schemas_exceed_the_size_cap,tool_choice_grammar_is_none_when_the_declared_schemas_exceed_the_ref_cap,special_token_id_follows_the_trie_classification,forced_tool_call_format_detects_hermes_marker,forced_tool_call_format_is_none_for_atem_template,lark_constraint_forces_hermes_wrapper(token-by-tokenconsume_tokenwithcompute_maskon every step, stopped at the end, prose masked out as the first token),lark_constraint_named_choice_refuses_other_tool_names,a_grammar_that_does_not_compile_degrades_to_instruction_only,anthropic_tool_choice_any_maps_to_required,anthropic_tool_choice_tool_maps_to_named, the streaming finish-gate cases, androuter_chat_forwards_forced_tool_choice_instead_of_rejecting_it(972 tests in the filter at the final commit).mlx-community/Qwen3-4B-4bit(Hermes format, grammar-capable) served bytarget/test-fast/mlxcel-server, 5 runs per request attemperature: 0.7:tool_choice: "required"returned aget_timecall withfinish_reason: "tool_calls"on 5 of 5 runs; the namedget_weatherform with two tools declared returnedget_weatheron 5 of 5 runs andget_timeon 0 of 5;requiredwith"tools": []returned HTTP 400, an undeclared named function returned HTTP 400, andrequiredplusresponse_format: json_schemareturned HTTP 400;requiredwithstream: truestreamed the tool-call start and arguments deltas and the final chunk carriedfinish_reason: "tool_calls";/v1/messageswithtool_choice: {"type": "any"}ended withstop_reason: "tool_use"and aget_timeblock. The server log carried no forced-choice warning across these runs. The review cycle re-ran the same checkpoint after the$refrelocation: a tool whoseparameterscarry$defsreturnedbook_trip({"to":{"city":"Seoul"}})withfinish_reason: "tool_calls"on 3 of 3 runs and over SSE, an unresolvable external$refdegraded to instruction-only with one fallback warning and still returned 200, and the original cases were unchanged.Changes during review
<...>as special, so a byte-literal"<tool_call>"masked out Qwen's own token. The grammar now references such markers by token id.$defs+#/$defs/...) failed to compile inside the wrapper and turned a request that worked onmaininto a 400; the schema's root-relative pointers are now relocated, and a grammar that still does not compile falls back to instruction-only enforcement instead of failing the request.toolsarray cost about 350 ms and 72 MB of transient allocation); the size and$refbudgets are now applied before anything is cloned (133 us for the same array).Not verified on this host
mlx-community/Muse-Glimmer-30B-4bit(ATEM, instruction-only path) is not available locally, so the "named form yieldsget_weatheron at least 9 of 10 runs" acceptance for the instruction-only path was not run. The ATEM detection (forced_tool_call_format() == Nonewithdefault_tool_call_format() == Some(Atem)) is unit-tested.cargo test --workspaceandcargo clippy --workspace --all-targets(the issue's full-workspace gates) were not run here; the narrow module runs above and the path-filtered CI cover the touched surface. No CUDA code is touched.Follow-ups (not in this PR)
{"type": "function", "name": "f"};ToolChoiceonly deserializes the Chat Completions nesting, so that shape is rejected at deserialization as it was before this PR.requiredand the string modes work on/v1/responses.requiredgrammar admits exactly one call; parallel calls on grammar-capable templates andparallel_tool_calls: falseenforcement are out of scope per the issue.Notes
PR for #1314 touches the same file; whichever merges second needs a rebase. The
routes/chat.rsedits here are scoped to validation, constraint setup, and the finish-path warning.