Skip to content

fix: normalize think tags in final chat answer - #14271

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
buua436:f024
Apr 22, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
buua436:f024

Conversation

@buua436

@buua436 buua436 commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

normalize think tags in final chat answer

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Apr 22, 2026
@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Added a helper to strip <think> tags and reconstruct visible answer content; final streamed responses in two code paths now pass the cleaned visible answer into decorate_answer(...) for the final final=True payloads, leaving intermediate streaming emissions unchanged.

Changes

Cohort / File(s) Summary
Dialog service — final payload processing
api/db/services/dialog_service.py
Added _extract_visible_answer(text: str) -> str to remove <think>/</think> tags and rebuild a minimal visible structure. Updated two finalization points (async_chat stream finalization and async_ask non-QA finalization) to call decorate_answer(_extract_visible_answer(...)) instead of passing raw thought + full_answer or full_answer. Intermediate streaming messages remain unchanged.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I hop through bytes and tidy thought,
I pull the whispers that were caught,
I strip the tags and stitch the view,
Final answers clean and true —
A rabbit's nod for changes wrought 🐇✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is incomplete and vague. While it includes the required template sections, the 'What problem does this PR solve?' section only repeats the title without providing meaningful context or background information. Expand the 'What problem does this PR solve?' section with specific details about the duplicate answer issue, when/how it occurs, and why normalizing think tags fixes it.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title 'fix: normalize think tags in final chat answer' directly corresponds to the main change: adding a helper to remove/normalize tags in final streamed responses.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@buua436 buua436 added the ci Continue Integration label Apr 22, 2026
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Apr 22, 2026
@buua436
buua436 marked this pull request as draft April 22, 2026 02:02
@buua436
buua436 marked this pull request as ready for review April 22, 2026 02:02
@buua436
buua436 marked this pull request as draft April 22, 2026 02:07

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/db/services/dialog_service.py`:
- Around line 803-809: The final answer is being unconditionally cleared after
decorate_answer (in the block using last_state.full_text and decorate_answer),
which removes the decorated final text for streaming consumers; make clearing
opt-in by checking flags: in async_chat read kwargs.get("suppress_final_answer")
and in async_ask read search_config.get("suppress_final_answer"), and only set
final["answer"] = "" when the respective flag is True (and likewise gate any
other clearing like final["final"] or final["audio_binary"] adjustments if they
were intended to be conditional); update callers that should suppress the
duplicate final event to pass suppress_final_answer=True, leaving existing
behavior unchanged otherwise (reference decorate_answer, async_chat, async_ask,
kwargs, search_config).
🪄 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: 0c8e85c9-d455-4acb-8fb9-996e7086845c

📥 Commits

Reviewing files that changed from the base of the PR and between 74b44e1 and 5621d59.

📒 Files selected for processing (1)
  • api/db/services/dialog_service.py

Comment on lines 803 to 809
full_answer = last_state.full_text if last_state else ""
if full_answer:
final = decorate_answer(thought + full_answer)
final["answer"] = ""
final["final"] = True
final["audio_binary"] = None
yield final

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Find streaming consumers that may rely on final ans["answer"] being populated.
# Expectation: any consumer that stores, forwards, or finalizes from ans["answer"] handles final empty-answer events explicitly,
# or the service keeps final["answer"] populated by default.

rg -n -C4 --type=py 'async\s+for\s+\w+\s+in\s+async_(chat|ask)\('
rg -n -C4 --type=py 'final_answer\s*=\s*.*(\["answer"\]|\.get\("answer"\))|full_content\s*=\s*.*(\["answer"\]|\.get\("answer"\))'

Repository: infiniflow/ragflow

Length of output: 9392


🏁 Script executed:

# First, let's check the actual code in dialog_service.py around the mentioned lines
wc -l api/db/services/dialog_service.py

Repository: infiniflow/ragflow

Length of output: 100


🏁 Script executed:

# Read the relevant sections to confirm the clearing behavior
sed -n '800,815p' api/db/services/dialog_service.py

Repository: infiniflow/ragflow

Length of output: 905


🏁 Script executed:

# Also read the second location mentioned (around line 1475-1479)
sed -n '1470,1485p' api/db/services/dialog_service.py

Repository: infiniflow/ragflow

Length of output: 750


🏁 Script executed:

# Get function signatures for async_chat and async_ask to see parameter handling
ast-grep --pattern 'async def async_chat($_) { $$$ }' | head -20

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Find the function definitions for async_chat and async_ask
rg -n 'async def async_chat\(' api/db/services/dialog_service.py | head -5

Repository: infiniflow/ragflow

Length of output: 128


🏁 Script executed:

rg -n 'async def async_ask\(' api/db/services/dialog_service.py | head -5

Repository: infiniflow/ragflow

Length of output: 154


🏁 Script executed:

# Read the async_chat function signature and parameters
sed -n '632,650p' api/db/services/dialog_service.py

Repository: infiniflow/ragflow

Length of output: 881


🏁 Script executed:

# Read the async_ask function signature
sed -n '1446,1465p' api/db/services/dialog_service.py

Repository: infiniflow/ragflow

Length of output: 1066


🏁 Script executed:

# Check what structure_answer does with the final answer
rg -n -A10 'def structure_answer' api/db/services/conversation_service.py

Repository: infiniflow/ragflow

Length of output: 423


🏁 Script executed:

# Verify that callers of async_chat pass **kwargs through properly
rg -n -B2 'async_chat\(dia, msg' api/apps/sdk/session.py

Repository: infiniflow/ragflow

Length of output: 395


🏁 Script executed:

# Check if any code depends on final["answer"] always being empty for correct behavior
rg -n 'final\["answer"\]\s*==""' api/db/services/dialog_service.py

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Get the full context of the SDK session.py final handling to understand full_content variable scope
sed -n '320,360p' api/apps/sdk/session.py

Repository: infiniflow/ragflow

Length of output: 2021


🏁 Script executed:

# Also check the second non-streaming path to see if it handles empty answer
sed -n '385,405p' api/apps/sdk/session.py

Repository: infiniflow/ragflow

Length of output: 927


🏁 Script executed:

# Check full_content initialization in sdk/session.py
sed -n '300,335p' api/apps/sdk/session.py

Repository: infiniflow/ragflow

Length of output: 1424


🏁 Script executed:

# Verify the non-streaming path behavior - trace what happens when stream=False
rg -n -A20 'stream.*False' api/db/services/dialog_service.py | grep -A20 'async_chat'

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Check if there are any other locations that check ans["answer"] == "" as an intentional guard
rg -n 'answer.*=.*""' api/db/services/dialog_service.py | head -10

Repository: infiniflow/ragflow

Length of output: 747


🏁 Script executed:

# Check the non-streaming path more carefully - what gets returned
sed -n '810,830p' api/db/services/dialog_service.py

Repository: infiniflow/ragflow

Length of output: 889


🏁 Script executed:

# Also check the async_ask non-streaming path
sed -n '1480,1510p' api/db/services/dialog_service.py

Repository: infiniflow/ragflow

Length of output: 1544


Don't clear the service-level final answer unconditionally.

decorate_answer() inserts citations, repairs references, and applies metadata that are only available in the final event. Clearing answer here means async_ask streaming consumers receive an empty final answer, and clients relying on ans["answer"] from the final event will see "". The clearing should be opt-in via a parameter flag, not unconditional.

Both functions support parameter passing:

  • async_chat(**kwargs) at line 489 already accepts **kwargs
  • async_ask(search_config={}) at line 1398 already supports config options

Gate the clearing with if kwargs.get("suppress_final_answer") in async_chat and if search_config.get("suppress_final_answer") in async_ask. Only pass the flag from callers that would otherwise duplicate the final event.

Proposed safer direction
         full_answer = last_state.full_text if last_state else ""
         if full_answer:
             final = decorate_answer(thought + full_answer)
-            final["answer"] = ""
+            if kwargs.get("suppress_final_answer"):
+                final["answer"] = ""
             final["final"] = True
             final["audio_binary"] = None
             yield final
@@
     full_answer = last_state.full_text if last_state else ""
     final = decorate_answer(full_answer)
-    final["answer"] = ""
+    if search_config.get("suppress_final_answer"):
+        final["answer"] = ""
     final["final"] = True
     yield final

Then pass suppress_final_answer=True only from the specific streaming path that would otherwise duplicate.

Also applies to: 1475-1479

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/db/services/dialog_service.py` around lines 803 - 809, The final answer
is being unconditionally cleared after decorate_answer (in the block using
last_state.full_text and decorate_answer), which removes the decorated final
text for streaming consumers; make clearing opt-in by checking flags: in
async_chat read kwargs.get("suppress_final_answer") and in async_ask read
search_config.get("suppress_final_answer"), and only set final["answer"] = ""
when the respective flag is True (and likewise gate any other clearing like
final["final"] or final["audio_binary"] adjustments if they were intended to be
conditional); update callers that should suppress the duplicate final event to
pass suppress_final_answer=True, leaving existing behavior unchanged otherwise
(reference decorate_answer, async_chat, async_ask, kwargs, search_config).

