agent.py 23 KB

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