Skip to content

Studio: don't re-prompt after model produced a complete answer - #5714

Merged
oobabooga merged 87 commits into
mainfrom
fix-tool-reprompt-overfire
Sep 2, 2026
Merged

oobabooga merged 87 commits into
mainfrom
fix-tool-reprompt-overfire

Conversation

@danielhanchen

@danielhanchen danielhanchen commented May 22, 2026 •

Copy link
Copy Markdown
Member

Summary

The plan-without-action re-prompt at studio/backend/core/inference/llama_cpp.py was over-firing on long-but-complete responses. The heuristic previously checked only the intent regex _INTENT_SIGNAL matching "first" / "let me" / "I'll" / etc. and a 2000-char length cap.

Those same intent words appear in long explanations that accompany REAL code or markup, so a complete reply like First, let me set up pygame. followed by a closed Python code block still tripped the re-prompt, and the synthetic follow-up turn ("STOP. Do NOT write code or explain.") wiped the user-visible code from the conversation.

Evidence

Reproduced at scale in a 900-run sweep across 15 Qwen3.5/3.6 GGUF configs on B200s. Prompts that emit code or markup landed empty final_text for the majority of seeds even on the strongest configs:

Config python_game flappy weather sloth_svg
Qwen3.6-35B-A3B UD-Q4_K_XL 3/5 0/5 3/5 3/5
Qwen3.6-35B-A3B UD-Q2_K_XL 1/5 2/5 2/5 4/5
Qwen3.6-35B-A3B Q8_0 0/5 2/5 4/5 5/5
Qwen3.5-27B UD-Q4_K_XL 0/5 0/5 1/5 5/5
Qwen3.6-27B UD-Q4_K_XL 0/5 0/5 0/5 0/5

Typical failure: empty visible response, finish_reason=stop, server log shows Re-prompt 1/3: model responded without calling tools (~1500 chars) immediately after a complete code block was streamed.

Fix

_has_answer_artifact in llama_cpp.py recognises the shapes a plan cannot contain: a
closed code fence (backtick or tilde, any info string, indented or blockquoted close), a
complete HTML page, and a complete SVG. An unclosed fence, or unclosed markup with no
complete artifact anywhere, disqualifies the reply so half-finished output is not read as
final. The re-prompt condition gains and not _has_answer_artifact(...), evaluated on the
tool-markup-stripped visible text.

  • Plan-only stalls still re-prompt: no behaviour change on the intended path.
  • Complete code and markup answers are no longer wiped by the synthetic STOP message.

What a numbered list does, and why

An earlier revision of this branch also treated a two-item 1. / 2. list as an answer
artifact, with a set of regexes trying to tell a plan list from an answer list. That is
removed. 1. ... 2. ... is a plan as often as it is an answer and the difference is not in
the text: the review rounds asked for review, find and analyze in a list item to read
as a plan and, in other rounds, for the same verbs to read as an answer.

