Skip to content

[Bug] Unsloth Studio sometimes nudges models for tool calls when they did not make any tool call #8907

Closed

Description

@jimster480

About
Docs, release notes, feedback, and build info.

Unsloth
Unsloth Version
v0.1.702-beta
Package Version
2026.8.16
llama.cpp Version
b10360-mix-87da1a2
Windows 10

Hardware
GPU 0
AMD Radeon PRO W7900 · 45 GiB
GPU 1
AMD Radeon PRO W7500 · 8 GiB
ROCm
7.13.99004

Just as the Title says; I did my test prompt of "Balls" and Qwen3.8-27B responded and then Unsloth Studio nudged it for a tool call that it didn't ask for.
Here are the logs + screenshot:

Image
{"timestamp": "2026-08-15T04:27:45.910037Z", "level": "info", "event": "request_completed", "method": "PUT", "path": "/api/chat/threads/__LOCALID_ZX1j2we/messages", "status_code": 200, "process_time_ms": 31.58}
{"timestamp": "2026-08-15T04:27:46.260870Z", "level": "info", "event": "request_completed", "method": "POST", "path": "/api/chat/messages:batch", "status_code": 200, "process_time_ms": 19.48}
{"timestamp": "2026-08-15T04:27:49.233208Z", "level": "info", "event": "engine_stats", "gen_tok_s": 31.3, "prompt_tok_s": 546.0, "running": 1, "waiting": 0}
{"timestamp": "2026-08-15T04:27:50.133001Z", "level": "info", "event": "request_completed", "method": "GET", "path": "/api/inference/monitor", "status_code": 200, "process_time_ms": 6.76}
{"timestamp": "2026-08-15T04:27:50.609302Z", "level": "info", "event": "Re-prompt 1/3: model responded without calling tools (313 chars)"}
{"timestamp": "2026-08-15T04:27:58.160456Z", "level": "info", "event": "request_completed", "method": "POST", "path": "/v1/chat/completions", "status_code": 200, "process_time_ms": 12288.86}
{"timestamp": "2026-08-15T04:27:58.212210Z", "level": "info", "event": "request_completed", "method": "GET", "path": "/api/chat/threads/__LOCALID_ZX1j2we/messages/x5SBXO1/forks", "status_code": 200, "process_time_ms": 6.52}
{"timestamp": "2026-08-15T04:27:58.223339Z", "level": "info", "event": "request_completed", "method": "GET", "path": "/api/chat/threads/__LOCALID_ZX1j2we/messages/x5SBXO1", "status_code": 200, "process_time_ms": 7.95}
{"timestamp": "2026-08-15T04:27:58.232114Z", "level": "info", "event": "request_completed", "method": "GET", "path": "/api/chat/threads/__LOCALID_ZX1j2we", "status_code": 200, "process_time_ms": 5.74}
{"timestamp": "2026-08-15T04:27:58.246192Z", "level": "info", "event": "request_completed", "method": "PUT", "path": "/api/chat/threads/__LOCALID_ZX1j2we/messages/x5SBXO1", "status_code": 200, "process_time_ms": 11.43}
{"timestamp": "2026-08-15T04:27:58.301750Z", "level": "info", "event": "request_completed", "method": "PUT", "path": "/api/chat/threads/__LOCALID_ZX1j2we/messages", "status_code": 200, "process_time_ms": 22.53}
{"timestamp": "2026-08-15T04:27:58.643072Z", "level": "info", "event": "request_completed", "method": "POST", "path": "/api/chat/messages:batch", "status_code": 200, "process_time_ms": 17.86}
{"timestamp": "2026-08-15T04:27:59.239242Z", "level": "info", "event": "engine_stats", "gen_tok_s": 30.5, "prompt_tok_s": 628.1, "running": 0, "waiting": 0}

Also the prompt speed was incorrect here as it never hit 843 tok/sec pp as seen by the above log.

Image

