2026-04-21 11:02:16 +08:00
|
|
|
|
"""
|
2026-05-07 00:48:17 +08:00
|
|
|
|
完成事件节点模块(新架构版本)
|
|
|
|
|
|
负责发送完成事件
|
2026-04-21 11:02:16 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
from typing import Any, Dict
|
2026-05-07 00:48:17 +08:00
|
|
|
|
from datetime import datetime
|
2026-04-21 11:02:16 +08:00
|
|
|
|
|
|
|
|
|
|
# 本地模块
|
2026-05-07 00:48:17 +08:00
|
|
|
|
from .state import AgentState
|
2026-05-06 01:15:52 +08:00
|
|
|
|
from backend.app.logger import info, warning
|
2026-04-21 11:02:16 +08:00
|
|
|
|
|
|
|
|
|
|
from langchain_core.runnables.config import RunnableConfig
|
|
|
|
|
|
|
2026-05-01 22:45:42 +08:00
|
|
|
|
|
2026-05-07 00:48:17 +08:00
|
|
|
|
async def finalize_node(state: AgentState, config: RunnableConfig) -> Dict[str, Any]:
|
2026-04-21 11:02:16 +08:00
|
|
|
|
"""
|
2026-05-07 00:48:17 +08:00
|
|
|
|
完成事件节点(新架构版本)
|
|
|
|
|
|
|
2026-04-21 11:02:16 +08:00
|
|
|
|
Args:
|
2026-05-01 23:20:31 +08:00
|
|
|
|
state: 当前对话状态
|
2026-04-21 11:02:16 +08:00
|
|
|
|
config: 运行时配置
|
2026-05-07 00:48:17 +08:00
|
|
|
|
|
2026-04-21 11:02:16 +08:00
|
|
|
|
Returns:
|
2026-05-07 00:48:17 +08:00
|
|
|
|
空(不修改状态)
|
2026-04-21 11:02:16 +08:00
|
|
|
|
"""
|
2026-05-07 00:48:17 +08:00
|
|
|
|
info("[Finalize] 进入完成节点")
|
|
|
|
|
|
|
2026-04-21 11:02:16 +08:00
|
|
|
|
try:
|
|
|
|
|
|
# 获取流式写入器并发送完成事件
|
2026-05-05 23:17:00 +08:00
|
|
|
|
from backend.app.main_graph.config import get_stream_writer
|
2026-04-21 11:02:16 +08:00
|
|
|
|
writer = get_stream_writer()
|
2026-05-07 00:48:17 +08:00
|
|
|
|
|
|
|
|
|
|
# 提取最后的回复
|
|
|
|
|
|
final_reply = ""
|
|
|
|
|
|
if state.messages:
|
|
|
|
|
|
last_msg = state.messages[-1]
|
|
|
|
|
|
final_reply = last_msg.content if hasattr(last_msg, 'content') else str(last_msg)
|
|
|
|
|
|
|
2026-05-01 23:20:31 +08:00
|
|
|
|
# 只在 writer 存在且不是 noop 时才发送
|
|
|
|
|
|
if writer and hasattr(writer, '__call__'):
|
|
|
|
|
|
try:
|
|
|
|
|
|
writer({
|
2026-05-05 04:32:42 +08:00
|
|
|
|
"type": "custom",
|
2026-05-01 23:20:31 +08:00
|
|
|
|
"data": {
|
|
|
|
|
|
"type": "done",
|
|
|
|
|
|
"token_usage": state.last_token_usage,
|
2026-05-05 04:32:42 +08:00
|
|
|
|
"elapsed_time": state.last_elapsed_time,
|
2026-05-07 00:48:17 +08:00
|
|
|
|
"final_result": final_reply
|
2026-05-01 23:20:31 +08:00
|
|
|
|
}
|
|
|
|
|
|
})
|
2026-05-05 04:32:42 +08:00
|
|
|
|
info("🏁 [完成事件] 已发送完成事件")
|
2026-05-01 23:20:31 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
warning(f"⚠️ [完成事件] 发送完成事件失败 (非致命): {e}")
|
2026-04-21 11:02:16 +08:00
|
|
|
|
except Exception as e:
|
2026-05-01 23:20:31 +08:00
|
|
|
|
warning(f"⚠️ [完成事件] 处理失败 (非致命): {e}")
|
2026-05-07 00:48:17 +08:00
|
|
|
|
|
|
|
|
|
|
info("[Finalize] 离开完成节点")
|
|
|
|
|
|
return {}
|