citu_agent.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. # agent/citu_agent.py
  2. from typing import Dict, Any, Literal
  3. from langgraph.graph import StateGraph, END
  4. from langchain.agents import AgentExecutor, create_openai_tools_agent
  5. from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
  6. from langchain_core.messages import SystemMessage, HumanMessage
  7. from agent.state import AgentState
  8. from agent.classifier import QuestionClassifier
  9. from agent.tools import TOOLS, generate_sql, execute_sql, generate_summary, general_chat
  10. from agent.utils import get_compatible_llm
  11. from app_config import ENABLE_RESULT_SUMMARY
  12. class CituLangGraphAgent:
  13. """Citu LangGraph智能助手主类 - 使用@tool装饰器 + Agent工具调用"""
  14. def __init__(self):
  15. # 加载配置
  16. try:
  17. from agent.config import get_current_config, get_nested_config
  18. self.config = get_current_config()
  19. print("[CITU_AGENT] 加载Agent配置完成")
  20. except ImportError:
  21. self.config = {}
  22. print("[CITU_AGENT] 配置文件不可用,使用默认配置")
  23. self.classifier = QuestionClassifier()
  24. self.tools = TOOLS
  25. self.llm = get_compatible_llm()
  26. # 注意:现在使用直接工具调用模式,不再需要预创建Agent执行器
  27. print("[CITU_AGENT] 使用直接工具调用模式")
  28. self.workflow = self._create_workflow()
  29. print("[CITU_AGENT] LangGraph Agent with Direct Tools初始化完成")
  30. def _create_workflow(self) -> StateGraph:
  31. """根据路由模式创建不同的工作流"""
  32. try:
  33. from app_config import QUESTION_ROUTING_MODE
  34. print(f"[CITU_AGENT] 创建工作流,路由模式: {QUESTION_ROUTING_MODE}")
  35. except ImportError:
  36. QUESTION_ROUTING_MODE = "hybrid"
  37. print(f"[CITU_AGENT] 配置导入失败,使用默认路由模式: {QUESTION_ROUTING_MODE}")
  38. workflow = StateGraph(AgentState)
  39. # 根据路由模式创建不同的工作流
  40. if QUESTION_ROUTING_MODE == "database_direct":
  41. # 直接数据库模式:跳过分类,直接进入数据库处理
  42. workflow.add_node("init_direct_database", self._init_direct_database_node)
  43. workflow.add_node("agent_database", self._agent_database_node)
  44. workflow.add_node("format_response", self._format_response_node)
  45. workflow.set_entry_point("init_direct_database")
  46. workflow.add_edge("init_direct_database", "agent_database")
  47. workflow.add_edge("agent_database", "format_response")
  48. workflow.add_edge("format_response", END)
  49. elif QUESTION_ROUTING_MODE == "chat_direct":
  50. # 直接聊天模式:跳过分类,直接进入聊天处理
  51. workflow.add_node("init_direct_chat", self._init_direct_chat_node)
  52. workflow.add_node("agent_chat", self._agent_chat_node)
  53. workflow.add_node("format_response", self._format_response_node)
  54. workflow.set_entry_point("init_direct_chat")
  55. workflow.add_edge("init_direct_chat", "agent_chat")
  56. workflow.add_edge("agent_chat", "format_response")
  57. workflow.add_edge("format_response", END)
  58. else:
  59. # 其他模式(hybrid, llm_only):使用原有的分类工作流
  60. workflow.add_node("classify_question", self._classify_question_node)
  61. workflow.add_node("agent_chat", self._agent_chat_node)
  62. workflow.add_node("agent_database", self._agent_database_node)
  63. workflow.add_node("format_response", self._format_response_node)
  64. workflow.set_entry_point("classify_question")
  65. # 添加条件边:分类后的路由
  66. workflow.add_conditional_edges(
  67. "classify_question",
  68. self._route_after_classification,
  69. {
  70. "DATABASE": "agent_database",
  71. "CHAT": "agent_chat"
  72. }
  73. )
  74. workflow.add_edge("agent_chat", "format_response")
  75. workflow.add_edge("agent_database", "format_response")
  76. workflow.add_edge("format_response", END)
  77. return workflow.compile()
  78. def _init_direct_database_node(self, state: AgentState) -> AgentState:
  79. """初始化直接数据库模式的状态"""
  80. try:
  81. from app_config import QUESTION_ROUTING_MODE
  82. # 设置直接数据库模式的分类状态
  83. state["question_type"] = "DATABASE"
  84. state["classification_confidence"] = 1.0
  85. state["classification_reason"] = "配置为直接数据库查询模式"
  86. state["classification_method"] = "direct_database"
  87. state["routing_mode"] = QUESTION_ROUTING_MODE
  88. state["current_step"] = "direct_database_init"
  89. state["execution_path"].append("init_direct_database")
  90. print(f"[DIRECT_DATABASE] 直接数据库模式初始化完成")
  91. return state
  92. except Exception as e:
  93. print(f"[ERROR] 直接数据库模式初始化异常: {str(e)}")
  94. state["error"] = f"直接数据库模式初始化失败: {str(e)}"
  95. state["error_code"] = 500
  96. state["execution_path"].append("init_direct_database_error")
  97. return state
  98. def _init_direct_chat_node(self, state: AgentState) -> AgentState:
  99. """初始化直接聊天模式的状态"""
  100. try:
  101. from app_config import QUESTION_ROUTING_MODE
  102. # 设置直接聊天模式的分类状态
  103. state["question_type"] = "CHAT"
  104. state["classification_confidence"] = 1.0
  105. state["classification_reason"] = "配置为直接聊天模式"
  106. state["classification_method"] = "direct_chat"
  107. state["routing_mode"] = QUESTION_ROUTING_MODE
  108. state["current_step"] = "direct_chat_init"
  109. state["execution_path"].append("init_direct_chat")
  110. print(f"[DIRECT_CHAT] 直接聊天模式初始化完成")
  111. return state
  112. except Exception as e:
  113. print(f"[ERROR] 直接聊天模式初始化异常: {str(e)}")
  114. state["error"] = f"直接聊天模式初始化失败: {str(e)}"
  115. state["error_code"] = 500
  116. state["execution_path"].append("init_direct_chat_error")
  117. return state
  118. def _classify_question_node(self, state: AgentState) -> AgentState:
  119. """问题分类节点 - 支持渐进式分类策略"""
  120. try:
  121. from app_config import QUESTION_ROUTING_MODE
  122. print(f"[CLASSIFY_NODE] 开始分类问题: {state['question']}")
  123. # 获取上下文类型(如果有的话)
  124. context_type = state.get("context_type")
  125. if context_type:
  126. print(f"[CLASSIFY_NODE] 检测到上下文类型: {context_type}")
  127. # 使用渐进式分类策略
  128. classification_result = self.classifier.classify(state["question"], context_type)
  129. # 更新状态
  130. state["question_type"] = classification_result.question_type
  131. state["classification_confidence"] = classification_result.confidence
  132. state["classification_reason"] = classification_result.reason
  133. state["classification_method"] = classification_result.method
  134. state["routing_mode"] = QUESTION_ROUTING_MODE
  135. state["current_step"] = "classified"
  136. state["execution_path"].append("classify")
  137. print(f"[CLASSIFY_NODE] 分类结果: {classification_result.question_type}, 置信度: {classification_result.confidence}")
  138. print(f"[CLASSIFY_NODE] 路由模式: {QUESTION_ROUTING_MODE}, 分类方法: {classification_result.method}")
  139. return state
  140. except Exception as e:
  141. print(f"[ERROR] 问题分类异常: {str(e)}")
  142. state["error"] = f"问题分类失败: {str(e)}"
  143. state["error_code"] = 500
  144. state["execution_path"].append("classify_error")
  145. return state
  146. def _agent_database_node(self, state: AgentState) -> AgentState:
  147. """数据库Agent节点 - 直接工具调用模式"""
  148. try:
  149. print(f"[DATABASE_AGENT] 开始处理数据库查询: {state['question']}")
  150. question = state["question"]
  151. # 步骤1:生成SQL
  152. print(f"[DATABASE_AGENT] 步骤1:生成SQL")
  153. sql_result = generate_sql.invoke({"question": question, "allow_llm_to_see_data": True})
  154. if not sql_result.get("success"):
  155. print(f"[DATABASE_AGENT] SQL生成失败: {sql_result.get('error')}")
  156. state["error"] = sql_result.get("error", "SQL生成失败")
  157. state["error_code"] = 500
  158. state["current_step"] = "database_error"
  159. state["execution_path"].append("agent_database_error")
  160. return state
  161. sql = sql_result.get("sql")
  162. state["sql"] = sql
  163. print(f"[DATABASE_AGENT] SQL生成成功: {sql}")
  164. # 步骤1.5:检查是否为解释性响应而非SQL
  165. error_type = sql_result.get("error_type")
  166. if error_type == "llm_explanation":
  167. # LLM返回了解释性文本,直接作为最终答案
  168. explanation = sql_result.get("error", "")
  169. state["chat_response"] = explanation + " 请尝试提问其它问题。"
  170. state["current_step"] = "database_completed"
  171. state["execution_path"].append("agent_database")
  172. print(f"[DATABASE_AGENT] 返回LLM解释性答案: {explanation}")
  173. return state
  174. # 额外验证:检查SQL格式(防止工具误判)
  175. from agent.utils import _is_valid_sql_format
  176. if not _is_valid_sql_format(sql):
  177. # 内容看起来不是SQL,当作解释性响应处理
  178. state["chat_response"] = sql + " 请尝试提问其它问题。"
  179. state["current_step"] = "database_completed"
  180. state["execution_path"].append("agent_database")
  181. print(f"[DATABASE_AGENT] 内容不是有效SQL,当作解释返回: {sql}")
  182. return state
  183. # 步骤2:执行SQL
  184. print(f"[DATABASE_AGENT] 步骤2:执行SQL")
  185. execute_result = execute_sql.invoke({"sql": sql})
  186. if not execute_result.get("success"):
  187. print(f"[DATABASE_AGENT] SQL执行失败: {execute_result.get('error')}")
  188. state["error"] = execute_result.get("error", "SQL执行失败")
  189. state["error_code"] = 500
  190. state["current_step"] = "database_error"
  191. state["execution_path"].append("agent_database_error")
  192. return state
  193. query_result = execute_result.get("data_result")
  194. state["query_result"] = query_result
  195. print(f"[DATABASE_AGENT] SQL执行成功,返回 {query_result.get('row_count', 0)} 行数据")
  196. # 步骤3:生成摘要(可通过配置控制,仅在有数据时生成)
  197. if ENABLE_RESULT_SUMMARY and query_result.get('row_count', 0) > 0:
  198. print(f"[DATABASE_AGENT] 步骤3:生成摘要")
  199. # 重要:提取原始问题用于摘要生成,避免历史记录循环嵌套
  200. original_question = self._extract_original_question(question)
  201. print(f"[DATABASE_AGENT] 原始问题: {original_question}")
  202. summary_result = generate_summary.invoke({
  203. "question": original_question, # 使用原始问题而不是enhanced_question
  204. "query_result": query_result,
  205. "sql": sql
  206. })
  207. if not summary_result.get("success"):
  208. print(f"[DATABASE_AGENT] 摘要生成失败: {summary_result.get('message')}")
  209. # 摘要生成失败不是致命错误,使用默认摘要
  210. state["summary"] = f"查询执行完成,共返回 {query_result.get('row_count', 0)} 条记录。"
  211. else:
  212. state["summary"] = summary_result.get("summary")
  213. print(f"[DATABASE_AGENT] 摘要生成成功")
  214. else:
  215. print(f"[DATABASE_AGENT] 跳过摘要生成(ENABLE_RESULT_SUMMARY={ENABLE_RESULT_SUMMARY},数据行数={query_result.get('row_count', 0)})")
  216. # 不生成摘要时,不设置summary字段,让格式化响应节点决定如何处理
  217. state["current_step"] = "database_completed"
  218. state["execution_path"].append("agent_database")
  219. print(f"[DATABASE_AGENT] 数据库查询完成")
  220. return state
  221. except Exception as e:
  222. print(f"[ERROR] 数据库Agent异常: {str(e)}")
  223. import traceback
  224. print(f"[ERROR] 详细错误信息: {traceback.format_exc()}")
  225. state["error"] = f"数据库查询失败: {str(e)}"
  226. state["error_code"] = 500
  227. state["current_step"] = "database_error"
  228. state["execution_path"].append("agent_database_error")
  229. return state
  230. def _agent_chat_node(self, state: AgentState) -> AgentState:
  231. """聊天Agent节点 - 直接工具调用模式"""
  232. try:
  233. print(f"[CHAT_AGENT] 开始处理聊天: {state['question']}")
  234. question = state["question"]
  235. # 构建上下文 - 仅使用真实的对话历史上下文
  236. # 注意:不要将分类原因传递给LLM,那是系统内部的路由信息
  237. enable_context_injection = self.config.get("chat_agent", {}).get("enable_context_injection", True)
  238. context = None
  239. if enable_context_injection:
  240. # TODO: 在这里可以添加真实的对话历史上下文
  241. # 例如从Redis或其他存储中获取最近的对话记录
  242. # context = get_conversation_history(state.get("session_id"))
  243. pass
  244. # 直接调用general_chat工具
  245. print(f"[CHAT_AGENT] 调用general_chat工具")
  246. chat_result = general_chat.invoke({
  247. "question": question,
  248. "context": context
  249. })
  250. if chat_result.get("success"):
  251. state["chat_response"] = chat_result.get("response", "")
  252. print(f"[CHAT_AGENT] 聊天处理成功")
  253. else:
  254. # 处理失败,使用备用响应
  255. state["chat_response"] = chat_result.get("response", "抱歉,我暂时无法处理您的问题。请稍后再试。")
  256. print(f"[CHAT_AGENT] 聊天处理失败,使用备用响应: {chat_result.get('error')}")
  257. state["current_step"] = "chat_completed"
  258. state["execution_path"].append("agent_chat")
  259. print(f"[CHAT_AGENT] 聊天处理完成")
  260. return state
  261. except Exception as e:
  262. print(f"[ERROR] 聊天Agent异常: {str(e)}")
  263. import traceback
  264. print(f"[ERROR] 详细错误信息: {traceback.format_exc()}")
  265. state["chat_response"] = "抱歉,我暂时无法处理您的问题。请稍后再试,或者尝试询问数据相关的问题。"
  266. state["current_step"] = "chat_error"
  267. state["execution_path"].append("agent_chat_error")
  268. return state
  269. def _format_response_node(self, state: AgentState) -> AgentState:
  270. """格式化最终响应节点"""
  271. try:
  272. print(f"[FORMAT_NODE] 开始格式化响应,问题类型: {state['question_type']}")
  273. state["current_step"] = "completed"
  274. state["execution_path"].append("format_response")
  275. # 根据问题类型和执行状态格式化响应
  276. if state.get("error"):
  277. # 有错误的情况
  278. state["final_response"] = {
  279. "success": False,
  280. "error": state["error"],
  281. "error_code": state.get("error_code", 500),
  282. "question_type": state["question_type"],
  283. "execution_path": state["execution_path"],
  284. "classification_info": {
  285. "confidence": state.get("classification_confidence", 0),
  286. "reason": state.get("classification_reason", ""),
  287. "method": state.get("classification_method", "")
  288. }
  289. }
  290. elif state["question_type"] == "DATABASE":
  291. # 数据库查询类型
  292. if state.get("chat_response"):
  293. # SQL生成失败的解释性响应(不受ENABLE_RESULT_SUMMARY配置影响)
  294. state["final_response"] = {
  295. "success": True,
  296. "response": state["chat_response"],
  297. "type": "DATABASE",
  298. "sql": state.get("sql"),
  299. "query_result": state.get("query_result"), # 获取query_result字段
  300. "execution_path": state["execution_path"],
  301. "classification_info": {
  302. "confidence": state["classification_confidence"],
  303. "reason": state["classification_reason"],
  304. "method": state["classification_method"]
  305. }
  306. }
  307. elif state.get("summary"):
  308. # 正常的数据库查询结果,有摘要的情况
  309. # 不将summary复制到response,让response保持为空
  310. state["final_response"] = {
  311. "success": True,
  312. "type": "DATABASE",
  313. "sql": state.get("sql"),
  314. "query_result": state.get("query_result"), # 获取query_result字段
  315. "summary": state["summary"],
  316. "execution_path": state["execution_path"],
  317. "classification_info": {
  318. "confidence": state["classification_confidence"],
  319. "reason": state["classification_reason"],
  320. "method": state["classification_method"]
  321. }
  322. }
  323. elif state.get("query_result"):
  324. # 有数据但没有摘要(摘要被配置禁用)
  325. query_result = state.get("query_result")
  326. row_count = query_result.get("row_count", 0)
  327. # 构建基本响应,不包含summary字段和response字段
  328. # 用户应该直接从query_result.columns和query_result.rows获取数据
  329. state["final_response"] = {
  330. "success": True,
  331. "type": "DATABASE",
  332. "sql": state.get("sql"),
  333. "query_result": query_result, # 获取query_result字段
  334. "execution_path": state["execution_path"],
  335. "classification_info": {
  336. "confidence": state["classification_confidence"],
  337. "reason": state["classification_reason"],
  338. "method": state["classification_method"]
  339. }
  340. }
  341. else:
  342. # 数据库查询失败,没有任何结果
  343. state["final_response"] = {
  344. "success": False,
  345. "error": state.get("error", "数据库查询未完成"),
  346. "type": "DATABASE",
  347. "sql": state.get("sql"),
  348. "execution_path": state["execution_path"]
  349. }
  350. else:
  351. # 聊天类型
  352. state["final_response"] = {
  353. "success": True,
  354. "response": state.get("chat_response", ""),
  355. "type": "CHAT",
  356. "execution_path": state["execution_path"],
  357. "classification_info": {
  358. "confidence": state["classification_confidence"],
  359. "reason": state["classification_reason"],
  360. "method": state["classification_method"]
  361. }
  362. }
  363. print(f"[FORMAT_NODE] 响应格式化完成")
  364. return state
  365. except Exception as e:
  366. print(f"[ERROR] 响应格式化异常: {str(e)}")
  367. state["final_response"] = {
  368. "success": False,
  369. "error": f"响应格式化异常: {str(e)}",
  370. "error_code": 500,
  371. "execution_path": state["execution_path"]
  372. }
  373. return state
  374. def _route_after_classification(self, state: AgentState) -> Literal["DATABASE", "CHAT"]:
  375. """
  376. 分类后的路由决策
  377. 完全信任QuestionClassifier的决策:
  378. - DATABASE类型 → 数据库Agent
  379. - CHAT和UNCERTAIN类型 → 聊天Agent
  380. 这样避免了双重决策的冲突,所有分类逻辑都集中在QuestionClassifier中
  381. """
  382. question_type = state["question_type"]
  383. confidence = state["classification_confidence"]
  384. print(f"[ROUTE] 分类路由: {question_type}, 置信度: {confidence} (完全信任分类器决策)")
  385. if question_type == "DATABASE":
  386. return "DATABASE"
  387. else:
  388. # 将 "CHAT" 和 "UNCERTAIN" 类型都路由到聊天流程
  389. # 聊天Agent可以处理不确定的情况,并在必要时引导用户提供更多信息
  390. return "CHAT"
  391. def process_question(self, question: str, session_id: str = None, context_type: str = None) -> Dict[str, Any]:
  392. """
  393. 统一的问题处理入口
  394. Args:
  395. question: 用户问题
  396. session_id: 会话ID
  397. context_type: 上下文类型 ("DATABASE" 或 "CHAT"),用于渐进式分类
  398. Returns:
  399. Dict包含完整的处理结果
  400. """
  401. try:
  402. print(f"[CITU_AGENT] 开始处理问题: {question}")
  403. if context_type:
  404. print(f"[CITU_AGENT] 上下文类型: {context_type}")
  405. # 初始化状态
  406. initial_state = self._create_initial_state(question, session_id, context_type)
  407. # 执行工作流
  408. final_state = self.workflow.invoke(
  409. initial_state,
  410. config={
  411. "configurable": {"session_id": session_id}
  412. } if session_id else None
  413. )
  414. # 提取最终结果
  415. result = final_state["final_response"]
  416. print(f"[CITU_AGENT] 问题处理完成: {result.get('success', False)}")
  417. return result
  418. except Exception as e:
  419. print(f"[ERROR] Agent执行异常: {str(e)}")
  420. return {
  421. "success": False,
  422. "error": f"Agent系统异常: {str(e)}",
  423. "error_code": 500,
  424. "execution_path": ["error"]
  425. }
  426. def _create_initial_state(self, question: str, session_id: str = None, context_type: str = None) -> AgentState:
  427. """创建初始状态 - 支持渐进式分类"""
  428. try:
  429. from app_config import QUESTION_ROUTING_MODE
  430. except ImportError:
  431. QUESTION_ROUTING_MODE = "hybrid"
  432. return AgentState(
  433. # 输入信息
  434. question=question,
  435. session_id=session_id,
  436. # 上下文信息
  437. context_type=context_type,
  438. # 分类结果 (初始值,会在分类节点或直接模式初始化节点中更新)
  439. question_type="UNCERTAIN",
  440. classification_confidence=0.0,
  441. classification_reason="",
  442. classification_method="",
  443. # 数据库查询流程状态
  444. sql=None,
  445. sql_generation_attempts=0,
  446. query_result=None,
  447. summary=None,
  448. # 聊天响应
  449. chat_response=None,
  450. # 最终输出
  451. final_response={},
  452. # 错误处理
  453. error=None,
  454. error_code=None,
  455. # 流程控制
  456. current_step="initialized",
  457. execution_path=["start"],
  458. retry_count=0,
  459. max_retries=3,
  460. # 调试信息
  461. debug_info={},
  462. # 路由模式
  463. routing_mode=QUESTION_ROUTING_MODE
  464. )
  465. def _extract_original_question(self, question: str) -> str:
  466. """
  467. 从enhanced_question中提取原始问题
  468. Args:
  469. question: 可能包含上下文的问题
  470. Returns:
  471. str: 原始问题
  472. """
  473. try:
  474. # 检查是否为enhanced_question格式
  475. if "\n[CONTEXT]\n" in question and "\n[CURRENT]\n" in question:
  476. # 提取[CURRENT]标签后的内容
  477. current_start = question.find("\n[CURRENT]\n")
  478. if current_start != -1:
  479. original_question = question[current_start + len("\n[CURRENT]\n"):].strip()
  480. return original_question
  481. # 如果不是enhanced_question格式,直接返回原问题
  482. return question.strip()
  483. except Exception as e:
  484. print(f"[WARNING] 提取原始问题失败: {str(e)}")
  485. return question.strip()
  486. def health_check(self) -> Dict[str, Any]:
  487. """健康检查"""
  488. try:
  489. # 从配置获取健康检查参数
  490. from agent.config import get_nested_config
  491. test_question = get_nested_config(self.config, "health_check.test_question", "你好")
  492. enable_full_test = get_nested_config(self.config, "health_check.enable_full_test", True)
  493. if enable_full_test:
  494. # 完整流程测试
  495. test_result = self.process_question(test_question, "health_check")
  496. return {
  497. "status": "healthy" if test_result.get("success") else "degraded",
  498. "test_result": test_result.get("success", False),
  499. "workflow_compiled": self.workflow is not None,
  500. "tools_count": len(self.tools),
  501. "agent_reuse_enabled": False,
  502. "message": "Agent健康检查完成"
  503. }
  504. else:
  505. # 简单检查
  506. return {
  507. "status": "healthy",
  508. "test_result": True,
  509. "workflow_compiled": self.workflow is not None,
  510. "tools_count": len(self.tools),
  511. "agent_reuse_enabled": False,
  512. "message": "Agent简单健康检查完成"
  513. }
  514. except Exception as e:
  515. return {
  516. "status": "unhealthy",
  517. "error": str(e),
  518. "workflow_compiled": self.workflow is not None,
  519. "tools_count": len(self.tools) if hasattr(self, 'tools') else 0,
  520. "agent_reuse_enabled": False,
  521. "message": "Agent健康检查失败"
  522. }