Skip to content

Commit ea4f5ca

Browse files
committed
feat(anthropic): expose model thinking process to client to help debug refusal reasons
1 parent 24a27aa commit ea4f5ca

2 files changed

Lines changed: 14 additions & 3 deletions

File tree

backend/api/anthropic.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,12 @@ async def generate():
196196
await asyncio.sleep(0.5)
197197
continue
198198

199+
# 暴露思考过程给客户端,帮助 LO 分析
200+
thinking_text = "".join(thinking_chunks)
201+
if thinking_text and tools:
202+
exposed_think = f"<think>\n{thinking_text}\n</think>\n\n"
203+
answer_text = exposed_think + answer_text
204+
199205
# Parse tools
200206
from backend.services.tool_parser import parse_tool_calls
201207
if tools:

backend/services/tool_parser.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -179,8 +179,11 @@ def _make_tool_block(name, input_data, prefix=""):
179179
return blocks, "tool_use"
180180

181181
# 5. 极端保底拦截:只要看到文本中含有明显意图,但正则全部失败,强制触发纠偏
182-
if answer.strip() and tools:
183-
lower_ans = answer.lower()
182+
# 这里我们排除了只包含 <think> 的情况,因为我们要把 thinking 原样透传给用户看
183+
answer_without_think = re.sub(r'<think>.*?</think>', '', answer, flags=re.DOTALL).strip()
184+
185+
if answer_without_think and tools:
186+
lower_ans = answer_without_think.lower()
184187
# 匹配明确的工具调用意图词
185188

186189
found_intent = False
@@ -211,7 +214,9 @@ def _make_tool_block(name, input_data, prefix=""):
211214
text_content = answer if answer.strip() else "[模型思考完毕,但未能按照要求输出✿ACTION✿工具调用。请重新调整提示词。]"
212215

213216
# 既然模型死活不调用,又没法报错给用户,就强制触发一个空操作的AskUserQuestion或者抛错,让工作流中断
214-
if not answer.strip():
217+
# 既然现在我们已经把 thinking 拼接到 answer 里了,answer.strip() 就不为空了。
218+
# 我们需要根据 answer_without_think 来判断它是否真正给出了回答。
219+
if not answer_without_think:
215220
if "AskUserQuestion" in tool_names:
216221
log.warning("[ToolParse] 强制使用 AskUserQuestion 以阻断空循环。")
217222
return _make_tool_block("AskUserQuestion", {"questions": [{"question": "系统:大模型连续5次拒绝输出任何内容,可能已触发内置安全限制或死循环。建议:1. 简化你的报错日志;2. 直接告诉模型“修改文件代码”,不要让它分析。", "options": [{"label": "好的,我重试", "description": "明白了"}], "header": "模型装死拦截", "multiSelect": False}]})

0 commit comments

Comments
 (0)