agent.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 使用 FastAPI + LangGraph 重构的 Agent 服务
  5. 提供强大的工作流管理和状态控制
  6. """
  7. import json
  8. import sys
  9. import os
  10. import time
  11. from typing import Any, Dict, List, Optional, TypedDict, Annotated
  12. from contextlib import asynccontextmanager
  13. import asyncio
  14. from utils.mysql_db import MysqlHelper
  15. # 保证可以导入本项目模块
  16. sys.path.append(os.path.dirname(os.path.abspath(__file__)))
  17. from fastapi import FastAPI, HTTPException, BackgroundTasks
  18. from fastapi.responses import JSONResponse
  19. from pydantic import BaseModel, Field
  20. import uvicorn
  21. from agents.clean_agent.agent import execute_agent_with_api
  22. from agents.expand_agent.agent import execute_expand_agent_with_api, _update_expansion_status
  23. # LangGraph 相关导入
  24. try:
  25. from langgraph.graph import StateGraph, END
  26. HAS_LANGGRAPH = True
  27. except ImportError:
  28. HAS_LANGGRAPH = False
  29. print("警告: LangGraph 未安装")
  30. from utils.logging_config import get_logger
  31. from tools.agent_tools import QueryDataTool, IdentifyTool, UpdateDataTool, StructureTool
  32. # 创建 logger
  33. logger = get_logger('Agent')
  34. # 状态定义
  35. class AgentState(TypedDict):
  36. request_id: str
  37. items: List[Dict[str, Any]]
  38. details: List[Dict[str, Any]]
  39. processed: int
  40. success: int
  41. error: Optional[str]
  42. status: str
  43. class ExpandRequest(BaseModel):
  44. requestId: str = Field(..., description="请求ID")
  45. query: str = Field(..., description="查询词")
  46. # 请求模型
  47. class TriggerRequest(BaseModel):
  48. requestId: str = Field(..., description="请求ID")
  49. # 响应模型
  50. class TriggerResponse(BaseModel):
  51. requestId: str
  52. processed: int
  53. success: int
  54. details: List[Dict[str, Any]]
  55. class ExtractRequest(BaseModel):
  56. requestId: str = Field(..., description="请求ID")
  57. query: str = Field(..., description="查询词")
  58. # 全局变量
  59. identify_tool = None
  60. def update_request_status(request_id: str, status: int):
  61. """
  62. 更新 knowledge_request 表中的 parsing_status
  63. Args:
  64. request_id: 请求ID
  65. status: 状态值 (1: 处理中, 2: 处理完成, 3: 处理失败)
  66. """
  67. try:
  68. from utils.mysql_db import MysqlHelper
  69. sql = "UPDATE knowledge_request SET parsing_status = %s WHERE request_id = %s"
  70. result = MysqlHelper.update_values(sql, (status, request_id))
  71. if result is not None:
  72. logger.info(f"更新请求状态成功: requestId={request_id}, status={status}")
  73. else:
  74. logger.error(f"更新请求状态失败: requestId={request_id}, status={status}")
  75. except Exception as e:
  76. logger.error(f"更新请求状态异常: requestId={request_id}, status={status}, error={e}")
  77. def _update_expansion_status(requestId: str, status: int):
  78. """更新扩展查询状态"""
  79. try:
  80. from utils.mysql_db import MysqlHelper
  81. sql = "UPDATE knowledge_request SET expansion_status = %s WHERE request_id = %s"
  82. MysqlHelper.update_values(sql, (status, requestId))
  83. logger.info(f"更新扩展查询状态成功: requestId={requestId}, status={status}")
  84. except Exception as e:
  85. logger.error(f"更新扩展查询状态失败: requestId={requestId}, status={status}, error={e}")
  86. @asynccontextmanager
  87. async def lifespan(app: FastAPI):
  88. """应用生命周期管理"""
  89. # 启动时执行
  90. logger.info("🚀 启动 Knowledge Agent 服务...")
  91. # 初始化全局工具
  92. global identify_tool
  93. identify_tool = IdentifyTool()
  94. # 启动后恢复中断的流程
  95. # 异步恢复中断流程,避免阻塞启动
  96. app.state.restore_task = asyncio.create_task(restore_interrupted_processes())
  97. yield
  98. # 关闭时执行
  99. logger.info("🛑 关闭 Knowledge Agent 服务...")
  100. # 优雅取消后台恢复任务
  101. restore_task = getattr(app.state, 'restore_task', None)
  102. if restore_task and not restore_task.done():
  103. restore_task.cancel()
  104. try:
  105. await restore_task
  106. except asyncio.CancelledError:
  107. logger.info("✅ 已取消后台恢复任务")
  108. async def restore_interrupted_processes():
  109. """
  110. 启动后恢复中断的流程
  111. 1. 找到knowledge_request表中parsing_status=1的request_id,去请求 /parse/async
  112. 2. 找到knowledge_request表中extraction_status=1的request_id和query,去请求 /extract
  113. 3. 找到knowledge_request表中expansion_status=1的request_id和query,去请求 /expand
  114. """
  115. try:
  116. logger.info("🔄 开始恢复中断的流程...")
  117. # 等待服务完全启动
  118. await asyncio.sleep(3)
  119. # 1. 恢复解析中断的流程
  120. await restore_parsing_processes()
  121. # 2. 恢复提取中断的流程
  122. await restore_extraction_processes()
  123. # 3. 恢复扩展中断的流程
  124. await restore_expansion_processes()
  125. logger.info("✅ 流程恢复完成")
  126. except Exception as e:
  127. logger.error(f"❌ 流程恢复失败: {e}")
  128. async def restore_parsing_processes():
  129. """恢复解析中断的流程"""
  130. try:
  131. from utils.mysql_db import MysqlHelper
  132. # 查询parsing_status=1的请求
  133. sql = "SELECT request_id FROM knowledge_request WHERE parsing_status = 1"
  134. rows = MysqlHelper.get_values(sql)
  135. if not rows:
  136. logger.info("📋 没有发现中断的解析流程")
  137. return
  138. logger.info(f"🔄 发现 {len(rows)} 个中断的解析流程,开始恢复...")
  139. for row in rows:
  140. request_id = row[0]
  141. try:
  142. # 调用 /parse/async 接口,带重试机制
  143. await call_parse_async_with_retry(request_id)
  144. logger.info(f"✅ 恢复解析流程成功: request_id={request_id}")
  145. except Exception as e:
  146. logger.error(f"❌ 恢复解析流程失败: request_id={request_id}, error={e}")
  147. except Exception as e:
  148. logger.error(f"❌ 恢复解析流程时发生错误: {e}")
  149. async def restore_extraction_processes():
  150. """恢复提取中断的流程"""
  151. try:
  152. from utils.mysql_db import MysqlHelper
  153. # 查询extraction_status=1的请求和query
  154. sql = "SELECT request_id, query FROM knowledge_request WHERE extraction_status = 1"
  155. rows = MysqlHelper.get_values(sql)
  156. if not rows:
  157. logger.info("📋 没有发现中断的提取流程")
  158. return
  159. logger.info(f"🔄 发现 {len(rows)} 个中断的提取流程,开始恢复...")
  160. for row in rows:
  161. request_id = row[0]
  162. query = row[1] if len(row) > 1 else ""
  163. try:
  164. # 直接调用提取函数,带重试机制(函数内部会处理状态更新)
  165. await call_extract_with_retry(request_id, query)
  166. logger.info(f"✅ 恢复提取流程成功: request_id={request_id}")
  167. except Exception as e:
  168. logger.error(f"❌ 恢复提取流程失败: request_id={request_id}, error={e}")
  169. except Exception as e:
  170. logger.error(f"❌ 恢复提取流程时发生错误: {e}")
  171. async def restore_expansion_processes():
  172. """恢复扩展中断的流程"""
  173. try:
  174. from utils.mysql_db import MysqlHelper
  175. # 查询expansion_status=1的请求和query
  176. sql = "SELECT request_id, query FROM knowledge_request WHERE expansion_status = 1"
  177. rows = MysqlHelper.get_values(sql)
  178. if not rows:
  179. logger.info("📋 没有发现中断的扩展流程")
  180. return
  181. logger.info(f"🔄 发现 {len(rows)} 个中断的扩展流程,开始恢复...")
  182. for row in rows:
  183. request_id = row[0]
  184. query = row[1] if len(row) > 1 else ""
  185. try:
  186. # 直接调用扩展函数,带重试机制(函数内部会处理状态更新)
  187. await call_expand_with_retry(request_id, query)
  188. logger.info(f"✅ 恢复扩展流程成功: request_id={request_id}")
  189. except Exception as e:
  190. logger.error(f"❌ 恢复扩展流程失败: request_id={request_id}, error={e}")
  191. except Exception as e:
  192. logger.error(f"❌ 恢复扩展流程时发生错误: {e}")
  193. async def call_parse_async_with_retry(request_id: str, max_retries: int = 3):
  194. """直接调用解析函数,带重试机制"""
  195. for attempt in range(max_retries):
  196. try:
  197. # 直接调用后台处理函数
  198. await process_request_background(request_id)
  199. logger.info(f"直接调用解析函数成功: request_id={request_id}")
  200. return
  201. except Exception as e:
  202. logger.warning(f"直接调用解析函数异常: request_id={request_id}, error={e}, attempt={attempt+1}")
  203. # 如果不是最后一次尝试,等待后重试
  204. if attempt < max_retries - 1:
  205. await asyncio.sleep(2 ** attempt) # 指数退避
  206. logger.error(f"直接调用解析函数最终失败: request_id={request_id}, 已重试{max_retries}次")
  207. async def call_extract_with_retry(request_id: str, query: str, max_retries: int = 3):
  208. """直接调用提取函数,带重试机制"""
  209. for attempt in range(max_retries):
  210. try:
  211. # 更新状态为处理中
  212. update_extract_status(request_id, 1)
  213. # 直接调用提取函数(同步函数,在线程池中执行)
  214. from agents.clean_agent.agent import execute_agent_with_api
  215. import concurrent.futures
  216. # 在线程池中执行同步函数
  217. loop = asyncio.get_event_loop()
  218. with concurrent.futures.ThreadPoolExecutor() as executor:
  219. result = await loop.run_in_executor(
  220. executor,
  221. execute_agent_with_api,
  222. json.dumps({"query_word": query, "request_id": request_id})
  223. )
  224. # 更新状态为处理完成
  225. update_extract_status(request_id, 2)
  226. logger.info(f"直接调用提取函数成功: request_id={request_id}, result={result}")
  227. return
  228. except Exception as e:
  229. logger.warning(f"直接调用提取函数异常: request_id={request_id}, error={e}, attempt={attempt+1}")
  230. # 更新状态为处理失败
  231. update_extract_status(request_id, 3)
  232. # 如果不是最后一次尝试,等待后重试
  233. if attempt < max_retries - 1:
  234. await asyncio.sleep(2 ** attempt) # 指数退避
  235. logger.error(f"直接调用提取函数最终失败: request_id={request_id}, 已重试{max_retries}次")
  236. async def call_expand_with_retry(request_id: str, query: str, max_retries: int = 3):
  237. """直接调用扩展函数,带重试机制"""
  238. for attempt in range(max_retries):
  239. try:
  240. # 直接调用扩展函数(同步函数,在线程池中执行)
  241. from agents.expand_agent.agent import execute_expand_agent_with_api
  242. import concurrent.futures
  243. # 在线程池中执行同步函数
  244. loop = asyncio.get_event_loop()
  245. with concurrent.futures.ThreadPoolExecutor() as executor:
  246. result = await loop.run_in_executor(
  247. executor,
  248. execute_expand_agent_with_api,
  249. request_id,
  250. query
  251. )
  252. logger.info(f"直接调用扩展函数成功: request_id={request_id}")
  253. return
  254. except Exception as e:
  255. logger.warning(f"直接调用扩展函数异常: request_id={request_id}, error={e}, attempt={attempt+1}")
  256. # 如果不是最后一次尝试,等待后重试
  257. if attempt < max_retries - 1:
  258. await asyncio.sleep(2 ** attempt) # 指数退避
  259. logger.error(f"直接调用扩展函数最终失败: request_id={request_id}, 已重试{max_retries}次")
  260. # 这些函数已被删除,因为我们现在直接调用相应的函数而不是通过HTTP请求
  261. # 创建 FastAPI 应用
  262. app = FastAPI(
  263. title="Knowledge Agent API",
  264. description="基于 LangGraph 的智能内容识别和结构化处理服务",
  265. version="2.0.0",
  266. lifespan=lifespan
  267. )
  268. # 并发控制:跟踪正在处理的 requestId,防止重复并发提交
  269. RUNNING_REQUESTS: set = set()
  270. RUNNING_LOCK = asyncio.Lock()
  271. # =========================
  272. # LangGraph 工作流定义
  273. # =========================
  274. def create_langgraph_workflow():
  275. """创建 LangGraph 工作流"""
  276. if not HAS_LANGGRAPH:
  277. return None
  278. # 工作流节点定义
  279. def fetch_data(state: AgentState) -> AgentState:
  280. """获取待处理数据"""
  281. try:
  282. request_id = state["request_id"]
  283. logger.info(f"开始获取数据: requestId={request_id}")
  284. # 更新状态为处理中
  285. update_request_status(request_id, 1)
  286. items = QueryDataTool.fetch_crawl_data_list(request_id)
  287. state["items"] = items
  288. state["processed"] = len(items)
  289. state["status"] = "data_fetched"
  290. logger.info(f"数据获取完成: requestId={request_id}, 数量={len(items)}")
  291. return state
  292. except Exception as e:
  293. logger.error(f"获取数据失败: {e}")
  294. state["error"] = str(e)
  295. state["status"] = "error"
  296. return state
  297. def process_items_batch(state: AgentState) -> AgentState:
  298. """批量处理所有数据项"""
  299. try:
  300. items = state["items"]
  301. if not items:
  302. state["status"] = "completed"
  303. return state
  304. success_count = 0
  305. details = []
  306. for idx, item in enumerate(items, start=1):
  307. try:
  308. crawl_data = item.get('crawl_data') or {}
  309. content_id = item.get('content_id') or ''
  310. task_id = item.get('task_id') or ''
  311. # 先在库中查询是否已经处理过
  312. check_sql = "SELECT id,status,indentify_data FROM knowledge_parsing_content WHERE request_id = %s AND content_id = %s"
  313. check_result = MysqlHelper.get_values(check_sql, (state["request_id"], content_id))
  314. result_status = 0
  315. result_id = 0
  316. result_indentify_data = {}
  317. if check_result:
  318. id, status, indentify_data = check_result[0]
  319. logger.info(f"查询到待结构化处理的条目,id: {id}, status: {status}, indentify_data: {indentify_data}")
  320. result_status = status
  321. result_id = id
  322. result_indentify_data = indentify_data
  323. if status == 5:
  324. success_count += 1
  325. continue
  326. # result_status == 0 表示为处理过,需要进行识别和结构化
  327. if result_status == 0 or result_status == 3:
  328. # Step 1: 识别
  329. identify_result = identify_tool.run(
  330. crawl_data if isinstance(crawl_data, dict) else {}
  331. )
  332. # Step 2: 结构化并入库
  333. affected = UpdateDataTool.store_indentify_result(
  334. state["request_id"],
  335. {
  336. "content_id": content_id,
  337. "task_id": task_id
  338. },
  339. identify_result
  340. )
  341. else:
  342. # result_indentify_data是JSON字符串,需要解析为对象
  343. identify_result = json.loads(result_indentify_data) if isinstance(result_indentify_data, str) else result_indentify_data
  344. affected = result_id
  345. # 使用StructureTool进行内容结构化处理
  346. structure_tool = StructureTool()
  347. structure_result = structure_tool.process_content_structure(identify_result)
  348. # 存储结构化解析结果
  349. parsing_affected = UpdateDataTool.store_parsing_result(
  350. state["request_id"],
  351. {
  352. "id": affected,
  353. "content_id": content_id,
  354. "task_id": task_id
  355. },
  356. structure_result
  357. )
  358. ok = affected is not None and affected > 0 and parsing_affected is not None and parsing_affected > 0
  359. if ok:
  360. success_count += 1
  361. else:
  362. success_count += 1
  363. logger.error(f"处理第 {idx} 项时出错: {identify_result.get('error') or structure_result.get('error')}")
  364. # 记录处理详情
  365. detail = {
  366. "index": idx,
  367. "dbInserted": ok,
  368. "identifyError": identify_result.get('error') or structure_result.get('error'),
  369. "status": 2 if ok else 3
  370. }
  371. details.append(detail)
  372. logger.info(f"处理进度: {idx}/{len(items)} - {'成功' if ok else '失败'}")
  373. except Exception as e:
  374. logger.error(f"处理第 {idx} 项时出错: {e}")
  375. detail = {
  376. "index": idx,
  377. "dbInserted": False,
  378. "identifyError": str(e),
  379. "status": 3
  380. }
  381. details.append(detail)
  382. state["success"] = success_count
  383. state["details"] = details
  384. state["status"] = "completed"
  385. return state
  386. except Exception as e:
  387. logger.error(f"批量处理失败: {e}")
  388. state["error"] = str(e)
  389. state["status"] = "error"
  390. return state
  391. def should_continue(state: AgentState) -> str:
  392. """判断是否继续处理"""
  393. if state.get("error"):
  394. # 处理失败,更新状态为3
  395. update_request_status(state["request_id"], 3)
  396. return "end"
  397. # 所有数据处理完毕,更新状态为2
  398. update_request_status(state["request_id"], 2)
  399. return "end"
  400. # 构建工作流图
  401. workflow = StateGraph(AgentState)
  402. # 添加节点
  403. workflow.add_node("fetch_data", fetch_data)
  404. workflow.add_node("process_items_batch", process_items_batch)
  405. # 设置入口点
  406. workflow.set_entry_point("fetch_data")
  407. # 添加边
  408. workflow.add_edge("fetch_data", "process_items_batch")
  409. workflow.add_edge("process_items_batch", END)
  410. # 编译工作流
  411. return workflow.compile()
  412. # 全局工作流实例
  413. WORKFLOW = create_langgraph_workflow() if HAS_LANGGRAPH else None
  414. # =========================
  415. # FastAPI 接口定义
  416. # =========================
  417. @app.get("/")
  418. async def root():
  419. """根路径,返回服务信息"""
  420. return {
  421. "service": "Knowledge Agent API",
  422. "version": "2.0.0",
  423. "status": "running",
  424. "langgraph_enabled": HAS_LANGGRAPH,
  425. "endpoints": {
  426. "parse": "/parse",
  427. "parse/async": "/parse/async",
  428. "health": "/health",
  429. "docs": "/docs"
  430. }
  431. }
  432. @app.get("/health")
  433. async def health_check():
  434. """健康检查接口"""
  435. return {
  436. "status": "healthy",
  437. "timestamp": time.time(),
  438. "langgraph_enabled": HAS_LANGGRAPH
  439. }
  440. @app.post("/parse", response_model=TriggerResponse)
  441. async def parse_processing(request: TriggerRequest, background_tasks: BackgroundTasks):
  442. """
  443. 解析内容处理
  444. - **requestId**: 请求ID,用于标识处理任务
  445. """
  446. try:
  447. logger.info(f"收到解析请求: requestId={request.requestId}")
  448. if WORKFLOW and HAS_LANGGRAPH:
  449. # 使用 LangGraph 工作流
  450. logger.info("使用 LangGraph 工作流处理")
  451. # 初始化状态
  452. initial_state = AgentState(
  453. request_id=request.requestId,
  454. items=[],
  455. details=[],
  456. processed=0,
  457. success=0,
  458. error=None,
  459. status="started"
  460. )
  461. # 执行工作流
  462. final_state = WORKFLOW.invoke(
  463. initial_state,
  464. config={
  465. "configurable": {"thread_id": f"thread_{request.requestId}"},
  466. "recursion_limit": 100 # 增加递归限制
  467. }
  468. )
  469. # 构建响应
  470. result = TriggerResponse(
  471. requestId=request.requestId,
  472. processed=final_state.get("processed", 0),
  473. success=final_state.get("success", 0),
  474. details=final_state.get("details", [])
  475. )
  476. return result
  477. except Exception as e:
  478. logger.error(f"处理请求失败: {e}")
  479. # 处理失败,更新状态为3
  480. update_request_status(request.requestId, 3)
  481. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
  482. @app.post("/parse/async", status_code=200)
  483. async def parse_processing_async(request: TriggerRequest, background_tasks: BackgroundTasks):
  484. """
  485. 异步解析内容处理(后台任务)
  486. - **requestId**: 请求ID,用于标识处理任务
  487. 行为:立即返回 200,并在后台继续处理任务。
  488. 若同一个 requestId 已有任务进行中,则立即返回失败(status=3)。
  489. """
  490. try:
  491. logger.info(f"收到异步解析请求: requestId={request.requestId}")
  492. # 并发防抖:同一 requestId 只允许一个在运行
  493. async with RUNNING_LOCK:
  494. if request.requestId in RUNNING_REQUESTS:
  495. return {
  496. "requestId": request.requestId,
  497. "status": 3,
  498. "message": "已有任务进行中,稍后再试",
  499. "langgraph_enabled": HAS_LANGGRAPH
  500. }
  501. RUNNING_REQUESTS.add(request.requestId)
  502. async def _background_wrapper(rid: str):
  503. try:
  504. await process_request_background(rid)
  505. finally:
  506. async with RUNNING_LOCK:
  507. RUNNING_REQUESTS.discard(rid)
  508. # 直接使用 asyncio 创建后台任务(不阻塞当前请求返回)
  509. asyncio.create_task(_background_wrapper(request.requestId))
  510. # 立即返回(不阻塞)
  511. return {
  512. "requestId": request.requestId,
  513. "status": 1,
  514. "message": "任务已进入队列并在后台处理",
  515. "langgraph_enabled": HAS_LANGGRAPH
  516. }
  517. except Exception as e:
  518. logger.error(f"提交异步任务失败: {e}")
  519. raise HTTPException(status_code=500, detail=f"提交任务失败: {str(e)}")
  520. async def process_request_background(request_id: str):
  521. """后台处理请求"""
  522. try:
  523. logger.info(f"开始后台处理: requestId={request_id}")
  524. if WORKFLOW and HAS_LANGGRAPH:
  525. # 使用 LangGraph 工作流
  526. # 更新状态为处理中
  527. update_request_status(request_id, 1)
  528. initial_state = AgentState(
  529. request_id=request_id,
  530. items=[],
  531. details=[],
  532. processed=0,
  533. success=0,
  534. error=None,
  535. status="started"
  536. )
  537. final_state = WORKFLOW.invoke(
  538. initial_state,
  539. config={
  540. "configurable": {"thread_id": f"thread_{request_id}"},
  541. "recursion_limit": 100 # 增加递归限制
  542. }
  543. )
  544. # 所有数据处理完毕,更新状态为2
  545. update_request_status(request_id, 2)
  546. logger.info(f"LangGraph 后台处理完成: requestId={request_id}, processed={final_state.get('processed', 0)}, success={final_state.get('success', 0)}")
  547. except Exception as e:
  548. logger.error(f"后台处理失败: requestId={request_id}, error={e}")
  549. # 处理失败,更新状态为3
  550. update_request_status(request_id, 3)
  551. extraction_requests: set = set()
  552. @app.post("/extract")
  553. async def extract(request: ExtractRequest):
  554. """
  555. 执行提取处理(异步方式)
  556. Args:
  557. request: 包含请求ID和查询词的请求体
  558. Returns:
  559. dict: 包含执行状态的字典
  560. """
  561. try:
  562. requestId = request.requestId
  563. query = request.query
  564. logger.info(f"收到提取请求: requestId={requestId}, query={query}")
  565. # 并发防抖:同一 requestId 只允许一个在运行
  566. if requestId in extraction_requests:
  567. return {"status": 1, "requestId": requestId, "message": "请求已在处理中"}
  568. extraction_requests.add(requestId)
  569. # 更新状态为处理中
  570. update_extract_status(requestId, 1)
  571. # 创建异步任务执行Agent
  572. async def _execute_extract_async():
  573. try:
  574. # 在线程池中执行同步函数
  575. import concurrent.futures
  576. loop = asyncio.get_event_loop()
  577. with concurrent.futures.ThreadPoolExecutor() as executor:
  578. result = await loop.run_in_executor(
  579. executor,
  580. execute_agent_with_api,
  581. json.dumps({"query_word": query, "request_id": requestId})
  582. )
  583. # 更新状态为处理完成
  584. update_extract_status(requestId, 2)
  585. logger.info(f"异步提取任务完成: requestId={requestId}")
  586. return result
  587. except Exception as e:
  588. logger.error(f"异步提取任务失败: requestId={requestId}, error={e}")
  589. # 更新状态为处理失败
  590. update_extract_status(requestId, 3)
  591. raise
  592. finally:
  593. extraction_requests.discard(requestId)
  594. # 创建异步任务但不等待完成
  595. asyncio.create_task(_execute_extract_async())
  596. # 立即返回状态
  597. return {"status": 1, "requestId": requestId, "message": "提取任务已启动并在后台处理"}
  598. except Exception as e:
  599. logger.error(f"启动提取任务失败: requestId={requestId}, error={e}")
  600. # 发生异常,更新状态为处理失败
  601. update_extract_status(requestId, 3)
  602. # 从运行集合中移除
  603. extraction_requests.discard(requestId)
  604. raise HTTPException(status_code=500, detail=f"启动提取任务失败: {str(e)}")
  605. @app.post("/expand")
  606. async def expand(request: ExpandRequest):
  607. """
  608. 执行扩展查询处理(异步方式)
  609. Args:
  610. request: 包含请求ID和查询词的请求体
  611. Returns:
  612. dict: 包含执行状态的字典
  613. """
  614. try:
  615. requestId = request.requestId
  616. query = request.query
  617. logger.info(f"收到扩展查询请求: requestId={requestId}, query={query}")
  618. # 并发防抖:同一 requestId 只允许一个在运行
  619. expansion_requests = getattr(app.state, 'expansion_requests', set())
  620. async with RUNNING_LOCK:
  621. if requestId in expansion_requests:
  622. return {"status": 1, "requestId": requestId, "message": "扩展查询已在处理中"}
  623. # 如果集合不存在,创建它
  624. if not hasattr(app.state, 'expansion_requests'):
  625. app.state.expansion_requests = set()
  626. app.state.expansion_requests.add(requestId)
  627. # 立即更新状态为处理中
  628. _update_expansion_status(requestId, 1)
  629. # 创建异步任务执行扩展Agent
  630. async def _execute_expand_async():
  631. try:
  632. # 在线程池中执行同步函数
  633. import concurrent.futures
  634. loop = asyncio.get_event_loop()
  635. with concurrent.futures.ThreadPoolExecutor() as executor:
  636. result = await loop.run_in_executor(
  637. executor,
  638. execute_expand_agent_with_api,
  639. requestId,
  640. query
  641. )
  642. # 更新状态为处理完成
  643. _update_expansion_status(requestId, 2)
  644. logger.info(f"异步扩展查询任务完成: requestId={requestId}")
  645. return result
  646. except Exception as e:
  647. logger.error(f"异步扩展查询任务失败: requestId={requestId}, error={e}")
  648. # 更新状态为处理失败
  649. _update_expansion_status(requestId, 3)
  650. raise
  651. finally:
  652. # 无论成功失败,都从运行集合中移除
  653. async with RUNNING_LOCK:
  654. if hasattr(app.state, 'expansion_requests'):
  655. app.state.expansion_requests.discard(requestId)
  656. # 创建异步任务但不等待完成
  657. asyncio.create_task(_execute_expand_async())
  658. # 立即返回状态
  659. return {"status": 1, "requestId": requestId, "message": "扩展查询任务已启动并在后台处理"}
  660. except Exception as e:
  661. logger.error(f"启动扩展查询任务失败: requestId={requestId}, error={e}")
  662. # 发生异常,更新状态为处理失败
  663. _update_expansion_status(requestId, 3)
  664. # 从运行集合中移除
  665. async with RUNNING_LOCK:
  666. if hasattr(app.state, 'expansion_requests'):
  667. app.state.expansion_requests.discard(requestId)
  668. raise HTTPException(status_code=500, detail=f"启动扩展查询任务失败: {str(e)}")
  669. except Exception as e:
  670. # 发生异常,更新状态为处理失败
  671. _update_expansion_status(request.requestId, 3)
  672. # 从运行集合中移除
  673. async with RUNNING_LOCK:
  674. if hasattr(app.state, 'expansion_requests'):
  675. app.state.expansion_requests.discard(request.requestId)
  676. raise HTTPException(status_code=500, detail=f"启动扩展查询任务失败: {str(e)}")
  677. def update_extract_status(request_id: str, status: int):
  678. try:
  679. from utils.mysql_db import MysqlHelper
  680. sql = "UPDATE knowledge_request SET extraction_status = %s WHERE request_id = %s"
  681. result = MysqlHelper.update_values(sql, (status, request_id))
  682. if result is not None:
  683. logger.info(f"更新请求状态成功: requestId={request_id}, status={status}")
  684. else:
  685. logger.error(f"更新请求状态失败: requestId={request_id}, status={status}")
  686. except Exception as e:
  687. logger.error(f"更新请求状态异常: requestId={request_id}, status={status}, error={e}")
  688. if __name__ == "__main__":
  689. # 从环境变量获取配置
  690. import os
  691. reload_enabled = os.getenv("RELOAD_ENABLED", "false").lower() == "true"
  692. log_level = os.getenv("LOG_LEVEL", "info")
  693. # 启动服务
  694. uvicorn.run(
  695. "agent:app",
  696. host="0.0.0.0",
  697. port=8080,
  698. reload=reload_enabled, # 通过环境变量控制
  699. log_level=log_level
  700. )