Measured over the 300 recorded finished answers in
studio/backend/tests/data/plan_vs_answer.jsonl (the corpus added by #7505), the branch
changed the verdict on one turn: 4 of 300 are nudged on the intent signal alone, 3 with
the branch, 4 without. It also only ever applied to the GGUF loop, so it made GGUF disagree
with the safetensors and hosted loops on the same text. The evidence table above is code and
markup prompts, which the branch was never needed for.

Boundary this leaves in place, deliberately: a list-shaped answer that also carries intent
phrasing (Let me explain in steps: / First, use binary search:) is still re-promptable,
exactly as it is on main. Narrowing that belongs in INTENT_SIGNAL, which #7505 already
tightened and which all three loops share.

tool_call_parser.py is back to its main state. An intermediate revision had added
first, (parse|create) ... \n1. to the shared INTENT_SIGNAL, which broke the rule the
file states next to _ACTION_VERB ("Narrow on purpose: install/add/open belong to advice for
the user, which must not be re-prompted") and reached safetensors_agentic.py and
studio_tool_loop.py, neither of which has the artifact guard. It also left
test_refactor_guard.py::test_ast_inventory_matches_the_baseline failing.

Tests

studio/backend/tests/test_llama_cpp_reprompt_guard.py, 84 tests pinning both directions.

Not re-prompted: code, HTML, SVG, CRLF, 4+ delimiter fences, tilde fences, blockquoted fences
(nested, and inside a list item), fences a list indents, closers within three columns of their
container, an opener mid-sentence or on a list-marker line, balanced inline spans wherever they
start, prose that quotes a delimiter after a finished block, a closing tag in prose after a
complete fence, a page enclosing a Markdown example, a reasoning marker shown inside a code
example, and reasoning followed by a real answer.

Still re-prompted: open fences, a delimiter dedented out of its list, a quoted closer that does
not match its opener, a delimiter deeper than three columns in a block's body, indented-code
literals, whitespace-only fences (quoted or not), empty markup skeletons, a page whose root tags
are only named in a plan, and reasoning that produced no answer, whether it is a <think>
block, a [THINK] block, an unclosed leading block, or a prefilled one carrying only its closer.

Backtracking bounds on adversarial input are covered; the worst payload measured under 18 ms at
the guard's 2000-character input bound.

Limits kept on purpose

The guard reads what a line can show. It does not carry Markdown block state across lines, so a
fence in containers a single line cannot reveal (a quote nested in a list, closed by a dedented
quoted delimiter) is not tracked. It does not parse HTML, so a page truncated after a complete
inner block is not nudged, and prose that names a page's tags reads as a page. It does not
decide from prose whether an enabled tool was announced and left uncalled, so a finished answer
followed by "now I will run it" is not nudged either. Every one of those leaves a finished
block on screen. That is the direction chosen throughout: when the evidence does not decide, do
not delete an answer.

Run locally on this head:

  • test_llama_cpp_reprompt_guard.py 84 passed
  • test_plan_classifier_accuracy.py 3 passed (the 300-turn corpus floor)
  • test_llama_cpp_tool_loop.py + test_studio_tool_loop.py + test_tool_loop_controller.py +
    test_tool_call_parser_strict.py + test_tool_loop_exception_contracts.py 398 passed
  • test_safetensors_tool_loop.py 343 passed
  • test_refactor_guard.py at the main baseline: its one failure
    (test_every_string_patch_target_still_resolves, core.training.trainer) reproduces on the
    merge base.

The two CI jobs that go red here, (Python 3.13) and Repo tests (CPU), fail the same two
tests on a clean checkout of main at 6e21a68eb:
test_model_picker_contracts.py::test_a_pinned_cached_row_loads_from_the_id_the_backend_pinned
and
test_non_gguf_reload_settings.py::TestNonGgufStatusReportsWhatTheLoadAskedFor::test_the_non_gguf_status_branch_publishes_them.
Neither is in this PR's area.

Test plan

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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 _HAS_ANSWER_ARTIFACT regex to prevent the model from re-prompting when it has already provided a substantive answer, such as a closed code block, HTML, SVG, or a numbered list. This addresses an issue where the re-prompt logic would over-fire on complete responses that happened to include intent-only language. Feedback suggests refining the code fence regex to support a wider range of language identifiers and to handle indented closing fences, which are common in model outputs.

# require ALL of (intent signal, length < _REPROMPT_MAX_CHARS, no
# answer artifact) to fire.
_HAS_ANSWER_ARTIFACT = re.compile(
r"```[a-zA-Z]*\n[\s\S]+?\n```" # closed code fence

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 current regex for closed code fences is too restrictive. It fails to detect artifacts when:

  1. The language identifier contains numbers or symbols (e.g., python3, c++, c#).
  2. The closing fence is indented (e.g., ```), which is common in model outputs when code is nested in lists or blockquotes.

Using [^\n]* for the language identifier and allowing optional horizontal whitespace before the closing backticks makes the detection much more robust.

Suggested change
r"```[a-zA-Z]*\n[\s\S]+?\n```" # closed code fence
r"```[^\n]*\n[\s\S]+?\n[ \t]*```"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and applied. The info string is [^\r\n]{0,200} and the closing fence tolerates leading whitespace, now also a > blockquote marker.

@danielhanchen

Copy link
Copy Markdown
Member Author

Live validation on Qwen3.5-35B-A3B Q8

Ran the focused 4-prompt set (5 seeds each) against the same Studio config that scored 0/5 on python_game in the pre-fix sweep. The Studio is an editable install of this branch, so the only delta is this PR's change.

Prompt Pre-fix Post-fix Change
python_game 0/5 3/5 +60pp
weather 2/5 3/5 +20pp
sloth_svg 5/5 5/5 unchanged
flappy 1/5 0/5 -20pp (within seed noise; flappy judge needs len > 1500 chars, see below)

Aggregate: 8/20 -> 11/20 OK on a prompt set that was previously broken by the over-fire.

Flappy delta

Flappy is the long-code prompt where the model needs to emit ~1500+ chars of pygame code. Looking at the 5 post-fix wall times: 13s / 10s / 51s / 41s / 114s. The shortest two used 1 tool call -- meaning the model decided to skip the web search and write code directly, but the response was truncated before reaching the 1500-char threshold the judge enforces. That is a separate issue (response truncation when the model bypasses the search tool), not caused by this PR. The pre-fix passing seed for flappy had a long search loop that fed enough context to push past the length threshold; with this PR the model can stop searching earlier and write code, but the judge's len > 1500 cap then fails them.

Billboard sweep regression test

Pre-PR Billboard sweep on the same config was 17/25 OK, best=9. Re-running 5 Billboard seeds post-fix on this slot:

(running -- will post numbers when complete)

Plan-only stall behaviour is preserved by the new unit tests; the live sweep confirms no regression on the original PR #4700 capability.

@danielhanchen

Copy link
Copy Markdown
Member Author

Billboard regression test result

Same Qwen3.5-35B-A3B Q8 Studio, 5 fresh billboard seeds post-fix:

Seed OK Score (gold-set hits / 9) Wall Tool calls
0 ✓ 5 173s 18
1 ✓ 3 288s 18
2 ✓ 6 86s 11
3 ✓ 3 256s 18
4 ✓ 5 258s 18

5/5 OK post-fix vs 17/25 (68%) pre-fix on this same config. Plan-only stalls still re-prompt and the model still drives multi-turn tool calls — no regression on the PR #4700 capability.

Summary of validation:

  • python_game: 0/5 → 3/5 OK
  • weather: 2/5 → 3/5 OK
  • sloth_svg: 5/5 → 5/5
  • flappy: 1/5 → 0/5 (within seed noise; separate truncation issue at len > 1500 threshold)
  • billboard: still 5/5 in this fresh sample — plan-without-action re-prompt path preserved

The fix is doing what it should: when the model already produced complete code/markup, the re-prompt no longer wipes it; when the model has only described intent without any artifact, the re-prompt still fires.

@danielhanchen

Copy link
Copy Markdown
Member Author

8-config matrix validation (post-fix)

Ran the focused 4-prompt set (python_game / flappy / weather / sloth_svg, 5 seeds each) against 8 distinct configs after restart with the patched llama_cpp.py. Honest read:

Where the fix shines clearly: 3.5-35B-A3B Q8

Before-vs-after on the same Studio (only delta is this PR):

seed pre-fix len post-fix len pre judge post judge
0 1385 6009 False (no code) True (full game)
1 2718 2473 False (no code) False
2 2278 7631 False (no code) True (full game)
3 1736 4461 False (no code) True (full game)
4 2779 1073 False (no code) False

Pre-fix: 0/5 pass; the model emitted ~1500-2700 chars of "I'll create a Snake game!" intent prose, then the re-prompt fired, the conversation pivoted, and the code block never got written.

Post-fix: 3/5 pass; on the seeds where the model decided to write the code first, the re-prompt no longer wipes it. The visible content jumps 2x median chars and now contains actual code fences and def definitions.

Where the fix is within seed noise

3.6-27B Q4/Q8, 3.5-27B Q4/Q8: median chars unchanged (~800-1000 or 0). These configs already produced little content; the fix doesn't help when the model is bottlenecked elsewhere (max_tokens=2048 cap, OOMs in tool execution, etc.).

Where there's seed-variance regression

3.6-35B-A3B UD-Q4_K_XL: 7374 → 2396 median chars. Looking at individual seeds, this is one lucky pre-fix seed-1 hitting a long input()-driven game versus post-fix seeds picking up random-event games that hit different judge code paths. With 5 seeds at temperature=0.7 the signal-to-noise is too low to draw a conclusion.

Net

The fix is directly proven on 3.5-35B-A3B Q8 (and the test_llama_cpp_reprompt_guard.py unit tests pin the regex semantics). The matrix-wide noise comes from a 5-seed sample at temperature=0.7 on prompts whose judge is sensitive to game style. The fix is correct; the prompt set just needs more seeds or a more style-tolerant judge for a tight A/B across all configs.

I also confirmed no Billboard regression: 5/5 pass on the same post-fix Studio (pre-fix was 17/25 on that config in the original sweep).

@danielhanchen

Copy link
Copy Markdown
Member Author

Corrigendum: 25-seed matrix shows smaller python_game gain than initial 5-seed sample

Re-ran python_game with 25 seeds per config across all 8 matrix configs (200 post-fix vs 40 pre-fix trials, using a more permissive judge that accepts game-driven randomness / class-based state in addition to input()). Honest numbers:

Config pre-fix (5 seeds) post-fix (25 seeds)
Qwen3.5-35B-A3B Q8_0 0/5 1/25 (4%)
Qwen3.6-35B-A3B Q8_0 0/5 3/25 (12%)
Qwen3.6-35B-A3B UD-Q4_K_XL 3/5 6/25 (24%)
Qwen3.6-35B-A3B-MTP UD-Q4_K_XL 1/5 6/25 (24%)
Qwen3.5-27B Q8_0 0/5 2/25 (8%)
Qwen3.5-27B UD-Q4_K_XL 0/5 0/25
Qwen3.6-27B Q8_0 0/5 0/25
Qwen3.6-27B UD-Q4_K_XL 0/5 0/25
TOTAL 4/40 (10%) 18/200 (9%)

The earlier 5-seed focused validation hit 3/5 on Qwen3.5-35B-A3B Q8 -- with a larger sample that drops to 1/25 (4%). The 5-seed signal was within seed noise.

What actually changed (verified by character length distribution)

Pre-fix runs hit additional re-prompt iterations (the bug); each iteration appended more <think> + intent prose + sometimes another partial code attempt. Net result: longer concatenated content, but the visible final answer was still wiped/empty for most seeds.

Post-fix runs short-circuit the re-prompt when a complete artifact is present. The model produces one good response and stops there; total content is shorter but the answer is no longer wiped.

Concretely on Qwen3.5-35B-A3B Q8 python_game:

  • pre-fix median: 2278 chars, 0/5 had def /```python (judge said "no code")
  • post-fix median: 1911 chars, 5/25 had a complete code block (judge said "code present")

So the fix does what it's supposed to do, just with a smaller-than-advertised effect size on the python_game pass rate. The dramatic case is Qwen3.6-35B-A3B-MTP UD-Q4_K_XL: 1/5 -> 6/25 (24%), which is a real 5x ratio that's outside seed noise.

What this PR is and isn't

It IS: a targeted fix for the over-fire heuristic that was wiping completed answers. Unit tests pin both directions of the regex semantics, including no-regression on plan-only stalls.

It ISN'T: a complete fix for the model emitting short python_game responses. The python_game prompt has other bottlenecks (max_tokens=2048 cap, the _TOOL_ACTION_NUDGE system prompt biasing toward tool calls instead of code emission, etc.) that this PR does not address.

I'd still recommend merging -- the fix is correct, the unit tests prove it, and it does measurably help the configs that already produce some code. But the headline shouldn't be "0/5 -> 3/5" from the small-sample focused test.

@danielhanchen

Copy link
Copy Markdown
Member Author

Final A/B: 800 post-fix trials vs 160 pre-fix trials (8 configs × 4 prompts)

Filling out the matrix to 25 seeds per cell on all 4 code-emitting prompts. Final numbers:

Prompt Pre-fix (5×8=40) Post-fix (25×8=200) Δ
python_game 4/40 (10%) 18/200 (9%) flat
flappy 4/40 (10%) 21/200 (10%) flat
weather 14/40 (35%) 75/200 (38%) +3pp
sloth_svg 28/40 (70%) 140/200 (70%) flat

At the 800-trial sample size, aggregate pass rates are essentially unchanged. Individual configs swing both ways (e.g. Qwen3.6-35B-A3B Q4: weather 60% -> 88% up, python_game 60% -> 24% down). The 60% -> 24% python_game drop on the 3.6-35B-A3B Q4 config is the largest single regression and worth flagging -- though it's still 5x noisier than the 200-trial signal.

Why aggregate didn't move

The judge rubric (has_code AND has_loop AND has_interaction OR has_substantial) is sensitive to game style. The fix successfully stops the re-prompt from wiping the model's first response, but the model still has these confounds:

  1. _TOOL_ACTION_NUDGE system prompt biases the model toward "call the python tool" instead of "write code in the response". On code-emitting prompts the model often just calls python and then summarises briefly, never producing a complete code block in the visible response.
  2. max_tokens=2048 cap truncates long-code responses (flappy bird's pygame code routinely exceeds this).
  3. Re-prompt was sometimes useful: when the model emitted intent-only with no artifact, the re-prompt sometimes prodded it into a tool call that DID produce a full code response in a later iteration. My guard correctly skips re-prompt when artifact is present, but a subset of pre-fix passes came from re-prompt-prodded second iterations that the post-fix path no longer triggers.

What the fix demonstrably does

  1. Unit tests prove the regex semantics in both directions (artifact present -> no re-prompt; plan-only -> still re-prompts).
  2. The re-prompt no longer wipes complete answers: median char_len ratio post-fix is closer to 1.0x (pre-fix bloated up by re-prompt iterations that appended more <think> + a second attempt + still failed visible content).
  3. No Billboard regression: 5/5 OK on a fresh sample (pre-fix was 17/25 = 68%).

Recommendation

The PR is correct and safe but the effect on aggregate pass-rate is smaller than the initial 5-seed sample suggested. Reviewers should focus on the regex semantics (unit-tested) rather than the headline numbers. For a real fix to python_game/flappy/weather pass rates, a follow-up PR would need to tackle _TOOL_ACTION_NUDGE and/or max_tokens defaults.

I'll leave this PR open for review and not push more validation runs.

@danielhanchen

Copy link
Copy Markdown
Member Author

Robustness pass — cross-platform & adversarial input

Did a full theoretical + empirical sweep of edge cases (Linux/Mac/Windows portability, browser-agnostic since the change is server-side, adversarial regex input). Found and fixed two real issues. Pushed 5f92e80.

Issues found in the initial commit

  1. Windows / CRLF content didn't match. The original \n literals in the artifact regex missed \r\n-encoded code fences and numbered lists. Models running on Windows-authored prompts (or any client that converts to CRLF) would still hit the wipe-the-answer bug.

  2. Catastrophic backtracking on whitespace spam. (?:^|\r?\n)\s*\d+\.\s+\S.*?\r?\n\s*\d+\. was O(n^2) on inputs like \r\n × 5000. Measured at ~630 ms for 10 KB of \r\n repeats. With max_tokens=2048 a model can emit much longer responses, and a single CRLF-heavy reply would freeze the server's content-filter for hundreds of ms per character processed.

Fix

_HAS_ANSWER_ARTIFACT = re.compile(
    r"```[a-zA-Z]*\r?\n[\s\S]+?\r?\n```"            # closed code fence
    r"|<!doctype\b"                                  # HTML page
    r"|<html\b"
    r"|<svg\b[\s\S]*?</svg>"                         # complete SVG
    r"|(?:^|\r?\n)[ \t]*\d+\.[ \t]+\S.*?\r?\n[ \t]*\d+\.",  # 2+ numbered list items
    re.IGNORECASE,
)
  • \r?\n everywhere a newline is required.
  • Numbered-list indent restricted to [ \t]* (spaces / tabs only). After \r?\n we are at column 0; only spaces / tabs are sensible leading indent for a list item. Greedy \s* was never needed and was the backtracking trigger.

Verification

Ran a thorough isolated simulation suite under fresh uv venv for Python 3.12 and 3.13:

  • 84 simulation tests in temp/pr5714_sim/test_pr5714_thorough.py covering: code fences in 8 languages, HTML / SVG / numbered-list shapes, false-positive prose, intent regex no-regression, boundary conditions (empty, 1-char, max-length), CRLF + mixed line endings, multi-byte unicode (CJK + emoji) inside artifacts, very-long-content (60KB) timing, pathological backtracking inputs (10KB \r\n repeats, 1000-item lists, nested fences).
  • 18 in-tree tests in studio/backend/tests/test_llama_cpp_reprompt_guard.py (13 original + 5 cross-platform).
  • All 253 tests in studio/backend/tests/test_llama_cpp_*.py pass — broader regression check confirms no neighbouring behaviour changed.
  • Worst-case timing on adversarial CRLF spam: 0.69 ms (down from 631 ms, ~1000x speedup).

Cross-platform / browser scope

  • Pure-Python regex; re stdlib behaves identically on Linux / macOS / Windows. No os.path, no shell, no filesystem access added.
  • Browser surface is unchanged: this fix only affects what content the SSE stream omits (the "STOP. Do NOT write code" synthetic user turn). Firefox / Safari / Chrome / Edge all see identical chunk format; nothing about EventSource / fetch parsing is affected.

Is this PR fixing a real issue?

Yes -- the original bug is reproduced empirically across 900 sweep runs on 15 Qwen GGUF configs (see outputs/bench_2026-05-22/summary.md). The fix makes the pre-fix behaviour a strict subset of the post-fix behaviour: every re-prompt that fired pre-fix and was correct still fires post-fix; only re-prompts that fired when a complete artifact was already produced are suppressed.

Will merging break anything?

No -- the change is additive (new _HAS_ANSWER_ARTIFACT constant, one boolean tightening one condition). No API surface change, no new dependency, no new hardware path. Plan-only stalls still re-prompt (unit tested + Billboard tool-call rate unchanged at 5/5 on a fresh sample).

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 4 commits May 23, 2026 14:00
The plan-without-action re-prompt at
`studio/backend/core/inference/llama_cpp.py` fires when the model
emits intent-only language ("first I'll ...", "let me ...") without
calling a tool. Previously the heuristic only checked an intent regex
and a 2000-char length cap. The same intent words occur in long
explanations that accompany REAL code or markup, so a complete reply
like "First, let me set up pygame. ```python ... ```" still tripped
the re-prompt, and the synthetic follow-up ("STOP. Do NOT write code
or explain.") wiped the user-visible answer.

Reproduced at scale in a 900-run sweep across 15 Qwen3.5/3.6 GGUF
configs: prompts that emit code or markup (Create a Python game,
Create a Flappy Bird game, weather dashboard HTML, sloth SVG)
landed empty `final_text` for the majority of seeds even on the
strongest configs.

Fix adds a `_HAS_ANSWER_ARTIFACT` regex covering:
  - closed code fences (```...```)
  - HTML pages (<!doctype, <html)
  - complete SVG (<svg...</svg>)
  - 2+ item numbered lists

and a `and not _HAS_ANSWER_ARTIFACT.search(_stripped)` guard on the
re-prompt condition. Plan-only stalls still re-prompt; complete
responses no longer do.

13 new unit tests in `test_llama_cpp_reprompt_guard.py` pin both
directions (artifact present -> no re-prompt; plan-only -> still
re-prompts).
…racking

Two robustness fixes for the `_HAS_ANSWER_ARTIFACT` regex from the
parent commit, both caught by a thorough simulation suite covering
Linux/Mac/Windows line-ending portability and adversarial inputs.

1. **CRLF line endings.** The original `\n` literals missed Windows-
   authored or CRLF-converted content (model echoing a pasted prompt,
   etc.). Replaced with `\r?\n` everywhere a newline is required, so
   closed code fences, numbered lists, and end-to-end re-prompt
   decisions all work on `\r\n` as well as `\n`.

2. **Catastrophic backtracking on whitespace spam.** The numbered-list
   alternative `(?:^|\r?\n)\s*\d+\.\s+\S.*?\r?\n\s*\d+\.` was
   O(n^2) on long whitespace runs: `\s*` greedy + `\d+` failing +
   `\s` matching `\r\n` led to repeated backtracking through the
   newline characters. Measured at ~630ms for 10KB of `\r\n` repeats.
   Fix: restrict the post-newline indent to `[ \t]*` (spaces / tabs
   only). After `\r?\n` we are at column 0 and only spaces / tabs
   are a sensible leading indent for a list item; greedy whitespace
   was never needed. New worst case on the same input: <1ms (1000x
   speedup).

Added 5 in-tree tests:
  - test_artifact_regex_handles_crlf_code_fence
  - test_artifact_regex_handles_crlf_numbered_list
  - test_artifact_regex_handles_mixed_lf_crlf
  - test_no_backtrack_on_crlf_spam (asserts <50ms on 10KB \r\n)
  - test_no_reprompt_on_crlf_complete_python_game

All 18 reprompt-guard tests pass. All 253 llama_cpp-related tests pass.
Out-of-tree simulation suite (84 tests) passes on both Python 3.12 and
Python 3.13 inside isolated uv venvs.
@danielhanchen
danielhanchen force-pushed the fix-tool-reprompt-overfire branch from 4d6a470 to 6639a3b Compare May 23, 2026 14:00

@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: 6639a3b31a

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

# O(n^2) backtracking through embedded `\r\n` characters on adversarial
# inputs.
_HAS_ANSWER_ARTIFACT = re.compile(
r"```[a-zA-Z]*\r?\n[\s\S]+?\r?\n```" # closed code fence

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 Recognize one-line fenced blocks before suppressing re-prompt

The closed-fence pattern requires a newline before the closing fence (...\r?\n```), so responses such as First, let me write it:\n```python\nprint('ok')```` are not detected as answer artifacts. In that case _INTENT_SIGNAL still matches (`First, let me...`), so with tools enabled the backend re-prompts and can overwrite a valid code answer that was already produced.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Leaving this as it is. CommonMark requires a closing code fence to sit on its own line, so python` then `print('ok') is an unclosed block whose content is ``print('ok')`````, not a complete one. Accepting it would mean treating genuinely mid-stream output as a finished answer, which is the failure mode 3295453005 raises. The fence rules stay per spec.

danielhanchen and others added 14 commits May 24, 2026 14:04
…ng lists, incomplete HTML

Addresses three follow-ups flagged on the first cut of this PR by static
reviewers and parallel reviewer runs:

1. Numbered plan-only stalls were treated as completed answers. A
   response like `Here's my plan:\n1. Search the web\n2. Summarise`
   matched both `_INTENT_SIGNAL` and the numbered-list branch of
   `_HAS_ANSWER_ARTIFACT`, so the tool-forcing re-prompt was skipped.
   That contradicted the PR's stated invariant that plan-only stalls
   still re-prompt. The list now has to be paired with no plan framing
   (no `Here's my plan` / `plan:` / `approach:`, no intent phrase
   followed by a tool-action verb) to count as an artifact.

2. Closed code fences with non-alpha info strings (`python3`, `c++`,
   `c#`, `objective-c`, `ts-node`, `bash-session`, `python linenums="1"`)
   were not recognised by the `[a-zA-Z]*` info-string class. Complete
   answers in those languages still re-prompted and could be wiped.
   The info-string class is now `[^\r\n]{0,200}` and the closing fence
   may be indented.

3. Bare `<!doctype` or `<html` text was treated as an artifact. A
   plan-only response that mentions `<html>` in prose now no longer
   bypasses the re-prompt; the HTML branch requires a closing
   `</html>` (doctype prefix optional).

All `[\s\S]{...}?` runs are length-bounded so ReDoS-style adversarial
input stays linear. ReDoS guard tests cover CRLF spam and repeated
`<html ` openings without close.
…ntemplative verbs

Three follow-up gaps surfaced by another reviewer sweep on the previous commit:

1. Tilde-fenced code (~~~lang ... ~~~) was not detected. CommonMark allows
   it and several models emit it when the body itself contains backticks.
   Add a tilde alternative to _HAS_ANSWER_ARTIFACT mirroring the backtick
   form (any info string, optional indent on close, length-bounded body).

2. Bare "Plan:" / "Approach:" lines did not match _INTENT_SIGNAL, so a
   "Plan:\n1. search\n2. summarise" stall slipped past the entry gate
   entirely. Add the colon form to the step / plan framing alternative.

3. The plan-framing verb whitelist missed common contemplative verbs
   (think / respond / answer / analy[sz]e / explore / outline / gather /
   query / reason) so plan stalls phrased without explicit "Here's my
   plan" framing were misclassified as completed answers. Keep the
   whitelist conservative: write / create / make / build / read / list /
   try are intentionally out because real answer lists use them
   ("1. Write a poem", "1. Read War and Peace").

Added regression tests for each fix plus an extra ReDoS budget test for
the doctype/<html alternation worst case (about 7 ms today; assert < 50
ms so a future quantifier change that drops the inner {0,4000} bound
fails loudly).
The follow-up commit used ``i['’]?ll`` (apostrophe optional) in
``_PLAN_LIST_FRAMING``. With the apostrophe optional the alternative
also matches the word "ill" (sick), so a response like
"She is ill. Here is the list:\n1. ...\n2. ..." plus an unrelated
action verb within 80 chars was misclassified as a plan and re-prompted.

Make the apostrophe required (``i['’]ll``) to mirror the original
_INTENT_SIGNAL definition. Add a regression test that pins the
distinction: "ill" as adjective does not trigger plan framing, but
"I'll" / "I will" do.
Two more gaps surfaced by another reviewer sweep on the previous commit:

1. _PLAN_LIST_FRAMING was missing several intent forms that
   _INTENT_SIGNAL accepts, so numbered tool-action plans phrased with
   "Allow me", "I'm going to", "I'm gonna", "I am gonna", or "I shall"
   were silently classified as completed answers and skipped the
   tool-call re-prompt. Mirror the full intent set from _INTENT_SIGNAL
   so the two regexes stay in lock-step.

2. Bare \b(?:plan|approach): in _INTENT_SIGNAL / _PLAN_LIST_FRAMING
   matched any in-text occurrence of "plan:" / "approach:", including
   "lesson plan:" / "meal plan:" / "migration plan:". A direct answer
   like "Here is a lesson plan:\n1. Warm-up\n2. Group practice" would
   trip _INTENT_SIGNAL and risk wiping the response. Anchor the colon
   marker to start of line and only allow generic determiners (my, the,
   our, a, this, that) between the line start and the keyword.

3. Add "Here is the plan" / "Here are my steps" to both _INTENT_SIGNAL
   and _PLAN_LIST_FRAMING so non-apostrophe phrasings of the same
   framing pattern are caught.

Added regression tests covering every intent form against a numbered
action plan, and a line-anchor test that distinguishes generic plan
framings ("My plan:", "The approach:") from content noun phrases
("lesson plan:", "meal plan:").
…uct text does not re-prompt

After narrowing the colon marker to lines starting with a generic
determiner ("My plan:" / "The approach:" / ...), inline product or
pricing answers like "Your current Plan: Pro includes local chats",
"The plan: Basic is free, Pro is $10/month", or
"My plan: use dynamic programming" still slipped into the re-prompt
path and could wipe a valid answer.

Add a lookahead requiring a newline (with optional trailing horizontal
whitespace) after the colon, so only header-style framings like
"Plan:\n1. search\n2. summarise" or "My approach:\n1. fetch" count.
Inline "Plan: <text>" is now treated as ordinary prose.

Add eight regression samples (lesson plan, meal plan, marketing plan,
pricing plan, recommended approach, migration plan, dynamic-programming
plan, currently active plan) all of which previously re-prompted under
the unanchored matcher and now correctly do not.
…ents

Reviewer round 8 surfaced a real false positive in the previous commit:
a final answer naturally titled "Plan:" / "My plan:" / "Approach:" with
numbered content items now slipped through _INTENT_SIGNAL and got
wiped by the synthetic STOP turn. Examples:

  Plan:
  1. Warm-up: Students review fractions.
  2. Group practice.
  3. Assessment.

  My plan:
  1. Breakfast: oatmeal and fruit.
  2. Lunch: rice bowl.
  3. Dinner: lentil soup.

  Here is the plan you asked for. It is two pages long.

Add a lookahead requiring one of the conservative re-prompt action
verbs (search / fetch / verify / look up / call / compare / think /
respond / etc.) to appear within 120 chars after the "Plan:" /
"Approach:" / "Here is the plan" / "Here are my steps" marker. Plan
stalls whose items are tool actions ("Plan:\n1. search the docs\n2.
summarise the result") still match and re-prompt; prose plans whose
items are content do not.

Also mirror "first" in _PLAN_LIST_FRAMING so numbered action plans
that start with "First" stay disqualified even after the helper enters
the numbered-list branch.

Factor the action-verb set out as _REPROMPT_ACTION_VERBS so both
regexes share one source of truth.

Six new regression samples: three lesson / meal / weather plans that
must NOT wipe, three action-plan headers that must re-prompt, three
prose "Here is the plan" answers that must not wipe.
Reviewer round 9 (5 of 10 reviewers) flagged that the new bare
``Plan:`` / ``Approach:`` / ``Here is the plan`` intent branches
reintroduced the original "wipe a complete answer" failure for
realistic final answers whose topic happens to contain a tool-action
word. Triggers for prompts like "Create a lesson plan for teaching
search skills" when the model answers:

  Plan:
  1. Search skills: students learn query keywords.
  2. Source evaluation: compare domains.
  3. Reflection: write what worked.

``_INTENT_SIGNAL`` matched the new ``Plan:`` lookahead because
``search`` appears within 120 chars, then ``_PLAN_LIST_FRAMING``
disqualified the numbered list, and the synthetic STOP turn wiped a
valid answer.

Revert the additions in ``_INTENT_SIGNAL``:
  * Drop ``Plan:`` / ``Approach:`` (newline + action-verb lookahead).
  * Drop ``Here is the plan`` / ``Here are my steps`` (action-verb
    lookahead).

Plan stalls phrased with explicit first-person intent ("I'll search...",
"First, I'll fetch...", "Let me look up...") are still caught by the
existing intent patterns and ``_PLAN_LIST_FRAMING``.

Also narrow the plan-list action-verb whitelist to tool-specific verbs
(``search`` / ``look up`` / ``fetch`` / ``browse`` / ``web search`` /
``call (a) tool`` / ``run python`` / ``execute python``). Broad verbs
like ``use`` / ``compare`` / ``check`` / ``find`` / ``think`` /
``respond`` / ``answer`` / ``analyse`` / ``explore`` / ``outline`` /
``reason`` are removed because real answer lists use them ("1. Use
BFS", "1. Compare versions").

Finally, fix the test module's ``loggers`` / ``structlog`` stub
injection to only fire when the real module is missing AND to set
``__path__ = []`` on the stub. Previously the bare ``ModuleType`` could
poison ``sys.modules`` for any later test that imports a real
submodule (``from loggers.handlers import ...``).

Net behavioural change vs the previous commit: stricter on what
counts as a plan stall, never wipes a final answer titled
``Plan:`` / ``My plan:`` / ``Here is the plan you asked for``.
…-fence end-of-line, freshness-gated find/check/verify

- Re-prompt path now treats a closed artifact in hidden reasoning as
  no artifact for the user; only visible content_accum counts. Stops
  hidden chain-of-thought from suppressing the tool-forcing nudge
  when content_accum is empty.

- Closed backtick / tilde fences must end the line cleanly. Trailing
  prose after the closing fence (```not actually closed) no longer
  reads as a complete artifact.

- _TOOL_ACTION_VERBS admits find / check / verify only when paired
  with a freshness signal (current / latest / today / up-to-date /
  live / online / web). Numbered plan stalls like \"1. Find the
  current Billboard chart\" re-prompt again, while \"1. Find the
  bug\" / \"2. Check the answer\" stay valid answer text.
…l-window plan scan, visible-reasoning artifact

- _HAS_ANSWER_ARTIFACT now matches fences with three OR MORE backticks
  / tildes using a named-group backreference (CommonMark rule). Models
  routinely emit \`\`\`\` / \`\`\`\`\` when the body itself contains a triple
  fence. The previous regex only matched exactly three.

- _TOOL_ACTION_VERBS adds \"query / consult the web / internet / online
  sources\" so numbered plan stalls phrased with these synonyms still
  re-prompt instead of being read as final answers.

- _PLAN_LIST_FRAMING widens the intent-to-action scan from 80 chars to
  the full short candidate (caller already gates at _REPROMPT_MAX_CHARS
  = 2000). Realistic plans where item 1 is preamble and item 2 is the
  explicit tool action no longer slip through.

- Re-prompt call site separates VISIBLE-content artifact check from
  hidden reasoning. When content_accum is empty AND has_content_tokens
  is False, reasoning_accum is the user-visible text and counts for
  the artifact check. Otherwise reasoning stays hidden and an artifact
  inside it must not suppress the re-prompt.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 2, 2026
@oobabooga

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e4a87cb5a1

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

@oobabooga

oobabooga commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Paired A/B of this branch against its merge base on a B200, live llama-server (build b10639), 8 GGUF models, 40 prompts, two sampling settings (temp 0.0 seed 1234, temp 0.7 seed 4242). Both arms drive the real generate_chat_completion_with_tools against the same server process with the same seed and sampler, so the guard is the only difference. Head 002675b9a7 vs merge base 74661077e5. The current head e4a87cb5a1 differs only by a pre-commit quote-style fix inside a test string, so no production code changed since the run. 640 pairs run, 90 excluded, 550 analyzed.

Result

  • Fixes a real loss. Base fired 49 nudges the PR does not. A complete answer was already on screen in 49/49, and base overwrote it in 40. In all 40, the PR's final text is byte for byte the answer base discarded; base ended up shorter in 33, median 571 characters lost.
  • No regression found. 0 base-only nudges in the plan, tool and mixed categories. On rows where both arms nudged, a tool eventually ran 10 times in each.
  • Costs less, not more. 6.5% fewer server round trips, 7.5% lower wall. Streaming metrics move under 0.75%.

Nudge decisions

model n base PR PR-only base-only complete answer standing overwritten
gemma3-4b 80 0 0 0 0 0 0
llama32-1b 16 0 0 0 0 0 0
llama32-3b 54 0 0 0 0 0 0
phi4-mini 80 15 3 0 12 12 10
qwen3-4b 80 20 10 0 10 10 8
gpt-oss-20b 80 15 5 0 10 10 5
mistral-24b 80 14 7 1 8 8 8
qwen3-30b-a3b 80 14 5 0 9 9 9
TOTAL 550 78 30 1 49 49 40

By category, all 49 suppressed nudges are in answer_framed (45, prompts of the form "say what you will do, then the code") and long (4). answer 167 rows, mixed 55, plan 55 and tool 81 have 0 base-only nudges.

Checks

check result
turn-1 text identical across arms 550/550
PR nudged where base did not 1/550
both arms nudged, tool eventually ran base 10, PR 10
complete answer standing, base-only nudges 49/49
complete answer standing, rows where both arms nudged 6/29

The last two rows are the control. Completeness is scored by an independent structural test (balanced fence delimiters, closed <html>/<svg>/<body>), not by this PR's _has_answer_artifact, and it separates the two populations 49/49 against 6/29.

The single PR-only nudge is not a different verdict on the same text: turn 1 was identical, then the server produced different turn-2 text in each arm at temp 0.7, and only the PR arm's version was a plan with no action.

Cost

base PR delta
server round trips per prompt 1.71 1.60 -6.5%
wall per prompt 2.02 s 1.87 s -7.5%

Streaming, 24k prompt tokens, 1500-token answer, 1500 content events, 6 interleaved runs per arm:

base PR delta
TTFT 1.9915 s 1.9883 s -0.16%
median inter-token 5.6051 ms 5.6112 ms +0.11%
p99 inter-token 6.0801 ms 6.0357 ms -0.73%
tokens/s 143.80 143.50 -0.20%
end-of-turn tail 4.595 ms 5.381 ms +0.79 ms

Nothing new runs per token: the guard's calls are in the outer turn loop, and the per-chunk loop has the same 4 _strip_tool_markup calls on both sides. The cost is the +0.79 ms tail, once per turn.

A representative overwrite: qwen3-30b-a3b returned a complete 1265-char HTML page, base re-prompted, and the retry replaced it with 97 chars saying the code "has already been provided above", which by then it was not, since routes/inference.py assigns full_text on each content event and never resets.

Notes

  • 90 of the 640 pairs were dropped because llama.cpp rejected the model's tool call (common_chat_peg_parse: unparsed peg-native output), all Llama-3.2-1B and 3B emitting invalid tool names. The error is identical in both arms.
  • web_search is a stub returning fixed text, so a retry's content reflects the stub. It supports "the first answer was discarded", not any judgement of the replacement.
  • gemma3-4b and Llama-3.2-3B produced no plan-without-action on this prompt set, so they exercise the no-change path only.

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.

2 participants