Repository navigation
Studio: honour forced tool_choice on local GGUF tool loops - #9773
mahiatlinux merged 11 commits into
Conversation
…#9730) Local llama.cpp always sent tool_choice=auto, so enabled_tools: ["web_search"] plus a forced web_search never reached llama-server. Small GGUF models then answered from memory. Forward the request's tool_choice and drop a forced function to auto after a tool actually runs, matching the external Studio loop. A local GGUF request has no provider_type, so hosted-only selection does not apply.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 104f26065b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Confirmed the local GGUF tool loop in studio/backend/core/inference/llama_cpp.py pins tool_choice to auto, so a forced function never reaches llama-server, and the reset back to auto after a tool runs matches the streaming path. Will get this reviewed. |
|
Fixed nine concrete tool-choice defects in nine separate commits.
Verification:
|
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
LGTM, ready to merge. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8736bb7bea
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # reset is POSSIBLE somewhere, not that this request can perform one. | ||
| checkpoint_fitted = _rolling_context_policy(payload) is not None, | ||
| ) | ||
| _reject_missing_forced_tool(payload.tool_choice, tools_to_use) |
There was a problem hiding this comment.
Validate forced tool choices before switching models
When an auto-switching request forces a function excluded by enabled_tools, this validation runs only after _maybe_auto_switch_model, so the server can unload/load the requested model and then return 400 without generating anything. The Anthropic server-tool path repeats the same ordering at routes/inference.py:23444, even though it already computes the selected catalog before switching; validate the forced choice against that pre-switch catalog so invalid requests cannot disrupt the resident model.
Useful? React with 👍 / 👎.
| tc, | ||
| forced = _forced_tool_call_pending, | ||
| provisional = provisional_match, | ||
| allowed_tool_names = {forced_name} if forced_name else None, |
There was a problem hiding this comment.
Drop stale mismatch nudges after the forced tool runs
When a model emits a parallel batch containing both the forced function and a hallucinated different function, the different call is collected as a forced_mismatch here while the requested call is still executed later in the same batch. The deferred feedback is then appended after the successful tool result and tells the next, now-auto pass to “Call the required tool instead,” even though that requirement was already satisfied; this can make small models repeat the tool unnecessarily. Discard forced-mismatch feedback once a matching call in the batch executes.
Useful? React with 👍 / 👎.
| controller_tools = ( | ||
| [] | ||
| if tool_choice == "none" | ||
| else _neutralize_tool_descriptions(tools, None, self.markup_profile) |
There was a problem hiding this comment.
Preserve continuation mode when tools are disabled
For an explicit Studio-tool request that also sets tool_choice="none" and continue_final_message=true, emptying the controller makes the loop skip directly to its synthesized final pass. Unlike the normal iteration payload, that final pass never sets continue_final_message or add_generation_prompt=false, so llama-server starts a fresh assistant turn instead of continuing the trailing partial (and strict templates may reject the boundary). Keep the continuation flags on this no-tools path or route it through the normal plain generator.
Useful? React with 👍 / 👎.
…y source proximity (#9809) * Studio: assert the tool loop controller catalog structurally, not by source proximity test_tool_loop_controllers_are_built_from_the_sanitized_catalog scraped a fixed 200-character window after each ToolLoopController( construction site and required the text of the sweep to fall inside it. #9773 hoisted the very same sweep one statement up into a controller_tools local so it could short-circuit on tool_choice == "none", which emptied the window and turned main red without changing a single thing about what reaches the controller. Resolve the tools argument through the AST instead: local assignments, conditional expressions and boolean operands are followed until the value terminates in the sweep, in a catalog builder that wraps it, or in an empty/None catalog. Reformatting, renaming the local or rewrapping the call all still resolve; handing the controller the raw catalog does not. Two supporting tests hold up the parts the resolver takes on trust: every production caller that supplies renderable_tools must pass a swept catalog, and the catalog builders must sweep and must never return their own tools argument. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: require the controller catalog to gate, and refuse one filled in place Two shapes reached the controller past the new dataflow resolver. A bare tools = None resolves (there is no catalog to sanitize) but sets _restrict_to_allowed = False, so prepare_call stops checking names at all and every tool the sweep dropped is executable again. The resolver now reports whether a value can hold a catalog as well as whether it is sanitized, and the construction sites require both; None still resolves as the branch of an if-expression that has nothing to authorize, which is the shape both loops use. A catalog bound to an empty literal and then filled in place -- controller_tools = []; controller_tools.extend(tools) -- resolved on the literal, because the binding table only sees rebinds. A resolved name that is appended to, extended, updated or assigned through a subscript is refused instead of modelled. Mutation proof over the two loops: raw catalog, raw catalog via the other loop, sweep without a markup profile, unrestricted controller, empty catalog filled in place, and catalog assigned by subscript all go red; a pure reformat of the construction site and unmodified head stay green. * Tighten the comments on the controller catalog guard * Studio: close four one-path holes in the controller catalog resolver Which branch gates was decided by an or over the branches, so ToolLoopController(tools = None if tools else swept) passed: the swept branch gates while None is selected exactly when there IS a catalog. A non-gating branch now has to be guarded by the emptiness of the catalog the other branch narrows, followed through the binding rather than matched on the name, so unrestricted_tools = not tools still resolves and the inversion does not. A parameter that is also rebound kept only its rebindings, and the resolver is flow-insensitive, so if sanitize: tools = neutralize_tool_descriptions(...) vouched for the raw parameter on the other path. A rebound parameter now has to clear its contract as well, which also closes catalog = catalog vouching for itself through the cycle. Lambda was in _NESTED_SCOPES but not in the scope chain, so a lambda parameter resolved against the outer name it shadows at runtime. studio_tool_loop.py is a third construction site the guard never named. It drives an external provider and builds its controller from policy.tools, and external_provider.py sweeps only what it sends and only for the providers whose prompt this repo templates, keeping that result local. Closing it needs the transport to report whether it templated the prompt, which is a product change for its own PR, so it is recorded in _CONTROLLER_MODULES_OUT_OF_SCOPE with the reason and a new test fails on any FOURTH site that is in neither list. Mutation proof now at 8 breakages red, with the pure reformat and unmodified head green. * Studio: read the sweep's keyword form, gate every boolean operand, classify per site The guard on the non-gating branch read only the sweep's first POSITIONAL argument, so respelling the same call as neutralize_tool_descriptions(tools = tools, markup = markup) left it with no root to match the predicate against and the safetensors site would have gone red on a pure refactor. That is the fragility this whole test exists to remove, reintroduced by the fix for it. The keyword spelling is now read as well, and it is a control in the mutation set rather than only an assertion. A boolean had no predicate to prove emptiness with and still took the OR of its operands, so tools = _authorized or None was accepted: short-circuit reaches None exactly when the sweep emptied the catalog, which is when the allowlist matters most. Every operand of a boolean now has to gate. The classification test keyed on the file name, so a SECOND controller inside studio_tool_loop.py, or a same-named module elsewhere in the tree, would have inherited the external-provider exemption. Sites are now keyed by path under studio/backend plus enclosing function. Mutation proof: 9 breakages red, 3 controls green. * Studio: key an exempted controller site by how many the function holds The classification key was (path, enclosing function), so two constructors inside stream_with_studio_tools collapsed to one entry and a second one would have inherited the external-provider exemption instead of forcing a decision. The key now carries the number of sites that function holds. The count rather than a line number: a line moves when anything above it does, so the test would fail on an unrelated edit, which is the fragility this file exists to remove. The count moves only when a controller is added or removed, which is exactly the event that has to force the decision. Verified by adding a second constructor to the exempt function, which turns the test red naming (studio_tool_loop.py, stream_with_studio_tools, 2) as unclassified. * Tighten the comments on the controller catalog resolver * Studio: gate every assignment path, scope the catalog roots, follow constructor aliases A name with several bindings took the OR of them, so controller_tools = None followed by if enabled: controller_tools = neutralize_tool_descriptions(...) resolved as gating with the unrestricted path still reachable. A conditional expression carries a predicate that can prove there is nothing to authorize; separate assignments carry none, so every binding of a name now has to gate. The catalog roots the branch predicate is matched against were bare identifiers, so an inner helper whose parameter shadows the name the outer scope swept satisfied the proof with a different catalog. Each root now carries the scope that binds it, and a binding is followed in its OWN scope chain from that scope outward rather than in the call site's. controller_cls = ToolLoopController then controller_cls(tools = raw) was not recognised as a construction site at all, so it escaped the resolver and the classification test together. Assignment aliases of the tracked callables are followed like an as import, restricted to those names so unrelated locals cannot answer to a trusted one. Mutation proof: 11 breakages red, 3 controls green. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Summary
Fixes unslothai/unsloth#9730. On a local GGUF model,
enable_tools: trueplusenabled_tools: ["web_search"]with a forcedtool_choiceran no tools, so small models answered from memory. The same request withenabled_toolsomitted still calledweb_search.enabled_tools: ["python"]was unaffected.The hosted-tool discriminator (
_selects_only_provider_hosted_tools) is not the local-GGUF path: a loaded GGUF has noprovider_type,provider_hosted_toolsis empty, and the local loop already keptweb_searchin the catalog. The GGUF agentic loop then hardcodedtool_choiceto"auto", so the request's forcedweb_searchnever reached llama-server.payload.tool_choiceintogenerate_chat_completion_with_tools(OpenAI chat and Anthropic GGUF loops)."auto"so the model can answer in prose (same rule asstream_with_studio_tools).enabled_toolsis onlyweb_search.enabled_tools: ["web_search"]withoutrun_tools_locallystill stays hosted.Test plan
pytest tests/test_llama_cpp_tool_loop.py::test_forced_web_search_tool_choice_is_sent_until_a_tool_runs— first llama-server payload is forcedweb_search, follow-up is"auto",tool_startfirespytest tests/test_openai_tool_passthrough.py::TestGgufVisionToolRouting::test_enabled_tools_web_search_only_enters_gguf_tool_loop— issue-shaped request enters the GGUF loop with catalog["web_search"]and the forcedtool_choicepytest tests/test_run_tools_locally_discriminator.py— local GGUF is not hosted-only;test_search_only_without_the_flag_stays_hostedstill holds for OpenAI/Gemini/Kimi/OpenRouterpytest tests/test_external_hosted_tool_passthrough.py::test_a_self_hosted_provider_still_runs_studios_own_web_search