Skip to content

Studio: honour forced tool_choice on local GGUF tool loops - #9773

Merged
mahiatlinux merged 11 commits into
unslothai:mainfrom
Souravrajvi0:feat/local-gguf-web-search-tools-0bdc
Aug 26, 2026
Merged

mahiatlinux merged 11 commits into
unslothai:mainfrom
Souravrajvi0:feat/local-gguf-web-search-tools-0bdc

Conversation

@Souravrajvi0

Copy link
Copy Markdown
Contributor

Summary

Fixes unslothai/unsloth#9730. On a local GGUF model, enable_tools: true plus enabled_tools: ["web_search"] with a forced tool_choice ran no tools, so small models answered from memory. The same request with enabled_tools omitted still called web_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 no provider_type, provider_hosted_tools is empty, and the local loop already kept web_search in the catalog. The GGUF agentic loop then hardcoded tool_choice to "auto", so the request's forced web_search never reached llama-server.

  • Forward payload.tool_choice into generate_chat_completion_with_tools (OpenAI chat and Anthropic GGUF loops).
  • Honour a forced function on the first turn; after a tool actually runs, drop it to "auto" so the model can answer in prose (same rule as stream_with_studio_tools).
  • Document that a local GGUF request is not a hosted-only selection even when enabled_tools is only web_search.
  • Hosted providers are unchanged: enabled_tools: ["web_search"] without run_tools_locally still 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 forced web_search, follow-up is "auto", tool_start fires
  • pytest 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 forced tool_choice
  • pytest tests/test_run_tools_locally_discriminator.py — local GGUF is not hosted-only; test_search_only_without_the_flag_stays_hosted still holds for OpenAI/Gemini/Kimi/OpenRouter
  • pytest tests/test_external_hosted_tool_passthrough.py::test_a_self_hosted_provider_still_runs_studios_own_web_search

…#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.
@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

@danielhanchen

Copy link
Copy Markdown
Member

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.

@mahiatlinux

Copy link
Copy Markdown
Contributor

Fixed nine concrete tool-choice defects in nine separate commits.

  1. d87264e40 fixes the core Studio: enabled_tools: ["web_search"] runs no tools at all on a local GGUF model #9730 contract mismatch. The managed llama-server reads tool_choice as auto, none, or required; it does not honor the OpenAI named-function object. Named choices now send required with a catalog narrowed to the selected function, then restore auto after the choice is resolved.

  2. 81768ef7b enforces tool_choice="none" inside the GGUF path. The local controller is disabled and the request is generated without a tool catalog, so a model-emitted structured call cannot execute.

  3. 2af207e19 resolves a forced choice after the user denies its approval. The next request uses auto instead of repeatedly prompting for the same forced call, while a voluntary retry can still run.

  4. 9b52c50aa canonicalizes Anthropic server-tool aliases only on the server-execution path. A forced web_fetch now targets the selected Studio function web_search; client-tool passthrough is unchanged.

  5. a24275e1e counts successful RAG autoinjection toward a matching forced search_knowledge_base choice and toward required. An unrelated forced choice, such as web_search, remains active.

  6. 6941af675 prevents RAG autoinjection when tool_choice="none". Attached-document retrieval no longer runs or emits tool cards before the disabled controller is reached.

  7. 46bd70a6b applies named-choice restrictions at the local authorization boundary as well as the outbound catalog. A structured call for another enabled tool cannot execute while a different named choice is active.

  8. 63686076f rejects a named choice that is absent from the selected catalog. Direct GGUF calls fail before dispatch, and the OpenAI and Anthropic local-tool routes return a 400 instead of letting llama-server silently default the invalid object to auto.

  9. 8736bb7be makes a wrong model-emitted tool a nonterminal forced-choice mismatch. It emits no provisional card or arguments, does not execute, and retries the original named choice until the requested tool runs or the bounded loop ends.

Verification:

  • 829 affected backend and controller tests passed in 352.16s.
  • Full ruff check passed for all changed source and test files.
  • Focused contract, denial, RAG, alias, authorization, invalid-catalog, retry, and provisional-card regressions passed.
  • GitHub reports the PR as mergeable with no conflicts at 8736bb7be.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

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".

@mahiatlinux

Copy link
Copy Markdown
Contributor

LGTM, ready to merge.

@mahiatlinux
mahiatlinux merged commit 50f6ba2 into unslothai:main Aug 26, 2026
43 of 45 checks passed

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines 26987 to +26990
tc,
forced = _forced_tool_call_pending,
provisional = provisional_match,
allowed_tool_names = {forced_name} if forced_name else None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +25715 to +25718
controller_tools = (
[]
if tool_choice == "none"
else _neutralize_tool_descriptions(tools, None, self.markup_profile)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

danielhanchen added a commit that referenced this pull request Aug 26, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Studio: enabled_tools: ["web_search"] runs no tools at all on a local GGUF model

3 participants