Files
ailine/backend/app/main_graph/nodes/finalize.py

52 lines
1.7 KiB
Python
Raw Normal View History

2026-04-21 11:02:16 +08:00
"""
完成事件节点模块
负责发送完成事件包含token使用情况和耗时信息
"""
from typing import Any, Dict
# 本地模块
from app.main_graph.state import MainGraphState
from app.utils.logging import log_state_change
from app.logger import info, warning
2026-04-21 11:02:16 +08:00
from langchain_core.runnables.config import RunnableConfig
async def finalize_node(state: MainGraphState, config: RunnableConfig) -> Dict[str, Any]:
2026-04-21 11:02:16 +08:00
"""
完成事件节点 - 发送完成事件包含token使用情况和耗时信息
2026-04-21 11:02:16 +08:00
Args:
state: 当前对话状态
2026-04-21 11:02:16 +08:00
config: 运行时配置
2026-04-21 11:02:16 +08:00
Returns:
空字典完成节点无状态更新
"""
log_state_change("finalize", state, "进入")
try:
# 获取流式写入器并发送完成事件
from app.main_graph.config import get_stream_writer
2026-04-21 11:02:16 +08:00
writer = get_stream_writer()
# 只在 writer 存在且不是 noop 时才发送
if writer and hasattr(writer, '__call__'):
try:
writer({
"type": "custom",
"data": {
"type": "done",
"token_usage": state.last_token_usage,
"elapsed_time": state.last_elapsed_time
}
})
info("🏁 [完成事件] 已发送完成事件包含token使用情况和耗时信息")
except Exception as e:
warning(f"⚠️ [完成事件] 发送完成事件失败 (非致命): {e}")
2026-04-21 11:02:16 +08:00
except Exception as e:
warning(f"⚠️ [完成事件] 处理失败 (非致命): {e}")
2026-04-21 11:02:16 +08:00
log_state_change("finalize", state, "离开")
return {}