Skip to content

fix(studio): prevent small models from stalling on tool-calling tasks - #4769

Merged
danielhanchen merged 2 commits into
mainfrom
fix/studio-tool-calling-small-models
Apr 2, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fix/studio-tool-calling-small-models

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Apr 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Small GGUF models (under ~9B params) in "Think, Search, Code" mode frequently stall after generating planning text like "Let me create this dashboard." without ever calling a tool. The model hits EOS after describing its plan, and the backend correctly returns -- but the user sees no tool calls and no code output.

Root cause: the system prompt nudge introduced in e159b93b encourages models to "fetch its full content by calling web_search with the url parameter," which creates a multi-step plan (search -> fetch URL -> create code) that small models cannot reliably execute in a single generation pass.

Changes

studio/backend/routes/inference.py

  • For models < 9B (detected via model name pattern), simplify _web_tips to just "Do not repeat the same search query" -- removing the URL-fetch encouragement that triggers multi-step planning
  • Append "Always call tools directly. Never describe what you plan to do -- just call the tool immediately." to the system prompt nudge for all models

studio/backend/core/inference/llama_cpp.py

  • In the _S_STREAMING exit path of the agentic loop, detect when the model produced a short response (under 500 chars) containing forward-looking intent signals ("let me", "I'll", "I will", "first,", "step N", etc.) without calling any tool
  • When detected, inject a user message asking the model to use tools and continue the loop
  • Capped at 1 re-prompt per request to prevent loops
  • The 500-char threshold prevents false positives on longer explanatory responses that naturally contain "I'll explain..." language

Benchmark results

161 total prompts tested (91 curated + 70 real-world from arena-expert-5k and gdpval)

Original bug (weather dashboard prompt):

Configuration Any Tool Called
Baseline 1/3 (33%)
Fix 3/3 (100%)

91 curated prompts by category:

Category Count Tools Used
Simple Q&A 15 5/15 (model chose to verify facts via search)
Conversational 5 0/5
Explanations 10 1/10
Creative writing 8 2/8
Advice 5 0/5
Code display (no exec) 5 1/5
Edge cases (regex traps) 10 4/10 (DNS, investing, dark matter -- reasonable to search)
Should use web tools 5 5/5 (100%)
Should use code tools 5 5/5 (100%)
Should create files 3 3/3 (100%)
Plan-risk (original bug) 8 7/8 (88%)
Mixed technical 12 2/12

70 real-world prompts (arena-expert-5k + gdpval):

Source Count Tools Used Re-prompts
Arena expert 50 42/50 (84%) 4
gdpval 20 6/20 (30%) 1

False positive analysis with the 500-char threshold:

  • Re-prompt rate: 5/70 (7%) on real-world prompts -- all on short plan preambles (154-411 chars)
  • Previously with 2000-char threshold: 30/70 (43%) -- way too aggressive
  • No re-prompt on direct answers like "What is 2+2?" or "Capital of France?"

Direct answer verification (should NOT trigger re-prompt):

Prompt Re-prompt? Tools?
"What is 2+2?" No None
"What is the capital of France?" No None
"Create a weather dashboard" Yes (134 chars) web_search, terminal
"Create a Python Snake Game" No web_search

Test plan

  • Benchmark with 91 curated prompts across 12 categories
  • Benchmark with 70 real-world prompts from arena-expert-5k and openai/gdpval
  • Verify re-prompt does NOT fire on direct answers
  • Verify re-prompt DOES fire on short plan preambles
  • Verify 500-char threshold prevents false positives on longer explanatory responses
  • Confirm weather dashboard prompt (original bug) is fixed at 100% tool calling
  • Verify larger models (9B+) still get the full URL-fetch guidance in _web_tips
  • Confirm no behavior change when tools are disabled

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

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

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

Comment on lines +2638 to +2639
yield {"type": "status", "text": ""}
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reset stream diff state before re-prompting

