agent.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. current_index: int
  42. current_item: Optional[Dict[str, Any]]
  43. identify_result: Optional[Dict[str, Any]]
  44. error: Optional[str]
  45. status: str
  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 ExpandRequest(BaseModel):
  56. requestId: str = Field(..., description="扩展查询请求ID")
  57. # 全局变量
  58. identify_tool = None
  59. def update_request_status(request_id: str, status: int):
  60. """
  61. 更新 knowledge_request 表中的 parsing_status
  62. Args:
  63. request_id: 请求ID
  64. status: 状态值 (1: 处理中, 2: 处理完成, 3: 处理失败)
  65. """
  66. try:
  67. from utils.mysql_db import MysqlHelper
  68. sql = "UPDATE knowledge_request SET parsing_status = %s WHERE request_id = %s"
  69. result = MysqlHelper.update_values(sql, (status, request_id))
  70. if result is not None:
  71. logger.info(f"更新请求状态成功: requestId={request_id}, status={status}")
  72. else:
  73. logger.error(f"更新请求状态失败: requestId={request_id}, status={status}")
  74. except Exception as e:
  75. logger.error(f"更新请求状态异常: requestId={request_id}, status={status}, error={e}")
  76. def _update_expansion_status(requestId: str, status: int):
  77. """更新扩展查询状态"""
  78. try:
  79. from utils.mysql_db import MysqlHelper
  80. sql = "UPDATE knowledge_request SET expansion_status = %s WHERE request_id = %s"
  81. MysqlHelper.update_values(sql, (status, requestId))
  82. logger.info(f"更新扩展查询状态成功: requestId={requestId}, status={status}")
  83. except Exception as e:
  84. logger.error(f"更新扩展查询状态失败: requestId={requestId}, status={status}, error={e}")
  85. @asynccontextmanager
  86. async def lifespan(app: FastAPI):
  87. """应用生命周期管理"""
  88. # 启动时初始化
  89. global identify_tool
  90. identify_tool = IdentifyTool()
  91. logger.info("Agent 服务启动完成")
  92. yield
  93. # 关闭时清理
  94. logger.info("Agent 服务正在关闭")
  95. # 创建 FastAPI 应用
  96. app = FastAPI(
  97. title="Knowledge Agent API",
  98. description="基于 LangGraph 的智能内容识别和结构化处理服务",
  99. version="2.0.0",
  100. lifespan=lifespan
  101. )
  102. # 并发控制:跟踪正在处理的 requestId,防止重复并发提交
  103. RUNNING_REQUESTS: set = set()
  104. RUNNING_LOCK = asyncio.Lock()
  105. # =========================
  106. # LangGraph 工作流定义
  107. # =========================
  108. def create_langgraph_workflow():
  109. """创建 LangGraph 工作流"""
  110. if not HAS_LANGGRAPH:
  111. return None
  112. # 工作流节点定义
  113. def fetch_data(state: AgentState) -> AgentState:
  114. """获取待处理数据"""
  115. try:
  116. request_id = state["request_id"]
  117. logger.info(f"开始获取数据: requestId={request_id}")
  118. # 更新状态为处理中
  119. update_request_status(request_id, 1)
  120. items = QueryDataTool.fetch_crawl_data_list(request_id)
  121. state["items"] = items
  122. state["processed"] = len(items)
  123. state["status"] = "data_fetched"
  124. logger.info(f"数据获取完成: requestId={request_id}, 数量={len(items)}")
  125. return state
  126. except Exception as e:
  127. logger.error(f"获取数据失败: {e}")
  128. state["error"] = str(e)
  129. state["status"] = "error"
  130. return state
  131. def process_item(state: AgentState) -> AgentState:
  132. """处理单个数据项"""
  133. try:
  134. items = state["items"]
  135. current_index = state.get("current_index", 0)
  136. if current_index >= len(items):
  137. state["status"] = "completed"
  138. return state
  139. item = items[current_index]
  140. state["current_item"] = item
  141. state["content_id"] = item.get('content_id') or ''
  142. state["task_id"] = item.get('task_id') or ''
  143. state["current_index"] = current_index + 1
  144. # 处理当前项
  145. crawl_data = item.get('crawl_data') or {}
  146. # Step 1: 识别
  147. identify_result = identify_tool.run(
  148. crawl_data if isinstance(crawl_data, dict) else {}
  149. )
  150. state["identify_result"] = identify_result
  151. # Step 2: 结构化并入库
  152. affected = UpdateDataTool.store_indentify_result(
  153. state["request_id"],
  154. {
  155. "content_id": state["content_id"],
  156. "task_id": state["task_id"]
  157. },
  158. identify_result
  159. )
  160. # 使用StructureTool进行内容结构化处理
  161. structure_tool = StructureTool()
  162. structure_result = structure_tool.process_content_structure(identify_result)
  163. # 存储结构化解析结果
  164. parsing_affected = UpdateDataTool.store_parsing_result(
  165. state["request_id"],
  166. {
  167. "content_id": state["content_id"],
  168. "task_id": state["task_id"]
  169. },
  170. structure_result
  171. )
  172. ok = affected is not None and affected > 0 and parsing_affected is not None and parsing_affected > 0
  173. if ok:
  174. state["success"] += 1
  175. # 记录处理详情
  176. detail = {
  177. "index": current_index + 1,
  178. "dbInserted": ok,
  179. "identifyError": identify_result.get('error'),
  180. "status": 2 if ok else 3
  181. }
  182. state["details"].append(detail)
  183. state["status"] = "item_processed"
  184. logger.info(f"处理进度: {current_index + 1}/{len(items)} - {'成功' if ok else '失败'}")
  185. return state
  186. except Exception as e:
  187. logger.error(f"处理第 {current_index + 1} 项时出错: {e}")
  188. detail = {
  189. "index": current_index + 1,
  190. "dbInserted": False,
  191. "identifyError": str(e),
  192. "status": 3
  193. }
  194. state["details"].append(detail)
  195. state["status"] = "item_error"
  196. return state
  197. def should_continue(state: AgentState) -> str:
  198. """判断是否继续处理"""
  199. if state.get("error"):
  200. # 处理失败,更新状态为3
  201. update_request_status(state["request_id"], 3)
  202. return "end"
  203. current_index = state.get("current_index", 0)
  204. items = state.get("items", [])
  205. if current_index >= len(items):
  206. # 所有数据处理完毕,更新状态为2
  207. update_request_status(state["request_id"], 2)
  208. return "end"
  209. return "continue"
  210. # 构建工作流图
  211. workflow = StateGraph(AgentState)
  212. # 添加节点
  213. workflow.add_node("fetch_data", fetch_data)
  214. workflow.add_node("process_item", process_item)
  215. # 设置入口点
  216. workflow.set_entry_point("fetch_data")
  217. # 添加边
  218. workflow.add_edge("fetch_data", "process_item")
  219. workflow.add_conditional_edges(
  220. "process_item",
  221. should_continue,
  222. {
  223. "continue": "process_item",
  224. "end": END
  225. }
  226. )
  227. # 编译工作流
  228. return workflow.compile()
  229. # 全局工作流实例
  230. WORKFLOW = create_langgraph_workflow() if HAS_LANGGRAPH else None
  231. # =========================
  232. # FastAPI 接口定义
  233. # =========================
  234. @app.get("/")
  235. async def root():
  236. """根路径,返回服务信息"""
  237. return {
  238. "service": "Knowledge Agent API",
  239. "version": "2.0.0",
  240. "status": "running",
  241. "langgraph_enabled": HAS_LANGGRAPH,
  242. "endpoints": {
  243. "parse": "/parse",
  244. "parse/async": "/parse/async",
  245. "health": "/health",
  246. "docs": "/docs"
  247. }
  248. }
  249. @app.get("/health")
  250. async def health_check():
  251. """健康检查接口"""
  252. return {
  253. "status": "healthy",
  254. "timestamp": time.time(),
  255. "langgraph_enabled": HAS_LANGGRAPH
  256. }
  257. @app.post("/parse", response_model=TriggerResponse)
  258. async def parse_processing(request: TriggerRequest, background_tasks: BackgroundTasks):
  259. """
  260. 解析内容处理
  261. - **requestId**: 请求ID,用于标识处理任务
  262. """
  263. try:
  264. logger.info(f"收到解析请求: requestId={request.requestId}")
  265. if WORKFLOW and HAS_LANGGRAPH:
  266. # 使用 LangGraph 工作流
  267. logger.info("使用 LangGraph 工作流处理")
  268. # 初始化状态
  269. initial_state = AgentState(
  270. request_id=request.requestId,
  271. items=[],
  272. details=[],
  273. processed=0,
  274. success=0,
  275. current_index=0,
  276. current_item=None,
  277. identify_result=None,
  278. error=None,
  279. status="started"
  280. )
  281. # 执行工作流
  282. final_state = WORKFLOW.invoke(
  283. initial_state,
  284. config={"configurable": {"thread_id": f"thread_{request.requestId}"}}
  285. )
  286. # 构建响应
  287. result = TriggerResponse(
  288. requestId=request.requestId,
  289. processed=final_state.get("processed", 0),
  290. success=final_state.get("success", 0),
  291. details=final_state.get("details", [])
  292. )
  293. else:
  294. # 回退到传统模式
  295. logger.info("使用传统模式处理")
  296. # 更新状态为处理中
  297. update_request_status(request.requestId, 1)
  298. # 获取待处理数据
  299. items = QueryDataTool.fetch_crawl_data_list(request.requestId)
  300. print(f"传统模式---items: {items}")
  301. if not items:
  302. # 无数据需要处理,更新状态为完成
  303. update_request_status(request.requestId, 2)
  304. return TriggerResponse(
  305. requestId=request.requestId,
  306. processed=0,
  307. success=0,
  308. details=[]
  309. )
  310. # 处理数据
  311. success_count = 0
  312. details: List[Dict[str, Any]] = []
  313. for idx, item in enumerate(items, start=1):
  314. try:
  315. crawl_data = item.get('crawl_data') or {}
  316. # Step 1: 识别
  317. identify_result = identify_tool.run(
  318. crawl_data if isinstance(crawl_data, dict) else {}
  319. )
  320. # Step 2: 结构化并入库
  321. affected = UpdateDataTool.store_indentify_result(
  322. request.requestId,
  323. {
  324. content_id: item.get('content_id') or '',
  325. task_id: item.get('task_id') or ''
  326. },
  327. identify_result
  328. )
  329. # 使用StructureTool进行内容结构化处理
  330. structure_tool = StructureTool()
  331. structure_result = structure_tool.process_content_structure(identify_result)
  332. # 存储结构化解析结果
  333. parsing_affected = UpdateDataTool.store_parsing_result(
  334. request.requestId,
  335. {
  336. content_id: item.get('content_id') or '',
  337. task_id: item.get('task_id') or ''
  338. },
  339. structure_result
  340. )
  341. ok = affected is not None and affected > 0
  342. if ok:
  343. success_count += 1
  344. details.append({
  345. "index": idx,
  346. "dbInserted": ok,
  347. "identifyError": identify_result.get('error'),
  348. "status": 2 if ok else 3
  349. })
  350. except Exception as e:
  351. logger.error(f"处理第 {idx} 项时出错: {e}")
  352. details.append({
  353. "index": idx,
  354. "dbInserted": False,
  355. "identifyError": str(e),
  356. "status": 3
  357. })
  358. result = TriggerResponse(
  359. requestId=request.requestId,
  360. processed=len(items),
  361. success=success_count,
  362. details=details
  363. )
  364. # 更新状态为处理完成
  365. update_request_status(request.requestId, 2)
  366. logger.info(f"处理完成: requestId={request.requestId}, processed={result.processed}, success={result.success}")
  367. return result
  368. except Exception as e:
  369. logger.error(f"处理请求失败: {e}")
  370. # 处理失败,更新状态为3
  371. update_request_status(request.requestId, 3)
  372. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
  373. @app.post("/parse/async", status_code=200)
  374. async def parse_processing_async(request: TriggerRequest, background_tasks: BackgroundTasks):
  375. """
  376. 异步解析内容处理(后台任务)
  377. - **requestId**: 请求ID,用于标识处理任务
  378. 行为:立即返回 200,并在后台继续处理任务。
  379. 若同一个 requestId 已有任务进行中,则立即返回失败(status=3)。
  380. """
  381. try:
  382. logger.info(f"收到异步解析请求: requestId={request.requestId}")
  383. # 并发防抖:同一 requestId 只允许一个在运行
  384. async with RUNNING_LOCK:
  385. if request.requestId in RUNNING_REQUESTS:
  386. return {
  387. "requestId": request.requestId,
  388. "status": 3,
  389. "message": "已有任务进行中,稍后再试",
  390. "langgraph_enabled": HAS_LANGGRAPH
  391. }
  392. RUNNING_REQUESTS.add(request.requestId)
  393. async def _background_wrapper(rid: str):
  394. try:
  395. await process_request_background(rid)
  396. finally:
  397. async with RUNNING_LOCK:
  398. RUNNING_REQUESTS.discard(rid)
  399. # 直接使用 asyncio 创建后台任务(不阻塞当前请求返回)
  400. asyncio.create_task(_background_wrapper(request.requestId))
  401. # 立即返回(不阻塞)
  402. return {
  403. "requestId": request.requestId,
  404. "status": 1,
  405. "message": "任务已进入队列并在后台处理",
  406. "langgraph_enabled": HAS_LANGGRAPH
  407. }
  408. except Exception as e:
  409. logger.error(f"提交异步任务失败: {e}")
  410. raise HTTPException(status_code=500, detail=f"提交任务失败: {str(e)}")
  411. async def process_request_background(request_id: str):
  412. """后台处理请求"""
  413. try:
  414. logger.info(f"开始后台处理: requestId={request_id}")
  415. if WORKFLOW and HAS_LANGGRAPH:
  416. # 使用 LangGraph 工作流
  417. # 更新状态为处理中
  418. update_request_status(request_id, 1)
  419. initial_state = AgentState(
  420. request_id=request_id,
  421. items=[],
  422. details=[],
  423. processed=0,
  424. success=0,
  425. current_index=0,
  426. current_item=None,
  427. identify_result=None,
  428. error=None,
  429. status="started"
  430. )
  431. final_state = WORKFLOW.invoke(
  432. initial_state,
  433. config={"configurable": {"thread_id": f"thread_{request_id}"}}
  434. )
  435. logger.info(f"LangGraph 后台处理完成: requestId={request_id}, processed={final_state.get('processed', 0)}, success={final_state.get('success', 0)}")
  436. else:
  437. # 传统模式
  438. # 更新状态为处理中
  439. update_request_status(request_id, 1)
  440. items = QueryDataTool.fetch_crawl_data_list(request_id)
  441. print(f"传统模式process_request_background---items: {items}")
  442. if not items:
  443. logger.info(f"后台处理完成: requestId={request_id}, 无数据需要处理")
  444. # 无数据需要处理,更新状态为完成
  445. update_request_status(request_id, 2)
  446. return
  447. success_count = 0
  448. for idx, item in enumerate(items, start=1):
  449. try:
  450. crawl_data = item.get('crawl_data') or {}
  451. content_id = item.get('content_id') or ''
  452. identify_result = identify_tool.run(
  453. crawl_data if isinstance(crawl_data, dict) else {}
  454. )
  455. affected = UpdateDataTool.store_indentify_result(
  456. request_id,
  457. {
  458. content_id: item.get('content_id') or '',
  459. task_id: item.get('task_id') or ''
  460. },
  461. identify_result
  462. )
  463. # 使用StructureTool进行内容结构化处理
  464. structure_tool = StructureTool()
  465. structure_result = structure_tool.process_content_structure(identify_result)
  466. # 存储结构化解析结果
  467. parsing_affected = UpdateDataTool.store_parsing_result(
  468. request_id,
  469. {
  470. content_id: item.get('content_id') or '',
  471. task_id: item.get('task_id') or ''
  472. },
  473. structure_result
  474. )
  475. if affected is not None and affected > 0:
  476. success_count += 1
  477. logger.info(f"后台处理进度: {idx}/{len(items)} - {'成功' if affected else '失败'} - 结构化{'成功' if parsing_affected else '失败'}")
  478. except Exception as e:
  479. logger.error(f"后台处理第 {idx} 项时出错: {e}")
  480. logger.info(f"传统模式后台处理完成: requestId={request_id}, processed={len(items)}, success={success_count}")
  481. # 更新状态为处理完成
  482. update_request_status(request_id, 2)
  483. except Exception as e:
  484. logger.error(f"后台处理失败: requestId={request_id}, error={e}")
  485. # 处理失败,更新状态为3
  486. update_request_status(request_id, 3)
  487. extraction_requests: set = set()
  488. @app.post("/extract")
  489. async def extract(requestId: str, query: str):
  490. try:
  491. # 检查请求是否已经在处理中
  492. async with RUNNING_LOCK:
  493. if requestId in extraction_requests:
  494. return {"status": 1, "request_id": requestId, "message": "请求已在处理中"}
  495. extraction_requests.add(requestId)
  496. try:
  497. # 更新状态为处理中
  498. update_extract_status(requestId, 1)
  499. # 执行Agent
  500. result = execute_agent_with_api(json.dumps({"query_word":query, "request_id": requestId}))
  501. finally:
  502. # 无论成功失败,都从运行集合中移除
  503. async with RUNNING_LOCK:
  504. extraction_requests.discard(requestId)
  505. except Exception as e:
  506. # 发生异常,更新状态为处理失败
  507. update_extract_status(requestId, 3)
  508. raise HTTPException(status_code=500, detail=f"执行Agent时出错: {str(e)}")
  509. @app.post("/expand")
  510. async def expand(request: ExpandRequest, query: str, background_tasks: BackgroundTasks):
  511. """
  512. 执行扩展查询处理
  513. Args:
  514. request: 包含请求ID的请求体
  515. background_tasks: FastAPI 后台任务
  516. Returns:
  517. dict: 包含执行状态的字典
  518. """
  519. try:
  520. # 立即更新状态为处理中
  521. _update_expansion_status(request.requestId, 1)
  522. # 添加后台任务
  523. background_tasks.add_task(execute_expand_agent_with_api, request.requestId, query)
  524. # 立即返回状态
  525. return {"status": 1, "requestId": request.requestId, "message": "扩展查询处理已启动"}
  526. except Exception as e:
  527. raise HTTPException(status_code=500, detail=f"执行Agent时出错: {str(e)}")
  528. def update_extract_status(request_id: str, status: int):
  529. try:
  530. from utils.mysql_db import MysqlHelper
  531. sql = "UPDATE knowledge_request SET extraction_status = %s WHERE request_id = %s"
  532. result = MysqlHelper.update_values(sql, (status, request_id))
  533. if result is not None:
  534. logger.info(f"更新请求状态成功: requestId={request_id}, status={status}")
  535. else:
  536. logger.error(f"更新请求状态失败: requestId={request_id}, status={status}")
  537. except Exception as e:
  538. logger.error(f"更新请求状态异常: requestId={request_id}, status={status}, error={e}")
  539. if __name__ == "__main__":
  540. # 启动服务
  541. uvicorn.run(
  542. "agent:app",
  543. host="0.0.0.0",
  544. port=8080,
  545. reload=True, # 开发模式,自动重载
  546. log_level="info"
  547. )