2026-04-21 11:02:16 +08:00
|
|
|
|
"""
|
2026-05-07 02:56:35 +08:00
|
|
|
|
AI Agent 服务类 - 完全简化版本!
|
|
|
|
|
|
按照指南实现,不用 stream_mode="messages" 避免重复 token!
|
2026-04-21 11:02:16 +08:00
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
import json
|
2026-05-07 02:21:09 +08:00
|
|
|
|
import asyncio
|
2026-05-05 17:30:55 +08:00
|
|
|
|
from typing import AsyncGenerator, Dict, Any, Optional, Tuple
|
2026-04-21 11:02:16 +08:00
|
|
|
|
|
2026-05-05 23:17:00 +08:00
|
|
|
|
# LangGraph 序列化器(修复 checkpoint 反序列化警告)
|
|
|
|
|
|
from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
|
|
|
|
|
|
|
2026-04-21 11:02:16 +08:00
|
|
|
|
# 本地模块
|
2026-05-07 02:56:35 +08:00
|
|
|
|
from backend.app.model_services import get_cached_chat_services
|
|
|
|
|
|
from backend.app.main_graph.main_graph_builder import build_agent_graph
|
2026-05-06 01:15:52 +08:00
|
|
|
|
from backend.app.logger import debug, info, warning, error
|
2026-05-07 02:56:35 +08:00
|
|
|
|
from backend.app.main_graph.state import AgentState
|
|
|
|
|
|
from .stream_context import set_stream_queue
|
2026-05-05 23:17:00 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-04-21 11:02:16 +08:00
|
|
|
|
class AIAgentService:
|
|
|
|
|
|
def __init__(self, checkpointer):
|
|
|
|
|
|
self.checkpointer = checkpointer
|
2026-05-07 00:48:17 +08:00
|
|
|
|
self.graph = None
|
|
|
|
|
|
self.chat_services = None
|
2026-05-01 15:43:45 +08:00
|
|
|
|
# Mem0 客户端
|
|
|
|
|
|
self.mem0_client = None
|
2026-04-21 11:02:16 +08:00
|
|
|
|
|
|
|
|
|
|
async def initialize(self):
|
2026-05-01 15:43:45 +08:00
|
|
|
|
# 0. 初始化 Mem0 客户端
|
2026-05-04 18:59:15 +08:00
|
|
|
|
from ..memory.mem0_client import Mem0Client
|
2026-05-05 13:30:31 +08:00
|
|
|
|
self.mem0_client = Mem0Client()
|
2026-05-01 15:43:45 +08:00
|
|
|
|
|
2026-05-07 00:48:17 +08:00
|
|
|
|
# 1. 获取缓存的模型字典
|
2026-05-05 17:30:55 +08:00
|
|
|
|
self.chat_services = get_cached_chat_services()
|
|
|
|
|
|
info(f"✅ 加载了 {len(self.chat_services)} 个可用模型: {list(self.chat_services.keys())}")
|
|
|
|
|
|
|
2026-05-07 00:48:17 +08:00
|
|
|
|
# 2. 构建图
|
|
|
|
|
|
info(f"🔄 构建 Agent 图...")
|
|
|
|
|
|
graph_builder = build_agent_graph(
|
2026-05-05 17:30:55 +08:00
|
|
|
|
chat_services=self.chat_services,
|
|
|
|
|
|
mem0_client=self.mem0_client
|
|
|
|
|
|
)
|
2026-05-07 00:48:17 +08:00
|
|
|
|
|
|
|
|
|
|
# 编译图
|
2026-05-05 17:30:55 +08:00
|
|
|
|
self.graph = graph_builder.compile(checkpointer=self.checkpointer)
|
2026-05-07 00:48:17 +08:00
|
|
|
|
info(f"✅ Agent 图初始化完成")
|
2026-05-05 17:30:55 +08:00
|
|
|
|
|
2026-04-21 11:02:16 +08:00
|
|
|
|
return self
|
|
|
|
|
|
|
2026-05-05 17:30:55 +08:00
|
|
|
|
def _resolve_model(self, model: str) -> str:
|
|
|
|
|
|
"""
|
|
|
|
|
|
解析并验证模型名称,不可用时回退到第一个可用模型
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
model: 目标模型名称
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
实际使用的模型名称
|
|
|
|
|
|
"""
|
|
|
|
|
|
if not model or model not in self.chat_services:
|
|
|
|
|
|
fallback = next(iter(self.chat_services.keys()))
|
|
|
|
|
|
warning(f"模型 '{model}' 不可用,回退到 '{fallback}'")
|
|
|
|
|
|
return fallback
|
|
|
|
|
|
return model
|
|
|
|
|
|
|
|
|
|
|
|
def _build_invocation(
|
|
|
|
|
|
self, message: str, thread_id: str, model: str, user_id: str
|
|
|
|
|
|
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
|
|
|
|
|
"""
|
|
|
|
|
|
构建图调用所需的 config 和 input_state
|
|
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
|
message: 用户消息
|
|
|
|
|
|
thread_id: 会话 ID
|
|
|
|
|
|
model: 模型名称
|
|
|
|
|
|
user_id: 用户 ID
|
|
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
(config, input_state) 元组
|
|
|
|
|
|
"""
|
2026-05-07 00:48:17 +08:00
|
|
|
|
from langchain_core.messages import HumanMessage
|
|
|
|
|
|
|
2026-04-21 11:02:16 +08:00
|
|
|
|
config = {
|
2026-05-05 04:32:42 +08:00
|
|
|
|
"configurable": {
|
|
|
|
|
|
"thread_id": thread_id,
|
|
|
|
|
|
},
|
2026-04-21 11:02:16 +08:00
|
|
|
|
"metadata": {"user_id": user_id}
|
|
|
|
|
|
}
|
2026-05-07 00:48:17 +08:00
|
|
|
|
|
2026-05-01 00:13:13 +08:00
|
|
|
|
input_state = {
|
2026-05-07 00:48:17 +08:00
|
|
|
|
"messages": [HumanMessage(content=message)],
|
2026-05-01 00:13:13 +08:00
|
|
|
|
"user_id": user_id,
|
|
|
|
|
|
}
|
2026-05-05 17:30:55 +08:00
|
|
|
|
return config, input_state
|
2026-04-21 11:02:16 +08:00
|
|
|
|
|
2026-05-05 17:30:55 +08:00
|
|
|
|
async def process_message(
|
|
|
|
|
|
self, message: str, thread_id: str, model: str = "", user_id: str = "default_user"
|
|
|
|
|
|
) -> dict:
|
|
|
|
|
|
"""处理用户消息,返回包含回复、token统计和耗时的字典"""
|
|
|
|
|
|
# 解析模型名称
|
|
|
|
|
|
resolved_model = self._resolve_model(model)
|
|
|
|
|
|
|
|
|
|
|
|
# 构建调用参数
|
|
|
|
|
|
config, input_state = self._build_invocation(message, thread_id, resolved_model, user_id)
|
|
|
|
|
|
|
|
|
|
|
|
result = await self.graph.ainvoke(input_state, config=config)
|
2026-05-08 02:05:35 +08:00
|
|
|
|
|
|
|
|
|
|
# 优先使用 final_reply(finalize 节点返回)
|
|
|
|
|
|
reply = result.get("final_reply", "")
|
|
|
|
|
|
if not reply and result.get("messages"):
|
2026-05-01 00:13:13 +08:00
|
|
|
|
reply = result["messages"][-1].content
|
2026-05-08 02:05:35 +08:00
|
|
|
|
|
2026-05-05 17:30:55 +08:00
|
|
|
|
token_usage = result.get("last_token_usage", {})
|
|
|
|
|
|
elapsed_time = result.get("last_elapsed_time", 0.0)
|
2026-04-21 11:02:16 +08:00
|
|
|
|
|
2026-05-08 02:05:35 +08:00
|
|
|
|
# 获取元数据
|
|
|
|
|
|
metadata = result.get("metadata", {})
|
|
|
|
|
|
|
2026-04-21 11:02:16 +08:00
|
|
|
|
return {
|
|
|
|
|
|
"reply": reply,
|
|
|
|
|
|
"token_usage": token_usage,
|
2026-05-05 17:30:55 +08:00
|
|
|
|
"elapsed_time": elapsed_time,
|
2026-05-08 02:05:35 +08:00
|
|
|
|
"model_used": resolved_model,
|
|
|
|
|
|
"metadata": metadata
|
2026-04-21 11:02:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-05-05 17:30:55 +08:00
|
|
|
|
async def process_message_stream(
|
|
|
|
|
|
self, message: str, thread_id: str, model: str = "", user_id: str = "default_user"
|
|
|
|
|
|
) -> AsyncGenerator[Dict[str, Any], None]:
|
2026-05-07 02:56:35 +08:00
|
|
|
|
"""流式处理消息 - 完全简化!"""
|
2026-05-05 17:30:55 +08:00
|
|
|
|
# 解析模型名称
|
|
|
|
|
|
resolved_model = self._resolve_model(model)
|
|
|
|
|
|
|
|
|
|
|
|
# 构建调用参数
|
|
|
|
|
|
config, input_state = self._build_invocation(message, thread_id, resolved_model, user_id)
|
|
|
|
|
|
|
2026-05-07 00:48:17 +08:00
|
|
|
|
info(f"🚀 开始执行 Agent 图,指定模型: {resolved_model}")
|
2026-05-05 17:30:55 +08:00
|
|
|
|
actual_model_used = resolved_model
|
2026-05-01 11:24:13 +08:00
|
|
|
|
|
2026-05-07 02:21:09 +08:00
|
|
|
|
# 创建 token 队列
|
2026-05-07 02:56:35 +08:00
|
|
|
|
queue = asyncio.Queue()
|
|
|
|
|
|
set_stream_queue(queue) # 设置上下文变量
|
2026-05-07 02:21:09 +08:00
|
|
|
|
|
2026-05-07 02:56:35 +08:00
|
|
|
|
async def run_graph():
|
2026-05-07 03:06:12 +08:00
|
|
|
|
"""后台任务:运行 graph,流式事件都从 agent 节点内部发送!"""
|
2026-05-07 02:21:09 +08:00
|
|
|
|
try:
|
|
|
|
|
|
info(f"📡 开始调用 graph.astream()...")
|
2026-05-07 02:05:23 +08:00
|
|
|
|
|
2026-05-07 02:56:35 +08:00
|
|
|
|
# 注意:只用 stream_mode=["updates"],不要 "messages"!避免重复 token!
|
2026-05-07 03:06:12 +08:00
|
|
|
|
async for _ in self.graph.astream(
|
2026-05-07 02:21:09 +08:00
|
|
|
|
input_state,
|
|
|
|
|
|
config=config,
|
2026-05-07 02:56:35 +08:00
|
|
|
|
stream_mode=["updates"],
|
2026-05-07 02:21:09 +08:00
|
|
|
|
version="v2",
|
|
|
|
|
|
subgraphs=True
|
|
|
|
|
|
):
|
2026-05-07 03:06:12 +08:00
|
|
|
|
# 流式事件都从 agent.py 节点内部通过队列发送了
|
|
|
|
|
|
# 这里不需要再发送任何事件
|
|
|
|
|
|
pass
|
2026-05-07 02:21:09 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
error(f"❌ 执行图时出错: {e}")
|
|
|
|
|
|
import traceback
|
|
|
|
|
|
error(f"📋 堆栈: {traceback.format_exc()}")
|
2026-05-07 02:56:35 +08:00
|
|
|
|
await queue.put({"type": "error", "message": str(e)})
|
2026-05-07 02:21:09 +08:00
|
|
|
|
finally:
|
2026-05-07 02:56:35 +08:00
|
|
|
|
await queue.put(None) # 结束哨兵
|
2026-05-07 02:21:09 +08:00
|
|
|
|
|
|
|
|
|
|
# 启动后台任务
|
2026-05-07 02:56:35 +08:00
|
|
|
|
bg_task = asyncio.create_task(run_graph())
|
2026-05-07 02:21:09 +08:00
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
while True:
|
2026-05-07 02:56:35 +08:00
|
|
|
|
event = await queue.get()
|
|
|
|
|
|
if event is None:
|
|
|
|
|
|
break
|
|
|
|
|
|
yield event
|
|
|
|
|
|
|
|
|
|
|
|
except GeneratorExit:
|
|
|
|
|
|
# 客户端断开连接,取消后台任务
|
|
|
|
|
|
info("⚠️ GeneratorExit,取消后台任务")
|
|
|
|
|
|
bg_task.cancel()
|
2026-05-07 02:21:09 +08:00
|
|
|
|
raise
|
2026-05-05 17:30:55 +08:00
|
|
|
|
finally:
|
2026-05-07 02:56:35 +08:00
|
|
|
|
# 保证任务被清理
|
|
|
|
|
|
if not bg_task.done():
|
|
|
|
|
|
info("⏹️ 清理后台任务")
|
|
|
|
|
|
bg_task.cancel()
|
2026-05-07 02:21:09 +08:00
|
|
|
|
try:
|
2026-05-07 02:56:35 +08:00
|
|
|
|
await bg_task
|
2026-05-07 02:21:09 +08:00
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
|
|
info("✅ 后台任务已取消")
|
|
|
|
|
|
|
|
|
|
|
|
# 发送结束事件,保证前端平稳关闭
|
2026-05-05 17:30:55 +08:00
|
|
|
|
yield {
|
|
|
|
|
|
"type": "done",
|
|
|
|
|
|
"model_used": actual_model_used
|
2026-04-26 16:05:44 +08:00
|
|
|
|
}
|