When this branch re-prompts, it emits only a status event and immediately continues, starting a new generation pass without a tool_start event. In routes/inference.py, prev_text is reset only on tool_start and otherwise used to diff cumulative content, so the next pass is diffed against stale text and the first characters/tokens are dropped or garbled for users in any plan-without-tool scenario.

Useful? React with 👍 / 👎.

Comment on lines +2289 to +2292
_PLAN_PATTERNS = _re_plan.compile(
r"(?i)\b(let me|i\'ll|i will|i\'m going to|"
r"now i\'ll|next i\'ll|i can|i should)\b"
)

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 Narrow plan pattern matching to avoid normal replies

This detector treats very common phrases like "i can" and "i should" as planning text, so many valid no-tool responses (for example, answers beginning with “I can help…”) will be misclassified and forced through extra re-prompt turns. That injects an artificial user message asking for tool use, which can cause unnecessary tool calls and latency regressions even when the model was already giving a correct final answer.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from 15e01ea to 5064633 Compare April 2, 2026 04:48

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

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

Comment on lines +2614 to +2617
if (
_reprompt_count < _MAX_REPROMPTS
and 0 < len(_stripped) < _REPROMPT_MAX_CHARS
):

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 Restrict re-prompt to plan text before forcing tool use

This re-prompt guard currently fires for any non-empty response shorter than 2000 chars, so valid direct answers in tool-enabled mode (for example, short factual replies) are always treated as failures and get an injected follow-up user message demanding tool use. That adds an unnecessary second model pass and can force needless tool calls/latency even when the first answer was already complete; the check needs a planning-specific predicate instead of length-only gating.

Useful? React with 👍 / 👎.

Comment on lines +2640 to +2641
yield {"type": "status", "text": ""}
continue

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 iteration budget when issuing a re-prompt

The re-prompt path uses continue inside the main for iteration in range(max_tool_iterations) loop, so it consumes one full tool-iteration slot even though no tool was called. With max_tool_iterations=1 (a supported request setting), the loop exits immediately after this branch and the request falls into the "used all available tool calls" fallback without ever giving the model a second generation pass, which defeats the intended recovery behavior.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from f624e87 to de5a0a8 Compare April 2, 2026 04:53

@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: 1a1abf0a5a

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

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +1103 to +1104
_size_match = _re_size.search(r"(\d+\.?\d*)\s*b", _model_id_lower)
_is_small_model = _size_match and float(_size_match.group(1)) < 9

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 Parse MoE model IDs correctly before applying small-model tips

The size heuristic uses r"(\d+\.?\d*)\s*b", which matches the first *b token in the model name; for MoE IDs like mixtral-8x7b, this resolves to 7b and marks the model as "small" even though the checkpoint is not in the intended <9B class. That incorrectly switches to the reduced _web_tips prompt and changes tool behavior for large MoE models. Please handle NxM naming patterns (or use explicit model metadata) before setting _is_small_model.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from 1a1abf0 to 666fa51 Compare April 2, 2026 05:44

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

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

