Files
ailine/backend/app/main_graph/nodes/reasoning.py
2026-05-05 00:54:04 +08:00

69 lines
2.1 KiB
Python

"""
React 推理节点
使用 intent.py 进行意图推理
"""
from typing import Dict, Any, Optional
from datetime import datetime
from app.core.intent import react_reason_async, ReasoningResult
from app.main_graph.state import MainGraphState
from app.logger import info
from ._utils import dispatch_custom_event, make_react_event
async def react_reason_node(state: MainGraphState, config: Optional[Dict[str, Any]] = None) -> MainGraphState:
"""React 模式推理节点:判断下一步做什么"""
state.current_phase = "react_reasoning"
state.reasoning_step += 1
info(f"[推理] 第 {state.reasoning_step} 次推理开始")
# 步骤1: 准备上下文
context = {
"retrieved_docs": state.rag_docs,
"previous_actions": [h.get("action") for h in state.reasoning_history],
"reasoning_history": state.reasoning_history,
"messages": state.messages,
"errors": state.errors
}
# 步骤2: 执行推理
result: ReasoningResult = await react_reason_async(state.user_query, context)
info(f"[推理] 推理结果: action={result.action.name}, confidence={result.confidence}")
if result.reasoning:
info(f"[推理] 推理过程: {result.reasoning}")
# 步骤3: 记录推理历史
state.reasoning_history.append({
"step": state.reasoning_step,
"action": result.action.name,
"confidence": result.confidence,
"reasoning": result.reasoning,
"timestamp": datetime.now().isoformat()
})
# 步骤4: 更新调试信息
state.debug_info["last_reasoning"] = {
"action": result.action.name,
"confidence": result.confidence,
"reasoning": result.reasoning
}
state.debug_info["reasoning_result"] = result
state.last_action = result.action.name
# 步骤5: 发送推理事件
await dispatch_custom_event(
"react_reasoning",
make_react_event(
state.reasoning_step,
result.action.name,
result.confidence,
result.reasoning
),
config
)
return state