agent.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. global identify_tool
  91. identify_tool = IdentifyTool()
  92. logger.info("Agent 服务启动完成")
  93. yield
  94. # 关闭时清理
  95. logger.info("Agent 服务正在关闭")
  96. # 创建 FastAPI 应用
  97. app = FastAPI(
  98. title="Knowledge Agent API",
  99. description="基于 LangGraph 的智能内容识别和结构化处理服务",
  100. version="2.0.0",
  101. lifespan=lifespan
  102. )
  103. # 并发控制:跟踪正在处理的 requestId,防止重复并发提交
  104. RUNNING_REQUESTS: set = set()
  105. RUNNING_LOCK = asyncio.Lock()
  106. # =========================
  107. # LangGraph 工作流定义
  108. # =========================
  109. def create_langgraph_workflow():
  110. """创建 LangGraph 工作流"""
  111. if not HAS_LANGGRAPH:
  112. return None
  113. # 工作流节点定义
  114. def fetch_data(state: AgentState) -> AgentState:
  115. """获取待处理数据"""
  116. try:
  117. request_id = state["request_id"]
  118. logger.info(f"开始获取数据: requestId={request_id}")
  119. # 更新状态为处理中
  120. update_request_status(request_id, 1)
  121. items = QueryDataTool.fetch_crawl_data_list(request_id)
  122. state["items"] = items
  123. state["processed"] = len(items)
  124. state["status"] = "data_fetched"
  125. logger.info(f"数据获取完成: requestId={request_id}, 数量={len(items)}")
  126. return state
  127. except Exception as e:
  128. logger.error(f"获取数据失败: {e}")
  129. state["error"] = str(e)
  130. state["status"] = "error"
  131. return state
  132. def process_items_batch(state: AgentState) -> AgentState:
  133. """批量处理所有数据项"""
  134. try:
  135. items = state["items"]
  136. if not items:
  137. state["status"] = "completed"
  138. return state
  139. success_count = 0
  140. details = []
  141. for idx, item in enumerate(items, start=1):
  142. try:
  143. crawl_data = item.get('crawl_data') or {}
  144. content_id = item.get('content_id') or ''
  145. task_id = item.get('task_id') or ''
  146. # 先在库中查询是否已经处理过
  147. check_sql = "SELECT id,status FROM knowledge_parsing_content WHERE request_id = %s AND content_id = %s"
  148. check_result = MysqlHelper.get_values(check_sql, (state["request_id"], content_id))
  149. if check_result:
  150. id, status = check_result[0]
  151. if status == 5:
  152. success_count += 1
  153. continue
  154. # Step 1: 识别
  155. identify_result = identify_tool.run(
  156. crawl_data if isinstance(crawl_data, dict) else {}
  157. )
  158. # Step 2: 结构化并入库
  159. affected = UpdateDataTool.store_indentify_result(
  160. state["request_id"],
  161. {
  162. "content_id": content_id,
  163. "task_id": task_id
  164. },
  165. identify_result
  166. )
  167. # 使用StructureTool进行内容结构化处理
  168. structure_tool = StructureTool()
  169. structure_result = structure_tool.process_content_structure(identify_result)
  170. # 存储结构化解析结果
  171. parsing_affected = UpdateDataTool.store_parsing_result(
  172. state["request_id"],
  173. {
  174. "id": affected,
  175. "content_id": content_id,
  176. "task_id": task_id
  177. },
  178. structure_result
  179. )
  180. ok = affected is not None and affected > 0 and parsing_affected is not None and parsing_affected > 0
  181. if ok:
  182. success_count += 1
  183. else:
  184. success_count += 1
  185. logger.error(f"处理第 {idx} 项时出错: {identify_result.get('error') or structure_result.get('error')}")
  186. # 记录处理详情
  187. detail = {
  188. "index": idx,
  189. "dbInserted": ok,
  190. "identifyError": identify_result.get('error') or structure_result.get('error'),
  191. "status": 2 if ok else 3
  192. }
  193. details.append(detail)
  194. logger.info(f"处理进度: {idx}/{len(items)} - {'成功' if ok else '失败'}")
  195. except Exception as e:
  196. logger.error(f"处理第 {idx} 项时出错: {e}")
  197. detail = {
  198. "index": idx,
  199. "dbInserted": False,
  200. "identifyError": str(e),
  201. "status": 3
  202. }
  203. details.append(detail)
  204. state["success"] = success_count
  205. state["details"] = details
  206. state["status"] = "completed"
  207. return state
  208. except Exception as e:
  209. logger.error(f"批量处理失败: {e}")
  210. state["error"] = str(e)
  211. state["status"] = "error"
  212. return state
  213. def should_continue(state: AgentState) -> str:
  214. """判断是否继续处理"""
  215. if state.get("error"):
  216. # 处理失败,更新状态为3
  217. update_request_status(state["request_id"], 3)
  218. return "end"
  219. # 所有数据处理完毕,更新状态为2
  220. update_request_status(state["request_id"], 2)
  221. return "end"
  222. # 构建工作流图
  223. workflow = StateGraph(AgentState)
  224. # 添加节点
  225. workflow.add_node("fetch_data", fetch_data)
  226. workflow.add_node("process_items_batch", process_items_batch)
  227. # 设置入口点
  228. workflow.set_entry_point("fetch_data")
  229. # 添加边
  230. workflow.add_edge("fetch_data", "process_items_batch")
  231. workflow.add_edge("process_items_batch", END)
  232. # 编译工作流
  233. return workflow.compile()
  234. # 全局工作流实例
  235. WORKFLOW = create_langgraph_workflow() if HAS_LANGGRAPH else None
  236. # =========================
  237. # FastAPI 接口定义
  238. # =========================
  239. @app.get("/")
  240. async def root():
  241. """根路径,返回服务信息"""
  242. return {
  243. "service": "Knowledge Agent API",
  244. "version": "2.0.0",
  245. "status": "running",
  246. "langgraph_enabled": HAS_LANGGRAPH,
  247. "endpoints": {
  248. "parse": "/parse",
  249. "parse/async": "/parse/async",
  250. "health": "/health",
  251. "docs": "/docs"
  252. }
  253. }
  254. @app.get("/health")
  255. async def health_check():
  256. """健康检查接口"""
  257. return {
  258. "status": "healthy",
  259. "timestamp": time.time(),
  260. "langgraph_enabled": HAS_LANGGRAPH
  261. }
  262. @app.post("/parse", response_model=TriggerResponse)
  263. async def parse_processing(request: TriggerRequest, background_tasks: BackgroundTasks):
  264. """
  265. 解析内容处理
  266. - **requestId**: 请求ID,用于标识处理任务
  267. """
  268. try:
  269. logger.info(f"收到解析请求: requestId={request.requestId}")
  270. if WORKFLOW and HAS_LANGGRAPH:
  271. # 使用 LangGraph 工作流
  272. logger.info("使用 LangGraph 工作流处理")
  273. # 初始化状态
  274. initial_state = AgentState(
  275. request_id=request.requestId,
  276. items=[],
  277. details=[],
  278. processed=0,
  279. success=0,
  280. error=None,
  281. status="started"
  282. )
  283. # 执行工作流
  284. final_state = WORKFLOW.invoke(
  285. initial_state,
  286. config={
  287. "configurable": {"thread_id": f"thread_{request.requestId}"},
  288. "recursion_limit": 100 # 增加递归限制
  289. }
  290. )
  291. # 构建响应
  292. result = TriggerResponse(
  293. requestId=request.requestId,
  294. processed=final_state.get("processed", 0),
  295. success=final_state.get("success", 0),
  296. details=final_state.get("details", [])
  297. )
  298. return result
  299. except Exception as e:
  300. logger.error(f"处理请求失败: {e}")
  301. # 处理失败,更新状态为3
  302. update_request_status(request.requestId, 3)
  303. raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")
  304. @app.post("/parse/async", status_code=200)
  305. async def parse_processing_async(request: TriggerRequest, background_tasks: BackgroundTasks):
  306. """
  307. 异步解析内容处理(后台任务)
  308. - **requestId**: 请求ID,用于标识处理任务
  309. 行为:立即返回 200,并在后台继续处理任务。
  310. 若同一个 requestId 已有任务进行中,则立即返回失败(status=3)。
  311. """
  312. try:
  313. logger.info(f"收到异步解析请求: requestId={request.requestId}")
  314. # 并发防抖:同一 requestId 只允许一个在运行
  315. async with RUNNING_LOCK:
  316. if request.requestId in RUNNING_REQUESTS:
  317. return {
  318. "requestId": request.requestId,
  319. "status": 3,
  320. "message": "已有任务进行中,稍后再试",
  321. "langgraph_enabled": HAS_LANGGRAPH
  322. }
  323. RUNNING_REQUESTS.add(request.requestId)
  324. async def _background_wrapper(rid: str):
  325. try:
  326. await process_request_background(rid)
  327. finally:
  328. async with RUNNING_LOCK:
  329. RUNNING_REQUESTS.discard(rid)
  330. # 直接使用 asyncio 创建后台任务(不阻塞当前请求返回)
  331. asyncio.create_task(_background_wrapper(request.requestId))
  332. # 立即返回(不阻塞)
  333. return {
  334. "requestId": request.requestId,
  335. "status": 1,
  336. "message": "任务已进入队列并在后台处理",
  337. "langgraph_enabled": HAS_LANGGRAPH
  338. }
  339. except Exception as e:
  340. logger.error(f"提交异步任务失败: {e}")
  341. raise HTTPException(status_code=500, detail=f"提交任务失败: {str(e)}")
  342. async def process_request_background(request_id: str):
  343. """后台处理请求"""
  344. try:
  345. logger.info(f"开始后台处理: requestId={request_id}")
  346. if WORKFLOW and HAS_LANGGRAPH:
  347. # 使用 LangGraph 工作流
  348. # 更新状态为处理中
  349. update_request_status(request_id, 1)
  350. initial_state = AgentState(
  351. request_id=request_id,
  352. items=[],
  353. details=[],
  354. processed=0,
  355. success=0,
  356. error=None,
  357. status="started"
  358. )
  359. final_state = WORKFLOW.invoke(
  360. initial_state,
  361. config={
  362. "configurable": {"thread_id": f"thread_{request_id}"},
  363. "recursion_limit": 100 # 增加递归限制
  364. }
  365. )
  366. # 所有数据处理完毕,更新状态为2
  367. update_request_status(request_id, 2)
  368. logger.info(f"LangGraph 后台处理完成: requestId={request_id}, processed={final_state.get('processed', 0)}, success={final_state.get('success', 0)}")
  369. except Exception as e:
  370. logger.error(f"后台处理失败: requestId={request_id}, error={e}")
  371. # 处理失败,更新状态为3
  372. update_request_status(request_id, 3)
  373. extraction_requests: set = set()
  374. @app.post("/extract")
  375. async def extract(request: ExtractRequest):
  376. try:
  377. requestId = request.requestId
  378. query = request.query
  379. # 检查请求是否已经在处理中
  380. async with RUNNING_LOCK:
  381. if requestId in extraction_requests:
  382. return {"status": 1, "request_id": requestId, "message": "请求已在处理中"}
  383. extraction_requests.add(requestId)
  384. try:
  385. # 更新状态为处理中
  386. update_extract_status(requestId, 1)
  387. # 执行Agent
  388. result = execute_agent_with_api(json.dumps({"query_word": query, "request_id": requestId}))
  389. update_extract_status(requestId, 2)
  390. finally:
  391. # 无论成功失败,都从运行集合中移除
  392. async with RUNNING_LOCK:
  393. extraction_requests.discard(requestId)
  394. return {"status": "success", "result": result}
  395. except Exception as e:
  396. # 发生异常,更新状态为处理失败
  397. update_extract_status(requestId, 3)
  398. raise HTTPException(status_code=500, detail=f"执行Agent时出错: {str(e)}")
  399. @app.post("/expand")
  400. async def expand(request: ExpandRequest, background_tasks: BackgroundTasks):
  401. """
  402. 执行扩展查询处理
  403. Args:
  404. request: 包含请求ID的请求体
  405. background_tasks: FastAPI 后台任务
  406. Returns:
  407. dict: 包含执行状态的字典
  408. """
  409. try:
  410. # 立即更新状态为处理中
  411. _update_expansion_status(request.requestId, 1)
  412. # 添加后台任务
  413. background_tasks.add_task(execute_expand_agent_with_api, request.requestId, request.query)
  414. # 立即返回状态
  415. return {"status": 1, "requestId": request.requestId, "message": "扩展查询处理已启动"}
  416. except Exception as e:
  417. raise HTTPException(status_code=500, detail=f"执行Agent时出错: {str(e)}")
  418. def update_extract_status(request_id: str, status: int):
  419. try:
  420. from utils.mysql_db import MysqlHelper
  421. sql = "UPDATE knowledge_request SET extraction_status = %s WHERE request_id = %s"
  422. result = MysqlHelper.update_values(sql, (status, request_id))
  423. if result is not None:
  424. logger.info(f"更新请求状态成功: requestId={request_id}, status={status}")
  425. else:
  426. logger.error(f"更新请求状态失败: requestId={request_id}, status={status}")
  427. except Exception as e:
  428. logger.error(f"更新请求状态异常: requestId={request_id}, status={status}, error={e}")
  429. if __name__ == "__main__":
  430. # 从环境变量获取配置
  431. import os
  432. reload_enabled = os.getenv("RELOAD_ENABLED", "false").lower() == "true"
  433. log_level = os.getenv("LOG_LEVEL", "info")
  434. # 启动服务
  435. uvicorn.run(
  436. "agent:app",
  437. host="0.0.0.0",
  438. port=8080,
  439. reload=reload_enabled, # 通过环境变量控制
  440. log_level=log_level
  441. )