Comment on lines +2631 to +2635
_stripped = content_accum.strip()
if (
_reprompt_count < _MAX_REPROMPTS
and 0 < len(_stripped) < _REPROMPT_MAX_CHARS
and _INTENT_SIGNAL.search(_stripped)

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 Include reasoning-only plan text in re-prompt trigger

The re-prompt guard only inspects content_accum, so it never fires when a model (especially with enable_thinking on) puts its planning text in reasoning_content and leaves content empty. In that case len(_stripped) is 0, the branch is skipped, and the request returns without any tool call, which is exactly the stall this change is trying to recover from. Please include reasoning-only outputs in the trigger condition (or evaluate a combined visible response) so plan-without-action responses in thinking mode are retried too.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from a54a849 to 0ca6ded Compare April 2, 2026 06:08

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

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

Comment on lines +2660 to +2663
_fu_r = _iter_usage or {}
_accumulated_completion_tokens += _fu_r.get(
"completion_tokens", 0
)

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 Accumulate timing stats when re-prompting

When the re-prompt branch fires, this code adds completion_tokens from the aborted iteration but does not add that iteration’s timings (predicted_ms / predicted_n) to the accumulated counters. As a result, later metadata can report total completion tokens across both passes while throughput timings only reflect the final pass, which skews performance telemetry and benchmark comparisons for any request that triggers a re-prompt.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from b4ff214 to 0a60b6e Compare April 2, 2026 06:16

@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: 4aaeaaef21

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

m = _SHARD_FULL_RE.match(gguf_filename)
if m:
prefix = m.group(1)
total = m.group(2)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Use total-shard group when matching variant shards

For sharded GGUF filenames like model-00001-of-00003.gguf, _SHARD_FULL_RE captures three groups (prefix, current shard index, total shard count), but this line reads group(2) as total. That makes sibling_pat look for files ending in -of-00001.gguf, so gguf_extra_shards stays empty and only one shard is downloaded when hf_variant is used. Split checkpoints then fail to load or produce corrupted model loads because required sibling shards are missing.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from 4aaeaae to 4b237d7 Compare April 2, 2026 06:34

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

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


# Reserve extra iterations for re-prompts so they don't
# consume the caller's tool-call budget.
for iteration in range(max_tool_iterations + _MAX_REPROMPTS):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Honor zero max_tool_iterations in agentic loop

max_tool_calls_per_message is documented as 0 = disabled (studio/backend/models/inference.py), but changing the loop to range(max_tool_iterations + _MAX_REPROMPTS) causes one full tool-enabled iteration even when max_tool_iterations is 0. In that configuration, requests that should never execute tools can still issue and run a tool call, which breaks the API contract and can trigger unintended external actions/cost.

Useful? React with 👍 / 👎.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +1238 to +1240
if not event["text"]:
prev_text = ""
continue

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 Emit empty status markers to clear tool status

This new branch drops empty status events, but the backend uses empty status as the explicit "clear" signal between tool phases and before answer streaming. Because the frontend only clears the running badge when it receives that empty status payload, tool runs can leave stale messages like "Searching..." visible until the entire stream ends, which is a regression for long post-tool responses.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from f657a1e to de978dd Compare April 2, 2026 08:01

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

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

Comment on lines +2338 to +2339
_extra = _MAX_REPROMPTS if max_tool_iterations > 0 else 0
for iteration in range(max_tool_iterations + _extra):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep tool-loop cap at max_tool_iterations

The loop now always runs max_tool_iterations + 1 whenever tool mode is enabled, even when no re-prompt happens. That means requests can execute one extra tool iteration beyond the caller’s configured limit (for example, max_tool_iterations=1 can still run a second tool round), which breaks the documented guardrail on tool usage/cost and can trigger unintended external actions.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member 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 re-prompting mechanism to handle 'plan-without-action' scenarios where models describe their intent instead of executing tool calls. It also optimizes performance by pre-compiling regex patterns and implements model-size-aware prompt adjustments. The review feedback suggests improving the robustness of the intent-detection regex to handle variations like 'I am' and curly apostrophes, and recommends refactoring duplicated model size extraction logic into a shared utility for better maintainability.

Comment on lines +33 to +47
_INTENT_SIGNAL = re.compile(
r"(?i)("
# Direct intent: "I'll ...", "I will ...", "Let me ..."
# Excludes "I can", "I should", "I want to", "let's" which
# appear frequently in direct answers / explanations.
r"\b(i'(ll|m going to|m gonna)|i will|i shall|let me|allow me)\b"
r"|"
# Step/plan framing: "First, ...", "Step 1:", "Here's my plan"
# Note: first[,:] does not need \b after punctuation.
r"\b(?:first[,:]|step \d+:?|here'?s (?:my |the |a )?(?:plan|approach))"
r"|"
# "Now I" / "Next I" patterns
r"\b(?:now i|next i)\b"
r")"
)

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.

medium

The _INTENT_SIGNAL regex can be made more robust to catch a wider range of planning language used by different models:

  • Support for "I am": Add support for "I am going to" and "I am gonna" (currently only handles the contracted "I'm").
  • Curly Apostrophes: Support curly apostrophes (’) which frequently appear in model outputs.
  • Optional Punctuation: Make the punctuation after "first" optional, as models often omit it (e.g., "First I will search...").
_INTENT_SIGNAL = re.compile(
    r"(?i)("
    # Direct intent: "I'll ...", "I will ...", "Let me ...", "I am going to ..."
    r"\b(i['’](ll|m going to|m gonna)|i am (going to|gonna)|i will|i shall|let me|allow me)\b"
    r"|"
    # Step/plan framing: "First ...", "Step 1:", "Here's my plan"
    r"\b(?:first\b|step \d+:?|here'?s (?:my |the |a )?(?:plan|approach))"
    r"|"
    # "Now I" / "Next I" patterns
    r"\b(?:now i|next i)\b"
    r")"
)

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +24 to +44
# Pre-compiled patterns for detecting model size from model name.
_MODEL_SIZE_RE = _re.compile(r"(\d+\.?\d*)\s*([bm])", _re.IGNORECASE)
# MoE active-parameter pattern: matches "A3B", "A3.5B", etc.
_ACTIVE_SIZE_RE = _re.compile(
r"(?:^|[-_/])a(\d+\.?\d*)\s*([bm])(?:$|[-_/])", _re.IGNORECASE
)


def _extract_model_size_b(model_id: str) -> float | None:
"""Extract model size in billions, preferring MoE active params."""
mid = (model_id or "").lower()
active = _ACTIVE_SIZE_RE.search(mid)
if active:
val = float(active.group(1))
return val / 1000.0 if active.group(2).lower() == "m" else val
size = _MODEL_SIZE_RE.search(mid)
if not size:
return None
val = float(size.group(1))
return val / 1000.0 if size.group(2).lower() == "m" else val

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.

medium

The model size extraction logic and its associated regex patterns are duplicated between this file and llama_cpp.py. To improve maintainability and ensure consistency across the backend (e.g., when adding support for new model naming conventions), this logic should be moved to a shared utility file, such as studio/backend/utils/models/model_config.py.

@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from e55a32e to 84c9915 Compare April 2, 2026 08:43

@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: 84c99154e1

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

import re as _re

# Model size extraction (shared with core/inference/llama_cpp.py)
from utils.models import extract_model_size_b as _extract_model_size_b

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Guard utils.models import with existing fallback logic

extract_model_size_b is imported before the module inserts backend_path and before the existing try/except ImportError fallback import block. In environments where utils is not already on sys.path (the exact case this file already handles later), importing this route now fails at module load with ModuleNotFoundError, so the inference router cannot start at all. Move this import into the guarded import section (or delay it) so fallback path resolution still works.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member 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 re-prompting mechanism to handle "plan-without-action" scenarios where models describe their intent instead of executing tool calls. It also centralizes regex patterns for tool parsing and GGUF shard detection, and adds a utility for extracting model sizes to adjust system prompts for smaller models. Review feedback suggests moving hardcoded constants and nudge strings to the module level to improve maintainability and readability.

Comment on lines 2298 to 2318
# identical call succeeded).
_tool_call_history: list[tuple[str, bool]] = [] # (key, failed)

for iteration in range(max_tool_iterations):
# ── Re-prompt on plan-without-action ─────────────────
# When the model describes what it intends to do (forward-looking
# language) without actually calling a tool, re-prompt once.
# Only triggers on responses that signal intent/planning -- a
# direct answer like "4" or "Hello!" will not match.
# Pattern is compiled once at module level (_INTENT_SIGNAL).
_reprompt_count = 0
_MAX_REPROMPTS = 1
_REPROMPT_MAX_CHARS = 500

# Reserve extra iterations for re-prompts so they don't
# consume the caller's tool-call budget. Only add the
# extra slot when tool iterations are actually allowed.
_extra = _MAX_REPROMPTS if max_tool_iterations > 0 else 0
for iteration in range(max_tool_iterations + _extra):
if cancel_event is not None and cancel_event.is_set():
return

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.

medium

The re-prompt logic uses a hardcoded limit of 1 re-prompt. This should be defined as a constant at the module level to improve maintainability and allow for easier configuration changes in the future.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +1147 to +1150
_nudge += (
" Always call tools directly. "
"Never describe what you plan to do -- just call the tool immediately."
)

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.

medium

The system prompt nudge is appended using string concatenation inside the loop. This should be defined as a constant or a template string outside the loop to avoid redundant string creation and improve readability.

@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from 197b509 to 0e6a576 Compare April 2, 2026 08:54
@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini 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: 593856f6ae

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

r"\b(i['\u2019](ll|m going to|m gonna)|i am (going to|gonna)|i will|i shall|let me|allow me)\b"
r"|"
# Step/plan framing: "First ...", "Step 1:", "Here's my plan"
r"\b(?:first\b|step \d+:?|here['\u2019]?s (?:my |the |a )?(?:plan|approach))"

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 Tighten intent regex to avoid ordinary "first" matches

The re-prompt path in generate_chat_completion_with_tools is gated by _INTENT_SIGNAL, but the pattern currently matches any standalone first. With tools enabled, short valid answers that naturally use that word (for example instructional replies like “First, …” or definitions like “First-class …”) are misclassified as plan-without-action text and forced into an extra re-prompt turn, adding latency and often unnecessary tool calls.

Useful? React with 👍 / 👎.

Comment on lines +1333 to +1334
size_val = _extract_model_size_b(mid)
if size_val is not None and size_val < 9:

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 Keep Qwen3.5 thinking threshold based on total model size

This check now uses extract_model_size_b, which prefers MoE active-size tags (for example A3B) over total parameter size. For a model id like Qwen3.5-35B-A3B, size_val becomes 3 and this branch disables thinking, even though the surrounding rule says only small Qwen3.5 models (<9B, like 0.8B/2B/4B) should default thinking off. That changes defaults for large Qwen3.5 MoE variants and can degrade response quality unexpectedly.

Useful? React with 👍 / 👎.

@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 re-prompting mechanism to handle "plan-without-action" scenarios where models describe intent instead of executing tool calls. It refactors regex patterns for GGUF shard detection and tool XML parsing into pre-compiled constants and adds a utility to extract model sizes for tailoring system prompts. Feedback identifies a potential logic flaw in intent detection when content is whitespace-only and suggests tightening the model size regex to prevent false matches with version numbers.

Comment on lines +2635 to +2637
_stripped = content_accum.strip()
if not _stripped and not has_content_tokens:
_stripped = reasoning_accum.strip()

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.

medium

When falling back to reasoning_accum for intent detection, the code assumes that if content_accum is empty, the model might have put its plan in the reasoning block. However, if has_content_tokens is true but content_accum.strip() is empty (e.g., only whitespace tokens), the fallback to reasoning won't trigger. This might be an edge case where a model outputs spaces before hitting EOS, causing a stall that isn't caught if the plan was in reasoning.

_stripped = content_accum.strip()
if not _stripped:
    _stripped = reasoning_accum.strip()

# ── Model size extraction ────────────────────────────────────
import re as _re

_MODEL_SIZE_RE = _re.compile(r"(\d+\.?\d*)\s*([bm])", _re.IGNORECASE)

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.

medium

The _MODEL_SIZE_RE pattern is quite broad and might match version numbers or other digits in a model path if they are followed by 'b' or 'm' (e.g., model_v1b). Since extract_model_size_b is used to determine if a model is 'small' for prompting logic, a false match could lead to incorrect system prompts.

Suggested change
_MODEL_SIZE_RE = _re.compile(r"(\d+\.?\d*)\s*([bm])", _re.IGNORECASE)
_MODEL_SIZE_RE = _re.compile(r"(?:^|[-_/])(\d+\.?\d*)\s*([bm])(?:$|[-_/])", _re.IGNORECASE)

Small GGUF models (< 9B params) in "Think, Search, Code" mode would
often describe what they planned to do ("Let me create this dashboard")
and then stop generating without ever calling a tool.

Three changes:

1. Simplify web_tips for small models: remove the "fetch its full content
   by calling web_search with the url parameter" guidance for models < 9B.
   This multi-step instruction causes small models to plan elaborate
   search-then-fetch-then-code sequences they cannot reliably execute.

2. Add "always call tools directly" imperative to the system prompt nudge
   so models act immediately instead of narrating their intentions.

3. Add plan-without-action re-prompt in the agentic loop: when the model
   emits planning text (matching patterns like "let me", "I'll", etc.)
   without calling any tool, inject a nudge asking it to call the tool
   and continue the loop. Capped at 2 re-prompts per request.

Benchmarked with Qwen3.5-4B-GGUF (N=5 trials per variant):
- Baseline: 40% of requests had any tool call
- Combined fix: 100% of requests had at least one tool call
@danielhanchen
danielhanchen force-pushed the fix/studio-tool-calling-small-models branch from 593856f to ad9b29e Compare April 2, 2026 09:04
@danielhanchen

Copy link
Copy Markdown
Member 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 centralizes regex patterns and model size extraction logic across the GGUF backend and inference routes. It introduces a re-prompting mechanism to nudge models into executing tools when they provide forward-looking intent without action, and tailors system prompts and tips for smaller models. A critical NameError was identified in llama_cpp.py where the re module is accessed in _download_gguf after its local import was removed, which will cause the application to crash.

if hf_variant:
try:
import re
from huggingface_hub import list_repo_files

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.

critical

The import re statement was removed, but re is still used in the _download_gguf method via _SHARD_FULL_RE.match on line 867 and re.escape on line 873. This will cause a NameError at runtime.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

re is imported at the top of the file (line 14: import re). The removed import re statements were redundant inline imports inside individual methods. All re.escape and re.compile calls still resolve to the module-level import.

@danielhanchen
danielhanchen merged commit e4d1499 into main Apr 2, 2026
5 checks passed
@danielhanchen
danielhanchen deleted the fix/studio-tool-calling-small-models branch April 2, 2026 09:11
shibizhao pushed a commit to shibizhao/unsloth-npu that referenced this pull request Apr 7, 2026
…unslothai#4769)

* fix(studio): prevent small models from stalling on tool-calling tasks

Small GGUF models (< 9B params) in "Think, Search, Code" mode would
often describe what they planned to do ("Let me create this dashboard")
and then stop generating without ever calling a tool.

Three changes:

1. Simplify web_tips for small models: remove the "fetch its full content
   by calling web_search with the url parameter" guidance for models < 9B.
   This multi-step instruction causes small models to plan elaborate
   search-then-fetch-then-code sequences they cannot reliably execute.

2. Add "always call tools directly" imperative to the system prompt nudge
   so models act immediately instead of narrating their intentions.

3. Add plan-without-action re-prompt in the agentic loop: when the model
   emits planning text (matching patterns like "let me", "I'll", etc.)
   without calling any tool, inject a nudge asking it to call the tool
   and continue the loop. Capped at 2 re-prompts per request.

Benchmarked with Qwen3.5-4B-GGUF (N=5 trials per variant):
- Baseline: 40% of requests had any tool call
- Combined fix: 100% of requests had at least one tool call

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant