review_agent.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  1. # -*- coding: utf-8 -*-
  2. """
  3. 配风计划审查 - Agent 工厂与编排器模块
  4. 核心功能:
  5. - 创建3个独立的审查 DeepAgent 实例(形式审查 / 数据一致性 / 计算核验)
  6. - 创建汇总 Agent 实例
  7. - 编排器:提取 PDF → 并行运行3个Agent → 汇总结果 → SSE 流式输出
  8. 架构:
  9. - 复用 vent_agent.py 的 _get_model() 和 FilesystemBackend 模式
  10. - 每个审查 Agent 有独立的 system_prompt + skills + tools
  11. - 编排器 stream_review() 使用 asyncio.Queue 实现并行 + 流式进度反馈
  12. """
  13. import asyncio
  14. import json
  15. import os
  16. import time
  17. import traceback
  18. import uuid
  19. from pathlib import Path
  20. from typing import AsyncGenerator, Optional
  21. from dotenv import load_dotenv
  22. load_dotenv()
  23. # 复用现有工具的模型加载函数
  24. from agents.vent_agent import _get_model as _get_vent_model
  25. # 导入 PDF 工具
  26. from tools.pdf_tools import extract_pdf_text, save_upload_file, calculate_file_hash
  27. # 导入计算工具
  28. from tools.calc_tools import (
  29. calc_face_by_gas,
  30. calc_face_by_workers,
  31. calc_face_by_wind_speed,
  32. calc_face_air_volume_max,
  33. calc_tunnel_by_gas,
  34. calc_tunnel_by_explosives,
  35. calc_tunnel_by_workers,
  36. calc_tunnel_by_wind_speed,
  37. calc_tunnel_by_vehicle,
  38. calc_tunnel_air_volume_max,
  39. calc_chamber_by_equipment,
  40. calc_chamber_by_wind_speed,
  41. calc_other_by_wind_speed,
  42. calc_effective_area,
  43. calc_total_air_volume,
  44. calc_gas_emission_from_wind,
  45. )
  46. # 工具中文名统一映射
  47. from tools.tool_names_cn import TOOL_NAME_CN as _tool_names
  48. # 导入 MCP 配风计划查询工具
  49. from tools.vent_plan_tools import (
  50. query_mining_plan,
  51. query_face_procedure,
  52. query_gas_report,
  53. query_wind_report,
  54. )
  55. # 导入报告生成工具
  56. from tools.report_utils import save_review_report, extract_mine_name
  57. # 导入系统时间工具
  58. from tools.time_tools import get_current_time
  59. # 导入数据库存储
  60. from db.chat_store import save_message, create_session, update_session_title
  61. # ============================================================
  62. # 中文名称映射(所有 yield 消息只输出中文,不出现英文代号)
  63. # ============================================================
  64. # 子智能体内部名称 → 中文显示名称
  65. AGENT_NAME_CN = {
  66. "form-reviewer": "基本形式审查",
  67. "data-checker": "数据一致性审查",
  68. "calc-verifier": "计算核验审查",
  69. }
  70. # 工具函数名 → 中文描述(统一维护在 tools/tool_names_cn.py)
  71. TOOL_NAME_CN = _tool_names
  72. def _cn_agent(name: str) -> str:
  73. """将子智能体内部名转为中文显示名,未收录则返回原名。"""
  74. return AGENT_NAME_CN.get(name, name)
  75. def _cn_tool(name: str) -> str:
  76. """将工具函数名转为中文描述,未收录则返回原名。"""
  77. return TOOL_NAME_CN.get(name, name)
  78. from langchain.agents.middleware.todo import write_todos
  79. from langgraph.checkpoint.memory import MemorySaver
  80. SKILLS_ROOT = str((Path(__file__).parent.parent / "skills").resolve())
  81. PROJECT_ROOT = str(Path(__file__).parent.parent)
  82. # ============================================================
  83. # 模型获取(复用现有项目的 _get_model)
  84. # ============================================================
  85. def _get_model(model_key: str = "DEEPAGENT_MODEL"):
  86. """获取模型实例,复用现有配置。
  87. 参数:
  88. model_key: 环境变量中的模型 key,默认 "DEEPAGENT_MODEL"。
  89. summary agent 使用 "SUMMARY_MODEL" 以获取更快/更便宜的模型。
  90. """
  91. return _get_vent_model(model_key=model_key)
  92. def _compress_result(text: str, max_chars: int = 8000) -> str:
  93. """轻度压缩子智能体输出文本,保留核心结构化数据的同时降低 token 数。
  94. 策略:
  95. 1. 若文本未超过 max_chars,仅清理冗余空行后返回
  96. 2. 超过时按优先级保留:表格 → 标题行 → 列表项 → 正文段落
  97. 3. 被截断的正文段落用 [...] 标记
  98. """
  99. if not text:
  100. return text
  101. # 统一换行符
  102. text = text.replace("\r\n", "\n").replace("\r", "\n")
  103. def _normalize_newlines(s: str) -> str:
  104. """将连续 3 个以上换行压缩为 2 个"""
  105. import re
  106. return re.sub(r"\n{3,}", "\n\n", s)
  107. # 先做空行归一化
  108. text = _normalize_newlines(text).strip()
  109. if len(text) <= max_chars:
  110. return text
  111. # ── 超过 max_chars,按优先级保留 ──
  112. lines = text.split("\n")
  113. result_lines: list = []
  114. chars_used = 0
  115. truncation_threshold = max_chars # 达到此阈值后停止添加
  116. # 第一遍:保留表格行和标题行(高优先级)
  117. kept_indices: set = set()
  118. for i, line in enumerate(lines):
  119. stripped = line.strip()
  120. # 表格分隔行或表格数据行
  121. if stripped.startswith("|---") or "|---" in stripped or stripped.startswith("|"):
  122. kept_indices.add(i)
  123. # Markdown 标题
  124. elif stripped.startswith("#") and not stripped.startswith("```"):
  125. kept_indices.add(i)
  126. # 列表项
  127. elif stripped.startswith("- ") or stripped.startswith("* ") or stripped.startswith("1. "):
  128. kept_indices.add(i)
  129. # 第二遍:按行拼接,优先保留标记行
  130. for i, line in enumerate(lines):
  131. if i in kept_indices:
  132. result_lines.append(line)
  133. chars_used += len(line) + 1
  134. elif chars_used < truncation_threshold:
  135. result_lines.append(line)
  136. chars_used += len(line) + 1
  137. compressed = "\n".join(result_lines)
  138. compressed = _normalize_newlines(compressed).strip()
  139. # 若仍然超限,硬截断并标记
  140. if len(compressed) > max_chars:
  141. # 尽量在换行处截断
  142. cut_pos = compressed.rfind("\n", 0, max_chars - 80)
  143. if cut_pos == -1:
  144. cut_pos = max_chars - 80
  145. compressed = compressed[:cut_pos] + "\n\n...[已截断,完整内容见子智能体原始输出]"
  146. if len(compressed) < len(text):
  147. compressed += "\n\n...[已截断,完整内容见子智能体原始输出]"
  148. return compressed
  149. # ============================================================
  150. # 系统提示词
  151. # ============================================================
  152. # 子智能体1: 基本形式审查
  153. FORM_REVIEW_SYSTEM_PROMPT = """你是一名煤矿配风计划形式审查专家。你的任务是对配风计划PDF文件进行基本形式审查。
  154. ## 可用工具
  155. - **get_current_time**: 获取当前系统日期时间(中国标准时间)。在版本审查和编制时间审查时必须先调用此工具获取当前时间,然后与PDF中提取的日期进行对比,判断时效性。
  156. - **write_todos**: 更新审查任务进度。
  157. ## 全局行为准则
  158. 1. 所有分析必须基于 PDF 文档中实际提取到的内容,绝不编造。
  159. 2. 未提取到的信息标注"文档中未找到"而非臆测。
  160. 3. 全程使用简体中文输出。
  161. 4. 禁止输出 ANSI 转义序列、内部工具名、函数名。
  162. 5. 全流程使用 write_todos 工具实时更新任务进度。
  163. ## 审查内容
  164. 严格按照技能(skill)中定义的5个审查维度执行:
  165. 1. 版本审查 - 检查配风计划月份是否为当月最新版本
  166. 2. 签字审查 - 仅检查签字栏是否有姓名记录,仅作提示,不做手写体/打印体区分,不纳入违规判定
  167. 3. 编制时间审查 - 检查编制时间是否在计划月份的上一个月
  168. 4. 计算过程完整性 - 检查所有用风地点是否均有完整计算和验算过程
  169. 5. 语病逻辑审查 - 检查前后文描述不一致的地方(不需要太严格)
  170. ## 输出要求
  171. 严格按照技能中定义的格式输出审查结果,不要添加额外标题或代码块。
  172. """
  173. # 子智能体2: 数据一致性审查
  174. DATA_CONSISTENCY_SYSTEM_PROMPT = """你是一名煤矿配风计划数据一致性审查专家。你的任务是对配风计划中数据的内部一致性和外部一致性进行审查。
  175. ## 可用 MCP 工具
  176. 你可以调用以下 MCP 工具查询外部数据源进行交叉校验:
  177. 1. **query_mining_plan(mine_name, plan_month)**
  178. - 查询煤矿月度采掘计划,获取在采在掘工作面清单
  179. - 用于「用风地点完整性」检查:对比采掘计划与配风计划中的工作面是否一致
  180. 2. **query_face_procedure(mine_name)**
  181. - 查询工作面作业规程,获取最大控顶距、最小控顶距、平均采高等参数
  182. - 用于「工作面参数一致性」检查:对比作业规程与配风计划中的参数是否一致
  183. 3. **query_gas_report(mine_name, year)**
  184. - 查询瓦斯等级鉴定报告,获取各工作面瓦斯/CO2 涌出量数据
  185. - **不强制要求本年度**:优先查询当前年度,若无数据则回退查询上一年度(year - 1)
  186. - 用于「瓦斯与二氧化碳数据一致性」检查:校验涌出量数据是否一致
  187. - **必须在审查结论中标注数据来源的报告年度**
  188. 4. **query_wind_report(mine_name, report_month)**
  189. - 查询测风报表,获取各测点温度、风速、风量、瓦斯浓度、CO2浓度数据
  190. - 用于「风速与温度匹配」检查:核验温度系数选择是否合理
  191. - **同时用于「瓦斯与CO2数据一致性」交叉验证**:找到各工作面的回风顺槽测点,调用 calc_gas_emission_from_wind 反算涌出量(实测风量 × 浓度 / 100),与配风计划值对比
  192. ## 全局行为准则
  193. 1. 所有分析必须基于 PDF 文档内容 + MCP 工具返回的真实数据,绝不编造。
  194. 2. 从 PDF 中提取煤矿名称、计划月份等信息,用于构造 MCP 查询参数。
  195. 3. **优先调用 MCP 工具**:每个审查维度开始时必须先调用对应的 MCP 工具获取数据,只有工具明确返回错误时才标注查询失败。
  196. 4. **瓦斯与CO2数据一致性双重验证**:
  197. - 来源A:query_gas_report(瓦斯鉴定报告)
  198. - 来源B:query_wind_report → 提取回风顺槽测点 → calc_gas_emission_from_wind 反算
  199. - 两方数据交叉对比,综合判定
  200. 5. 全程使用简体中文输出。
  201. 6. 禁止输出 ANSI 转义序列、内部工具名、函数名。
  202. 7. 全流程使用 write_todos 工具实时更新任务进度。
  203. ## 审查内容
  204. 严格按照技能(skill)中定义的4个审查维度执行:
  205. 1. 用风地点完整性 - 调用 query_mining_plan 获取采掘计划,对比配风计划
  206. 2. 瓦斯与二氧化碳数据一致性 - 调用 query_gas_report 获取鉴定报告(优先本年度,无数据则查上一年度),逐项对比,必须标注报告年度
  207. 3. 工作面参数一致性 - 调用 query_face_procedure 获取作业规程,逐参数对比
  208. 4. 风速与温度匹配 - 调用 query_wind_report 获取测风数据,核验温度系数
  209. ## 输出要求
  210. 严格按照技能中定义的格式输出审查结果,每个审查维度标注数据来源。
  211. """
  212. # 子智能体3: 计算核验
  213. CALC_VERIFY_SYSTEM_PROMPT = """你是一名煤矿通风需风量计算核验专家。你的任务是对配风计划中各用风地点的需风量计算过程进行逐项核验。
  214. ## 全局行为准则
  215. 1. 必须调用计算工具(calc_face_air_volume_max、calc_tunnel_air_volume_max 等)获取准确计算结果,不能仅凭 LLM 知识计算。
  216. 2. 每个计算过程都要展示公式、代入数值、计算结果(列式计算),不能只给结果。
  217. 3. 若 PDF 中缺少某参数,标注"文档中无此数据,无法计算",绝不编造。
  218. 4. 全程使用简体中文输出。
  219. 5. 禁止输出 ANSI 转义序列、内部工具名、函数名。
  220. 6. 全流程使用 write_todos 工具实时更新任务进度。
  221. ## 核验流程
  222. 1. 从 PDF 文本中提取每个用风地点的参数(名称、类型、瓦斯涌出量、人数、风速、断面积等)
  223. 2. 根据用风地点类型,调用对应的计算工具
  224. 3. 将配风计划中的需风量值与工具计算值进行对比
  225. 4. 按偏差判定:≤5% 一致,5%~10% 符合,>10% 不符
  226. ## 输出要求
  227. 严格按照技能中定义的表格格式输出核验结果,每个地点一张表,最后汇总。
  228. """
  229. # 汇总 Agent(仅负责元信息生成:概况 + 违规汇总 + 修改建议)
  230. # 子智能体的详细审查内容(第2/3/4节)由系统直接嵌入报告,不经过 LLM,确保 100% 不丢失。
  231. SUMMARY_SYSTEM_PROMPT = """你是一名煤矿配风计划审查主管。你的任务是根据子智能体的审查关键发现,生成最终审查报告的**元信息部分**。
  232. ## ⚠️ 你的职责范围(重要)
  233. 你**只负责**以下3个部分:
  234. 1. **审查概况**:从子智能体发现中提炼整体结论
  235. 2. **违规项汇总**:从子智能体发现中提取并归类所有违规项
  236. 3. **修改建议**:针对违规项给出具体可操作的建议
  237. ## ⚠️ 你不需要做的
  238. - **不要**重复输出子智能体的详细审查内容(形式审查详情、数据对比表、计算核验表等)——这些由系统直接嵌入报告,你只需从关键发现中提炼结论。
  239. - **不要**写"参见上文""详细内容见附件"等托词——你的输出是独立的元信息。
  240. ## 汇总规则
  241. 1. 从子智能体的关键发现中提取:煤矿名称、计划月份、核心问题
  242. 2. 违规项分为"红线问题"(硬性违规)和"一般问题"(需整改)
  243. 3. 每个违规项必须对应至少一条修改建议
  244. 4. 全程使用简体中文输出
  245. 5. 禁止输出 ANSI 转义序列、内部工具名、函数名
  246. ## 输出格式(严格遵循)
  247. 按以下顺序输出,从 ## 标题开始,不要加代码块标记:
  248. ## 一、审查概况
  249. | 项目 | 内容 |
  250. |------|------|
  251. | 煤矿名称 | {从子智能体发现中提取} |
  252. | 计划月份 | {从子智能体发现中提取} |
  253. | 审查结论 | {通过/不通过/需整改}(一句话说明理由) |
  254. ## 五、违规项汇总
  255. ### 红线问题
  256. (逐条列出,含问题描述 + 严重程度 + 涉及的具体用风地点或数据项)
  257. ### 一般问题
  258. (逐条列出,含问题描述 + 严重程度 + 涉及的具体用风地点或数据项)
  259. ## 六、修改建议
  260. (逐条列出,每条对应上述一个违规项,给出具体、可操作的修改方案)
  261. """
  262. # ============================================================
  263. # Agent 创建函数
  264. # ============================================================
  265. # 全局 Agent 实例缓存
  266. _form_review_agent: Optional[object] = None
  267. _data_consistency_agent: Optional[object] = None
  268. _calc_verify_agent: Optional[object] = None
  269. _summary_agent: Optional[object] = None
  270. def create_form_review_agent():
  271. """创建「基本形式审查」Agent。
  272. 审查配风计划的基本形式合规性:版本、签字、编制时间、计算过程、语病逻辑。
  273. 使用运行时模型配置(支持前端动态切换)。
  274. """
  275. from deepagents import create_deep_agent
  276. from deepagents.backends import FilesystemBackend
  277. from deepagents import FilesystemPermission
  278. from api.model_config import get_model_instance
  279. skills = ["skills/vent-plan-review-form"]
  280. print(f"[skills] Agent=form-review-agent skills={skills}")
  281. agent = create_deep_agent(
  282. model=get_model_instance(),
  283. tools=[write_todos, get_current_time],
  284. skills=skills,
  285. system_prompt=FORM_REVIEW_SYSTEM_PROMPT,
  286. backend=FilesystemBackend(root_dir=PROJECT_ROOT, virtual_mode=True),
  287. permissions=[
  288. FilesystemPermission(operations=["write"], paths=["/**"], mode="deny"),
  289. ],
  290. middleware=[],
  291. name="form-review-agent",
  292. checkpointer=MemorySaver(),
  293. )
  294. return agent
  295. def create_data_consistency_agent():
  296. """创建「数据一致性审查」Agent。
  297. 审查配风计划数据的内部和外部一致性。
  298. 使用运行时模型配置(支持前端动态切换)。
  299. """
  300. from deepagents import create_deep_agent
  301. from deepagents.backends import FilesystemBackend
  302. from deepagents import FilesystemPermission
  303. from api.model_config import get_model_instance
  304. skills = ["skills/vent-plan-review-data"]
  305. print(f"[skills] Agent=data-consistency-agent skills={skills}")
  306. agent = create_deep_agent(
  307. model=get_model_instance(),
  308. tools=[
  309. write_todos,
  310. get_current_time,
  311. query_mining_plan,
  312. query_face_procedure,
  313. query_gas_report,
  314. query_wind_report,
  315. calc_gas_emission_from_wind,
  316. ],
  317. skills=skills,
  318. system_prompt=DATA_CONSISTENCY_SYSTEM_PROMPT,
  319. backend=FilesystemBackend(root_dir=PROJECT_ROOT, virtual_mode=True),
  320. permissions=[
  321. FilesystemPermission(operations=["write"], paths=["/**"], mode="deny"),
  322. ],
  323. middleware=[],
  324. name="data-consistency-agent",
  325. checkpointer=MemorySaver(),
  326. )
  327. return agent
  328. def create_calc_verification_agent():
  329. """创建「计算核验」Agent。
  330. 逐地点核验需风量计算过程,使用本地计算工具。
  331. 使用运行时模型配置(支持前端动态切换)。
  332. """
  333. from deepagents import create_deep_agent
  334. from deepagents.backends import FilesystemBackend
  335. from deepagents import FilesystemPermission
  336. from api.model_config import get_model_instance
  337. skills = ["skills/vent-plan-review-calc"]
  338. print(f"[skills] Agent=calc-verification-agent skills={skills}")
  339. agent = create_deep_agent(
  340. model=get_model_instance(),
  341. tools=[
  342. write_todos,
  343. calc_face_by_gas,
  344. calc_face_by_workers,
  345. calc_face_by_wind_speed,
  346. calc_face_air_volume_max,
  347. calc_tunnel_by_gas,
  348. calc_tunnel_by_explosives,
  349. calc_tunnel_by_workers,
  350. calc_tunnel_by_wind_speed,
  351. calc_tunnel_by_vehicle,
  352. calc_tunnel_air_volume_max,
  353. calc_chamber_by_equipment,
  354. calc_chamber_by_wind_speed,
  355. calc_other_by_wind_speed,
  356. calc_effective_area,
  357. calc_total_air_volume,
  358. ],
  359. skills=skills,
  360. system_prompt=CALC_VERIFY_SYSTEM_PROMPT,
  361. backend=FilesystemBackend(root_dir=PROJECT_ROOT, virtual_mode=True),
  362. permissions=[
  363. FilesystemPermission(operations=["write"], paths=["/**"], mode="deny"),
  364. ],
  365. middleware=[],
  366. name="calc-verification-agent",
  367. checkpointer=MemorySaver(),
  368. )
  369. return agent
  370. def create_summary_agent():
  371. """创建「汇总审查」Agent。
  372. 汇总3个子智能体的审查结果,生成最终审查报告。
  373. 使用运行时模型配置(支持前端动态切换)。
  374. """
  375. from deepagents import create_deep_agent
  376. from deepagents.backends import FilesystemBackend
  377. from deepagents import FilesystemPermission
  378. from api.model_config import get_model_instance
  379. skills = ["skills/vent-plan-review-summary"]
  380. print(f"[skills] Agent=summary-agent skills={skills}")
  381. agent = create_deep_agent(
  382. model=get_model_instance(),
  383. tools=[write_todos],
  384. skills=skills,
  385. system_prompt=SUMMARY_SYSTEM_PROMPT,
  386. backend=FilesystemBackend(root_dir=PROJECT_ROOT, virtual_mode=True),
  387. permissions=[
  388. FilesystemPermission(operations=["write"], paths=["/**"], mode="deny"),
  389. ],
  390. middleware=[],
  391. name="summary-agent",
  392. checkpointer=MemorySaver(),
  393. )
  394. return agent
  395. def get_form_review_agent():
  396. """获取形式审查 Agent 单例"""
  397. global _form_review_agent
  398. if _form_review_agent is None:
  399. _form_review_agent = create_form_review_agent()
  400. return _form_review_agent
  401. def get_data_consistency_agent():
  402. """获取数据一致性审查 Agent 单例"""
  403. global _data_consistency_agent
  404. if _data_consistency_agent is None:
  405. _data_consistency_agent = create_data_consistency_agent()
  406. return _data_consistency_agent
  407. def get_calc_verification_agent():
  408. """获取计算核验 Agent 单例"""
  409. global _calc_verify_agent
  410. if _calc_verify_agent is None:
  411. _calc_verify_agent = create_calc_verification_agent()
  412. return _calc_verify_agent
  413. def get_summary_agent():
  414. """获取汇总 Agent 单例"""
  415. global _summary_agent
  416. if _summary_agent is None:
  417. _summary_agent = create_summary_agent()
  418. return _summary_agent
  419. def invalidate_cache():
  420. """失效所有审查 Agent 缓存(模型切换时调用)。"""
  421. global _form_review_agent, _data_consistency_agent, _calc_verify_agent, _summary_agent
  422. _form_review_agent = None
  423. _data_consistency_agent = None
  424. _calc_verify_agent = None
  425. _summary_agent = None
  426. print("[模型切换] 审查 Agent 缓存已全部失效")
  427. # ============================================================
  428. # SSE 事件辅助函数
  429. # ============================================================
  430. def _sse_event(event_type: str, **kwargs) -> str:
  431. """生成 SSE 格式的事件字符串。
  432. Args:
  433. event_type: 事件类型 (progress / agent_start / agent_done / agent_error / token / done / error)
  434. **kwargs: 事件的其他字段
  435. Returns:
  436. SSE 格式字符串: "data: {json}\n\n"
  437. """
  438. data = {"type": event_type, **kwargs}
  439. return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
  440. def _extract_agent_response(result) -> str:
  441. """从 Agent 调用结果中提取文本响应。
  442. Args:
  443. result: agent.ainvoke() 的返回值
  444. Returns:
  445. str: 提取的文本内容
  446. """
  447. if result is None:
  448. return ""
  449. # 尝试从 messages 中提取最后一条 AI 消息
  450. if isinstance(result, dict):
  451. messages = result.get("messages", [])
  452. if messages:
  453. # 从后往前找最后一条 AI 消息
  454. for msg in reversed(messages):
  455. if hasattr(msg, "content") and hasattr(msg, "type") and msg.type == "ai":
  456. content = msg.content
  457. if isinstance(content, str):
  458. return content
  459. elif isinstance(content, list):
  460. return "".join(
  461. block.get("text", "") if isinstance(block, dict) else str(block)
  462. for block in content
  463. )
  464. elif isinstance(msg, dict) and msg.get("type") == "ai":
  465. return msg.get("content", "")
  466. return str(result)
  467. # ============================================================
  468. # 核心编排器 - stream_review()
  469. # ============================================================
  470. async def stream_review(
  471. file,
  472. message: Optional[str] = None,
  473. session_id: Optional[str] = None,
  474. force_refresh: bool = False,
  475. ) -> AsyncGenerator[str, None]:
  476. """配风计划审查 SSE 流式编排器。
  477. 流程:
  478. 1. 保存上传的 PDF 文件并计算哈希
  479. 2. 检查缓存 → 提取文本(或从缓存读取)
  480. 3. 创建3个审查 Agent(或获取缓存单例)
  481. 4. 使用 asyncio.Queue 并行运行3个 Agent,收集进度事件
  482. 5. 流式 yield SSE 事件到前端
  483. 6. 汇总3个审查结果,生成最终报告
  484. Args:
  485. file: FastAPI UploadFile 对象
  486. message: 用户附加消息(可选)
  487. session_id: 会话ID(可选)
  488. force_refresh: 是否强制重新提取(忽略缓存),默认 False
  489. Yields:
  490. SSE 格式字符串
  491. """
  492. # 生成会话ID
  493. if session_id is None:
  494. session_id = str(uuid.uuid4())
  495. # 确保会话存在于数据库,并设置标题
  496. user_msg = message or "请对配风计划进行审查"
  497. create_session(session_id, title=f"配风计划审查: {file.filename or '未知文件'}")
  498. save_message(session_id, "user", user_msg)
  499. pdf_path = None
  500. try:
  501. overall_start = time.time()
  502. # ============================================================
  503. # 阶段1: 保存文件并提取 PDF 文本
  504. # ============================================================
  505. yield _sse_event("progress", message="正在保存上传的 PDF 文件...", agent="system")
  506. pdf_path = await save_upload_file(file)
  507. # 计算文件哈希,用于缓存 key
  508. loop = asyncio.get_event_loop()
  509. file_hash = await loop.run_in_executor(None, calculate_file_hash, pdf_path)
  510. yield _sse_event("progress",
  511. message=f"PDF 文件已保存 ({os.path.basename(pdf_path)}),文件标识: {file_hash[:12]}...,正在提取文本内容...",
  512. agent="system",
  513. hash_id=file_hash)
  514. # 检查缓存状态(用于前端提示)
  515. cache_path = Path(PROJECT_ROOT) / "data" / "pdf_cache" / f"{file_hash}.txt"
  516. cache_hit = cache_path.exists() and not force_refresh
  517. if cache_hit:
  518. yield _sse_event("progress",
  519. message=f"📦 缓存命中!该 PDF 已解析过,直接从缓存加载...",
  520. agent="system",
  521. hash_id=file_hash,
  522. cache_hit=True)
  523. # 创建进度队列:OCR 线程通过 call_soon_threadsafe 写入,主循环轮询读取
  524. progress_queue: asyncio.Queue = asyncio.Queue()
  525. def on_ocr_progress(page_num: int, total_pages: int):
  526. """OCR 页码回调(线程中执行 → 桥接到异步)"""
  527. try:
  528. loop.call_soon_threadsafe(
  529. progress_queue.put_nowait,
  530. {"page": page_num, "total": total_pages}
  531. )
  532. except Exception:
  533. pass
  534. # 在 executor 中运行 PDF 提取(不阻塞事件循环),同时轮询进度队列 yield SSE
  535. extract_task = loop.run_in_executor(
  536. None,
  537. lambda: extract_pdf_text(
  538. pdf_path,
  539. force_refresh=force_refresh,
  540. progress_callback=on_ocr_progress,
  541. )
  542. )
  543. # 轮询:每 0.3 秒检查提取是否完成 + 是否有新页码事件
  544. while not extract_task.done():
  545. try:
  546. while True:
  547. evt = progress_queue.get_nowait()
  548. if evt is not None:
  549. yield _sse_event(
  550. "progress",
  551. message=f"文字识别正在处理第 {evt['page']}/{evt['total']} 页...",
  552. agent="system",
  553. hash_id=file_hash,
  554. ocr_progress={"page": evt["page"], "total": evt["total"]},
  555. )
  556. except asyncio.QueueEmpty:
  557. pass
  558. await asyncio.sleep(0.3)
  559. pdf_text = await extract_task
  560. if pdf_text.startswith("[错误]"):
  561. yield _sse_event("error", message=pdf_text, hash_id=file_hash)
  562. yield _sse_event("done", session_id=session_id)
  563. return
  564. yield _sse_event("progress",
  565. message=f"PDF 文本提取完成,共 {len(pdf_text)} 字符。正在初始化审查智能体...",
  566. agent="system",
  567. hash_id=file_hash,
  568. cache_hit=cache_hit)
  569. # 从 PDF 文本中提取煤矿名称,用于报告文件名
  570. mine_name = await loop.run_in_executor(None, extract_mine_name, pdf_text)
  571. if mine_name:
  572. print(f"[审查] 识别煤矿名称: {mine_name}")
  573. # ============================================================
  574. # 阶段2: 创建/获取3个审查 Agent
  575. # ============================================================
  576. # 在 executor 中运行 Agent 创建(create_deep_agent 编译状态图可能耗时)
  577. agent1 = await loop.run_in_executor(None, get_form_review_agent)
  578. agent2 = await loop.run_in_executor(None, get_data_consistency_agent)
  579. agent3 = await loop.run_in_executor(None, get_calc_verification_agent)
  580. yield _sse_event("progress",
  581. message="3个审查智能体已就绪,正在并行执行审查...",
  582. agent="system")
  583. # ============================================================
  584. # 阶段3: 并行执行3个 Agent
  585. # ============================================================
  586. # 构建各 Agent 的输入消息
  587. user_message = message or "请对配风计划进行审查"
  588. input_msg = {
  589. "messages": [
  590. {"role": "user", "content": f"用户指令:{user_message}\n\n以下是配风计划PDF文件提取的文本内容,请按照技能中的步骤执行审查任务:\n\n{pdf_text}"}
  591. ]
  592. }
  593. # 使用 asyncio.Queue 收集进度事件
  594. queue: asyncio.Queue = asyncio.Queue()
  595. async def run_agent(agent_name: str, agent, agent_input: dict):
  596. """在后台流式运行单个 Agent,将所有中间事件推送到队列。
  597. 事件类型:
  598. - agent_start: 开始审查
  599. - agent_thinking: LLM 正在推理
  600. - agent_executing: 正在执行工具(含工具名列表 + 中文名)
  601. - agent_todos: write_todos 更新了任务列表
  602. - agent_tool_result: 工具执行完成(含中文名)
  603. - agent_done: 审查完成(含完整回复文本 + 耗时)
  604. - agent_error: 审查出错
  605. """
  606. agent_cn = _cn_agent(agent_name)
  607. t0 = time.time()
  608. try:
  609. await queue.put({
  610. "type": "agent_start",
  611. "agent": agent_name,
  612. "cn_agent": agent_cn,
  613. "message": f"「{agent_cn}」开始审查...",
  614. })
  615. full_response = ""
  616. async for chunk in agent.astream(
  617. agent_input,
  618. stream_mode=["updates", "messages", "custom"],
  619. version="v2",
  620. ):
  621. # ── updates 模式:步骤级事件 ──
  622. if chunk["type"] == "updates":
  623. for node_name in chunk["data"]:
  624. if node_name == "model":
  625. await queue.put({
  626. "type": "agent_thinking",
  627. "agent": agent_name,
  628. "cn_agent": agent_cn,
  629. "message": f"「{agent_cn}」正在分析...",
  630. })
  631. elif node_name == "tools":
  632. tools_data = chunk["data"].get(node_name, {})
  633. tool_names = []
  634. for msg in tools_data.get("messages", []):
  635. name = getattr(msg, "name", None) or (msg.get("name") if isinstance(msg, dict) else None)
  636. if name:
  637. tool_names.append(name)
  638. if tool_names:
  639. descs = [_cn_tool(t) for t in tool_names]
  640. await queue.put({
  641. "type": "agent_executing",
  642. "agent": agent_name,
  643. "cn_agent": agent_cn,
  644. "message": f"「{agent_cn}」正在{'、'.join(descs)}...",
  645. "tools": tool_names,
  646. "cn_tools": descs,
  647. })
  648. # ── messages 模式:token / tool_result / todo 事件 ──
  649. elif chunk["type"] == "messages":
  650. token_data = chunk["data"]
  651. if isinstance(token_data, (list, tuple)) and len(token_data) >= 1:
  652. msg_obj = token_data[0]
  653. else:
  654. msg_obj = token_data
  655. # 工具结果
  656. is_tool_msg = hasattr(msg_obj, "type") and msg_obj.type == "tool"
  657. if is_tool_msg:
  658. tool_name = getattr(msg_obj, "name", "unknown")
  659. cn_tool = _cn_tool(tool_name)
  660. if tool_name == "write_todos":
  661. tool_content = _extract_text_content(msg_obj) or ""
  662. todo_list = _parse_todo_json(tool_content)
  663. if todo_list:
  664. await queue.put({
  665. "type": "agent_todos",
  666. "agent": agent_name,
  667. "cn_agent": agent_cn,
  668. "message": f"「{agent_cn}」已更新任务进度",
  669. "todos": todo_list,
  670. })
  671. else:
  672. await queue.put({
  673. "type": "agent_tool_result",
  674. "agent": agent_name,
  675. "cn_agent": agent_cn,
  676. "message": f"「{agent_cn}」{cn_tool} 完成",
  677. "tool": tool_name,
  678. "cn_tool": cn_tool,
  679. })
  680. else:
  681. # AI 生成的文本 token
  682. content = _extract_text_content(msg_obj)
  683. if content and isinstance(content, str):
  684. full_response += content
  685. duration_ms = int((time.time() - t0) * 1000)
  686. await queue.put({
  687. "type": "agent_done",
  688. "agent": agent_name,
  689. "cn_agent": agent_cn,
  690. "message": f"「{agent_cn}」审查完成({duration_ms}ms)",
  691. "content": full_response,
  692. "duration_ms": duration_ms,
  693. })
  694. except Exception as e:
  695. traceback.print_exc()
  696. await queue.put({
  697. "type": "agent_error",
  698. "agent": agent_name,
  699. "cn_agent": agent_cn,
  700. "message": f"「{agent_cn}」审查出错: {str(e)}",
  701. "error": str(e),
  702. })
  703. # 并行启动3个 Agent
  704. tasks = [
  705. asyncio.create_task(run_agent("form-reviewer", agent1, input_msg)),
  706. asyncio.create_task(run_agent("data-checker", agent2, input_msg)),
  707. asyncio.create_task(run_agent("calc-verifier", agent3, input_msg)),
  708. ]
  709. # 从队列读取事件并 yield SSE
  710. completed = 0
  711. results = {}
  712. while completed < 3:
  713. event = await queue.get()
  714. if event["type"] == "agent_start":
  715. yield _sse_event("agent_start",
  716. agent=event["agent"],
  717. cn_agent=event.get("cn_agent", event["agent"]),
  718. message=event["message"])
  719. elif event["type"] == "agent_thinking":
  720. yield _sse_event("agent_thinking",
  721. agent=event["agent"],
  722. cn_agent=event.get("cn_agent", event["agent"]),
  723. message=event["message"])
  724. elif event["type"] == "agent_executing":
  725. yield _sse_event("agent_executing",
  726. agent=event["agent"],
  727. cn_agent=event.get("cn_agent", event["agent"]),
  728. message=event["message"],
  729. tools=event.get("tools", []),
  730. cn_tools=event.get("cn_tools", event.get("tools", [])))
  731. elif event["type"] == "agent_todos":
  732. yield _sse_event("agent_todos",
  733. agent=event["agent"],
  734. cn_agent=event.get("cn_agent", event["agent"]),
  735. message=event["message"],
  736. todos=event.get("todos", []))
  737. elif event["type"] == "agent_tool_result":
  738. yield _sse_event("agent_tool_result",
  739. agent=event["agent"],
  740. cn_agent=event.get("cn_agent", event["agent"]),
  741. message=event["message"],
  742. tool=event.get("tool", ""),
  743. cn_tool=event.get("cn_tool", event.get("tool", "")))
  744. elif event["type"] == "agent_done":
  745. completed += 1
  746. results[event["agent"]] = event["content"]
  747. preview = event["content"][:300] + "..." if len(event["content"]) > 300 else event["content"]
  748. yield _sse_event("agent_done",
  749. agent=event["agent"],
  750. cn_agent=event.get("cn_agent", event["agent"]),
  751. message=event["message"],
  752. preview=preview,
  753. duration_ms=event.get("duration_ms", 0),
  754. progress=f"{completed}/3")
  755. elif event["type"] == "agent_error":
  756. completed += 1
  757. results[event["agent"]] = f"[审查出错] {event.get('error', '未知错误')}"
  758. yield _sse_event("agent_error",
  759. agent=event["agent"],
  760. cn_agent=event.get("cn_agent", event["agent"]),
  761. message=event["message"],
  762. progress=f"{completed}/3")
  763. # 等待所有 task 完成
  764. await asyncio.gather(*tasks, return_exceptions=True)
  765. # ============================================================
  766. # 阶段4: 汇总结果(新架构:子智能体输出直接嵌入 + LLM 仅生成元信息)
  767. #
  768. # 旧架构问题:把 3 个子智能体全量输出(可达 50k+ chars)传给 flash 模型
  769. # 要求"全量重现",模型偶尔摆烂只输出一句托词 → 子智能体结果全部丢失。
  770. #
  771. # 新架构:子智能体原始输出直接嵌入报告第 2/3/4 节(100% 不丢失);
  772. # LLM 仅接收关键摘要(~6k chars),负责生成第 1 节(概况)、
  773. # 第 5 节(违规汇总)、第 6 节(修改建议)。
  774. # ============================================================
  775. yield _sse_event("progress",
  776. message="3个子智能体均已审查完成,正在汇总审查结果...",
  777. agent="system")
  778. # ── 获取子智能体原始完整输出 ──
  779. raw_form = results.get("form-reviewer", "无结果")
  780. raw_data = results.get("data-checker", "无结果")
  781. raw_calc = results.get("calc-verifier", "无结果")
  782. print(f"[审查] 子智能体结果长度: form={len(raw_form)}, "
  783. f"data={len(raw_data)}, calc={len(raw_calc)}")
  784. # ── Step 1: 提取关键摘要(供 LLM 综合判断,每份最多 2000 字符)──
  785. key_form = _extract_key_findings(raw_form)
  786. key_data = _extract_key_findings(raw_data)
  787. key_calc = _extract_key_findings(raw_calc)
  788. total_key_chars = len(key_form) + len(key_data) + len(key_calc)
  789. print(f"[审查] 关键摘要总长度: {total_key_chars} 字符 "
  790. f"(原始: {len(raw_form) + len(raw_data) + len(raw_calc)} 字符)")
  791. yield _sse_event("progress",
  792. message="正在生成审查概况与违规汇总...",
  793. agent="system")
  794. # ── Step 2: 调用 summary LLM 生成元信息(概况 + 违规汇总 + 修改建议)──
  795. # 只传关键摘要,不传全量子智能体输出,大幅降低上下文大小,
  796. # 从根本上避免 flash 模型因上下文过大而"摆烂"。
  797. meta_prompt = f"""请根据以下3个子智能体的审查关键发现,生成最终审查报告的元信息部分。
  798. ## 审查关键发现
  799. ### 基本形式审查(关键发现):
  800. {key_form}
  801. ### 数据一致性审查(关键发现):
  802. {key_data}
  803. ### 计算核验审查(关键发现):
  804. {key_calc}
  805. ## 任务
  806. 请严格按照系统提示词(system prompt)中定义的格式,输出以下3个部分
  807. (只输出这3个部分,不要输出代码块标记,不要输出子智能体的详细审查内容):
  808. ## 一、审查概况
  809. (表格形式:煤矿名称、计划月份、审查结论 + 一句话理由)
  810. ## 五、违规项汇总
  811. (红线问题 + 一般问题,逐条列出,含涉及的具体用风地点)
  812. ## 六、修改建议
  813. (逐条列出,每条对应一个违规项,给出具体可操作的修改方案)
  814. """
  815. summary_agent = await loop.run_in_executor(None, get_summary_agent)
  816. meta_input = {
  817. "messages": [{"role": "user", "content": meta_prompt}]
  818. }
  819. # 流式获取 LLM 元信息输出(带心跳,防止长时间等待无反馈)
  820. meta_text = ""
  821. try:
  822. import asyncio as _asyncio_mod
  823. astream_iter = summary_agent.astream(
  824. meta_input,
  825. stream_mode=["updates", "messages"],
  826. version="v2",
  827. ).__aiter__()
  828. first_token_received = False
  829. heartbeat_start = time.time()
  830. while True:
  831. try:
  832. if first_token_received:
  833. chunk = await astream_iter.__anext__()
  834. else:
  835. chunk = await _asyncio_mod.wait_for(
  836. astream_iter.__anext__(), timeout=5.0
  837. )
  838. if not first_token_received:
  839. first_token_received = True
  840. elapsed = int(time.time() - heartbeat_start)
  841. if elapsed >= 5:
  842. print(f"[审查] Summary LLM 首 token 延迟: {elapsed}s")
  843. except _asyncio_mod.TimeoutError:
  844. elapsed = int(time.time() - heartbeat_start)
  845. yield _sse_event("progress",
  846. message=f"模型正在处理中(已等待 {elapsed} 秒)...",
  847. agent="system")
  848. continue
  849. except StopAsyncIteration:
  850. break
  851. if chunk["type"] == "messages":
  852. token_data = chunk["data"]
  853. if isinstance(token_data, (list, tuple)) and len(token_data) >= 1:
  854. msg_obj = token_data[0]
  855. else:
  856. msg_obj = token_data
  857. is_tool_msg = hasattr(msg_obj, "type") and msg_obj.type == "tool"
  858. if not is_tool_msg:
  859. content = _extract_text_content(msg_obj)
  860. if content and isinstance(content, str):
  861. meta_text += content
  862. except Exception as e:
  863. print(f"[审查] Summary LLM 调用出错: {e}")
  864. meta_text = ""
  865. # ── Step 3: 校验 LLM 输出质量 ──
  866. lazy_detected = _is_lazy_summary(meta_text)
  867. if lazy_detected:
  868. print(f"[审查] ⚠️ 检测到 LLM 懒输出(长度={len(meta_text)}),将使用兜底模板")
  869. else:
  870. print(f"[审查] Summary LLM 元信息生成完成,长度={len(meta_text)}")
  871. # ── Step 4: 解析 LLM 输出中的三个部分 ──
  872. sec1 = "" # 审查概况
  873. sec5 = "" # 违规项汇总
  874. sec6 = "" # 修改建议
  875. if meta_text and not lazy_detected:
  876. # 清理前导语:LLM 可能输出"好的,以下是..."等前缀
  877. import re as _re
  878. anchor_match = _re.search(r"## 一、审查概况", meta_text)
  879. if anchor_match and anchor_match.start() > 0:
  880. skipped = meta_text[:anchor_match.start()].strip()
  881. if skipped:
  882. print(f"[审查] 已跳过 LLM 前导语 ({len(skipped)} 字符): {skipped[:80]}...")
  883. meta_text = meta_text[anchor_match.start():]
  884. parts_1 = meta_text.split("## 五、违规项汇总", 1)
  885. sec1 = parts_1[0].strip()
  886. if len(parts_1) > 1:
  887. parts_2 = parts_1[1].split("## 六、修改建议", 1)
  888. sec5 = ("## 五、违规项汇总\n" + parts_2[0]).strip()
  889. if len(parts_2) > 1:
  890. sec6 = ("## 六、修改建议\n" + parts_2[1]).strip()
  891. # ── Step 5: 流式组装最终报告并 yield SSE token 事件 ──
  892. mine_title = mine_name or ""
  893. report_title = (
  894. f"# {mine_title}配风计划审查报告\n\n"
  895. if mine_title
  896. else "# 配风计划审查报告\n\n"
  897. )
  898. yield _sse_event("token", content=report_title)
  899. # 收集各部分用于最终组装 full_report(DB 存储 + Word 导出)
  900. report_parts = [report_title]
  901. # 第1节:审查概况(LLM 生成 or 兜底)
  902. if sec1:
  903. yield _sse_event("token", content=sec1 + "\n\n")
  904. report_parts.append(sec1 + "\n\n")
  905. else:
  906. fbk1 = (
  907. "## 一、审查概况\n\n"
  908. f"| 项目 | 内容 |\n|------|------|\n"
  909. f"| 煤矿名称 | {mine_title or '(待补充)'} |\n"
  910. "| 审查结论 | 详见以下各节审查详情 |\n\n"
  911. )
  912. yield _sse_event("token", content=fbk1)
  913. report_parts.append(fbk1)
  914. # 第2节:形式审查结果(子智能体原始输出直接嵌入,分块传输避免前端卡顿)
  915. yield _sse_event("token", content="## 二、形式审查结果\n\n")
  916. report_parts.append("## 二、形式审查结果\n\n")
  917. for chunk_event in _chunk_text_for_sse(raw_form):
  918. yield chunk_event
  919. report_parts.append(raw_form)
  920. report_parts.append("\n\n")
  921. # 第3节:数据一致性审查结果(直接嵌入)
  922. yield _sse_event("token", content="## 三、数据一致性审查结果\n\n")
  923. report_parts.append("## 三、数据一致性审查结果\n\n")
  924. for chunk_event in _chunk_text_for_sse(raw_data):
  925. yield chunk_event
  926. report_parts.append(raw_data)
  927. report_parts.append("\n\n")
  928. # 第4节:计算核验结果(直接嵌入,通常是最大的一块内容)
  929. yield _sse_event("token", content="## 四、计算核验结果\n\n")
  930. report_parts.append("## 四、计算核验结果\n\n")
  931. for chunk_event in _chunk_text_for_sse(raw_calc):
  932. yield chunk_event
  933. report_parts.append(raw_calc)
  934. report_parts.append("\n\n")
  935. # 第5节:违规项汇总(LLM 生成 or 兜底)
  936. if sec5:
  937. yield _sse_event("token", content=sec5 + "\n\n")
  938. report_parts.append(sec5 + "\n\n")
  939. else:
  940. fbk5 = (
  941. "## 五、违规项汇总\n\n"
  942. "> ⚠ 。"
  943. "请参见以上各节中标注的不符/缺失/违规/红线等标记,逐一核实。\n\n"
  944. "(请根据以上各节中标注的具体问题进行人工汇总)\n\n"
  945. )
  946. yield _sse_event("token", content=fbk5)
  947. report_parts.append(fbk5)
  948. # 第6节:修改建议(LLM 生成 or 兜底)
  949. if sec6:
  950. yield _sse_event("token", content=sec6)
  951. report_parts.append(sec6)
  952. else:
  953. fbk6 = (
  954. "## 六、修改建议\n\n"
  955. "> ⚠️ 自动生成失败。"
  956. "请参见以上各节中各子智能体给出的具体审查意见和修改建议。\n"
  957. )
  958. yield _sse_event("token", content=fbk6)
  959. report_parts.append(fbk6)
  960. # ── 组装最终完整报告(用于 DB 存储和 Word 导出)──
  961. full_report = "".join(report_parts)
  962. print(f"[审查] 最终报告总长度: {len(full_report)} 字符 "
  963. f"(子智能体内容: {len(raw_form) + len(raw_data) + len(raw_calc)} 字符, "
  964. f"元信息: {len(meta_text)} 字符, "
  965. f"LLM状态: {'懒输出-已兜底' if lazy_detected else '正常'})")
  966. # ============================================================
  967. # 阶段5: 生成 Word 文档 + 下载链接
  968. # ============================================================
  969. yield _sse_event("progress",
  970. message="正在生成 Word 审查报告...",
  971. agent="system")
  972. download_url = None
  973. if full_report.strip():
  974. # ── 保存审查报告到数据库(历史查询)──
  975. try:
  976. save_message(session_id, "assistant", full_report)
  977. # 更新会话标题为煤矿名称(更易识别)
  978. if mine_name:
  979. update_session_title(session_id, f"配风计划审查: {mine_name}")
  980. print(f"[审查] 报告已保存到会话 {session_id}")
  981. except Exception as e:
  982. print(f"[审查] 保存报告到数据库失败: {e}")
  983. try:
  984. # 在 executor 中运行 docx 转换(pypandoc 是同步的)
  985. # 使用煤矿名称作为文件名标题
  986. _, download_url = await loop.run_in_executor(
  987. None,
  988. lambda: save_review_report(full_report, title=mine_name),
  989. )
  990. print(f"[报告] Word 文档已生成,下载URL: {download_url}")
  991. yield _sse_event("progress",
  992. message=f"Word 报告已生成,点击下载",
  993. agent="system",
  994. download_url=download_url)
  995. except Exception as e:
  996. import traceback
  997. print(f"[报告] Word 生成失败: {e}")
  998. traceback.print_exc()
  999. yield _sse_event("progress",
  1000. message=f"Word 报告生成失败({e}),但审查文本已完整生成",
  1001. agent="system")
  1002. # ============================================================
  1003. # 阶段6: 完成
  1004. # ============================================================
  1005. yield _sse_event("done",
  1006. session_id=session_id,
  1007. download_url=download_url,
  1008. duration_ms=int((time.time() - overall_start) * 1000))
  1009. # 打印完整报告到控制台
  1010. print("\n" + "=" * 60)
  1011. print("配风计划审查完成")
  1012. print("=" * 60)
  1013. print(full_report)
  1014. print("=" * 60)
  1015. except Exception as e:
  1016. traceback.print_exc()
  1017. yield _sse_event("error", message=f"审查过程出错: {str(e)}")
  1018. yield _sse_event("done", session_id=session_id)
  1019. finally:
  1020. # 清理临时文件
  1021. if pdf_path and os.path.exists(pdf_path):
  1022. try:
  1023. os.unlink(pdf_path)
  1024. except OSError:
  1025. pass
  1026. def _extract_text_content(msg_obj) -> str | None:
  1027. """从 LangChain 消息对象中提取文本内容。"""
  1028. if isinstance(msg_obj, dict):
  1029. return msg_obj.get("content")
  1030. elif hasattr(msg_obj, "content"):
  1031. raw = getattr(msg_obj, "content", None)
  1032. if isinstance(raw, str):
  1033. return raw
  1034. elif isinstance(raw, list):
  1035. parts = []
  1036. for block in raw:
  1037. if isinstance(block, dict) and block.get("type") == "text":
  1038. parts.append(block.get("text", ""))
  1039. elif hasattr(block, "type") and getattr(block, "type", "") == "text":
  1040. parts.append(getattr(block, "text", ""))
  1041. return "".join(parts) if parts else None
  1042. return None
  1043. def _parse_todo_json(text: str) -> list | None:
  1044. """从 write_todos 输出文本中提取 todo 列表。
  1045. write_todos 输出格式: "Updated todo list to [{'content': '...', 'status': '...'}, ...]"
  1046. 返回 JSON-serializable list of dicts,失败返回 None。
  1047. """
  1048. import re
  1049. import ast
  1050. match = re.search(r"\[.*\]", text, re.DOTALL)
  1051. if not match:
  1052. return None
  1053. try:
  1054. python_list = ast.literal_eval(match.group())
  1055. if isinstance(python_list, list):
  1056. return python_list
  1057. except (ValueError, SyntaxError):
  1058. pass
  1059. return None
  1060. # ============================================================
  1061. # 汇总输出质量保障(防止 LLM 懒输出/内容丢失)
  1062. # ============================================================
  1063. def _is_lazy_summary(text: str) -> bool:
  1064. """检测 LLM 汇总输出是否为懒输出(内容过短或仅含托词)。
  1065. 懒输出的典型特征:
  1066. - 总长度极短(< 100 字符)且无结构化内容
  1067. - 包含"完整呈现/全量输出/无省略"等托词但实际内容极少
  1068. 注意:阈值不能太高,因为 LLM 可能输出短但有效的元信息(100-300 字符的概况+违规+建议)。
  1069. Returns:
  1070. True 若检测到懒输出
  1071. """
  1072. if not text or not text.strip():
  1073. return True
  1074. stripped = text.strip()
  1075. # 极短(< 80 字符):几乎不可能是有效报告
  1076. if len(stripped) < 80:
  1077. return True
  1078. # 匹配典型托词模式:LLM 输出了"完整呈现"之类的敷衍话
  1079. import re
  1080. lazy_patterns = [
  1081. r"以上为本次.*完整.*(?:报告|审查)",
  1082. r"所有.*子智能体.*已.*(?:完整|全量).*呈现",
  1083. r"全量.*逐条.*逐表.*完整",
  1084. r"以上.*审查.*完成[。.]?$",
  1085. r"完整.*最终报告.*无.*(?:省略|摘要|删减)",
  1086. r"详细内容.*见.*(?:附件|原始输出|子智能体)",
  1087. ]
  1088. for pattern in lazy_patterns:
  1089. if re.search(pattern, stripped):
  1090. # 匹配了托词模式:如果文本 < 500 字符,大概率是纯敷衍
  1091. if len(stripped) < 500:
  1092. return True
  1093. # 即使 > 500 字符,如果托词占据了 > 30% 的内容,也很可疑
  1094. # (正常输出的结尾语不会这么长)
  1095. match = re.search(pattern, stripped)
  1096. if match and len(match.group()) > len(stripped) * 0.3:
  1097. return True
  1098. # 检查内容密度:如果文本中实质性内容行极少(< 3 行非标题/分隔符内容),
  1099. # 且总长度 < 200 字符,判定为懒输出
  1100. lines = [l.strip() for l in stripped.split("\n")]
  1101. content_lines = [
  1102. l for l in lines
  1103. if l
  1104. and not l.startswith("#")
  1105. and not l.startswith("---")
  1106. and not l.startswith("|") # 表格分隔行不算实质性内容
  1107. and l not in ("---", "|---|---", "")
  1108. ]
  1109. if len(content_lines) < 3 and len(stripped) < 200:
  1110. return True
  1111. return False
  1112. def _extract_key_findings(text: str, max_chars: int = 2000) -> str:
  1113. """从子智能体完整输出中提取关键发现摘要。
  1114. 策略:取前 max_chars 字符(子智能体通常在开头给出审查结论),
  1115. 并额外提取后续包含审查关键词的重要行。
  1116. Args:
  1117. text: 子智能体的完整输出文本
  1118. max_chars: 基础摘要的最大字符数
  1119. Returns:
  1120. 压缩后的关键发现摘要(远小于原文,但保留核心结论)
  1121. """
  1122. if not text:
  1123. return "(无内容)"
  1124. # 清理换行
  1125. text = text.replace("\r\n", "\n").replace("\r", "\n")
  1126. if len(text) <= max_chars:
  1127. return text
  1128. head = text[:max_chars]
  1129. # 额外提取包含关键词的重要行(从 max_chars 之后的部分)
  1130. keywords = [
  1131. "问题", "不符", "缺失", "错误", "偏差", "违规",
  1132. "红线", "结论", "判定", "审查意见", "不一致",
  1133. ]
  1134. important_lines: list = []
  1135. for line in text[max_chars:].split("\n"):
  1136. stripped = line.strip()
  1137. if any(kw in stripped for kw in keywords) and len(stripped) > 8:
  1138. important_lines.append(stripped)
  1139. if len(important_lines) >= 15: # 最多收集 15 行
  1140. break
  1141. if important_lines:
  1142. head += "\n\n...[后续关键发现]...\n" + "\n".join(important_lines)
  1143. return head
  1144. def _assemble_report_fallback(
  1145. raw_form: str,
  1146. raw_data: str,
  1147. raw_calc: str,
  1148. mine_name: str = "",
  1149. ) -> str:
  1150. """LLM 懒输出时的兜底方案:用模板组装完整报告。
  1151. 子智能体原始输出直接嵌入第 2/3/4 节,元信息用简单模板填充。
  1152. 确保即使 LLM 完全失败,审查报告的实质内容也 100% 不丢失。
  1153. Args:
  1154. raw_form: 形式审查子智能体完整输出
  1155. raw_data: 数据一致性审查子智能体完整输出
  1156. raw_calc: 计算核验子智能体完整输出
  1157. mine_name: 煤矿名称(可选)
  1158. Returns:
  1159. 完整的 Markdown 审查报告
  1160. """
  1161. mine_str = mine_name or "(待补充)"
  1162. title = f"# {mine_str}配风计划审查报告" if mine_name else "# 配风计划审查报告"
  1163. report = f"""{title}
  1164. ## 一、审查概况
  1165. | 项目 | 内容 |
  1166. |------|------|
  1167. | 煤矿名称 | {mine_str} |
  1168. | 审查结论 | 请参见以下各节中3个子智能体的逐项审查详情 |
  1169. ## 二、形式审查结果
  1170. {raw_form}
  1171. ## 三、数据一致性审查结果
  1172. {raw_data}
  1173. ## 四、计算核验结果
  1174. {raw_calc}
  1175. ## 五、违规项汇总
  1176. > ⚠️ LLM 自动汇总生成失败,以下为系统自动兜底。请参见以上各节中标注的"不符""缺失""违规""红线"等标记,逐一核实。
  1177. (请根据以上各节中标注的具体问题进行人工汇总)
  1178. ## 六、修改建议
  1179. > ⚠️ LLM 自动生成失败。请参见以上各节中各子智能体给出的具体审查意见和修改建议。
  1180. """
  1181. return report
  1182. def _chunk_text_for_sse(text: str, chunk_size: int = 2000):
  1183. """将大文本分块,逐块 yield SSE token 事件。
  1184. 用于子智能体原始输出直接嵌入时避免单次 SSE 事件过大导致前端卡顿。
  1185. Args:
  1186. text: 要分块的文本
  1187. chunk_size: 每块最大字符数
  1188. Yields:
  1189. SSE 事件字符串
  1190. """
  1191. for i in range(0, len(text), chunk_size):
  1192. yield _sse_event("token", content=text[i:i + chunk_size])