agent.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. """
  2. 基于 StateGraph 的、具备上下文感知能力的 React Agent 核心实现
  3. """
  4. import logging
  5. import json
  6. import pandas as pd
  7. import httpx
  8. from typing import List, Optional, Dict, Any, Tuple
  9. from contextlib import AsyncExitStack
  10. from langchain_openai import ChatOpenAI
  11. from langchain_core.messages import HumanMessage, ToolMessage, BaseMessage, SystemMessage, AIMessage
  12. from langgraph.graph import StateGraph, END
  13. from langgraph.prebuilt import ToolNode
  14. import redis.asyncio as redis
  15. try:
  16. from langgraph.checkpoint.redis import AsyncRedisSaver
  17. except ImportError:
  18. AsyncRedisSaver = None
  19. # 从新模块导入配置、状态和工具
  20. try:
  21. # 尝试相对导入(当作为模块导入时)
  22. from . import config
  23. from .state import AgentState
  24. from .sql_tools import sql_tools
  25. except ImportError:
  26. # 如果相对导入失败,尝试绝对导入(直接运行时)
  27. import config
  28. from state import AgentState
  29. from sql_tools import sql_tools
  30. from langchain_core.runnables import RunnablePassthrough
  31. logger = logging.getLogger(__name__)
  32. class CustomReactAgent:
  33. """
  34. 一个使用 StateGraph 构建的、具备上下文感知和持久化能力的 Agent。
  35. """
  36. def __init__(self):
  37. """私有构造函数,请使用 create() 类方法来创建实例。"""
  38. self.llm = None
  39. self.tools = None
  40. self.agent_executor = None
  41. self.checkpointer = None
  42. self._exit_stack = None
  43. self.redis_client = None
  44. @classmethod
  45. async def create(cls):
  46. """异步工厂方法,创建并初始化 CustomReactAgent 实例。"""
  47. instance = cls()
  48. await instance._async_init()
  49. return instance
  50. async def _async_init(self):
  51. """异步初始化所有组件。"""
  52. logger.info("🚀 开始初始化 CustomReactAgent...")
  53. # 1. 初始化异步Redis客户端
  54. self.redis_client = redis.from_url(config.REDIS_URL, decode_responses=True)
  55. try:
  56. await self.redis_client.ping()
  57. logger.info(f" ✅ Redis连接成功: {config.REDIS_URL}")
  58. except Exception as e:
  59. logger.error(f" ❌ Redis连接失败: {e}")
  60. raise
  61. # 2. 初始化 LLM
  62. self.llm = ChatOpenAI(
  63. api_key=config.QWEN_API_KEY,
  64. base_url=config.QWEN_BASE_URL,
  65. model=config.QWEN_MODEL,
  66. temperature=0.1,
  67. timeout=config.NETWORK_TIMEOUT, # 添加超时配置
  68. max_retries=0, # 禁用OpenAI客户端重试,改用Agent层统一重试
  69. extra_body={
  70. "enable_thinking": False,
  71. "misc": {
  72. "ensure_ascii": False
  73. }
  74. },
  75. # 新增:优化HTTP连接配置
  76. http_client=httpx.Client(
  77. limits=httpx.Limits(
  78. max_connections=config.HTTP_MAX_CONNECTIONS,
  79. max_keepalive_connections=config.HTTP_MAX_KEEPALIVE_CONNECTIONS,
  80. keepalive_expiry=config.HTTP_KEEPALIVE_EXPIRY, # 30秒keep-alive过期
  81. ),
  82. timeout=httpx.Timeout(
  83. connect=config.HTTP_CONNECT_TIMEOUT, # 连接超时
  84. read=config.NETWORK_TIMEOUT, # 读取超时
  85. write=config.HTTP_CONNECT_TIMEOUT, # 写入超时
  86. pool=config.HTTP_POOL_TIMEOUT # 连接池超时
  87. )
  88. )
  89. )
  90. logger.info(f" LLM 已初始化,模型: {config.QWEN_MODEL}")
  91. # 3. 绑定工具
  92. self.tools = sql_tools
  93. self.llm_with_tools = self.llm.bind_tools(self.tools)
  94. logger.info(f" 已绑定 {len(self.tools)} 个工具。")
  95. # 4. 初始化 Redis Checkpointer
  96. if config.REDIS_ENABLED and AsyncRedisSaver is not None:
  97. try:
  98. self._exit_stack = AsyncExitStack()
  99. checkpointer_manager = AsyncRedisSaver.from_conn_string(config.REDIS_URL)
  100. self.checkpointer = await self._exit_stack.enter_async_context(checkpointer_manager)
  101. await self.checkpointer.asetup()
  102. logger.info(f" AsyncRedisSaver 持久化已启用: {config.REDIS_URL}")
  103. except Exception as e:
  104. logger.error(f" ❌ RedisSaver 初始化失败: {e}", exc_info=True)
  105. if self._exit_stack:
  106. await self._exit_stack.aclose()
  107. self.checkpointer = None
  108. else:
  109. logger.warning(" Redis 持久化功能已禁用。")
  110. # 5. 构建 StateGraph
  111. self.agent_executor = self._create_graph()
  112. logger.info(" StateGraph 已构建并编译。")
  113. logger.info("✅ CustomReactAgent 初始化完成。")
  114. async def close(self):
  115. """清理资源,关闭 Redis 连接。"""
  116. if self._exit_stack:
  117. await self._exit_stack.aclose()
  118. self._exit_stack = None
  119. self.checkpointer = None
  120. logger.info("✅ RedisSaver 资源已通过 AsyncExitStack 释放。")
  121. if self.redis_client:
  122. await self.redis_client.aclose()
  123. logger.info("✅ Redis客户端已关闭。")
  124. def _create_graph(self):
  125. """定义并编译最终的、正确的 StateGraph 结构。"""
  126. builder = StateGraph(AgentState)
  127. # 定义所有需要的节点 - 全部改为异步
  128. builder.add_node("agent", self._async_agent_node)
  129. builder.add_node("prepare_tool_input", self._async_prepare_tool_input_node)
  130. builder.add_node("tools", ToolNode(self.tools))
  131. builder.add_node("update_state_after_tool", self._async_update_state_after_tool_node)
  132. builder.add_node("format_final_response", self._async_format_final_response_node)
  133. # 建立正确的边连接
  134. builder.set_entry_point("agent")
  135. builder.add_conditional_edges(
  136. "agent",
  137. self._async_should_continue,
  138. {
  139. "continue": "prepare_tool_input",
  140. "end": "format_final_response"
  141. }
  142. )
  143. builder.add_edge("prepare_tool_input", "tools")
  144. builder.add_edge("tools", "update_state_after_tool")
  145. builder.add_edge("update_state_after_tool", "agent")
  146. builder.add_edge("format_final_response", END)
  147. return builder.compile(checkpointer=self.checkpointer)
  148. async def _async_should_continue(self, state: AgentState) -> str:
  149. """异步判断是继续调用工具还是结束。"""
  150. last_message = state["messages"][-1]
  151. if hasattr(last_message, "tool_calls") and last_message.tool_calls:
  152. return "continue"
  153. return "end"
  154. async def _async_agent_node(self, state: AgentState) -> Dict[str, Any]:
  155. """异步Agent 节点:使用异步LLM调用。"""
  156. logger.info(f"🧠 [Async Node] agent - Thread: {state['thread_id']}")
  157. messages_for_llm = list(state["messages"])
  158. # 🎯 添加数据库范围系统提示词(仅在对话开始时添加)
  159. if len(state["messages"]) == 1 and isinstance(state["messages"][0], HumanMessage):
  160. db_scope_prompt = self._get_database_scope_prompt()
  161. if db_scope_prompt:
  162. messages_for_llm.insert(0, SystemMessage(content=db_scope_prompt))
  163. logger.info(" ✅ 已添加数据库范围判断提示词")
  164. # 检查是否需要分析验证错误
  165. next_step = state.get("suggested_next_step")
  166. if next_step == "analyze_validation_error":
  167. # 查找最近的 valid_sql 错误信息
  168. for msg in reversed(state["messages"]):
  169. if isinstance(msg, ToolMessage) and msg.name == "valid_sql":
  170. error_guidance = self._generate_validation_error_guidance(msg.content)
  171. messages_for_llm.append(SystemMessage(content=error_guidance))
  172. logger.info(" ✅ 已添加SQL验证错误指导")
  173. break
  174. elif next_step and next_step != "analyze_validation_error":
  175. instruction = f"Suggestion: Consider using the '{next_step}' tool for the next step."
  176. messages_for_llm.append(SystemMessage(content=instruction))
  177. # 添加重试机制处理网络连接问题
  178. import asyncio
  179. max_retries = config.MAX_RETRIES
  180. for attempt in range(max_retries):
  181. try:
  182. # 使用异步调用
  183. response = await self.llm_with_tools.ainvoke(messages_for_llm)
  184. # 新增:详细的响应检查和日志
  185. logger.info(f" LLM原始响应内容: '{response.content}'")
  186. logger.info(f" 响应内容长度: {len(response.content) if response.content else 0}")
  187. logger.info(f" 响应内容类型: {type(response.content)}")
  188. logger.info(f" LLM是否有工具调用: {hasattr(response, 'tool_calls') and response.tool_calls}")
  189. if hasattr(response, 'tool_calls') and response.tool_calls:
  190. logger.info(f" 工具调用数量: {len(response.tool_calls)}")
  191. for i, tool_call in enumerate(response.tool_calls):
  192. logger.info(f" 工具调用[{i}]: {tool_call.get('name', 'Unknown')}")
  193. # 🎯 改进的响应检查和重试逻辑
  194. # 检查空响应情况 - 将空响应也视为需要重试的情况
  195. if not response.content and not (hasattr(response, 'tool_calls') and response.tool_calls):
  196. logger.warning(" ⚠️ LLM返回空响应且无工具调用")
  197. if attempt < max_retries - 1:
  198. # 空响应也进行重试
  199. wait_time = config.RETRY_BASE_DELAY * (2 ** attempt)
  200. logger.info(f" 🔄 空响应重试,{wait_time}秒后重试...")
  201. await asyncio.sleep(wait_time)
  202. continue
  203. else:
  204. # 所有重试都失败,返回降级回答
  205. logger.error(f" ❌ 多次尝试仍返回空响应,返回降级回答")
  206. fallback_content = "抱歉,我现在无法正确处理您的问题。请稍后重试或重新表述您的问题。"
  207. fallback_response = AIMessage(content=fallback_content)
  208. return {"messages": [fallback_response]}
  209. elif response.content and response.content.strip() == "":
  210. logger.warning(" ⚠️ LLM返回只包含空白字符的内容")
  211. if attempt < max_retries - 1:
  212. # 空白字符也进行重试
  213. wait_time = config.RETRY_BASE_DELAY * (2 ** attempt)
  214. logger.info(f" 🔄 空白字符重试,{wait_time}秒后重试...")
  215. await asyncio.sleep(wait_time)
  216. continue
  217. else:
  218. # 所有重试都失败,返回降级回答
  219. logger.error(f" ❌ 多次尝试仍返回空白字符,返回降级回答")
  220. fallback_content = "抱歉,我现在无法正确处理您的问题。请稍后重试或重新表述您的问题。"
  221. fallback_response = AIMessage(content=fallback_content)
  222. return {"messages": [fallback_response]}
  223. elif not response.content and hasattr(response, 'tool_calls') and response.tool_calls:
  224. logger.info(" ✅ LLM只返回工具调用,无文本内容(正常情况)")
  225. # 🎯 最终检查:确保响应是有效的
  226. if ((response.content and response.content.strip()) or
  227. (hasattr(response, 'tool_calls') and response.tool_calls)):
  228. logger.info(f" ✅ 异步LLM调用成功,返回有效响应")
  229. return {"messages": [response]}
  230. else:
  231. # 这种情况理论上不应该发生,但作为最后的保障
  232. logger.error(f" ❌ 意外的响应格式,进行重试")
  233. if attempt < max_retries - 1:
  234. wait_time = config.RETRY_BASE_DELAY * (2 ** attempt)
  235. logger.info(f" 🔄 意外响应格式重试,{wait_time}秒后重试...")
  236. await asyncio.sleep(wait_time)
  237. continue
  238. else:
  239. fallback_content = "抱歉,我现在无法正确处理您的问题。请稍后重试或重新表述您的问题。"
  240. fallback_response = AIMessage(content=fallback_content)
  241. return {"messages": [fallback_response]}
  242. except Exception as e:
  243. error_msg = str(e)
  244. error_type = type(e).__name__
  245. logger.warning(f" ⚠️ LLM调用失败 (尝试 {attempt + 1}/{max_retries}): {error_type}: {error_msg}")
  246. # 🎯 改进的错误分类逻辑:检查异常类型和错误消息
  247. is_network_error = False
  248. is_parameter_error = False
  249. # 1. 检查异常类型
  250. network_exception_types = [
  251. 'APIConnectionError', 'ConnectTimeout', 'ReadTimeout',
  252. 'TimeoutError', 'APITimeoutError', 'ConnectError',
  253. 'HTTPError', 'RequestException', 'ConnectionError'
  254. ]
  255. if error_type in network_exception_types:
  256. is_network_error = True
  257. logger.info(f" 📊 根据异常类型判断为网络错误: {error_type}")
  258. # 2. 检查BadRequestError中的参数错误
  259. if error_type == 'BadRequestError':
  260. # 检查是否是消息格式错误
  261. if any(keyword in error_msg.lower() for keyword in [
  262. 'must be followed by tool messages',
  263. 'invalid_parameter_error',
  264. 'assistant message with "tool_calls"',
  265. 'tool_call_id',
  266. 'message format'
  267. ]):
  268. is_parameter_error = True
  269. logger.info(f" 📊 根据错误消息判断为参数格式错误: {error_msg[:100]}...")
  270. # 3. 检查错误消息内容(不区分大小写)
  271. error_msg_lower = error_msg.lower()
  272. network_keywords = [
  273. 'connection error', 'connect error', 'timeout', 'timed out',
  274. 'network', 'connection refused', 'connection reset',
  275. 'remote host', '远程主机', '网络连接', '连接超时',
  276. 'request timed out', 'read timeout', 'connect timeout'
  277. ]
  278. for keyword in network_keywords:
  279. if keyword in error_msg_lower:
  280. is_network_error = True
  281. logger.info(f" 📊 根据错误消息判断为网络错误: '{keyword}' in '{error_msg}'")
  282. break
  283. # 处理可重试的错误
  284. if is_network_error or is_parameter_error:
  285. if attempt < max_retries - 1:
  286. # 渐进式重试间隔:3, 6, 12秒
  287. wait_time = config.RETRY_BASE_DELAY * (2 ** attempt)
  288. error_type_desc = "网络错误" if is_network_error else "参数格式错误"
  289. logger.info(f" 🔄 {error_type_desc},{wait_time}秒后重试...")
  290. # 🎯 对于参数错误,修复消息历史后重试
  291. if is_parameter_error:
  292. try:
  293. messages_for_llm = await self._handle_parameter_error_with_retry(
  294. messages_for_llm, error_msg, attempt
  295. )
  296. logger.info(f" 🔧 消息历史修复完成,继续重试...")
  297. except Exception as fix_error:
  298. logger.error(f" ❌ 消息历史修复失败: {fix_error}")
  299. # 修复失败,使用原始消息继续重试
  300. await asyncio.sleep(wait_time)
  301. continue
  302. else:
  303. # 所有重试都失败了,返回一个降级的回答
  304. error_type_desc = "网络连接" if is_network_error else "请求格式"
  305. logger.error(f" ❌ {error_type_desc}持续失败,返回降级回答")
  306. # 检查是否有SQL执行结果可以利用
  307. sql_data = await self._async_extract_latest_sql_data(state["messages"])
  308. if sql_data:
  309. fallback_content = f"抱歉,由于{error_type_desc}问题,无法生成完整的文字总结。不过查询已成功执行,结果如下:\n\n" + sql_data
  310. else:
  311. fallback_content = f"抱歉,由于{error_type_desc}问题,无法完成此次请求。请稍后重试或检查网络连接。"
  312. fallback_response = AIMessage(content=fallback_content)
  313. return {"messages": [fallback_response]}
  314. else:
  315. # 非网络错误,直接抛出
  316. logger.error(f" ❌ LLM调用出现非可重试错误: {error_type}: {error_msg}")
  317. raise e
  318. def _print_state_info(self, state: AgentState, node_name: str) -> None:
  319. """
  320. 打印 state 的全部信息,用于调试
  321. """
  322. logger.info(" ~" * 10 + " State Print Start" + " ~" * 10)
  323. logger.info(f"📋 [State Debug] {node_name} - 当前状态信息:")
  324. # 🎯 打印 state 中的所有字段
  325. logger.info(" State中的所有字段:")
  326. for key, value in state.items():
  327. if key == "messages":
  328. logger.info(f" {key}: {len(value)} 条消息")
  329. else:
  330. logger.info(f" {key}: {value}")
  331. # 原有的详细消息信息
  332. logger.info(f" 用户ID: {state.get('user_id', 'N/A')}")
  333. logger.info(f" 线程ID: {state.get('thread_id', 'N/A')}")
  334. logger.info(f" 建议下一步: {state.get('suggested_next_step', 'N/A')}")
  335. messages = state.get("messages", [])
  336. logger.info(f" 消息历史数量: {len(messages)}")
  337. if messages:
  338. logger.info(" 最近的消息:")
  339. for i, msg in enumerate(messages[-10:], start=max(0, len(messages)-10)): # 显示最后10条消息
  340. msg_type = type(msg).__name__
  341. content = str(msg.content)
  342. # 对于长内容,使用多行显示
  343. if len(content) > 200:
  344. logger.info(f" [{i}] {msg_type}:")
  345. logger.info(f" {content}")
  346. else:
  347. logger.info(f" [{i}] {msg_type}: {content}")
  348. # 如果是 AIMessage 且有工具调用,显示工具调用信息
  349. if hasattr(msg, 'tool_calls') and msg.tool_calls:
  350. for tool_call in msg.tool_calls:
  351. tool_name = tool_call.get('name', 'Unknown')
  352. tool_args = tool_call.get('args', {})
  353. logger.info(f" 工具调用: {tool_name}")
  354. # 对于复杂参数,使用JSON格式化
  355. import json
  356. try:
  357. formatted_args = json.dumps(tool_args, ensure_ascii=False, indent=2)
  358. logger.info(f" 参数:")
  359. for line in formatted_args.split('\n'):
  360. logger.info(f" {line}")
  361. except Exception:
  362. logger.info(f" 参数: {str(tool_args)}")
  363. logger.info(" ~" * 10 + " State Print End" + " ~" * 10)
  364. async def _async_prepare_tool_input_node(self, state: AgentState) -> Dict[str, Any]:
  365. """
  366. 异步信息组装节点:为需要上下文的工具注入历史消息。
  367. """
  368. logger.info(f"🛠️ [Async Node] prepare_tool_input - Thread: {state['thread_id']}")
  369. # 🎯 打印 state 全部信息
  370. # self._print_state_info(state, "prepare_tool_input")
  371. last_message = state["messages"][-1]
  372. if not hasattr(last_message, "tool_calls") or not last_message.tool_calls:
  373. return {"messages": [last_message]}
  374. # 创建一个新的 AIMessage 来替换,避免直接修改 state 中的对象
  375. new_tool_calls = []
  376. for tool_call in last_message.tool_calls:
  377. if tool_call["name"] == "generate_sql":
  378. logger.info(" 检测到 generate_sql 调用,注入历史消息。")
  379. # 复制一份以避免修改原始 tool_call
  380. modified_args = tool_call["args"].copy()
  381. # 🎯 改进的消息过滤逻辑:只保留有用的对话上下文,排除当前问题
  382. clean_history = []
  383. messages_except_current = state["messages"][:-1] # 排除最后一个消息(当前问题)
  384. for msg in messages_except_current:
  385. if isinstance(msg, HumanMessage):
  386. # 保留历史用户消息(但不包括当前问题)
  387. clean_history.append({
  388. "type": "human",
  389. "content": msg.content
  390. })
  391. elif isinstance(msg, AIMessage):
  392. # 只保留最终的、面向用户的回答(包含"[Formatted Output]"的消息)
  393. if msg.content and "[Formatted Output]" in msg.content:
  394. # 去掉 "[Formatted Output]" 标记,只保留真正的回答
  395. clean_content = msg.content.replace("[Formatted Output]\n", "")
  396. clean_history.append({
  397. "type": "ai",
  398. "content": clean_content
  399. })
  400. # 跳过包含工具调用的 AIMessage(中间步骤)
  401. # 跳过所有 ToolMessage(工具执行结果)
  402. modified_args["history_messages"] = clean_history
  403. logger.info(f" 注入了 {len(clean_history)} 条过滤后的历史消息")
  404. new_tool_calls.append({
  405. "name": tool_call["name"],
  406. "args": modified_args,
  407. "id": tool_call["id"],
  408. })
  409. else:
  410. new_tool_calls.append(tool_call)
  411. # 用包含修改后参数的新消息替换掉原来的
  412. last_message.tool_calls = new_tool_calls
  413. return {"messages": [last_message]}
  414. async def _async_update_state_after_tool_node(self, state: AgentState) -> Dict[str, Any]:
  415. """在工具执行后,更新 suggested_next_step 并清理参数。"""
  416. logger.info(f"📝 [Node] update_state_after_tool - Thread: {state['thread_id']}")
  417. # 🎯 打印 state 全部信息
  418. self._print_state_info(state, "update_state_after_tool")
  419. last_tool_message = state['messages'][-1]
  420. tool_name = last_tool_message.name
  421. tool_output = last_tool_message.content
  422. next_step = None
  423. if tool_name == 'generate_sql':
  424. if "失败" in tool_output or "无法生成" in tool_output:
  425. next_step = 'answer_with_common_sense'
  426. else:
  427. next_step = 'valid_sql'
  428. # 🎯 清理 generate_sql 的 history_messages 参数,设置为空字符串
  429. # self._clear_history_messages_parameter(state['messages'])
  430. elif tool_name == 'valid_sql':
  431. if "失败" in tool_output:
  432. next_step = 'analyze_validation_error'
  433. else:
  434. next_step = 'run_sql'
  435. elif tool_name == 'run_sql':
  436. next_step = 'summarize_final_answer'
  437. logger.info(f" Tool '{tool_name}' executed. Suggested next step: {next_step}")
  438. return {"suggested_next_step": next_step}
  439. def _clear_history_messages_parameter(self, messages: List[BaseMessage]) -> None:
  440. """
  441. 将 generate_sql 工具的 history_messages 参数设置为空字符串
  442. """
  443. for message in messages:
  444. if hasattr(message, "tool_calls") and message.tool_calls:
  445. for tool_call in message.tool_calls:
  446. if tool_call["name"] == "generate_sql" and "history_messages" in tool_call["args"]:
  447. tool_call["args"]["history_messages"] = ""
  448. logger.info(f" 已将 generate_sql 的 history_messages 设置为空字符串")
  449. async def _async_format_final_response_node(self, state: AgentState) -> Dict[str, Any]:
  450. """异步最终输出格式化节点。"""
  451. logger.info(f"🎨 [Async Node] format_final_response - Thread: {state['thread_id']}")
  452. # 保持原有的消息格式化(用于shell.py兼容)
  453. last_message = state['messages'][-1]
  454. last_message.content = f"[Formatted Output]\n{last_message.content}"
  455. # 生成API格式的数据
  456. api_data = await self._async_generate_api_data(state)
  457. # 打印api_data
  458. print("-"*20+"api_data_start"+"-"*20)
  459. print(api_data)
  460. print("-"*20+"api_data_end"+"-"*20)
  461. return {
  462. "messages": [last_message],
  463. "api_data": api_data # 新增:API格式数据
  464. }
  465. async def _async_generate_api_data(self, state: AgentState) -> Dict[str, Any]:
  466. """异步生成API格式的数据结构"""
  467. logger.info("📊 异步生成API格式数据...")
  468. # 提取基础响应内容
  469. last_message = state['messages'][-1]
  470. response_content = last_message.content
  471. # 去掉格式化标记,获取纯净的回答
  472. if response_content.startswith("[Formatted Output]\n"):
  473. response_content = response_content.replace("[Formatted Output]\n", "")
  474. # 初始化API数据结构
  475. api_data = {
  476. "response": response_content
  477. }
  478. # 提取SQL和数据记录
  479. sql_info = await self._async_extract_sql_and_data(state['messages'])
  480. if sql_info['sql']:
  481. api_data["sql"] = sql_info['sql']
  482. if sql_info['records']:
  483. api_data["records"] = sql_info['records']
  484. # 生成Agent元数据
  485. api_data["react_agent_meta"] = await self._async_collect_agent_metadata(state)
  486. logger.info(f" API数据生成完成,包含字段: {list(api_data.keys())}")
  487. return api_data
  488. async def _async_extract_sql_and_data(self, messages: List[BaseMessage]) -> Dict[str, Any]:
  489. """异步从消息历史中提取SQL和数据记录"""
  490. result = {"sql": None, "records": None}
  491. # 查找最后一个HumanMessage之后的工具执行结果
  492. last_human_index = -1
  493. for i in range(len(messages) - 1, -1, -1):
  494. if isinstance(messages[i], HumanMessage):
  495. last_human_index = i
  496. break
  497. if last_human_index == -1:
  498. return result
  499. # 在当前对话轮次中查找工具执行结果
  500. current_conversation = messages[last_human_index:]
  501. sql_query = None
  502. sql_data = None
  503. for msg in current_conversation:
  504. if isinstance(msg, ToolMessage):
  505. if msg.name == 'generate_sql':
  506. # 提取生成的SQL
  507. content = msg.content
  508. if content and not any(keyword in content for keyword in ["失败", "无法生成", "Database query failed"]):
  509. sql_query = content.strip()
  510. elif msg.name == 'run_sql':
  511. # 提取SQL执行结果
  512. try:
  513. import json
  514. parsed_data = json.loads(msg.content)
  515. if isinstance(parsed_data, list) and len(parsed_data) > 0:
  516. # DataFrame.to_json(orient='records') 格式
  517. columns = list(parsed_data[0].keys()) if parsed_data else []
  518. sql_data = {
  519. "columns": columns,
  520. "rows": parsed_data,
  521. "total_row_count": len(parsed_data),
  522. "is_limited": False # 当前版本没有实现限制
  523. }
  524. except (json.JSONDecodeError, Exception) as e:
  525. logger.warning(f" 解析SQL结果失败: {e}")
  526. if sql_query:
  527. result["sql"] = sql_query
  528. if sql_data:
  529. result["records"] = sql_data
  530. return result
  531. async def _async_collect_agent_metadata(self, state: AgentState) -> Dict[str, Any]:
  532. """收集Agent元数据"""
  533. messages = state['messages']
  534. # 统计工具使用情况
  535. tools_used = []
  536. sql_execution_count = 0
  537. context_injected = False
  538. # 计算对话轮次(HumanMessage的数量)
  539. conversation_rounds = sum(1 for msg in messages if isinstance(msg, HumanMessage))
  540. # 分析工具调用和执行
  541. for msg in messages:
  542. if isinstance(msg, ToolMessage):
  543. if msg.name not in tools_used:
  544. tools_used.append(msg.name)
  545. if msg.name == 'run_sql':
  546. sql_execution_count += 1
  547. elif isinstance(msg, AIMessage) and hasattr(msg, 'tool_calls') and msg.tool_calls:
  548. for tool_call in msg.tool_calls:
  549. tool_name = tool_call.get('name')
  550. if tool_name and tool_name not in tools_used:
  551. tools_used.append(tool_name)
  552. # 检查是否注入了历史上下文
  553. if (tool_name == 'generate_sql' and
  554. tool_call.get('args', {}).get('history_messages')):
  555. context_injected = True
  556. # 构建执行路径(简化版本)
  557. execution_path = ["agent"]
  558. if tools_used:
  559. execution_path.extend(["prepare_tool_input", "tools"])
  560. execution_path.append("format_final_response")
  561. return {
  562. "thread_id": state['thread_id'],
  563. "conversation_rounds": conversation_rounds,
  564. "tools_used": tools_used,
  565. "execution_path": execution_path,
  566. "total_messages": len(messages),
  567. "sql_execution_count": sql_execution_count,
  568. "context_injected": context_injected,
  569. "agent_version": "custom_react_v1"
  570. }
  571. async def _async_extract_latest_sql_data(self, messages: List[BaseMessage]) -> Optional[str]:
  572. """从消息历史中提取最近的run_sql执行结果,但仅限于当前对话轮次。"""
  573. logger.info("🔍 提取最新的SQL执行结果...")
  574. # 🎯 只查找最后一个HumanMessage之后的SQL执行结果
  575. last_human_index = -1
  576. for i in range(len(messages) - 1, -1, -1):
  577. if isinstance(messages[i], HumanMessage):
  578. last_human_index = i
  579. break
  580. if last_human_index == -1:
  581. logger.info(" 未找到用户消息,跳过SQL数据提取")
  582. return None
  583. # 只在当前对话轮次中查找SQL结果
  584. current_conversation = messages[last_human_index:]
  585. logger.info(f" 当前对话轮次包含 {len(current_conversation)} 条消息")
  586. for msg in reversed(current_conversation):
  587. if isinstance(msg, ToolMessage) and msg.name == 'run_sql':
  588. logger.info(f" 找到当前对话轮次的run_sql结果: {msg.content[:100]}...")
  589. # 🎯 处理Unicode转义序列,将其转换为正常的中文字符
  590. try:
  591. # 先尝试解析JSON以验证格式
  592. parsed_data = json.loads(msg.content)
  593. # 重新序列化,确保中文字符正常显示
  594. formatted_content = json.dumps(parsed_data, ensure_ascii=False, separators=(',', ':'))
  595. logger.info(f" 已转换Unicode转义序列为中文字符")
  596. return formatted_content
  597. except json.JSONDecodeError:
  598. # 如果不是有效JSON,直接返回原内容
  599. logger.warning(f" SQL结果不是有效JSON格式,返回原始内容")
  600. return msg.content
  601. logger.info(" 当前对话轮次中未找到run_sql执行结果")
  602. return None
  603. async def chat(self, message: str, user_id: str, thread_id: Optional[str] = None) -> Dict[str, Any]:
  604. """
  605. 处理用户聊天请求。
  606. """
  607. if not thread_id:
  608. now = pd.Timestamp.now()
  609. milliseconds = int(now.microsecond / 1000)
  610. thread_id = f"{user_id}:{now.strftime('%Y%m%d%H%M%S')}{milliseconds:03d}"
  611. logger.info(f"🆕 新建会话,Thread ID: {thread_id}")
  612. config = {
  613. "configurable": {
  614. "thread_id": thread_id,
  615. }
  616. }
  617. inputs = {
  618. "messages": [HumanMessage(content=message)],
  619. "user_id": user_id,
  620. "thread_id": thread_id,
  621. "suggested_next_step": None,
  622. }
  623. try:
  624. logger.info(f"🚀 开始处理用户消息: {message[:50]}...")
  625. final_state = await self.agent_executor.ainvoke(inputs, config)
  626. # 🔍 调试:打印 final_state 的所有 keys
  627. logger.info(f"🔍 Final state keys: {list(final_state.keys())}")
  628. answer = final_state["messages"][-1].content
  629. # 🎯 提取最近的 run_sql 执行结果(不修改messages)
  630. sql_data = await self._async_extract_latest_sql_data(final_state["messages"])
  631. logger.info(f"✅ 处理完成 - Final Answer: '{answer}'")
  632. # 构建返回结果(保持简化格式用于shell.py)
  633. result = {
  634. "success": True,
  635. "answer": answer,
  636. "thread_id": thread_id
  637. }
  638. # 只有当存在SQL数据时才添加到返回结果中
  639. if sql_data:
  640. result["sql_data"] = sql_data
  641. logger.info(" 📊 已包含SQL原始数据")
  642. # 🔧 修复:检查 api_data 是否在 final_state 中
  643. if "api_data" in final_state:
  644. result["api_data"] = final_state["api_data"]
  645. logger.info(" 🔌 已包含API格式数据")
  646. else:
  647. # 🔧 备用方案:如果 final_state 中没有 api_data,手动生成
  648. logger.warning(" ⚠️ final_state 中未找到 api_data,手动生成...")
  649. api_data = await self._async_generate_api_data(final_state)
  650. result["api_data"] = api_data
  651. logger.info(" 🔌 已手动生成API格式数据")
  652. return result
  653. except Exception as e:
  654. logger.error(f"❌ 处理过程中发生严重错误 - Thread: {thread_id}: {e}", exc_info=True)
  655. return {"success": False, "error": str(e), "thread_id": thread_id}
  656. async def get_conversation_history(self, thread_id: str) -> List[Dict[str, Any]]:
  657. """从 checkpointer 获取指定线程的对话历史。"""
  658. if not self.checkpointer:
  659. return []
  660. config = {"configurable": {"thread_id": thread_id}}
  661. try:
  662. conversation_state = await self.checkpointer.aget(config)
  663. except RuntimeError as e:
  664. if "Event loop is closed" in str(e):
  665. logger.warning(f"⚠️ Event loop已关闭,尝试重新获取对话历史: {thread_id}")
  666. # 如果事件循环关闭,返回空结果而不是抛出异常
  667. return []
  668. else:
  669. raise
  670. if not conversation_state:
  671. return []
  672. history = []
  673. messages = conversation_state.get('channel_values', {}).get('messages', [])
  674. for msg in messages:
  675. if isinstance(msg, HumanMessage):
  676. role = "human"
  677. elif isinstance(msg, ToolMessage):
  678. role = "tool"
  679. else: # AIMessage
  680. role = "ai"
  681. history.append({
  682. "type": role,
  683. "content": msg.content,
  684. "tool_calls": getattr(msg, 'tool_calls', None)
  685. })
  686. return history
  687. async def get_user_recent_conversations(self, user_id: str, limit: int = 10) -> List[Dict[str, Any]]:
  688. """
  689. 获取指定用户的最近聊天记录列表
  690. 利用thread_id格式 'user_id:timestamp' 来查询
  691. """
  692. if not self.checkpointer:
  693. return []
  694. try:
  695. # 使用统一的异步Redis客户端
  696. redis_client = self.redis_client
  697. # 1. 扫描匹配该用户的所有checkpoint keys
  698. # checkpointer的key格式通常是: checkpoint:thread_id:checkpoint_id
  699. pattern = f"checkpoint:{user_id}:*"
  700. logger.info(f"🔍 扫描模式: {pattern}")
  701. user_threads = {}
  702. cursor = 0
  703. while True:
  704. cursor, keys = await redis_client.scan(
  705. cursor=cursor,
  706. match=pattern,
  707. count=1000
  708. )
  709. for key in keys:
  710. try:
  711. # 解析key获取thread_id和checkpoint信息
  712. # key格式: checkpoint:user_id:timestamp:status:checkpoint_id
  713. key_str = key.decode() if isinstance(key, bytes) else key
  714. parts = key_str.split(':')
  715. if len(parts) >= 4:
  716. # thread_id = user_id:timestamp
  717. thread_id = f"{parts[1]}:{parts[2]}"
  718. timestamp = parts[2]
  719. # 跟踪每个thread的最新checkpoint
  720. if thread_id not in user_threads:
  721. user_threads[thread_id] = {
  722. "thread_id": thread_id,
  723. "timestamp": timestamp,
  724. "latest_key": key_str
  725. }
  726. else:
  727. # 保留最新的checkpoint key(通常checkpoint_id越大越新)
  728. if len(parts) > 4 and parts[4] > user_threads[thread_id]["latest_key"].split(':')[4]:
  729. user_threads[thread_id]["latest_key"] = key_str
  730. except Exception as e:
  731. logger.warning(f"解析key {key} 失败: {e}")
  732. continue
  733. if cursor == 0:
  734. break
  735. # 关闭临时Redis连接
  736. await redis_client.close()
  737. # 2. 按时间戳排序(新的在前)
  738. sorted_threads = sorted(
  739. user_threads.values(),
  740. key=lambda x: x["timestamp"],
  741. reverse=True
  742. )[:limit]
  743. # 3. 获取每个thread的详细信息
  744. conversations = []
  745. for thread_info in sorted_threads:
  746. try:
  747. thread_id = thread_info["thread_id"]
  748. thread_config = {"configurable": {"thread_id": thread_id}}
  749. try:
  750. state = await self.checkpointer.aget(thread_config)
  751. except RuntimeError as e:
  752. if "Event loop is closed" in str(e):
  753. logger.warning(f"⚠️ Event loop已关闭,跳过thread: {thread_id}")
  754. continue
  755. else:
  756. raise
  757. if state and state.get('channel_values', {}).get('messages'):
  758. messages = state['channel_values']['messages']
  759. # 生成对话预览
  760. preview = self._generate_conversation_preview(messages)
  761. conversations.append({
  762. "thread_id": thread_id,
  763. "user_id": user_id,
  764. "timestamp": thread_info["timestamp"],
  765. "message_count": len(messages),
  766. "last_message": messages[-1].content if messages else None,
  767. "last_updated": state.get('created_at'),
  768. "conversation_preview": preview,
  769. "formatted_time": self._format_timestamp(thread_info["timestamp"])
  770. })
  771. except Exception as e:
  772. logger.error(f"获取thread {thread_info['thread_id']} 详情失败: {e}")
  773. continue
  774. logger.info(f"✅ 找到用户 {user_id} 的 {len(conversations)} 个对话")
  775. return conversations
  776. except Exception as e:
  777. logger.error(f"❌ 获取用户 {user_id} 对话列表失败: {e}")
  778. return []
  779. def _generate_conversation_preview(self, messages: List[BaseMessage]) -> str:
  780. """生成对话预览"""
  781. if not messages:
  782. return "空对话"
  783. # 获取第一个用户消息作为预览
  784. for msg in messages:
  785. if isinstance(msg, HumanMessage):
  786. content = str(msg.content)
  787. return content[:50] + "..." if len(content) > 50 else content
  788. return "系统消息"
  789. def _format_timestamp(self, timestamp: str) -> str:
  790. """格式化时间戳为可读格式"""
  791. try:
  792. # timestamp格式: 20250710123137984
  793. if len(timestamp) >= 14:
  794. year = timestamp[:4]
  795. month = timestamp[4:6]
  796. day = timestamp[6:8]
  797. hour = timestamp[8:10]
  798. minute = timestamp[10:12]
  799. second = timestamp[12:14]
  800. return f"{year}-{month}-{day} {hour}:{minute}:{second}"
  801. except Exception:
  802. pass
  803. return timestamp
  804. def _get_database_scope_prompt(self) -> str:
  805. """Get database scope prompt for intelligent query decision making"""
  806. try:
  807. import os
  808. # Read agent/tools/db_query_decision_prompt.txt
  809. project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  810. db_scope_file = os.path.join(project_root, "agent", "tools", "db_query_decision_prompt.txt")
  811. with open(db_scope_file, 'r', encoding='utf-8') as f:
  812. db_scope_content = f.read().strip()
  813. prompt = f"""You are an intelligent database query assistant. When deciding whether to use database query tools, please follow these rules:
  814. === DATABASE BUSINESS SCOPE ===
  815. {db_scope_content}
  816. === DECISION RULES ===
  817. 1. If the question involves data within the above business scope (service areas, branches, revenue, traffic flow, etc.), use the generate_sql tool
  818. 2. If the question is about general knowledge (like "when do lychees ripen?", weather, historical events, etc.), answer directly based on your knowledge WITHOUT using database tools
  819. 3. When answering general knowledge questions, clearly indicate that this is based on general knowledge, not database data
  820. === FALLBACK STRATEGY ===
  821. When generate_sql returns an error message or when queries return no results:
  822. 1. First, check if the question is within the database scope described above
  823. 2. For questions clearly OUTSIDE the database scope (world events, general knowledge, etc.):
  824. - Provide the answer based on your knowledge immediately
  825. - CLEARLY indicate this is based on general knowledge, not database data
  826. - Use format: "Based on general knowledge (not database data): [answer]"
  827. 3. For questions within database scope but queries return no results:
  828. - If it's a reasonable question that might have a general answer, provide it
  829. - Still indicate the source: "Based on general knowledge (database had no results): [answer]"
  830. 4. For questions that definitely require specific database data:
  831. - Acknowledge the limitation and suggest the data may not be available
  832. - Do not attempt to guess or fabricate specific data
  833. Please intelligently choose whether to query the database based on the nature of the user's question."""
  834. return prompt
  835. except Exception as e:
  836. logger.warning(f"⚠️ Unable to read database scope description file: {e}")
  837. return ""
  838. def _generate_validation_error_guidance(self, validation_error: str) -> str:
  839. """根据验证错误类型生成具体的修复指导"""
  840. if "字段不存在" in validation_error or "column" in validation_error.lower():
  841. return """SQL验证失败:字段不存在错误。
  842. 处理建议:
  843. 1. 检查字段名是否拼写正确
  844. 2. 如果字段确实不存在,请告知用户缺少该字段,并基于常识提供答案
  845. 3. 不要尝试修复不存在的字段,直接给出基于常识的解释"""
  846. elif "表不存在" in validation_error or "table" in validation_error.lower():
  847. return """SQL验证失败:表不存在错误。
  848. 处理建议:
  849. 1. 检查表名是否拼写正确
  850. 2. 如果表确实不存在,请告知用户该数据不在数据库中
  851. 3. 基于问题性质,提供常识性的答案或建议用户确认数据源"""
  852. elif "语法错误" in validation_error or "syntax error" in validation_error.lower():
  853. return """SQL验证失败:语法错误。
  854. 处理建议:
  855. 1. 仔细检查SQL语法(括号、引号、关键词等)
  856. 2. 修复语法错误后,调用 valid_sql 工具重新验证
  857. 3. 常见问题:缺少逗号、括号不匹配、关键词拼写错误"""
  858. else:
  859. return f"""SQL验证失败:{validation_error}
  860. 处理建议:
  861. 1. 如果是语法问题,请修复后重新验证
  862. 2. 如果是字段/表不存在,请向用户说明并提供基于常识的答案
  863. 3. 避免猜测或编造数据库中不存在的信息"""
  864. # === 参数错误诊断和修复函数 ===
  865. def _diagnose_parameter_error(self, messages: List[BaseMessage], error_msg: str) -> Dict[str, Any]:
  866. """
  867. 诊断参数错误的详细原因
  868. """
  869. logger.error("🔍 开始诊断参数错误...")
  870. logger.error(f" 错误消息: {error_msg}")
  871. diagnosis = {
  872. "error_type": "parameter_error",
  873. "incomplete_tool_calls": [],
  874. "orphaned_tool_messages": [],
  875. "total_messages": len(messages),
  876. "recommended_action": None
  877. }
  878. # 分析消息历史
  879. logger.error("📋 消息历史分析:")
  880. for i, msg in enumerate(messages):
  881. msg_type = type(msg).__name__
  882. if isinstance(msg, AIMessage):
  883. has_tool_calls = hasattr(msg, 'tool_calls') and msg.tool_calls
  884. content_summary = f"'{msg.content[:50]}...'" if msg.content else "空内容"
  885. logger.error(f" [{i}] {msg_type}: {content_summary}")
  886. if has_tool_calls:
  887. logger.error(f" 工具调用: {len(msg.tool_calls)} 个")
  888. for j, tc in enumerate(msg.tool_calls):
  889. tool_name = tc.get('name', 'Unknown')
  890. tool_id = tc.get('id', 'Unknown')
  891. logger.error(f" [{j}] {tool_name} (ID: {tool_id})")
  892. # 查找对应的ToolMessage
  893. found_response = False
  894. for k in range(i + 1, len(messages)):
  895. if (isinstance(messages[k], ToolMessage) and
  896. messages[k].tool_call_id == tool_id):
  897. found_response = True
  898. break
  899. elif isinstance(messages[k], (HumanMessage, AIMessage)):
  900. # 遇到新的对话轮次,停止查找
  901. break
  902. if not found_response:
  903. diagnosis["incomplete_tool_calls"].append({
  904. "message_index": i,
  905. "tool_name": tool_name,
  906. "tool_id": tool_id,
  907. "ai_message_content": msg.content
  908. })
  909. logger.error(f" ❌ 未找到对应的ToolMessage!")
  910. else:
  911. logger.error(f" ✅ 找到对应的ToolMessage")
  912. elif isinstance(msg, ToolMessage):
  913. logger.error(f" [{i}] {msg_type}: {msg.name} (ID: {msg.tool_call_id})")
  914. # 检查是否有对应的AIMessage
  915. found_ai_message = False
  916. for k in range(i - 1, -1, -1):
  917. if (isinstance(messages[k], AIMessage) and
  918. hasattr(messages[k], 'tool_calls') and
  919. messages[k].tool_calls):
  920. if any(tc.get('id') == msg.tool_call_id for tc in messages[k].tool_calls):
  921. found_ai_message = True
  922. break
  923. elif isinstance(messages[k], HumanMessage):
  924. break
  925. if not found_ai_message:
  926. diagnosis["orphaned_tool_messages"].append({
  927. "message_index": i,
  928. "tool_name": msg.name,
  929. "tool_call_id": msg.tool_call_id
  930. })
  931. logger.error(f" ❌ 未找到对应的AIMessage!")
  932. elif isinstance(msg, HumanMessage):
  933. logger.error(f" [{i}] {msg_type}: '{msg.content[:50]}...'")
  934. # 生成修复建议
  935. if diagnosis["incomplete_tool_calls"]:
  936. logger.error(f"🔧 发现 {len(diagnosis['incomplete_tool_calls'])} 个不完整的工具调用")
  937. diagnosis["recommended_action"] = "fix_incomplete_tool_calls"
  938. elif diagnosis["orphaned_tool_messages"]:
  939. logger.error(f"🔧 发现 {len(diagnosis['orphaned_tool_messages'])} 个孤立的工具消息")
  940. diagnosis["recommended_action"] = "remove_orphaned_tool_messages"
  941. else:
  942. logger.error("🔧 未发现明显的消息格式问题")
  943. diagnosis["recommended_action"] = "unknown"
  944. return diagnosis
  945. def _fix_by_adding_missing_tool_messages(self, messages: List[BaseMessage], diagnosis: Dict) -> List[BaseMessage]:
  946. """
  947. 通过添加缺失的ToolMessage来修复消息历史
  948. """
  949. logger.info("🔧 策略1: 补充缺失的ToolMessage")
  950. fixed_messages = list(messages)
  951. for incomplete in diagnosis["incomplete_tool_calls"]:
  952. # 为缺失的工具调用添加错误响应
  953. error_tool_message = ToolMessage(
  954. content="工具调用已超时或失败,请重新尝试。",
  955. tool_call_id=incomplete["tool_id"],
  956. name=incomplete["tool_name"]
  957. )
  958. # 插入到合适的位置
  959. insert_index = incomplete["message_index"] + 1
  960. fixed_messages.insert(insert_index, error_tool_message)
  961. logger.info(f" ✅ 为工具调用 {incomplete['tool_name']}({incomplete['tool_id']}) 添加错误响应")
  962. return fixed_messages
  963. def _fix_by_removing_incomplete_tool_calls(self, messages: List[BaseMessage], diagnosis: Dict) -> List[BaseMessage]:
  964. """
  965. 通过删除不完整的工具调用来修复消息历史
  966. """
  967. logger.info("🔧 策略2: 删除不完整的工具调用")
  968. fixed_messages = []
  969. for i, msg in enumerate(messages):
  970. if isinstance(msg, AIMessage) and hasattr(msg, 'tool_calls') and msg.tool_calls:
  971. # 检查这个消息是否有不完整的工具调用
  972. has_incomplete = any(
  973. inc["message_index"] == i
  974. for inc in diagnosis["incomplete_tool_calls"]
  975. )
  976. if has_incomplete:
  977. # 如果有文本内容,保留文本内容但删除工具调用
  978. if msg.content and msg.content.strip():
  979. logger.info(f" 🔧 保留文本内容,删除工具调用: '{msg.content[:50]}...'")
  980. fixed_msg = AIMessage(content=msg.content)
  981. fixed_messages.append(fixed_msg)
  982. else:
  983. # 如果没有文本内容,创建一个说明性的消息
  984. logger.info(f" 🔧 创建说明性消息替换空的工具调用")
  985. fixed_msg = AIMessage(content="我需要重新分析这个问题。")
  986. fixed_messages.append(fixed_msg)
  987. else:
  988. fixed_messages.append(msg)
  989. else:
  990. fixed_messages.append(msg)
  991. return fixed_messages
  992. def _fix_by_rebuilding_history(self, messages: List[BaseMessage]) -> List[BaseMessage]:
  993. """
  994. 重建消息历史,只保留完整的对话轮次
  995. """
  996. logger.info("🔧 策略3: 重建消息历史")
  997. clean_messages = []
  998. current_conversation = []
  999. for msg in messages:
  1000. if isinstance(msg, HumanMessage):
  1001. # 新的对话轮次开始
  1002. if current_conversation:
  1003. # 检查上一轮对话是否完整
  1004. if self._is_conversation_complete(current_conversation):
  1005. clean_messages.extend(current_conversation)
  1006. logger.info(f" ✅ 保留完整的对话轮次 ({len(current_conversation)} 条消息)")
  1007. else:
  1008. logger.info(f" ❌ 跳过不完整的对话轮次 ({len(current_conversation)} 条消息)")
  1009. current_conversation = [msg]
  1010. else:
  1011. current_conversation.append(msg)
  1012. # 处理最后一轮对话
  1013. if current_conversation:
  1014. if self._is_conversation_complete(current_conversation):
  1015. clean_messages.extend(current_conversation)
  1016. else:
  1017. # 最后一轮对话不完整,只保留用户消息
  1018. clean_messages.extend([msg for msg in current_conversation if isinstance(msg, HumanMessage)])
  1019. logger.info(f" 📊 重建完成: {len(messages)} -> {len(clean_messages)} 条消息")
  1020. return clean_messages
  1021. def _is_conversation_complete(self, conversation: List[BaseMessage]) -> bool:
  1022. """
  1023. 检查对话轮次是否完整
  1024. """
  1025. for msg in conversation:
  1026. if (isinstance(msg, AIMessage) and
  1027. hasattr(msg, 'tool_calls') and
  1028. msg.tool_calls):
  1029. # 检查是否有对应的ToolMessage
  1030. tool_call_ids = [tc.get('id') for tc in msg.tool_calls]
  1031. found_responses = sum(
  1032. 1 for m in conversation
  1033. if isinstance(m, ToolMessage) and m.tool_call_id in tool_call_ids
  1034. )
  1035. if found_responses < len(tool_call_ids):
  1036. return False
  1037. return True
  1038. async def _handle_parameter_error_with_retry(self, messages: List[BaseMessage], error_msg: str, attempt: int) -> List[BaseMessage]:
  1039. """
  1040. 处理参数错误的完整流程
  1041. """
  1042. logger.error(f"🔧 处理参数错误 (重试 {attempt + 1}/3)")
  1043. # 1. 诊断问题
  1044. diagnosis = self._diagnose_parameter_error(messages, error_msg)
  1045. # 2. 根据重试次数选择修复策略
  1046. if attempt == 0:
  1047. # 第一次重试:补充缺失的ToolMessage
  1048. fixed_messages = self._fix_by_adding_missing_tool_messages(messages, diagnosis)
  1049. elif attempt == 1:
  1050. # 第二次重试:删除不完整的工具调用
  1051. fixed_messages = self._fix_by_removing_incomplete_tool_calls(messages, diagnosis)
  1052. else:
  1053. # 第三次重试:重建消息历史
  1054. fixed_messages = self._fix_by_rebuilding_history(messages)
  1055. logger.info(f"🔧 修复完成: {len(messages)} -> {len(fixed_messages)} 条消息")
  1056. return fixed_messages
  1057. def _generate_contextual_fallback(self, messages: List[BaseMessage], diagnosis: Dict) -> str:
  1058. """
  1059. 基于上下文生成合理的回答
  1060. """
  1061. # 分析用户的最新问题
  1062. last_human_message = None
  1063. for msg in reversed(messages):
  1064. if isinstance(msg, HumanMessage):
  1065. last_human_message = msg
  1066. break
  1067. if not last_human_message:
  1068. return "抱歉,我无法理解您的问题。"
  1069. # 分析是否是数据库相关问题
  1070. question = last_human_message.content.lower()
  1071. if any(keyword in question for keyword in ['查询', '数据', '服务区', '收入', '车流量']):
  1072. return f"抱歉,在处理您关于「{last_human_message.content}」的查询时遇到了技术问题。请稍后重试,或者重新描述您的问题。"
  1073. else:
  1074. return "抱歉,我现在无法正确处理您的问题。请稍后重试或重新表述您的问题。"