From ff29484d42e452db7d8c403a9cca90c41bb2784f Mon Sep 17 00:00:00 2001 From: buua436 Date: Wed, 22 Apr 2026 11:15:08 +0800 Subject: [PATCH] fix: normalize think tags in final chat answer (#14271) ### What problem does this PR solve? normalize think tags in final chat answer ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) --- api/db/services/dialog_service.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/api/db/services/dialog_service.py b/api/db/services/dialog_service.py index cadf76c2aa..517989e011 100644 --- a/api/db/services/dialog_service.py +++ b/api/db/services/dialog_service.py @@ -802,7 +802,7 @@ async def async_chat(dialog, messages, stream=True, **kwargs): yield {"answer": value, "reference": {}, "audio_binary": tts(tts_mdl, value), "final": False} full_answer = last_state.full_text if last_state else "" if full_answer: - final = decorate_answer(thought + full_answer) + final = decorate_answer(_extract_visible_answer(thought + full_answer)) final["final"] = True final["audio_binary"] = None yield final @@ -1328,6 +1328,19 @@ class _ThinkStreamState: self.buffer = "" +def _extract_visible_answer(text: str) -> str: + text = text or "" + if "" not in text: + return re.sub(r"", "", text) + + thought, answer = text.rsplit("", 1) + thought = re.sub(r"", "", thought).strip() + answer = re.sub(r"", "", answer) + if not thought: + return answer + return f"{thought}{answer}" + + def _next_think_delta(state: _ThinkStreamState) -> str: full_text = state.full_text if full_text == state.last_full: @@ -1472,7 +1485,7 @@ async def async_ask(question, kb_ids, tenant_id, chat_llm_name=None, search_conf continue yield {"answer": value, "reference": {}, "final": False} full_answer = last_state.full_text if last_state else "" - final = decorate_answer(full_answer) + final = decorate_answer(_extract_visible_answer(full_answer)) final["final"] = True yield final