@buua436
buua436 marked this pull request as ready for review April 22, 2026 02:52
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Apr 22, 2026
@buua436 buua436 changed the title fix: avoid duplicate final chat answer fix: normalize think tags in final chat answer Apr 22, 2026

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/db/services/dialog_service.py`:
- Around line 1331-1341: _fix the bug where citations can be injected into
thought text by ensuring _extract_visible_answer only returns the visible answer
(no <think> wrappers) used by async_ask.decorate_answer; make thought
preservation explicit for async_chat by either adding a new helper (e.g.,
_separate_thought_and_answer) or adding a preserve_thought flag to
_extract_visible_answer, update async_chat.decorate_answer to call the new
helper/flag to reconstruct the <think>...<\/think> wrapper around the thought
after citations are inserted into the visible answer, and ensure
async_ask.decorate_answer continues to receive and operate on only the visible
answer so insert_citations cannot touch thought text.
🪄 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: e75849b4-0e5b-4cda-9822-9a6050364cc9

📥 Commits

Reviewing files that changed from the base of the PR and between 5621d59 and a93caa3.

📒 Files selected for processing (1)
  • api/db/services/dialog_service.py

Comment on lines +1331 to +1341
def _extract_visible_answer(text: str) -> str:
text = text or ""
if "</think>" not in text:
return re.sub(r"</?think>", "", text)

thought, answer = text.rsplit("</think>", 1)
thought = re.sub(r"</?think>", "", thought).strip()
answer = re.sub(r"</?think>", "", answer)
if not thought:
return answer
return f"<think>{thought}</think>{answer}"

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.

⚠️ Potential issue | 🟠 Major

Keep async_ask citation decoration on visible answer text only.

_extract_visible_answer() can return <think>...</think>{answer}. Unlike async_chat.decorate_answer(), async_ask.decorate_answer() does not split that block before insert_citations(...), so citations may be inserted into thought text and the final answer can expose/store it.

Proposed fix: make thought preservation explicit and keep async_ask visible-only
-def _extract_visible_answer(text: str) -> str:
+def _extract_visible_answer(text: str, include_thought: bool = False) -> str:
     text = text or ""
     if "</think>" not in text:
         return re.sub(r"</?think>", "", text)
 
     thought, answer = text.rsplit("</think>", 1)
     thought = re.sub(r"</?think>", "", thought).strip()
     answer = re.sub(r"</?think>", "", answer)
-    if not thought:
+    if not include_thought or not thought:
         return answer
     return f"<think>{thought}</think>{answer}"

Then preserve the current async_chat behavior explicitly while leaving async_ask as visible-only:

-            final = decorate_answer(_extract_visible_answer(thought + full_answer))
+            final = decorate_answer(_extract_visible_answer(thought + full_answer, include_thought=True))
-    final = decorate_answer(_extract_visible_answer(full_answer))
+    final = decorate_answer(_extract_visible_answer(full_answer))

Also applies to: 1488-1488

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/db/services/dialog_service.py` around lines 1331 - 1341, _fix the bug
where citations can be injected into thought text by ensuring
_extract_visible_answer only returns the visible answer (no <think> wrappers)
used by async_ask.decorate_answer; make thought preservation explicit for
async_chat by either adding a new helper (e.g., _separate_thought_and_answer) or
adding a preserve_thought flag to _extract_visible_answer, update
async_chat.decorate_answer to call the new helper/flag to reconstruct the
<think>...<\/think> wrapper around the thought after citations are inserted into
the visible answer, and ensure async_ask.decorate_answer continues to receive
and operate on only the visible answer so insert_citations cannot touch thought
text.

@JinHai-CN
JinHai-CN merged commit ff29484 into infiniflow:main Apr 22, 2026
1 of 2 checks passed
@Lynn-Inf Lynn-Inf mentioned this pull request Apr 23, 2026
4 tasks done
@coderabbitai coderabbitai Bot mentioned this pull request Jun 8, 2026
1 task done
SailedApple1991 added a commit to SailedApple1991/greenlaw-ragflow that referenced this pull request Jun 14, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants