feat: 新增 react_reason 循环思考过程的流式显示
All checks were successful
构建并部署 AI Agent 服务 / deploy (push) Successful in 5m38s

- 修改 react_nodes.py,在推理时保存推理过程到状态
- 修改 agent_service.py,检测并发送推理过程事件到前端
- 修改 chat_area.py,接收并显示推理过程
- 修改 useChat.ts,添加对推理过程事件的支持
This commit is contained in:
2026-05-02 07:48:45 +08:00
parent 5f53f80d1f
commit 26b15aa4e5
4 changed files with 93 additions and 3 deletions

View File

@@ -26,11 +26,12 @@ from app.main_graph.utils.retry_utils import (
RetryConfig,
SUBGRAPH_RETRY_CONFIG
)
from app.logger import info
# ========== 1. React 推理节点 ==========
def react_reason_node(state: MainGraphState) -> MainGraphState:
def react_reason_node(state: MainGraphState, config: Optional[Dict[str, Any]] = None) -> MainGraphState:
"""
React 模式推理节点:判断下一步做什么
@@ -38,6 +39,22 @@ def react_reason_node(state: MainGraphState) -> MainGraphState:
"""
state.current_phase = "react_reasoning"
state.reasoning_step += 1
# 发送推理开始事件
if config:
try:
from langchain_core.runnables.config import RunnableConfig
# 尝试获取回调管理器并发送自定义事件
callbacks = config.get("callbacks")
if callbacks:
from langchain_core.callbacks.manager import adispatch_custom_event
# 注意:这是异步操作,我们需要特殊处理
# 这里我们使用自定义流式写入器(如果存在)
pass
except Exception as e:
info(f"[react_reason] 无法发送回调事件: {e}")
info(f"[react_reason] 第 {state.reasoning_step} 次推理开始")
# 检查是否超过最大步数
if state.reasoning_step > state.max_steps:
@@ -61,6 +78,10 @@ def react_reason_node(state: MainGraphState) -> MainGraphState:
# 使用 intent.py 进行推理
# 注意:这里使用同步版本,内部会根据情况处理
result: ReasoningResult = react_reason(state.user_query, context)
info(f"[react_reason] 推理结果: action={result.action.name}, confidence={result.confidence}")
if result.reasoning:
info(f"[react_reason] 推理过程: {result.reasoning}")
# 记录推理历史
state.reasoning_history.append({
@@ -83,6 +104,16 @@ def react_reason_node(state: MainGraphState) -> MainGraphState:
# 确定下一步动作
state.last_action = result.action.name
# 发送推理完成事件通过状态更新agent_service 会处理)
# 我们在状态中保存推理内容,以便 agent_service 可以通过 state_update 事件发送
state.debug_info["latest_reasoning"] = {
"step": state.reasoning_step,
"action": result.action.name,
"confidence": result.confidence,
"reasoning": result.reasoning,
"sent": False # 标记是否已发送到前端
}
return state