feat: 完成极简 LangGraph 架构迁移,添加 Baosi API 支持
Some checks failed
构建并部署 AI Agent 服务 / deploy (push) Failing after 6m36s
Some checks failed
构建并部署 AI Agent 服务 / deploy (push) Failing after 6m36s
主要变更: - 迁移到极简 LangGraph 标准架构(START → init_state → 记忆 → Agent ⇄ Tools → finalize → END) - 添加 Baosi API 支持,配置 ops4.7 模型 - 保留本地模型作为默认首选,Baosi 作为备选 - 新架构使用 LangGraph 原生 ToolNode 和 bind_tools - 移除旧的混合路由、JSON 解析等复杂逻辑 - 把旧代码移到 deprecated/ 目录 - 添加新的 Agent 节点和 Tools 模块 - 添加测试脚本验证新架构 - 所有测试通过 ✓
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
AI Agent 服务类 - 单图方案 + 动态模型选择
|
||||
AI Agent 服务类 - 极简 LangGraph Agent 架构
|
||||
接收外部传入的 checkpointer,不负责管理连接生命周期
|
||||
"""
|
||||
|
||||
@@ -12,61 +12,16 @@ from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
|
||||
|
||||
# 本地模块
|
||||
from ..model_services import get_cached_chat_services
|
||||
from ..main_graph.main_graph_builder import build_react_main_graph
|
||||
from ..main_graph.tools.graph_tools import AVAILABLE_TOOLS, TOOLS_BY_NAME
|
||||
from ..main_graph.config import set_stream_writer
|
||||
from ..main_graph.utils.rag_initializer import init_rag_tool
|
||||
from ..main_graph.main_graph_builder import build_agent_graph
|
||||
from backend.app.logger import debug, info, warning, error
|
||||
from ..main_graph.state import MainGraphState, CurrentAction
|
||||
|
||||
|
||||
# ========== 自定义类型序列化器 ==========
|
||||
def create_serde() -> JsonPlusSerializer:
|
||||
"""创建带自定义类型注册的序列化器"""
|
||||
from backend.app.core.intent import ReasoningAction, RetrievalConfig, ReasoningResult
|
||||
from backend.app.main_graph.state import (
|
||||
CurrentAction, ErrorSeverity, ErrorRecord,
|
||||
ReactReasoningState, HybridRouterState, FastPathState
|
||||
)
|
||||
from backend.app.main_graph.nodes.hybrid_router import HybridRouterResult
|
||||
|
||||
return JsonPlusSerializer(
|
||||
allowed_msgpack_modules=[
|
||||
# 新路径
|
||||
("backend.app.core.intent", "ReasoningAction"),
|
||||
("backend.app.core.intent", "RetrievalConfig"),
|
||||
("backend.app.core.intent", "ReasoningResult"),
|
||||
("backend.app.main_graph.state", "CurrentAction"),
|
||||
("backend.app.main_graph.state", "ErrorSeverity"),
|
||||
("backend.app.main_graph.state", "ErrorRecord"),
|
||||
("backend.app.main_graph.state", "ReactReasoningState"),
|
||||
("backend.app.main_graph.state", "HybridRouterState"),
|
||||
("backend.app.main_graph.state", "FastPathState"),
|
||||
("backend.app.main_graph.nodes.hybrid_router", "HybridRouterResult"),
|
||||
# 旧路径(兼容旧 checkpoint 数据)
|
||||
("app.core.intent", "ReasoningAction"),
|
||||
("app.core.intent", "RetrievalConfig"),
|
||||
("app.core.intent", "ReasoningResult"),
|
||||
("app.main_graph.state", "CurrentAction"),
|
||||
("app.main_graph.state", "ErrorSeverity"),
|
||||
("app.main_graph.state", "ErrorRecord"),
|
||||
("app.main_graph.state", "ReactReasoningState"),
|
||||
("app.main_graph.state", "HybridRouterState"),
|
||||
("app.main_graph.state", "FastPathState"),
|
||||
("app.main_graph.nodes.hybrid_router", "HybridRouterResult"),
|
||||
]
|
||||
)
|
||||
from ..main_graph.state import AgentState
|
||||
|
||||
|
||||
class AIAgentService:
|
||||
def __init__(self, checkpointer):
|
||||
self.checkpointer = checkpointer
|
||||
self.graph = None # 只有一张图
|
||||
self.chat_services = None # 缓存的模型字典
|
||||
self.tools = AVAILABLE_TOOLS.copy()
|
||||
self.tools_by_name = TOOLS_BY_NAME.copy()
|
||||
# RAG 管道(可选,需要时设置)
|
||||
self.rag_pipeline = None
|
||||
self.graph = None
|
||||
self.chat_services = None
|
||||
# Mem0 客户端
|
||||
self.mem0_client = None
|
||||
|
||||
@@ -75,27 +30,20 @@ class AIAgentService:
|
||||
from ..memory.mem0_client import Mem0Client
|
||||
self.mem0_client = Mem0Client()
|
||||
|
||||
# 1. 初始化 RAG 工具(如果需要)
|
||||
rag_tool = await init_rag_tool()
|
||||
if rag_tool:
|
||||
self.tools.append(rag_tool)
|
||||
self.tools_by_name[rag_tool.name] = rag_tool
|
||||
self.rag_tool = rag_tool # 保存到实例变量,供 config 注入
|
||||
|
||||
# 2. 获取缓存的模型字典
|
||||
# 1. 获取缓存的模型字典
|
||||
self.chat_services = get_cached_chat_services()
|
||||
info(f"✅ 加载了 {len(self.chat_services)} 个可用模型: {list(self.chat_services.keys())}")
|
||||
|
||||
# 3. 只构建一次图(传入 chat_services 字典)
|
||||
info(f"🔄 构建单图...")
|
||||
graph_builder = build_react_main_graph(
|
||||
# 2. 构建图
|
||||
info(f"🔄 构建 Agent 图...")
|
||||
graph_builder = build_agent_graph(
|
||||
chat_services=self.chat_services,
|
||||
tools=self.tools,
|
||||
mem0_client=self.mem0_client
|
||||
)
|
||||
# 注意:serde 已在创建 checkpointer 时传入,这里只需传入 checkpointer
|
||||
|
||||
# 编译图
|
||||
self.graph = graph_builder.compile(checkpointer=self.checkpointer)
|
||||
info(f"✅ 单图初始化完成")
|
||||
info(f"✅ Agent 图初始化完成")
|
||||
|
||||
return self
|
||||
|
||||
@@ -130,19 +78,18 @@ class AIAgentService:
|
||||
Returns:
|
||||
(config, input_state) 元组
|
||||
"""
|
||||
from langchain_core.messages import HumanMessage
|
||||
|
||||
config = {
|
||||
"configurable": {
|
||||
"thread_id": thread_id,
|
||||
"rag_tool": getattr(self, "rag_tool", None),
|
||||
},
|
||||
"metadata": {"user_id": user_id}
|
||||
}
|
||||
|
||||
input_state = {
|
||||
"user_query": message,
|
||||
"messages": [{"role": "user", "content": message}],
|
||||
"messages": [HumanMessage(content=message)],
|
||||
"user_id": user_id,
|
||||
"current_model": model,
|
||||
"current_action": CurrentAction.NONE
|
||||
}
|
||||
return config, input_state
|
||||
|
||||
@@ -157,19 +104,19 @@ class AIAgentService:
|
||||
config, input_state = self._build_invocation(message, thread_id, resolved_model, user_id)
|
||||
|
||||
result = await self.graph.ainvoke(input_state, config=config)
|
||||
|
||||
reply = result.get("final_result", "")
|
||||
if not reply and result.get("messages"):
|
||||
|
||||
reply = ""
|
||||
if result.get("messages"):
|
||||
reply = result["messages"][-1].content
|
||||
|
||||
token_usage = result.get("last_token_usage", {})
|
||||
elapsed_time = result.get("last_elapsed_time", 0.0)
|
||||
actual_model = result.get("current_model", resolved_model)
|
||||
|
||||
return {
|
||||
"reply": reply,
|
||||
"token_usage": token_usage,
|
||||
"elapsed_time": elapsed_time,
|
||||
"model_used": actual_model
|
||||
"model_used": resolved_model
|
||||
}
|
||||
|
||||
def _serialize_value(self, value):
|
||||
@@ -259,28 +206,8 @@ class AIAgentService:
|
||||
updates_data = chunk["data"]
|
||||
new_actual_model = actual_model_used
|
||||
|
||||
debug(f"[Stream] updates 数据: {list(updates_data.keys()) if isinstance(updates_data, dict) else type(updates_data)}")
|
||||
|
||||
# 特别检查 final_result 和 current_model
|
||||
if isinstance(updates_data, dict):
|
||||
if "final_result" in updates_data:
|
||||
debug(f"[Stream] 收到 final_result: {str(updates_data['final_result'])[:100]}...")
|
||||
if "current_model" in updates_data:
|
||||
new_actual_model = updates_data["current_model"]
|
||||
info(f"[Stream] 实际使用模型: {new_actual_model}")
|
||||
|
||||
serialized_data = self._serialize_value(updates_data)
|
||||
|
||||
# 检查是否有人工审核请求
|
||||
if "review_pending" in serialized_data and serialized_data["review_pending"]:
|
||||
review_id = serialized_data.get("review_id", "")
|
||||
content_to_review = serialized_data.get("content_to_review", "")
|
||||
yield {
|
||||
"type": "human_review_request",
|
||||
"review_id": review_id,
|
||||
"content": content_to_review
|
||||
}
|
||||
|
||||
# 检查是否有工具结果
|
||||
if "messages" in serialized_data:
|
||||
for msg in serialized_data["messages"]:
|
||||
@@ -307,36 +234,6 @@ class AIAgentService:
|
||||
# 返回更新后的模型
|
||||
yield {"type": "_update_state", "actual_model_used": new_actual_model}
|
||||
|
||||
async def _handle_custom_chunk(self, chunk: Dict[str, Any]) -> AsyncGenerator[Dict[str, Any], None]:
|
||||
"""处理 custom 类型的 chunk"""
|
||||
custom_data = chunk["data"]
|
||||
|
||||
# 处理我们从 react_reason_node 发送的自定义推理事件
|
||||
if isinstance(custom_data, dict):
|
||||
# 检查是否是我们的推理事件
|
||||
if "action" in custom_data and "reasoning" in custom_data:
|
||||
yield {
|
||||
"type": "react_reasoning",
|
||||
"step": custom_data.get("step", 1),
|
||||
"action": custom_data.get("action", "unknown"),
|
||||
"confidence": custom_data.get("confidence", 0),
|
||||
"reasoning": custom_data.get("reasoning", "")
|
||||
}
|
||||
else:
|
||||
# 处理其他自定义事件
|
||||
serialized_data = self._serialize_value(custom_data)
|
||||
yield {
|
||||
"type": "custom",
|
||||
"data": serialized_data
|
||||
}
|
||||
else:
|
||||
# 处理其他自定义事件
|
||||
serialized_data = self._serialize_value(custom_data)
|
||||
yield {
|
||||
"type": "custom",
|
||||
"data": serialized_data
|
||||
}
|
||||
|
||||
async def process_message_stream(
|
||||
self, message: str, thread_id: str, model: str = "", user_id: str = "default_user"
|
||||
) -> AsyncGenerator[Dict[str, Any], None]:
|
||||
@@ -347,8 +244,7 @@ class AIAgentService:
|
||||
# 构建调用参数
|
||||
config, input_state = self._build_invocation(message, thread_id, resolved_model, user_id)
|
||||
|
||||
# ========== React 循环路径 ==========
|
||||
info(f"🚀 开始执行单图,指定模型: {resolved_model}")
|
||||
info(f"🚀 开始执行 Agent 图,指定模型: {resolved_model}")
|
||||
current_node = None
|
||||
tool_calls_in_progress: Dict[str, Any] = {}
|
||||
actual_model_used = resolved_model
|
||||
@@ -361,7 +257,7 @@ class AIAgentService:
|
||||
async for chunk in self.graph.astream(
|
||||
input_state,
|
||||
config=config,
|
||||
stream_mode=["messages", "updates", "custom"],
|
||||
stream_mode=["messages", "updates"],
|
||||
version="v2",
|
||||
subgraphs=True
|
||||
):
|
||||
@@ -375,10 +271,10 @@ class AIAgentService:
|
||||
if event.get("type") == "_update_state":
|
||||
current_node = event.get("current_node", current_node)
|
||||
else:
|
||||
# 如果是 llm_call 节点的 token,收集完整消息
|
||||
# 如果是 agent 节点的 token,收集完整消息
|
||||
if (
|
||||
event.get("type") == "llm_token"
|
||||
and event.get("node") == "llm_call"
|
||||
and event.get("node") == "agent"
|
||||
and "token" in event
|
||||
):
|
||||
full_message_content += event["token"]
|
||||
@@ -393,18 +289,13 @@ class AIAgentService:
|
||||
else:
|
||||
yield event
|
||||
|
||||
elif chunk_type == "custom":
|
||||
async for event in self._handle_custom_chunk(chunk):
|
||||
yield event
|
||||
|
||||
# 完整消息集合完成后,一次性打印
|
||||
info(f"✅ graph.astream() 完成,共 {chunk_count} 个 chunks")
|
||||
if full_message_content:
|
||||
info(f"📄 完整消息内容: {repr(full_message_content)}")
|
||||
info(f"🤖 实际使用模型: {actual_model_used}")
|
||||
|
||||
except Exception as e:
|
||||
error(f"❌ 执行单图时出错: {e}")
|
||||
error(f"❌ 执行图时出错: {e}")
|
||||
import traceback
|
||||
error(f"📋 堆栈: {traceback.format_exc()}")
|
||||
yield {
|
||||
|
||||
Reference in New Issue
Block a user