Activity

  1. added
    feature request
    on Aug 15, 2026
  2. danielhanchen commented on Aug 17, 2026

    @danielhanchen
    Member

    Sometimes this happens hmmm

  3. ekimtan commented on Aug 17, 2026

    @ekimtan

    I encountered this issue as well and asked claude to debug it. Here are the findings, might be useful

    The re-prompt gate has three different defaults for the same feature:

    path gate default when the request omits nudge_tool_calls
    passthrough_healing.py:61 nudge_enabled() UNSLOTH_TOOL_CALL_NUDGE off — the comment at :56 says "Nudging is OPT-IN"
    safetensors_agentic.py:1012 and nudge_tool_calls off
    llama_cpp.py:20741 and (nudge_tool_calls is None or nudge_tool_calls) on
    studio_tool_loop.py (external providers) none — the file has no reference to nudge_enabled always on

    Your Re-prompt 1/3 line comes from llama_cpp.py, the default-on one, so a UI request that never mentions nudge_tool_calls gets nudged even though the documented default is off. That alone explains the "Balls" case.

    The external-provider loop is worse. Besides being ungated, it never adds the streamed answer to conversation — append_assistant_turn runs only inside the if stalled_hosted: branch (compare safetensors_agentic.py:1031, which appends unconditionally). So the re-prompted model sees only the original question plus the nudge and re-answers from scratch; round 1 has already reached the client, so the UI concatenates up to 4 complete answers into one assistant message — and resends all of them on every later turn.

    From my logs (llama.cpp as an external provider): one inbound POST /v1/chat/completions at 35738 ms containing four Proxying chat completion calls, delta counts 899 + 844 + 956 + 1049 = 3748, exactly the message's totalChunks, with 0.001 s between rounds. Note that path logs nothing when it nudges, so there is no Re-prompt n/3 line to spot it by.

    The trigger is is_short_intent_without_action(): under 2000 chars and matching INTENT_SIGNAL. An ordinary conversational "Let me take them in order" is enough, which is why it looks random.

    This looks like a regression of #7122 — #7134 fixed the safetensors path but didn't touch studio_tool_loop.py.

    Repro below drives the real loop with a stub transport — no GPU, model, server or credentials. Run it with the Python that has unsloth installed (for Desktop, the bundled interpreter). On an unpatched install it prints:

    provider invocations : 4
       call 1: 1 msg(s) ['user']
       call 2: 1 msg(s) ['user']
       call 3: 1 msg(s) ['user']
       call 4: 1 msg(s) ['user']
    
    answers on the client stream : 4
    

    Note every call gets a 1-message conversation — the assistant turn is never added, which is why each round re-answers from scratch. --answer "Done. The file has 12 lines." (no intent phrase) and --no-tools both give 1 call / 1 answer.

    repro_loop.py
    #!/usr/bin/env python3
    """
    Repro for the external-provider tool-loop re-prompt (unslothai/unsloth#8907).
    
    Drives studio_tool_loop.stream_with_studio_tools with a stub transport, so it
    needs no GPU, no model, no server and no credentials. Run it with the Python
    that has unsloth installed (for Unsloth Desktop that is the bundled
    interpreter, e.g. <data-dir>/studio/unsloth_studio/Scripts/python.exe).
    
        python repro_loop.py            # -> 4 provider calls, 4 answers
        python repro_loop.py --answer "Done. The file has 12 lines."   # -> 1, 1
        python repro_loop.py --no-tools # empty catalog, loop never runs -> 1, 1
    
    The stub returns the same answer however the conversation looks, which is how
    the real model behaves here: the loop never appends the streamed answer to
    `conversation`, so the model cannot tell it already answered.
    
    Exit code 0 when exactly one answer was produced, 1 otherwise.
    """
    
    import argparse
    import asyncio
    import json
    import site
    import sys
    import threading
    from pathlib import Path
    
    DEFAULT_ANSWER = "Let me take a look at that for you."
    
    TOOL_CATALOG = [
        {
            "type": "function",
            "function": {
                "name": "read_file",
                "description": "Read a file from disk.",
                "parameters": {
                    "type": "object",
                    "properties": {"path": {"type": "string"}},
                    "required": ["path"],
                },
            },
        }
    ]
    
    
    def find_backend(explicit=None):
        """Locate studio/backend so `core.inference...` imports resolve."""
        if explicit:
            return Path(explicit)
        roots = list(site.getsitepackages())
        try:
            roots.append(site.getusersitepackages())
        except Exception:
            pass
        roots.extend(p for p in sys.path if p)
        for root in roots:
            candidate = Path(root) / "studio" / "backend"
            if (candidate / "core" / "inference" / "studio_tool_loop.py").is_file():
                return candidate
        raise SystemExit(
            "Could not find studio/backend. Run this with the Python that has "
            "unsloth installed, or pass --backend <path-to-studio/backend>."
        )
    
    
    def _chunk(**delta):
        return "data: " + json.dumps(
            {
                "id": "chatcmpl-stub",
                "object": "chat.completion.chunk",
                "model": "stub",
                "choices": [{"index": 0, "delta": delta, "finish_reason": None}],
            }
        )
    
    
    class StubTransport:
        heals_text_tool_calls = True
        sanitizes_provider_frames = False
    
        def __init__(self, answer):
            self.answer = answer
            self.calls = []
    
        def stream(self, *, messages, tools, tool_choice, cancel_event):
            self.calls.append(
                {"n_messages": len(messages), "roles": [m.get("role") for m in messages]}
            )
            # A real model rewords each attempt, so is_reprompt_repeat() -- which
            # only catches a verbatim restatement -- does not end the loop.
            answer = f"{self.answer} (attempt {len(self.calls)})"
    
            async def gen():
                yield _chunk(reasoning_content="Thinking about the request.")
                yield _chunk(content=answer)
                yield "data: " + json.dumps(
                    {
                        "id": "chatcmpl-stub",
                        "object": "chat.completion.chunk",
                        "model": "stub",
                        "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
                    }
                )
                yield "data: [DONE]"
    
            return gen()
    
    
    async def main_async(args):
        sys.path.insert(0, str(find_backend(args.backend)))
        from core.inference.studio_tool_loop import (
            ToolLoopPolicy,
            ToolLoopRun,
            stream_with_studio_tools,
        )
        from core.inference.tool_call_parser import (
            INTENT_SIGNAL,
            MAX_ACT_REPROMPTS,
            REPROMPT_MAX_CHARS,
            is_short_intent_without_action,
        )
    
        hit = INTENT_SIGNAL.search(args.answer.strip())
        print(f"answer           : {args.answer!r}")
        print(f"length           : {len(args.answer)} (threshold {REPROMPT_MAX_CHARS})")
        print(f"INTENT_SIGNAL    : {hit.group(0)!r}" if hit else "INTENT_SIGNAL    : no match")
        print(f"would nudge      : {is_short_intent_without_action(args.answer)}")
        print(f"MAX_ACT_REPROMPTS: {MAX_ACT_REPROMPTS}\n")
    
        transport = StubTransport(args.answer)
        answers, reasonings = [], 0
    
        async for line in stream_with_studio_tools(
            transport,
            run=ToolLoopRun(
                messages=[{"role": "user", "content": "Check the config file for me."}],
                model="stub",
            ),
            policy=ToolLoopPolicy(
                tools=[] if args.no_tools else TOOL_CATALOG,
                max_calls=25,
                timeout=300,
                permission_mode="auto",
                confirm_calls=False,
                bypass_permissions=False,
                rag_scope=None,
            ),
            cancel_event=threading.Event(),
        ):
            line = line.strip()
            if not line.startswith("data:"):
                continue
            body = line[5:].strip()
            if body == "[DONE]":
                continue
            try:
                data = json.loads(body)
            except json.JSONDecodeError:
                continue
            for choice in data.get("choices", []) or []:
                delta = choice.get("delta", {}) or {}
                if delta.get("reasoning_content"):
                    reasonings += 1
                if delta.get("content"):
                    answers.append(delta["content"])
    
        print(f"provider invocations : {len(transport.calls)}")
        for i, call in enumerate(transport.calls, 1):
            print(f"   call {i}: {call['n_messages']} msg(s) {call['roles']}")
        print(f"\nanswers on the client stream : {len(answers)}")
        for i, a in enumerate(answers, 1):
            print(f"   answer {i}: {a!r}")
        print(f"reasoning blocks             : {reasonings}\n")
    
        if len(answers) > 1:
            print(f"RESULT: {len(answers)} answers in one response.")
            return 1
        print("RESULT: exactly one answer.")
        return 0
    
    
    def main():
        ap = argparse.ArgumentParser()
        ap.add_argument("--answer", default=DEFAULT_ANSWER)
        ap.add_argument("--no-tools", action="store_true")
        ap.add_argument("--backend", help="path to site-packages/studio/backend")
        return asyncio.run(main_async(ap.parse_args()))
    
    
    if __name__ == "__main__":
        sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugfeature request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions