Skip to content

Improve local chat tool call flow - #5962

Merged
danielhanchen merged 29 commits into
unslothai:mainfrom
wasimysaid:chat-tool-call-inline-ordering
Jun 9, 2026
Merged

danielhanchen merged 29 commits into
unslothai:mainfrom
wasimysaid:chat-tool-call-inline-ordering

Conversation

@wasimysaid

@wasimysaid wasimysaid commented Jun 2, 2026 •

Copy link
Copy Markdown
Collaborator

This PR improves how Studio handles local chat tool calls.

It fixes the original issue where tool cards could appear in the wrong place or before the assistant text that led into them. It also makes local tool turns more stable across GGUF and safetensors models.

What changed

  • Keeps assistant text before a tool call
  • Replays tool cards in the same order the model produced them
  • Keeps tool cards attached to the right assistant message
  • Accepts late structured GGUF tool calls after streamed text
  • Avoids showing repeated forced turn planning text
  • Keeps render_html repeat handling internal
  • Bounds repeated duplicate tool calls so local models do not loop forever
  • Shares local tool loop state between GGUF and safetensors paths
  • Keeps MCP empty discovery from falling back to built in tools at the route layer

Why it matters

Local models do not always emit tool calls cleanly at the start of a turn. They can stream some text first. They can emit structured tool calls late. They can also repeat the same call.

Studio now treats those cases as one coherent assistant turn. The visible chat stays readable. The tool cards stay in order. The final answer is easier to follow.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request enhances tool call handling and streaming in the inference backends and frontend chat adapter. Key changes include tracking tool call provenance (such as whether a tool call was healed, forced, or provisional) in both the llama_cpp and safetensors backends, and refactoring the frontend chat adapter to correctly position tool calls within the assistant's response stream using a text cursor. Additionally, the tool nudge prompts have been updated to be more flexible, streaming-specific tool markup stripping has been introduced, and corresponding unit tests have been added. There are no review comments, so no further feedback is provided.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@wasimysaid wasimysaid changed the title Studio: Fix chat tool call ordering Improve local chat tool call flow Jun 4, 2026
@wasimysaid
wasimysaid marked this pull request as ready for review June 4, 2026 06:06
@wasimysaid
wasimysaid requested a review from danielhanchen as a code owner June 4, 2026 06:06
@wasimysaid

Copy link
Copy Markdown
Collaborator Author

@codex review

@wasimysaid

Copy link
Copy Markdown
Collaborator Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a centralized ToolLoopController to manage local agentic tool loop state, handle duplicate, disabled, and one-shot tool calls, and record results or no-ops across GGUF and safetensors backends. It also refactors tool action nudges, integrates selective XML display stripping based on the auto-heal setting, and updates the frontend chat adapter to track tool call provenance and preserve correct message ordering. Extensive backend tests have been added to verify these changes. No review comments were provided for evaluation.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@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: cda66cab06

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

shimmyshimmer and others added 3 commits June 8, 2026 15:48
Resolve conflicts preferring PR tool-loop semantics with main's
ruff line-length 100 formatting and the unslothai#6072 exception/sandbox
hardening. PR's shared tool_loop_controller, allow_incomplete parser,
active_tools-gated signals, and _build_tool_action_nudge helper kept.
…text

Strict mode (allow_incomplete=False, Auto-Heal disabled) bound the
function body to the end of the response, so a complete call followed by
trailing prose was rejected while the JSON-style <tool_call> path already
tolerated it. Bind the body to the last </function> via rfind (so a
literal </function> inside a code parameter value still parses) and reject
only when no closing tag is present.

Adds test_tool_call_parser_strict.py (function/JSON parity, trailing text,
code-value close tag, incomplete-still-rejected) and
test_gguf_route_cursor_reset.py (preface -> disabled-tool no-op -> final
pass; final answer survives the SSE cursor reset, with a negative control).
@danielhanchen

danielhanchen commented Jun 8, 2026 •

Copy link
Copy Markdown
Member

Synced this branch with main and pushed the conflict resolution, so the PR is mergeable again. The conflicts were almost all from the ruff line-length 100 reformatting plus the route exception/sandbox hardening; I kept the PR's tool-loop semantics and main's formatting and hardening. The shared tool_loop_controller, the allow_incomplete parser path, the active_tools-gated streaming signals, and _build_tool_action_nudge all came through unchanged.

Also addressed the two open review comments:

  • tool_call_parser: with Auto-Heal disabled, a complete <function=...>...</function> call was rejected whenever the model appended any text after the closing tag, because the body was sliced to the end of the response rather than to </function>. The JSON <tool_call> path already tolerated trailing text, so function-style calls were silently dropped. Fixed by binding the body to the last </function> (rfind, so a literal </function> inside a code parameter still parses), and still rejecting calls with no closing tag. Added test_tool_call_parser_strict.py.
  • GGUF cursor reset after an internal no-op: this is already handled. The route resets the cumulative prev_text cursor on an empty status event, and the GGUF loop emits an empty status after a no-op break and again before the final pass, so the final answer is not diffed against the stale preface. Added test_gguf_route_cursor_reset.py, which drives the real generator through a faithful copy of the route cursor loop and includes a negative control proving the empty-status reset is load-bearing.

Validation:

  • Backend tool-loop suite green: test_tool_loop_controller, test_tool_xml_strip, test_anthropic_messages, test_safetensors_tool_loop, test_llama_cpp_tool_loop, plus the two new files. Full backend suite is 2114 passed; the only failure is the live-server E2E (test_studio_api::test_curl_basic) which needs a running server.
  • Cross-OS CI for the tool-loop tests passes on ubuntu-latest, windows-latest and macos-14.

Live before/after in Studio with local GGUFs (PRE = main, POST = this branch, identical prompts, temperature 0, enable_tools), across the full model lineup including the MTP and A3B MoE builds. The clearest difference is the duplicate-call bounding: on a "compute with code then answer" prompt, main re-issued the identical python call several times and repeated the final answer, while this branch bounds it to one call and moves to the answer.

Model PRE python calls POST python calls
Qwen3.5-4B 4 1
Qwen3.5-9B 6 1
gemma-4-E2B 8 1
gemma-4-E4B 2 1
gemma-4-12b 5 1
Qwen3.6-27B-MTP 9 1
Qwen3.6-35B-A3B-MTP 4 1

web_search, code execution and terminal still work on all seven models, with no tool-call XML leaking into the visible text on either side.

Accuracy did not regress. I ran a ground-truth-checked eval (temperature 0) on the two tool types: 12 deterministic code-execution prompts and 10 stable-fact web-search prompts, across Qwen3.5-4B, Qwen3.5-9B, gemma-4-E2B and Qwen3.6-27B-MTP. Per side that is 48 code and 40 web prompts.

code tool-fired code answer-correct web tool-fired web answer-correct
PRE (main) 48/48 48/48 40/40 40/40
POST (this branch) 47/48 48/48 40/40 40/40

Both sides answer 100 percent correctly; web_search fires and returns a grounded answer on all 40. The one code tool-fire difference is Qwen3.5-4B doing 123*456 in its head on POST rather than calling python, and the answer was still correct. So the duplicate-call bounding does not cost correctness or tool firing.

One unrelated observation: a thinking block leaks into the visible answer in 12 of 28 of the earlier traces, identical on PRE and POST, so it is a pre-existing display issue on main, not something this PR changes.

shimmyshimmer and others added 3 commits June 9, 2026 13:24
Resolve conflicts in the Studio tool-call loop after main's comment-tightening
(unslothai#6029/unslothai#6095/unslothai#6099) and Hub/Download Manager (unslothai#5916):

- llama_cpp.py, safetensors_agentic.py: keep the shared ToolLoopController flow
  (prepare_call/record_result/record_noop) over main's inline duplicate
  detection; the controller reproduces main's status text, error prefixes,
  image-sentinel strip, and allowed-tool gating.
- routes/inference.py: keep _build_tool_action_nudge (captures main's small-model
  web-tip simplification and date line) over the inline nudge.
- orchestrator.py: keep the active_tools single-turn signature with main's
  tighter comment.
- chat-adapter.ts: keep serializeAssistantReplayMessages/buildReplayContent;
  drop main's now-redundant collectAssistantToolCalls/collectToolResultMessages
  (their Gemini native_part handling lives in the PR's per-part helpers).
- test_safetensors_tool_loop.py: keep the controller-based duplicate test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants