49 lines
1.7 KiB
Python
49 lines
1.7 KiB
Python
"""
|
|
路由决策节点
|
|
根据当前状态决定下一步走向
|
|
"""
|
|
|
|
from typing import Literal
|
|
from langchain_core.messages import AIMessage
|
|
|
|
# 本地模块
|
|
from app.config import ENABLE_GRAPH_TRACE, MEMORY_SUMMARIZE_INTERVAL
|
|
from app.graph.state import MessagesState
|
|
from app.logger import info
|
|
|
|
|
|
def should_continue(state: MessagesState) -> Literal['tool_node', 'summarize', 'finalize']:
|
|
"""
|
|
决定下一步:工具调用、生成摘要还是结束
|
|
|
|
Args:
|
|
state: 当前对话状态
|
|
|
|
Returns:
|
|
下一个节点名称
|
|
"""
|
|
last_message = state["messages"][-1]
|
|
|
|
# 1. 如果需要调用工具,优先进入工具节点
|
|
if isinstance(last_message, AIMessage) and last_message.tool_calls:
|
|
if ENABLE_GRAPH_TRACE:
|
|
info(f"🔀 [路由决策] 检测到 {len(last_message.tool_calls)} 个工具调用 → 转向 'tool_node'")
|
|
return 'tool_node'
|
|
|
|
# 2. 如果是 AI 的最终回复,判断是否达到摘要生成阈值
|
|
if isinstance(last_message, AIMessage):
|
|
turns = state.get("turns_since_last_summary", 0)
|
|
if turns >= MEMORY_SUMMARIZE_INTERVAL:
|
|
if ENABLE_GRAPH_TRACE:
|
|
info(f"🔀 [路由决策] 收到 AI 最终回复,已达摘要阈值({turns}/{MEMORY_SUMMARIZE_INTERVAL}) → 转向 'summarize'")
|
|
return 'summarize'
|
|
else:
|
|
if ENABLE_GRAPH_TRACE:
|
|
info(f"🔀 [路由决策] 收到 AI 最终回复,未达摘要阈值({turns}/{MEMORY_SUMMARIZE_INTERVAL}) → 结束流程")
|
|
return 'finalize'
|
|
|
|
# 3. 其他情况(如只有用户消息)直接结束
|
|
if ENABLE_GRAPH_TRACE:
|
|
info(f"🔀 [路由决策] 非 AI 消息(如纯用户消息) → 结束流程")
|
|
return 'finalize'
|