Repository navigation
fix: normalize think tags in final chat answer - #14271
Conversation
📝 WalkthroughWalkthroughAdded a helper to strip Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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: 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
📒 Files selected for processing (1)
api/db/services/dialog_service.py
| 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 |
There was a problem hiding this comment.
🧩 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.pyRepository: 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.pyRepository: 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.pyRepository: 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 -20Repository: 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 -5Repository: infiniflow/ragflow
Length of output: 128
🏁 Script executed:
rg -n 'async def async_ask\(' api/db/services/dialog_service.py | head -5Repository: 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.pyRepository: infiniflow/ragflow
Length of output: 881
🏁 Script executed:
# Read the async_ask function signature
sed -n '1446,1465p' api/db/services/dialog_service.pyRepository: 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.pyRepository: 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.pyRepository: 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.pyRepository: 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.pyRepository: 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.pyRepository: infiniflow/ragflow
Length of output: 927
🏁 Script executed:
# Check full_content initialization in sdk/session.py
sed -n '300,335p' api/apps/sdk/session.pyRepository: 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 -10Repository: 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.pyRepository: 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.pyRepository: 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**kwargsasync_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 finalThen 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).
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
api/db/services/dialog_service.py
| 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}" |
There was a problem hiding this comment.
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.
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?
normalize think tags in final chat answer
Type of change