Skip to content

Keep thinking tags as content after a prompt that closes the thought - #1525

Merged
leehack merged 7 commits into
mainfrom
fix/750-thinking-off-tags-as-content
Oct 28, 2026
Merged

leehack merged 7 commits into
mainfrom
fix/750-thinking-off-tags-as-content

Conversation

@leehack

@leehack leehack commented Oct 28, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • With thinking off, DeepSeek V3.1, Qwen3, QwQ, Qwen3.5 and Ling templates end the prompt with an empty <think></think>. llama.cpp 620d2225 then parses the reply as content and tool calls, thinking tags included. llamadart extracted <think> blocks as reasoning and, with thinking off, dropped them. Now the DeepSeek V3, Hermes and Qwen3-Coder XML parse and stream keep them in the content.
  • Detection is from the template's own render, not from enableThinking or llamadart's rewritten prompt: the DeepSeek V3, Hermes and Qwen3-Coder XML handlers mark their result (internal withThinkingForcedClosed / thinkingForcedClosedOf in thinking_utils.dart, an Expando like markPromptExcludedFromPenalties) when the render ends with an empty start/end pair (isThinkingForcedClosed), before they close a thought the template left open. So templates that do not close the thought keep parsing a leading thought, as upstream does: Bielik, Reka, Spark's bare </think>, and StepFun3.5-Flash, whose template always ends <think>\n (llamadart appends </think> with thinking off; upstream keeps it open and parses the reasoning). Gated by a new registry trait closedThoughtKeepsTagsAsContent (deepseekV3, hermes, qwen3CoderXml); a forced-open thought wins.
  • No public API change. ChatTemplateEngine.parse gains thinkingForcedClosed (internal engine; not exported).
  • Part of #750 (item 2).

Production-readiness scope

  • User-facing scope: with enableThinking: false (or a thinking-off kwarg) on these models, a <think> block the model still writes appears in chunk.text / message content instead of vanishing.
  • Supported platforms/paths: all; Dart-side parse shared by native and web.
  • Unsupported or intentionally unavailable paths: N/A. Other formats and prompts without an empty thought keep their parse; with thinking off the stream still drops that reasoning (documented in template-engine-internals.md).
  • Out of scope / follow-ups: StepFun3.5-Flash with thinking off, when the model still writes Plan\n</think>\n\nSunny.: a chunked stream emits the thought as content before the end tag (same on main; final parse and one-chunk stream give Sunny.). Forced-open verbatim parity is #1524; Cohere follow-ups are #1526. Remaining divergences are recorded on #750.

Completeness checklist

  • Declared scope is fully implemented, or explicitly reduced above.
  • Unsupported platform/option combinations fail loudly with actionable diagnostics or are clearly documented as unavailable. (N/A: no new option.)
  • Public API docs, README/website docs, examples, support matrices, and changelog entries are updated where relevant. (template-engine-internals.md, chat-template-and-parsing.md, skills/llamadart-chat-streaming/SKILL.md, both changelogs. README/examples/support matrix: N/A.)
  • Regression coverage covers the original issue plus key negative/version-skew paths where relevant.
  • Public capability changes update the validation coverage registry with a pack or a reasoned, issue-linked exemption; inventory checks pass (or N/A with scope). N/A: parse parity fix, no public capability change.
  • Security/privacy review completed: no secrets, bearer tokens, signed URLs, or raw secret-bearing paths leak through logs, cache keys, metadata, errors, or snapshots.
  • Follow-up work that is useful but not required for this PR is tracked in GitHub Issues, or explicitly marked "None" above.

PR type guidance

  • Bugfix PR: root cause: the parse and stream extracted <think> whatever the prompt rendered; upstream's PEG parser has no reasoning rule after a closed thought. Tests: new upstream oracle fixture test/fixtures/closed_thought_upstream.json (DeepSeek V3.1, Qwen3-4B, QwQ, Qwen3.5; 8 outputs each, enable_thinking = false) through parse, tool-free parse and whole/bytewise stream with tools on/off and a thinking-on kwarg; the mark survives required-tool and response-schema grammar and token counting; StepFun3.5-Flash (vendored template, open_thought_templates, 5 outputs with and without tools) keeps its reasoning and tool calls in parse and stream as upstream does; a registry-wide test that exactly the trait formats change; forced-open precedence in parse and stream; an unmarked result keeps reasoning. Platforms: all (Dart parse).
  • Feature PR / Docs-only PR: N/A.

Test Plan

  • dart run tool/prepare_workspace.dart
  • dart format --output=none --set-exit-if-changed .
  • dart analyze
  • dart test -p vm -j 1 --exclude-tags local-only (+9330 ~5 at merged head d4aeac801, all passed); Chrome test/unit/core/template + stream parser tests +1119 at d4aeac801
  • dart test -p chrome --exclude-tags local-only (CI)
  • Other targeted/local-only validation: ./tool/testing/run_template_parity_suites.sh (all suites passed); dart test -p vm test/unit/tooling/package_skills_test.dart; oracle, sweep, render matrix and mutation runs below.

Evidence (oracle built from llama.cpp 620d2225):

Check Base (22a0c4518) Head
Failing-first: new fixture/unit tests 24 fail all pass
Failing-first: StepFun cases at f51c9eb0f 4 of 5 fail (reply parsed as content) all pass at 14f1e0bf2
Auditor oracle harness (common_chat_session whole + bytewise), 127,332 cases over 94 templates, thinking on/off, kwarg, tool choices; stream whole, bytewise, 3-char, every 2-chunk split OK 45,488 OK 48,134; 0 cases OK->BAD; 2,646 BAD->OK; 198 BAD cases change but stay BAD; StepFun cases identical to base
Parse/stream sweep (auditor harness, SPLIT2=1), 64,298 cases changes only in thinking-off cases of DeepSeek V3.1, QwQ, Qwen3-0.6B, Qwen3-4B, Qwen3.5 x2, Ling (220 each); StepFun unchanged; 0 new stream != parse; stream != parse for deepseekV3 210 -> 0, qwen3CoderXml 1000 -> 580, hermes 5194 -> 4354 (bytewise; rest pre-existing, e.g. thinking-off stream drops reasoning other formats parse)
Render matrix, 15,792 renders 0 changed

Mutants: engine ignores thinkingForcedClosed, ignores forced-open precedence; stream does not keep tags as content, detects from enableThinking, ignores the start tag, final parse not passed the flag; each handler ignores the flag; XML extraction always skipped; each registry trait off (hermes, deepseekV3, qwen3CoderXml). 13 of 13 killed. Two equivalent mutants (trait gating in the engine, the partial-parse argument) showed dead code, which was removed.

Mutants at 14f1e0bf2 (StepFun fix, internal mark): Qwen3-Coder XML marks from the rewritten prompt; stream sniffs the prompt again; stream ignores the mark; stream ignores forced-open precedence; each of the three handlers does not mark; the helper never marks; the renderer, required-tool and response-schema copies drop the mark. 11 of 14 killed. The 3 survivors drop the mark in copies only Ministral, generic/content-only and the content-only format switch reach, whose handlers never mark (equivalent). Oracle and sweep numbers above are from 38847aa2d; 14f1e0bf2 reproduces them row for row on the StepFun, Qwen3.5, Qwen3-4B, DeepSeek V3.1 and Bielik subset (6,200 oracle rows identical; StepFun's 1,240 identical to base).

Merged head d4aeac801 vs main c91b35202 (same auditor harness, both trees run fresh):

Check main c91b35202 d4aeac801
Oracle, 127,332 cases OK 47,274 OK 49,920; 0 OK->BAD; 2,646 BAD->OK; 198 BAD cases change but stay BAD; StepFun identical to main
Sweep (SPLIT2=1), 64,298 cases changes only in thinking-off DeepSeek V3.1, QwQ, Qwen3-0.6B, Qwen3-4B, Qwen3.5 x2, Ling (220 each); 0 new stream != parse
vs auditor's local merge f89e8e982 only the 220 StepFun thinking-off cases differ (the P2 fix)

Matrix Evidence

Matrix row Scope covered Platform / model / backend Result Evidence / notes
static-format-analyze format, analyzer, web/native import boundaries macOS, Flutter 3.47.1 PASS local + CI
root-vm native-safe unit/integration coverage on the Dart VM macOS VM PASS +9330 ~5 at d4aeac801
root-chrome browser-compatible unit/integration coverage Chrome CI CI run on this head
coverage-lib >=70% line coverage VM CI CI run on this head
structured-output-adversarial partial/final streaming, thinking prefixes with tool choice, pinned upstream template/parser parity Dart parse vs llama.cpp 620d2225 PASS oracle, sweep (whole/bytewise/3-char chunks, auto/required/none, parallel), render matrix, parity suites
high-risk-exact-head-independent-qa independent blocking review of exact head fresh auditor session, exact head c21f1c7 PASS CLEAR: CLEAR delta re-audit at d4aeac8; main merge c21f1c7 delta-checked; evidence /opt/UnitySrc/personal/llama/llamadart-evidence/pr-1525/audit/r2/evidence-1525-d4aeac8.json
docs-site website build CI guide, skill and changelog text
gguf-chat-features-smoke real GGUF chat/thinking N/A N/A parse-only; pinned against upstream emissions

Review Notes

High-risk regression review

  • Classification: high-risk (structuredOutput, backendRuntime)
  • Implementation task: #750 lane of #922
  • Independent blocking QA task: fresh auditor session, CLEAR, 0 known PR-caused P1, 0 unresolved threads
  • Exact head / current base: c21f1c7 / 0615470 (merge-tree clean)
  • Production-branch deletion, bypass, or miswire proof: the mutants above remove each production branch and each is killed.
  • Affected-family real-model/artifact evidence: model weights not run; the fixture holds primary upstream emissions from llama.cpp 620d2225 for the affected templates.
  • Explicit unavailable-family or other N/A evidence: DeepSeek V3.1, Qwen3, QwQ and Qwen3.5 GGUF weights not used; durable upstream fixtures instead.
  • Known PR-caused P1 regressions: 0
  • Unresolved review threads: 0
  • Merge note: #1524 landed first; main c91b35202 is merged in with --no-ff (no rebase). Conflicts in chat_format_registry.dart, hermes_handler.dart _parse, qwen3_coder_xml_handler.dart parseWithTools and xml_tool_call_format.dart resolved as the auditor's local merge f89e8e982 (both traits kept; the verbatim forced-open branch is gated on extractsThought), plus the internal closed-thought mark.

StepFun3.5-Flash always ends its prompt with `<think>\n`; with thinking
off llamadart closes that thought, and the parse read the rewritten
prompt as a closed one, turning the reasoning and `</think>` into
content. llama.cpp 620d2225 keeps that thought open and parses it.

The DeepSeek V3, Hermes and Qwen3-Coder XML handlers now report
`LlamaChatTemplateResult.thinkingForcedClosed` from the template's
render, before closing an open thought, and the stream and final parse
use it instead of inspecting the prompt.
The template's closed thought now travels as an internal mark on the
render result (`withThinkingForcedClosed` / `thinkingForcedClosedOf` in
thinking_utils), not as a public `LlamaChatTemplateResult` field. Behavior
is unchanged.
# Conflicts:
#	lib/src/core/template/chat_format_registry.dart
#	lib/src/core/template/handlers/hermes_handler.dart
#	lib/src/core/template/handlers/qwen3_coder_xml_handler.dart
#	lib/src/core/template/xml_tool_call_format.dart
@leehack
leehack marked this pull request as ready for review October 28, 2026 13:09
@leehack
leehack merged commit 9c29ff2 into main Oct 28, 2026
38 checks passed
@leehack
leehack deleted the fix/750-thinking-off-tags-as-content branch October 28, 2026 13:09
@github-actions

Copy link
Copy Markdown
Contributor

Chat app preview removed for leehack/llamadart-chat-pr-1525.

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