Repository navigation
fix: refine think stream parsing - #15745
Conversation
📝 WalkthroughWalkthroughRefactors the ChangesThink-stream parser refactoring
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/db/services/dialog_service.py`:
- Around line 1474-1478: The branch that checks num_tokens_from_string against
min_tokens has mis-indented lines inside the function using state.answer_buffer;
fix the IndentationError by aligning the inner block (the assignment
state.answer_buffer = "" and the return out) to the same indentation level as
the if body and ensure the final return None aligns with the if (so the if, its
body, and the subsequent return all use consistent indentation) in the function
that contains state.answer_buffer and num_tokens_from_string.
- Around line 1543-1548: When switching from answer mode to think mode (the
branch that checks state.in_think and yields ("marker", "<think>", state)), the
code incorrectly calls _flush_think_buffer() even though buffered content is in
the answer buffer; change the flush to the answer buffer flush (call the
function that empties answer_buffer, e.g., _flush_answer_buffer()) so any
pending answer text is emitted before setting state.in_think = True and yielding
the "<think>" marker, and keep the rest of the logic (yielding flushed text if
not None, setting state.in_think, yielding marker) unchanged.
- Around line 1565-1576: At stream end, when state.close_pending is True the
code clears buffers and sets state.in_think = False but never emits the closing
marker; update the end-of-stream block in dialog_service.py to, if
state.close_pending is True, first yield ("marker", "</think>", state), clear
state.close_pending, then proceed to flush any
state.pending_after_close/state.answer_buffer/state.think_buffer and set
state.in_think = False so downstream consumers receive the end-to-think marker;
reference the existing variables state.close_pending, state.pending_after_close,
state.think_buffer, state.answer_buffer and state.in_think to locate and modify
the logic.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 1380bc03-da5f-4560-80a6-055106d1b4f3
📒 Files selected for processing (1)
api/db/services/dialog_service.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15745 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
wangq8
left a comment
There was a problem hiding this comment.
Review: fix: refine think stream parsing (#15745)
This PR rewrites the <think>/</think> streaming parser in _stream_with_think_delta, replacing the old delta-based approach with a new loop that maintains separate think_buffer and answer_buffer buffers and explicitly marks tag boundaries. The approach is cleaner, but there are 3 bugs that need fixing before merge.
Bug 1 — Missing </think> marker at end-of-stream (lines 1574-1575)
if state.close_pending:
state.in_think = FalseWhen the stream ends while close_pending is True, the code only flips in_think but never yields ("marker", "</think>", state). Downstream consumers (lines 325-328, 889-892, 1683-1686) rely on this marker to set end_to_think: True on the response — without it, the client never gets the end-of-think signal and may misrender the answer.
Compare with the old code which did emit it:
if state.endswith_think:
yield ("marker", "</think>", state)Fix: yield the </think> marker before clearing in_think:
if state.close_pending:
yield ("marker", "</think>", state)
state.in_think = FalseBug 2 — Answer buffer not flushed when switching to think mode (lines 1543-1548)
if not state.in_think:
think_piece = _flush_think_buffer()
if think_piece is not None:
yield ("text", think_piece, state)
state.in_think = True
yield ("marker", "<think>", state)When entering think mode from answer mode, the code flushes _flush_think_buffer() but that buffer is empty (we were in answer mode). Meanwhile, state.answer_buffer may contain text from before the <think> tag that hasn't reached the min_tokens threshold yet. This text becomes stuck — never emitted, and will eventually be flushed as answer text at end-of-stream, out of order with the think content.
Fix: Add a _flush_answer_buffer helper and call it here:
def _flush_answer_buffer():
if not state.answer_buffer:
return None
out = state.answer_buffer
state.answer_buffer = ""
return out
# then in the <think> handler:
if not state.in_think:
answer_piece = _flush_answer_buffer()
if answer_piece is not None:
yield ("text", answer_piece, state)
state.in_think = True
yield ("marker", "<think>", state)Issue 3 — Indentation inconsistency in _emit_text (lines 1474-1477)
if num_tokens_from_string(state.answer_buffer) >= min_tokens:
out = state.answer_buffer
state.answer_buffer = ""
return outThe if body is indented by 8 spaces (to column 16) while the rest of the function uses 4-space increments per level (the think branch equivalent is at column 12→16). Python accepts this, but it's inconsistent and will confuse readers. Align to 4-space-per-level.
Minor: Dead field last_idx
_ThinkStreamState.last_idx (line 1438) was used by the removed _next_think_delta function. It is never read in the new code and should be removed from __init__.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
test/testcases/unit/test_think_stream_parser.py (2)
343-347: ⚡ Quick winRemove unnecessary stdout redirection.
The stdout is redirected to a buffer that is never used or inspected. This adds unnecessary complexity without providing value.
♻️ Proposed fix
for case_name, case in CASES: with self.subTest(case=case_name): - buf = io.StringIO() - with redirect_stdout(buf): - think_text, answer_text, markers = asyncio.run( - _collect_case(case["chunks"], case["min_tokens"]) - ) + think_text, answer_text, markers = asyncio.run( + _collect_case(case["chunks"], case["min_tokens"]) + )If this redirection was intended to suppress debug output, consider removing any debug print statements from the implementation instead.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/testcases/unit/test_think_stream_parser.py` around lines 343 - 347, The test is redirecting stdout to an unused StringIO buffer around the call to asyncio.run(_collect_case(...)); remove the temporary buf and the with redirect_stdout(buf): block so the test simply calls asyncio.run(_collect_case(case["chunks"], case["min_tokens"])) and assigns think_text, answer_text, markers directly; if stdout suppression was required, remove or silence debug prints inside _collect_case instead of swallowing output here.
352-353: 💤 Low valueConsider validating markers for all test cases.
Currently, only some test cases validate the
markerssequence. For consistency and completeness, consider adding expected markers to all cases to ensure the marker emission behavior is fully validated across all scenarios.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/testcases/unit/test_think_stream_parser.py` around lines 352 - 353, The test only asserts markers when an individual test case includes an "markers" key; update the test data so every case includes an expected "markers" sequence and keep the existing assertion (self.assertEqual(markers, expected["markers"], case_name)) to validate marker emission across all scenarios; look for the test cases collection (e.g., the list/dict of cases used by test_think_stream_parser) and add a "markers" entry for each case to reflect the expected marker sequence for that scenario.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/testcases/unit/test_think_stream_parser.py`:
- Around line 339-340: The test method in TestThinkStreamParser
(test_think_stream_parser_cases) needs a pytest priority marker; add an import
for pytest if missing and annotate the method with the appropriate marker (e.g.,
add `@pytest.mark.p1` directly above def test_think_stream_parser_cases(self):) so
the test carries the required p1/p2/p3 priority marker.
---
Nitpick comments:
In `@test/testcases/unit/test_think_stream_parser.py`:
- Around line 343-347: The test is redirecting stdout to an unused StringIO
buffer around the call to asyncio.run(_collect_case(...)); remove the temporary
buf and the with redirect_stdout(buf): block so the test simply calls
asyncio.run(_collect_case(case["chunks"], case["min_tokens"])) and assigns
think_text, answer_text, markers directly; if stdout suppression was required,
remove or silence debug prints inside _collect_case instead of swallowing output
here.
- Around line 352-353: The test only asserts markers when an individual test
case includes an "markers" key; update the test data so every case includes an
expected "markers" sequence and keep the existing assertion
(self.assertEqual(markers, expected["markers"], case_name)) to validate marker
emission across all scenarios; look for the test cases collection (e.g., the
list/dict of cases used by test_think_stream_parser) and add a "markers" entry
for each case to reflect the expected marker sequence for that scenario.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c487f239-fced-45eb-b2f8-96616eda3265
📒 Files selected for processing (2)
api/db/services/dialog_service.pytest/testcases/unit/test_think_stream_parser.py
🚧 Files skipped from review as they are similar to previous changes (1)
- api/db/services/dialog_service.py
| class TestThinkStreamParser(unittest.TestCase): | ||
| def test_think_stream_parser_cases(self): |
There was a problem hiding this comment.
Add pytest priority marker to the test method.
The test method is missing a pytest priority marker (p1/p2/p3). As per coding guidelines, Python tests should use pytest with priority markers.
📝 Proposed fix
+import pytest
+
class TestThinkStreamParser(unittest.TestCase):
+ `@pytest.mark.p1`
def test_think_stream_parser_cases(self):🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@test/testcases/unit/test_think_stream_parser.py` around lines 339 - 340, The
test method in TestThinkStreamParser (test_think_stream_parser_cases) needs a
pytest priority marker; add an import for pytest if missing and annotate the
method with the appropriate marker (e.g., add `@pytest.mark.p1` directly above def
test_think_stream_parser_cases(self):) so the test carries the required p1/p2/p3
priority marker.
Source: Coding guidelines
chat-internals port (route-independent; fork keeps /chats contract + parallel gather + cache + infiniflow#12689). Replaced fork's think-stream helper block (_ThinkStreamState / _next_think_delta / _stream_with_think_delta) with upstream v0.26's final version, which folds in: - infiniflow#15745 refine think stream parsing (big refactor; min_tokens 1->16) - infiniflow#15891 remove think text buffering (real-time reasoning) - infiniflow#15651 prevent duplicated post-think text - infiniflow#15582 think stream tail handling - infiniflow#14271 normalize think tags in final answer (adds _extract_visible_answer; removes _next_think_delta) Plus applied infiniflow#14271's 2 consumer wraps: async_chat + async_ask now call decorate_answer(_extract_visible_answer(...)). SKIPPED infiniflow#13917 (remove final["answer"]=""): conflicts with fork's deliberate answer-clearing — async_chat explicitly caches the full answer then blanks it for the streaming client ('preserve full answer for caching before clearing'). Touching it risks fork's cache/stream contract. Verified: call convention unchanged (3 consumers); _next_think_delta fully removed (0 refs); _extract_visible_answer logic correct (5 cases); fork customs intact (parallel gather x8, cache x5); py_compile. Live SSE smoke -> batch F.
What problem does this PR solve?
Refine the stream parsing for
<think>/</think>so MiniMax and DeepSeek-style chunking both flush in the right order without mixing think and answer buffers.Type of change