controller.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. """Plan-and-Execute Controller Agent:动态规划执行路径并调度专职 Agent
  2. 核心职责:
  3. - Plan 阶段:调用 LLM 生成动态执行计划(步骤列表),失败时回退默认七步
  4. - Execute 阶段:逐步执行计划,支持并行调度、动态调整、异常降级
  5. - Controller 自主决定调用哪个 Agent/工具,体现 Plan-and-Execute 框架
  6. """
  7. from __future__ import annotations
  8. import asyncio
  9. import json
  10. import logging
  11. import os
  12. import re
  13. from typing import Any, Callable, Optional
  14. from backend.agents.specialized import build_all_specialized_agents
  15. from backend.config import settings
  16. from backend.llm.client import DeepSeekClient
  17. from backend.llm.json_utils import parse_json_safe
  18. from backend.memory.manager import MemoryManager
  19. from backend.storage.paper_library import compute_paper_id, get_paper_library
  20. from backend.tools.base import ToolRegistry
  21. logger = logging.getLogger(__name__)
  22. # Agent 名称 → 前端进度 stage 映射(与 StepStage 枚举值一致)
  23. AGENT_STAGE_MAP: dict[str, str] = {
  24. "PaperParser": "step1_parse",
  25. "Extractor": "step2_extract",
  26. "Indexer": "step3_index",
  27. "GapAnalyzer": "step4_gap",
  28. "InnovationGenerator": "step5_innovation",
  29. "ExperimentDesigner": "step6_experiment",
  30. "Integration": "step7_integrate",
  31. }
  32. # 默认七步计划模板(LLM 生成失败时的兜底)
  33. DEFAULT_PLAN: list[dict] = [
  34. {
  35. "step": 1,
  36. "agent": "PaperParser",
  37. "action": "扫描文件夹并解析所有 PDF 论文为结构化文本",
  38. "depends_on": [],
  39. },
  40. {
  41. "step": 2,
  42. "agent": "Extractor",
  43. "action": "对每篇已解析论文抽取结构化字段",
  44. "depends_on": [1],
  45. },
  46. {
  47. "step": 3,
  48. "agent": "Indexer",
  49. "action": "对已解析论文构建向量索引",
  50. "depends_on": [1],
  51. },
  52. {
  53. "step": 4,
  54. "agent": "GapAnalyzer",
  55. "action": "跨论文综合分析识别研究空白",
  56. "depends_on": [2],
  57. },
  58. {
  59. "step": 5,
  60. "agent": "InnovationGenerator",
  61. "action": "针对 Gap 生成创新点并筛选",
  62. "depends_on": [4],
  63. },
  64. {
  65. "step": 6,
  66. "agent": "ExperimentDesigner",
  67. "action": "为创新点设计实验方案",
  68. "depends_on": [5],
  69. },
  70. {
  71. "step": 7,
  72. "agent": "Integration",
  73. "action": "整合所有结果输出最终研究提案",
  74. "depends_on": [6],
  75. },
  76. ]
  77. # progress_callback 类型别名
  78. ProgressCallback = Callable[[str, str, str, float, Optional[dict]], Any]
  79. class Controller:
  80. """Plan-and-Execute Controller:规划执行路径并逐步调度专职 Agent
  81. Controller 自主决定调用哪个 Agent/工具,而非硬编码固定流程。
  82. 每步执行后根据结果动态调整剩余计划,支持并行调度与异常降级。
  83. """
  84. def __init__(
  85. self,
  86. client: DeepSeekClient,
  87. registry: ToolRegistry,
  88. memory: MemoryManager,
  89. ) -> None:
  90. self.client = client
  91. self.registry = registry
  92. self.memory = memory
  93. # 初始化 6 个专职 Agent
  94. self.agents = build_all_specialized_agents(client, registry)
  95. # 执行状态
  96. self.plan: list[dict] = []
  97. self.step_results: dict[int, dict] = {}
  98. self.tool_call_records: list[dict] = []
  99. self.degraded_steps: list[dict] = []
  100. # 步骤1 产出的已解析论文列表,供步骤2 并行抽取使用
  101. self._parsed_papers: list[dict] = []
  102. # 步骤2 产出的已抽取记录列表,供步骤4 Gap 分析使用
  103. self._extracted_records: list[dict] = []
  104. # 用户研究方向(步骤5 创新生成时注入提示词)
  105. self.research_direction: Optional[str] = None
  106. # 论文库单例
  107. self._paper_library = get_paper_library()
  108. # ------------------------------------------------------------------ #
  109. # Plan 阶段
  110. # ------------------------------------------------------------------ #
  111. async def plan_task(self, folder_path: str) -> list[dict]:
  112. """Plan 阶段:调用 LLM 生成动态执行计划
  113. 让 LLM 根据任务自主规划步骤顺序/增减,体现动态编排。
  114. LLM 调用失败或输出无效时回退到默认七步计划。
  115. Args:
  116. folder_path: 待分析的 PDF 文件夹路径
  117. Returns:
  118. 计划列表,每步含 {step, agent, action, depends_on}
  119. """
  120. agent_descriptions = "\n".join(
  121. f"- {name}:{cls.__doc__ or ''}"
  122. for name, cls in [
  123. ("PaperParser", "扫描文件夹并解析 PDF"),
  124. ("Extractor", "单篇论文结构化抽取"),
  125. ("Indexer", "向量索引构建"),
  126. ("GapAnalyzer", "跨论文 Gap 识别"),
  127. ("InnovationGenerator", "创新点生成与筛选"),
  128. ("ExperimentDesigner", "实验方案设计"),
  129. ("Integration", "整合输出研究提案"),
  130. ]
  131. )
  132. prompt = (
  133. f"你是论文创新 Agent 的 Controller。请为以下任务生成动态执行计划。\n\n"
  134. f"任务:分析文件夹 {folder_path} 中的 PDF 论文,"
  135. f"识别研究空白,生成 2-3 个创新点并设计实验方案。\n\n"
  136. f"可用 Agent:\n{agent_descriptions}\n\n"
  137. f"请生成执行计划,输出 JSON 数组,每个元素含:\n"
  138. f"- step: 步骤序号(整数)\n"
  139. f"- agent: Agent 名称(上述之一)\n"
  140. f"- action: 该步骤具体任务描述\n"
  141. f"- depends_on: 依赖的步骤序号列表\n\n"
  142. f"你可以根据任务自主调整顺序或增减步骤。"
  143. f"默认链路:解析→抽取→索引→Gap分析→创新生成→实验设计→整合。\n"
  144. f"严格只输出 JSON 数组,不要其他文本。"
  145. )
  146. messages = [
  147. {
  148. "role": "system",
  149. "content": "你是 Agent 编排器,负责生成可执行的动态计划。只输出 JSON。",
  150. },
  151. {"role": "user", "content": prompt},
  152. ]
  153. try:
  154. response = await self.client.chat(messages=messages)
  155. content = response.choices[0].message.content or ""
  156. raw_plan = parse_json_safe(content)
  157. if isinstance(raw_plan, list) and len(raw_plan) > 0:
  158. normalized = self._normalize_plan(raw_plan)
  159. if normalized:
  160. logger.info("LLM 生成计划成功,共 %d 步", len(normalized))
  161. self.plan = normalized
  162. return normalized
  163. logger.warning("LLM 计划输出无效,回退默认计划")
  164. except Exception as exc:
  165. logger.warning("LLM 生成计划失败,回退默认计划: %s", exc)
  166. # 兜底:默认七步计划
  167. default = [dict(s) for s in DEFAULT_PLAN]
  168. default[0]["action"] = f"扫描文件夹 {folder_path} 并解析所有 PDF 论文为结构化文本"
  169. self.plan = default
  170. return default
  171. def _normalize_plan(self, plan: list) -> list[dict]:
  172. """规范化 LLM 输出的计划:补全字段、过滤无效项"""
  173. normalized: list[dict] = []
  174. for idx, item in enumerate(plan):
  175. if not isinstance(item, dict):
  176. continue
  177. agent = str(item.get("agent", "")).strip()
  178. action = str(item.get("action", "")).strip()
  179. if not agent or not action:
  180. continue
  181. step = item.get("step", idx + 1)
  182. depends_on = item.get("depends_on", [])
  183. if not isinstance(depends_on, list):
  184. depends_on = []
  185. normalized.append(
  186. {
  187. "step": step,
  188. "agent": agent,
  189. "action": action,
  190. "depends_on": depends_on,
  191. }
  192. )
  193. return normalized
  194. # ------------------------------------------------------------------ #
  195. # Execute 阶段
  196. # ------------------------------------------------------------------ #
  197. async def execute_plan(
  198. self,
  199. plan: list[dict],
  200. progress_callback: Optional[ProgressCallback] = None,
  201. post_step_hook: Optional[Callable] = None,
  202. ) -> dict:
  203. """Execute 阶段:逐步执行计划,动态调整,并行调度,异常降级
  204. Args:
  205. plan: 计划列表
  206. progress_callback: 进度回调 async (stage, status, message, progress, payload)
  207. post_step_hook: 步骤后钩子 async (step, result) -> result,用于插入 Reflexion
  208. Returns:
  209. {steps_results, tool_call_records, degraded_steps}
  210. """
  211. remaining = list(plan)
  212. total = max(len(remaining), 1)
  213. completed = 0
  214. while remaining:
  215. step = remaining.pop(0)
  216. step_num = step.get("step", completed + 1)
  217. agent_name = step.get("agent", "")
  218. action = step.get("action", "")
  219. progress = completed / total
  220. # 推送 running 进度
  221. await self._emit_progress(
  222. progress_callback, agent_name, "running", action, progress
  223. )
  224. # 构建上下文
  225. context = self._build_context(step)
  226. try:
  227. result = await self._execute_step(step, context, progress_callback)
  228. # 步骤后钩子(供 WorkflowOrchestrator 插入 Reflexion 自校验)
  229. if post_step_hook is not None:
  230. try:
  231. hooked = await post_step_hook(step, result)
  232. if hooked is not None:
  233. result = hooked
  234. except Exception as exc:
  235. logger.warning("post_step_hook 执行失败: %s", exc)
  236. self.step_results[step_num] = result
  237. self.tool_call_records.extend(result.get("tool_calls", []))
  238. # 动态调整剩余计划
  239. remaining = self._adjust_plan(remaining, step, result)
  240. await self._emit_progress(
  241. progress_callback,
  242. agent_name,
  243. "done",
  244. f"步骤 {step_num}({agent_name})完成",
  245. (completed + 1) / total,
  246. {"step": step_num, "agent": agent_name},
  247. )
  248. except Exception as exc:
  249. logger.error(
  250. "步骤 %d(%s)执行失败: %s", step_num, agent_name, exc, exc_info=True
  251. )
  252. self.step_results[step_num] = {
  253. "agent": agent_name,
  254. "result": "",
  255. "tool_calls": [],
  256. "error": str(exc),
  257. }
  258. # 评估是否降级
  259. degraded = self._evaluate_degradation(agent_name, str(exc))
  260. if degraded:
  261. self.degraded_steps.append(degraded)
  262. await self._emit_progress(
  263. progress_callback,
  264. agent_name,
  265. "degraded",
  266. f"步骤 {step_num} 降级: {degraded['reason']}",
  267. (completed + 1) / total,
  268. {"step": step_num, "degradation": degraded},
  269. )
  270. else:
  271. await self._emit_progress(
  272. progress_callback,
  273. agent_name,
  274. "failed",
  275. f"步骤 {step_num} 失败: {exc}",
  276. (completed + 1) / total,
  277. {"step": step_num, "error": str(exc)},
  278. )
  279. completed += 1
  280. total = completed + len(remaining)
  281. return {
  282. "steps_results": self.step_results,
  283. "tool_call_records": self.tool_call_records,
  284. "degraded_steps": self.degraded_steps,
  285. }
  286. async def _execute_step(
  287. self,
  288. step: dict,
  289. context: str,
  290. progress_callback: Optional[ProgressCallback] = None,
  291. ) -> dict:
  292. """执行单个步骤:根据 agent 名称选择执行策略"""
  293. agent_name = step.get("agent", "")
  294. action = step.get("action", "")
  295. # Integration 步骤:Controller 直接调用 LLM 整合
  296. if agent_name == "Integration" or agent_name not in self.agents:
  297. return await self._execute_integration(action, context)
  298. # Extractor 步骤:若已有多篇解析论文,并行抽取
  299. if agent_name == "Extractor" and self._parsed_papers:
  300. return await self._execute_extraction_parallel(action, context)
  301. # GapAnalyzer 步骤:直接用预处理阶段的抽取记录调用工具
  302. if agent_name == "GapAnalyzer" and self._extracted_records:
  303. return await self._execute_gap_analysis(action, context)
  304. # InnovationGenerator 步骤:直接调用工具并注入 research_direction
  305. if agent_name == "InnovationGenerator":
  306. return await self._execute_innovation_generation(action, context)
  307. # ExperimentDesigner 步骤:直接调用工具并注入 innovations
  308. if agent_name == "ExperimentDesigner":
  309. return await self._execute_experiment_design(action, context)
  310. # 其他步骤:单 Agent 执行
  311. return await self._execute_single(agent_name, action, context)
  312. async def _execute_single(
  313. self, agent_name: str, action: str, context: str
  314. ) -> dict:
  315. """单 Agent 执行步骤"""
  316. agent = self.agents.get(agent_name)
  317. if agent is None:
  318. raise ValueError(f"未知 Agent: {agent_name}")
  319. result = await agent.run(task=action, context=context)
  320. # PaperParser 完成后,收集已解析论文供后续并行抽取
  321. if agent_name == "PaperParser":
  322. await self._collect_parsed_papers(result, action)
  323. return result
  324. async def _execute_extraction_parallel(
  325. self, action: str, context: str
  326. ) -> dict:
  327. """并行抽取多篇论文结构化字段
  328. 使用 asyncio.gather + semaphore(MAX_CONCURRENT_PAPERS) 并行调度。
  329. 每篇论文独立处理,失败隔离不影响其余。
  330. """
  331. if not self._parsed_papers:
  332. # 无已解析论文,降级为单 Agent 执行
  333. logger.warning("无已解析论文,Extractor 降级为单 Agent 执行")
  334. return await self._execute_single("Extractor", action, context)
  335. semaphore = asyncio.Semaphore(settings.MAX_CONCURRENT_PAPERS)
  336. agent = self.agents["Extractor"]
  337. async def extract_one(paper: dict) -> dict:
  338. """单篇论文抽取任务:直接调用 extract_paper_structure 工具(绕过模型 Function Calling)
  339. 说明:参数已由 Controller 确定(paper_path + parsed_paper),
  340. 让模型再选一次工具反而会出现参数传递错误(DeepSeek 有时把整段 JSON 当字符串传),
  341. 浪费迭代次数。这里直接用 ToolLoop 调用工具,再让模型基于结果生成摘要。
  342. """
  343. async with semaphore:
  344. paper_path = paper.get("path", "")
  345. try:
  346. # 1) 直接调用 extract_paper_structure 工具(参数已知)
  347. extract_fn = self.registry.get_callable("extract_paper_structure")
  348. if extract_fn is None:
  349. raise RuntimeError("extract_paper_structure 工具未注册")
  350. import time as _time
  351. _t0 = _time.perf_counter()
  352. extraction_result = await self._invoke_tool(
  353. "extract_paper_structure",
  354. paper_path=paper_path,
  355. parsed_paper=paper,
  356. )
  357. _duration = round(_time.perf_counter() - _t0, 3)
  358. # 2) 记录工具调用
  359. self.tool_call_records.append(
  360. {
  361. "tool_name": "extract_paper_structure",
  362. "args_summary": json.dumps(
  363. {"paper_path": paper_path}, ensure_ascii=False
  364. )[:200],
  365. "success": True,
  366. "duration_sec": _duration,
  367. "error": None,
  368. }
  369. )
  370. # 3) 让 LLM 基于抽取结果生成一段摘要(用于前端展示 + 下游 Agent)
  371. if isinstance(extraction_result, str):
  372. extraction_text = extraction_result
  373. else:
  374. extraction_text = json.dumps(
  375. extraction_result, ensure_ascii=False, default=str
  376. )
  377. summary_messages = [
  378. {
  379. "role": "system",
  380. "content": (
  381. "你是论文结构化抽取结果的整理助手。"
  382. "请基于给定的抽取结果,输出 200 字以内的核心摘要,"
  383. "包含 title/task_problem/method/key_contributions 四项要点。"
  384. ),
  385. },
  386. {
  387. "role": "user",
  388. "content": f"论文路径:{paper_path}\n\n抽取结果:\n{extraction_text[:6000]}",
  389. },
  390. ]
  391. try:
  392. resp = await self.client.chat(messages=summary_messages)
  393. summary_text = resp.choices[0].message.content or extraction_text[:2000]
  394. except Exception:
  395. # LLM 摘要失败时直接用原始抽取结果
  396. summary_text = extraction_text[:2000]
  397. return {
  398. "agent": "Extractor",
  399. "result": summary_text,
  400. "tool_calls": [
  401. {
  402. "tool_name": "extract_paper_structure",
  403. "args_summary": json.dumps(
  404. {"paper_path": paper_path}, ensure_ascii=False
  405. )[:200],
  406. "success": True,
  407. "duration_sec": _duration,
  408. "error": None,
  409. "result": extraction_result, # 供 ReportAgent 聚合使用
  410. }
  411. ],
  412. "paper_path": paper_path,
  413. "extraction": extraction_result,
  414. }
  415. except Exception as exc:
  416. logger.warning("论文 %s 抽取失败: %s", paper_path, exc)
  417. return {
  418. "agent": "Extractor",
  419. "result": "",
  420. "tool_calls": [],
  421. "error": str(exc),
  422. "paper_path": paper_path,
  423. }
  424. # 并行调度所有论文抽取
  425. results = await asyncio.gather(
  426. *[extract_one(p) for p in self._parsed_papers]
  427. )
  428. # 合并结果与工具调用记录
  429. all_tool_calls: list[dict] = []
  430. result_parts: list[str] = []
  431. success_count = 0
  432. for r in results:
  433. all_tool_calls.extend(r.get("tool_calls", []))
  434. result_text = r.get("result", "")
  435. if result_text:
  436. result_parts.append(result_text)
  437. success_count += 1
  438. logger.info(
  439. "并行抽取完成: %d/%d 篇成功", success_count, len(self._parsed_papers)
  440. )
  441. return {
  442. "agent": "Extractor",
  443. "result": "\n---\n".join(result_parts),
  444. "tool_calls": all_tool_calls,
  445. "papers_count": len(results),
  446. "success_count": success_count,
  447. "individual_results": results,
  448. }
  449. async def _execute_gap_analysis(self, action: str, context: str) -> dict:
  450. """GapAnalyzer 步骤:直接用预处理阶段的抽取记录调用 analyze_gaps 工具
  451. 绕过 Function Calling,避免参数传递错误(与 Extractor 并行抽取同理)。
  452. """
  453. import time as _time
  454. if not self._extracted_records:
  455. logger.warning("无已抽取记录,GapAnalyzer 降级为单 Agent 执行")
  456. return await self._execute_single("GapAnalyzer", action, context)
  457. _t0 = _time.perf_counter()
  458. try:
  459. gaps_result = await self._invoke_tool(
  460. "analyze_gaps", papers_records=self._extracted_records
  461. )
  462. _duration = round(_time.perf_counter() - _t0, 3)
  463. tool_call = {
  464. "tool_name": "analyze_gaps",
  465. "args_summary": json.dumps(
  466. {"papers_count": len(self._extracted_records)}, ensure_ascii=False
  467. )[:200],
  468. "success": True,
  469. "duration_sec": _duration,
  470. "error": None,
  471. "result": gaps_result,
  472. }
  473. # 生成摘要文本供前端展示与下游 Integration 使用
  474. gaps = gaps_result.get("gaps", []) if isinstance(gaps_result, dict) else []
  475. summary_text = f"识别到 {len(gaps)} 个研究空白(Gap)"
  476. return {
  477. "agent": "GapAnalyzer",
  478. "result": summary_text,
  479. "tool_calls": [tool_call],
  480. "gaps_count": len(gaps),
  481. }
  482. except Exception as exc:
  483. logger.error("Gap 分析失败: %s", exc)
  484. return {
  485. "agent": "GapAnalyzer",
  486. "result": "",
  487. "tool_calls": [],
  488. "error": str(exc),
  489. }
  490. async def _execute_innovation_generation(self, action: str, context: str) -> dict:
  491. """InnovationGenerator 步骤:直接调用 generate_innovations 工具,注入 research_direction
  492. 从上一个步骤(GapAnalyzer)的结果中提取 gaps,直接调用工具,
  493. 避免 Function Calling 不可靠地传递 research_direction 参数。
  494. """
  495. import time as _time
  496. # 从 step_results 中提取 gaps(GapAnalyzer 的 tool_calls 里)
  497. gaps: list[dict] = []
  498. for step_num, result in self.step_results.items():
  499. if not isinstance(result, dict):
  500. continue
  501. if result.get("agent") != "GapAnalyzer":
  502. continue
  503. for tc in result.get("tool_calls", []):
  504. if isinstance(tc, dict) and tc.get("tool_name") == "analyze_gaps":
  505. res = tc.get("result")
  506. if isinstance(res, dict):
  507. gaps = res.get("gaps", [])
  508. break
  509. if gaps:
  510. break
  511. if not gaps:
  512. logger.warning("无 Gap 数据,InnovationGenerator 跳过")
  513. return {
  514. "agent": "InnovationGenerator",
  515. "result": "无 Gap 数据,未生成创新点",
  516. "tool_calls": [],
  517. }
  518. _t0 = _time.perf_counter()
  519. try:
  520. innovations_result = await self._invoke_tool(
  521. "generate_innovations",
  522. gaps=gaps,
  523. research_direction=self.research_direction,
  524. )
  525. _duration = round(_time.perf_counter() - _t0, 3)
  526. tool_call = {
  527. "tool_name": "generate_innovations",
  528. "args_summary": json.dumps(
  529. {"gaps_count": len(gaps), "research_direction": self.research_direction or ""},
  530. ensure_ascii=False,
  531. )[:200],
  532. "success": True,
  533. "duration_sec": _duration,
  534. "error": None,
  535. "result": innovations_result,
  536. }
  537. innovations = innovations_result.get("innovations", []) if isinstance(innovations_result, dict) else []
  538. summary_text = f"生成 {len(innovations)} 个创新点"
  539. return {
  540. "agent": "InnovationGenerator",
  541. "result": summary_text,
  542. "tool_calls": [tool_call],
  543. "innovations_count": len(innovations),
  544. }
  545. except Exception as exc:
  546. logger.error("创新点生成失败: %s", exc)
  547. return {
  548. "agent": "InnovationGenerator",
  549. "result": "",
  550. "tool_calls": [],
  551. "error": str(exc),
  552. }
  553. async def _execute_experiment_design(self, action: str, context: str) -> dict:
  554. """ExperimentDesigner 步骤:直接调用 design_experiments 工具,注入 innovations
  555. 从上一个步骤(InnovationGenerator)的结果中提取 innovations,直接调用工具,
  556. 避免 Function Calling 不可靠地传递 innovations 参数(实测 LLM 经常漏传)。
  557. """
  558. import time as _time
  559. # 从 step_results 中提取 innovations(InnovationGenerator 的 tool_calls 里)
  560. innovations: list[dict] = []
  561. for step_num, result in self.step_results.items():
  562. if not isinstance(result, dict):
  563. continue
  564. if result.get("agent") != "InnovationGenerator":
  565. continue
  566. for tc in result.get("tool_calls", []):
  567. if isinstance(tc, dict) and tc.get("tool_name") == "generate_innovations":
  568. res = tc.get("result")
  569. if isinstance(res, dict):
  570. innovations = res.get("innovations", [])
  571. break
  572. if innovations:
  573. break
  574. if not innovations:
  575. logger.warning("无 Innovation 数据,ExperimentDesigner 跳过")
  576. return {
  577. "agent": "ExperimentDesigner",
  578. "result": "无创新点数据,未生成实验方案",
  579. "tool_calls": [],
  580. }
  581. _t0 = _time.perf_counter()
  582. try:
  583. plans_result = await self._invoke_tool(
  584. "design_experiments", innovations=innovations
  585. )
  586. _duration = round(_time.perf_counter() - _t0, 3)
  587. tool_call = {
  588. "tool_name": "design_experiments",
  589. "args_summary": json.dumps(
  590. {"innovations_count": len(innovations)}, ensure_ascii=False
  591. )[:200],
  592. "success": True,
  593. "duration_sec": _duration,
  594. "error": None,
  595. "result": plans_result,
  596. }
  597. plans = plans_result.get("experiment_plans", []) if isinstance(plans_result, dict) else []
  598. summary_text = f"为 {len(plans)} 个创新点设计了实验方案"
  599. return {
  600. "agent": "ExperimentDesigner",
  601. "result": summary_text,
  602. "tool_calls": [tool_call],
  603. "plans_count": len(plans),
  604. }
  605. except Exception as exc:
  606. logger.error("实验方案设计失败: %s", exc)
  607. return {
  608. "agent": "ExperimentDesigner",
  609. "result": "",
  610. "tool_calls": [],
  611. "error": str(exc),
  612. }
  613. async def _execute_integration(self, action: str, context: str) -> dict:
  614. """Integration 步骤:Controller 直接调用 LLM 整合所有步骤结果"""
  615. import time as _time
  616. _t0 = _time.perf_counter()
  617. parts: list[str] = []
  618. for step_num, result in self.step_results.items():
  619. result_text = (
  620. result.get("result", "") if isinstance(result, dict) else str(result)
  621. )
  622. if result_text:
  623. parts.append(f"## 步骤 {step_num} 结果\n{result_text[:3000]}")
  624. all_results = "\n\n".join(parts) if parts else context
  625. messages = [
  626. {
  627. "role": "system",
  628. "content": (
  629. "你是研究提案整合专家。请整合各步骤结果,"
  630. "输出结构化研究提案(背景综述/创新点论证/实验方案/参考文献溯源)。"
  631. ),
  632. },
  633. {
  634. "role": "user",
  635. "content": f"任务:{action}\n\n各步骤结果:\n{all_results[:10000]}",
  636. },
  637. ]
  638. try:
  639. _t_llm0 = _time.perf_counter()
  640. response = await self.client.chat(messages=messages)
  641. logger.info(
  642. "[Integration timing] LLM 整合调用: %.2fs",
  643. _time.perf_counter() - _t_llm0,
  644. )
  645. result_text = response.choices[0].message.content or ""
  646. except Exception as exc:
  647. logger.error("整合步骤失败: %s", exc)
  648. result_text = ""
  649. logger.info(
  650. "[Integration timing] 整合步骤总耗时: %.2fs, 输出 %d 字符",
  651. _time.perf_counter() - _t0, len(result_text),
  652. )
  653. return {
  654. "agent": "Integration",
  655. "result": result_text,
  656. "tool_calls": [],
  657. }
  658. async def _collect_parsed_papers(self, result: dict, action: str) -> None:
  659. """从 PaperParser 结果中收集已解析论文,供后续并行抽取使用
  660. 优先从结果文本解析 JSON;失败则直接调用 scan_folder + parse_pdf 工具获取。
  661. """
  662. # 尝试从结果文本中解析 JSON 论文列表
  663. text = result.get("result", "")
  664. papers = parse_json_safe(text)
  665. if isinstance(papers, list) and papers:
  666. self._parsed_papers = papers
  667. logger.info("从 PaperParser 结果收集到 %d 篇论文", len(papers))
  668. return
  669. # 兜底:从 action 提取文件夹路径,直接调用工具获取结构化论文
  670. folder_path = self._extract_folder_path(action)
  671. if not folder_path:
  672. logger.warning("无法从 action 提取文件夹路径,跳过论文收集")
  673. return
  674. try:
  675. scan_result = await self._invoke_tool("scan_folder", folder_path=folder_path)
  676. pdf_files = scan_result.get("pdf_files", [])
  677. logger.info("扫描到 %d 个 PDF 文件,开始解析", len(pdf_files))
  678. # 并行解析所有 PDF
  679. semaphore = asyncio.Semaphore(settings.MAX_CONCURRENT_PAPERS)
  680. async def parse_one(pdf_path: str) -> dict:
  681. async with semaphore:
  682. try:
  683. return await self._invoke_tool("parse_pdf", file_path=pdf_path)
  684. except Exception as exc:
  685. logger.warning("解析 %s 失败: %s", pdf_path, exc)
  686. return {"path": pdf_path, "error": str(exc)}
  687. parsed = await asyncio.gather(*[parse_one(p) for p in pdf_files])
  688. # 过滤掉解析失败的
  689. self._parsed_papers = [p for p in parsed if "error" not in p]
  690. logger.info("成功解析 %d 篇论文", len(self._parsed_papers))
  691. except Exception as exc:
  692. logger.error("收集已解析论文失败: %s", exc)
  693. self._parsed_papers = []
  694. def _extract_folder_path(self, action: str) -> str:
  695. """从 action 描述中提取文件夹路径"""
  696. # 匹配 "扫描文件夹 {path}" 或 "文件夹 {path}" 模式
  697. match = re.search(r"文件夹\s+([^\s,,。]+)", action)
  698. if match:
  699. return match.group(1)
  700. return ""
  701. async def _invoke_tool(self, tool_name: str, **kwargs) -> Any:
  702. """调用注册表中的工具(自动区分同步/异步)"""
  703. fn = self.registry.get_callable(tool_name)
  704. if fn is None:
  705. raise ValueError(f"工具 {tool_name} 未注册")
  706. if asyncio.iscoroutinefunction(fn):
  707. return await fn(**kwargs)
  708. return await asyncio.to_thread(fn, **kwargs)
  709. # ------------------------------------------------------------------ #
  710. # 动态调整与降级
  711. # ------------------------------------------------------------------ #
  712. def _adjust_plan(
  713. self, remaining: list[dict], step: dict, result: dict
  714. ) -> list[dict]:
  715. """根据当前步骤结果动态调整剩余计划
  716. - 抽取完全失败 → 跳过依赖它的 Gap 分析及后续步骤
  717. - 索引失败 → 不跳过后续步骤,但标记降级(GapAnalyzer 仅用结构化字段)
  718. """
  719. agent_name = step.get("agent", "")
  720. has_error = isinstance(result, dict) and bool(result.get("error"))
  721. if agent_name == "Extractor":
  722. # 抽取结果为空或全部失败 → 跳过后续依赖步骤
  723. success_count = result.get("success_count", 0) if isinstance(result, dict) else 0
  724. papers_count = result.get("papers_count", 0) if isinstance(result, dict) else 0
  725. if has_error or (papers_count > 0 and success_count == 0):
  726. logger.warning("抽取无有效结果,跳过 Gap 分析及后续步骤")
  727. remaining = [
  728. s
  729. for s in remaining
  730. if s.get("agent")
  731. not in ("GapAnalyzer", "InnovationGenerator", "ExperimentDesigner")
  732. ]
  733. if agent_name == "Indexer" and has_error:
  734. # 索引失败,后续 GapAnalyzer 仅用结构化字段(不跳过,仅记录降级)
  735. logger.info("索引失败,后续步骤将仅用结构化字段(跳过 RAG)")
  736. return remaining
  737. def _evaluate_degradation(
  738. self, agent_name: str, error: str
  739. ) -> Optional[dict]:
  740. """评估步骤失败是否可降级继续
  741. Returns:
  742. 降级记录 dict,或 None(不可降级)
  743. """
  744. if agent_name == "Indexer":
  745. return {
  746. "step": agent_name,
  747. "reason": f"向量索引构建失败: {error};降级为仅用结构化字段,跳过 RAG",
  748. "strategy": "skip_rag",
  749. }
  750. if agent_name == "InnovationGenerator":
  751. err_lower = error.lower()
  752. if "web_search" in err_lower or "search" in err_lower or "联网" in error:
  753. return {
  754. "step": agent_name,
  755. "reason": f"联网搜索失败: {error};降级为跳过新颖性去重",
  756. "strategy": "skip_novelty_check",
  757. }
  758. return None
  759. # ------------------------------------------------------------------ #
  760. # 辅助方法
  761. # ------------------------------------------------------------------ #
  762. def _build_context(self, step: dict) -> str:
  763. """构建步骤上下文:从依赖步骤的结果中提取"""
  764. depends_on = step.get("depends_on", [])
  765. if not depends_on:
  766. return ""
  767. parts: list[str] = []
  768. for dep in depends_on:
  769. if dep in self.step_results:
  770. result = self.step_results[dep]
  771. result_str = json.dumps(result, ensure_ascii=False, default=str)[
  772. :5000
  773. ]
  774. parts.append(f"步骤 {dep} 结果:\n{result_str}")
  775. return "\n\n".join(parts)
  776. async def _emit_progress(
  777. self,
  778. callback: Optional[ProgressCallback],
  779. agent_name: str,
  780. status: str,
  781. message: str,
  782. progress: float,
  783. payload: Optional[dict] = None,
  784. ) -> None:
  785. """推送进度事件到回调"""
  786. if callback is None:
  787. return
  788. stage = AGENT_STAGE_MAP.get(agent_name, agent_name)
  789. try:
  790. await callback(stage, status, message, progress, payload)
  791. except Exception as exc:
  792. logger.warning("进度回调执行失败: %s", exc)
  793. # ------------------------------------------------------------------ #
  794. # 预处理阶段(步骤1-3:解析 → 抽取 → 索引)
  795. # ------------------------------------------------------------------ #
  796. async def _preprocess_papers(
  797. self,
  798. folder_path: Optional[str] = None,
  799. paper_ids: Optional[list[str]] = None,
  800. progress_callback: Optional[ProgressCallback] = None,
  801. ) -> None:
  802. """预处理阶段:PDF 解析 → 结构化抽取 → 向量索引,带缓存复用
  803. 对每篇论文检查 PaperLibrary 中的预处理状态:
  804. - 已完成的步骤直接从磁盘加载(标记 cached)
  805. - 未完成的步骤执行后写盘并更新状态
  806. Args:
  807. folder_path: PDF 文件夹路径(与 paper_ids 二选一)
  808. paper_ids: 上传论文 ID 列表(与 folder_path 二选一)
  809. progress_callback: 进度回调
  810. """
  811. import time as _time
  812. # 1. 收集待处理论文文件路径列表
  813. paper_files: list[tuple[str, str]] = [] # [(file_path, filename), ...]
  814. if paper_ids:
  815. for pid in paper_ids:
  816. entry = self._paper_library.get(pid)
  817. if entry is None:
  818. logger.warning("论文 paper_id=%s 不在库中,跳过", pid[:12])
  819. continue
  820. file_path = entry.get("original_path", "")
  821. if file_path:
  822. paper_files.append((file_path, entry.get("filename", "")))
  823. elif folder_path:
  824. scan_result = await self._invoke_tool("scan_folder", folder_path=folder_path)
  825. pdf_files = scan_result.get("pdf_files", [])
  826. for fp in pdf_files:
  827. paper_files.append((fp, os.path.basename(fp)))
  828. else:
  829. logger.warning("未提供 folder_path 或 paper_ids,跳过预处理")
  830. return
  831. if not paper_files:
  832. logger.warning("未找到任何 PDF 文件")
  833. return
  834. _pre_t0 = _time.perf_counter()
  835. logger.info("预处理开始:共 %d 篇论文", len(paper_files))
  836. # 2. 步骤1:PDF 解析(带缓存)
  837. _parse_t0 = _time.perf_counter()
  838. await self._emit_progress(
  839. progress_callback, "PaperParser", "running",
  840. f"开始解析 {len(paper_files)} 篇 PDF", 0.0,
  841. )
  842. semaphore = asyncio.Semaphore(settings.MAX_CONCURRENT_PAPERS)
  843. all_cached_parse = True
  844. async def parse_one(file_path: str, filename: str) -> dict:
  845. nonlocal all_cached_parse
  846. async with semaphore:
  847. try:
  848. paper_id = compute_paper_id(file_path)
  849. # 注册到论文库
  850. source = "upload" if paper_ids else "folder"
  851. self._paper_library.register(paper_id, filename, source, file_path)
  852. entry = self._paper_library.get(paper_id)
  853. # 检查缓存
  854. if entry and entry.get("parse_status") == "done":
  855. from backend.tools.parse_pdf import load_parsed
  856. cached = load_parsed(paper_id)
  857. if cached and "error" not in cached:
  858. logger.info("论文 %s 解析结果命中缓存", file_path)
  859. return cached
  860. all_cached_parse = False
  861. # 执行解析
  862. parsed = await self._invoke_tool("parse_pdf", file_path=file_path)
  863. if "error" in parsed:
  864. self._paper_library.update_status(paper_id, parse_status="failed")
  865. return parsed
  866. # 写入缓存
  867. from backend.tools.parse_pdf import save_parsed
  868. save_parsed(paper_id, parsed)
  869. title = parsed.get("title", "") if isinstance(parsed, dict) else ""
  870. self._paper_library.update_status(
  871. paper_id, parse_status="done", title=title
  872. )
  873. return parsed
  874. except Exception as exc:
  875. logger.error("解析 %s 失败: %s", file_path, exc)
  876. return {"error": f"解析失败: {exc}", "path": file_path}
  877. parsed_results = await asyncio.gather(
  878. *[parse_one(fp, fn) for fp, fn in paper_files]
  879. )
  880. _parse_done = _time.perf_counter()
  881. logger.info(
  882. "[预处理 timing] 步骤1 解析完成: %.2fs (含 gather),成功 %d/%d",
  883. _parse_done - _parse_t0,
  884. len([p for p in parsed_results if "error" not in p]),
  885. len(parsed_results),
  886. )
  887. self._parsed_papers = [p for p in parsed_results if "error" not in p]
  888. parse_status = "cached" if all_cached_parse and self._parsed_papers else "done"
  889. await self._emit_progress(
  890. progress_callback, "PaperParser", parse_status,
  891. f"解析完成:{len(self._parsed_papers)}/{len(paper_files)} 篇成功", 0.15,
  892. )
  893. if not self._parsed_papers:
  894. logger.error("无有效解析结果,终止预处理")
  895. return
  896. # 3. 步骤2:结构化抽取(带缓存)
  897. _extract_t0 = _time.perf_counter()
  898. await self._emit_progress(
  899. progress_callback, "Extractor", "running",
  900. f"开始抽取 {len(self._parsed_papers)} 篇论文结构化字段", 0.2,
  901. )
  902. all_cached_extract = True
  903. async def extract_one(paper: dict) -> dict:
  904. nonlocal all_cached_extract
  905. async with semaphore:
  906. paper_path = paper.get("path", "")
  907. try:
  908. paper_id = compute_paper_id(paper_path)
  909. entry = self._paper_library.get(paper_id)
  910. # 检查缓存
  911. if entry and entry.get("extract_status") == "done":
  912. from backend.tools.extract_paper_structure import load_record
  913. cached = load_record(paper_path, paper_id=paper_id)
  914. if cached:
  915. logger.info("论文 %s 抽取结果命中缓存", paper_path)
  916. return cached
  917. all_cached_extract = False
  918. # 执行抽取
  919. _t0 = _time.perf_counter()
  920. extraction = await self._invoke_tool(
  921. "extract_paper_structure",
  922. paper_path=paper_path,
  923. parsed_paper=paper,
  924. )
  925. _duration = round(_time.perf_counter() - _t0, 3)
  926. if isinstance(extraction, dict) and extraction.get("path"):
  927. # 写入缓存
  928. from backend.tools.extract_paper_structure import save_record
  929. save_record(extraction, paper_id=paper_id)
  930. self._paper_library.update_status(paper_id, extract_status="done")
  931. # 记录工具调用(供 _build_final_results 聚合)
  932. self.tool_call_records.append({
  933. "tool_name": "extract_paper_structure",
  934. "args_summary": json.dumps(
  935. {"paper_path": paper_path}, ensure_ascii=False
  936. )[:200],
  937. "success": True,
  938. "duration_sec": _duration,
  939. "error": None,
  940. "result": extraction,
  941. })
  942. return extraction
  943. except Exception as exc:
  944. logger.warning("论文 %s 抽取失败: %s", paper_path, exc)
  945. return {}
  946. extract_results = await asyncio.gather(
  947. *[extract_one(p) for p in self._parsed_papers]
  948. )
  949. _extract_done = _time.perf_counter()
  950. logger.info(
  951. "[预处理 timing] 步骤2 抽取完成: %.2fs (含 gather),成功 %d/%d",
  952. _extract_done - _extract_t0,
  953. len([r for r in extract_results if r and "path" in r]),
  954. len(extract_results),
  955. )
  956. self._extracted_records = [r for r in extract_results if r and "path" in r]
  957. extract_status = "cached" if all_cached_extract and self._extracted_records else "done"
  958. await self._emit_progress(
  959. progress_callback, "Extractor", extract_status,
  960. f"抽取完成:{len(self._extracted_records)}/{len(self._parsed_papers)} 篇成功", 0.4,
  961. )
  962. # 将抽取阶段的 tool_calls 存入 step_results,供 _build_final_results 聚合
  963. _t_agg0 = _time.perf_counter()
  964. extract_tool_calls = [
  965. tc for tc in self.tool_call_records
  966. if tc.get("tool_name") == "extract_paper_structure"
  967. ]
  968. self.step_results[2] = {
  969. "agent": "Extractor",
  970. "result": f"抽取完成:{len(self._extracted_records)} 篇",
  971. "tool_calls": extract_tool_calls,
  972. "papers_count": len(self._parsed_papers),
  973. "success_count": len(self._extracted_records),
  974. }
  975. # 4. 步骤3:向量索引构建(带去重)
  976. _index_t0 = _time.perf_counter()
  977. logger.info(
  978. "[预处理 timing] 抽取→索引间隔: %.2fs (聚合 step_results + emit_progress)",
  979. _index_t0 - _extract_done,
  980. )
  981. await self._emit_progress(
  982. progress_callback, "Indexer", "running",
  983. "开始构建向量索引", 0.45,
  984. )
  985. all_cached_index = True
  986. papers_to_index: list[dict] = []
  987. _dedup_t0 = _time.perf_counter()
  988. for paper in self._parsed_papers:
  989. paper_path = paper.get("path", "")
  990. try:
  991. paper_id = compute_paper_id(paper_path)
  992. entry = self._paper_library.get(paper_id)
  993. if entry and entry.get("index_status") == "done":
  994. logger.info("论文 %s 已索引,跳过", paper_path)
  995. continue
  996. all_cached_index = False
  997. papers_to_index.append(paper)
  998. except Exception:
  999. papers_to_index.append(paper)
  1000. logger.info(
  1001. "[预处理 timing] 索引去重检查(paper_library): %.2fs,待索引 %d 篇",
  1002. _time.perf_counter() - _dedup_t0, len(papers_to_index),
  1003. )
  1004. if papers_to_index:
  1005. _t0 = _time.perf_counter()
  1006. index_result = await self._invoke_tool(
  1007. "build_vector_index", papers_json=papers_to_index
  1008. )
  1009. _duration = round(_time.perf_counter() - _t0, 3)
  1010. indexed_count = index_result.get("indexed_count", 0) if isinstance(index_result, dict) else 0
  1011. # 更新索引状态
  1012. for paper in papers_to_index:
  1013. paper_path = paper.get("path", "")
  1014. try:
  1015. paper_id = compute_paper_id(paper_path)
  1016. self._paper_library.update_status(paper_id, index_status="done")
  1017. except Exception:
  1018. pass
  1019. self.tool_call_records.append({
  1020. "tool_name": "build_vector_index",
  1021. "args_summary": json.dumps(
  1022. {"papers_count": len(papers_to_index)}, ensure_ascii=False
  1023. )[:200],
  1024. "success": True,
  1025. "duration_sec": _duration,
  1026. "error": None,
  1027. "result": index_result,
  1028. })
  1029. index_status = "cached" if all_cached_index else "done"
  1030. await self._emit_progress(
  1031. progress_callback, "Indexer", index_status,
  1032. f"索引构建完成(新索引 {len(papers_to_index)} 篇,复用缓存 {len(self._parsed_papers) - len(papers_to_index)} 篇)", 0.5,
  1033. )
  1034. logger.info(
  1035. "[预处理 timing] 步骤3 索引完成: %.2fs | 预处理总耗时: %.2fs | 解析=%d 抽取=%d 待索引=%d",
  1036. _time.perf_counter() - _index_t0,
  1037. _time.perf_counter() - _pre_t0,
  1038. len(self._parsed_papers), len(self._extracted_records), len(papers_to_index),
  1039. )
  1040. # ------------------------------------------------------------------ #
  1041. # 完整流程
  1042. # ------------------------------------------------------------------ #
  1043. async def run(
  1044. self,
  1045. folder_path: Optional[str] = None,
  1046. paper_ids: Optional[list[str]] = None,
  1047. research_direction: Optional[str] = None,
  1048. progress_callback: Optional[ProgressCallback] = None,
  1049. post_step_hook: Optional[Callable] = None,
  1050. ) -> dict:
  1051. """完整流程:预处理(步骤1-3) → plan_task → execute_plan(步骤4-7) → 返回最终结果
  1052. Args:
  1053. folder_path: PDF 文件夹路径(与 paper_ids 二选一)
  1054. paper_ids: 上传论文 ID 列表(与 folder_path 二选一)
  1055. research_direction: 用户研究方向(可选,注入创新生成提示词)
  1056. progress_callback: 进度回调
  1057. post_step_hook: 步骤后钩子(供 Reflexion 插入)
  1058. Returns:
  1059. {steps_results, tool_call_records, degraded_steps, plan}
  1060. """
  1061. # 重置状态
  1062. self.step_results = {}
  1063. self.tool_call_records = []
  1064. self.degraded_steps = []
  1065. self._parsed_papers = []
  1066. self._extracted_records = []
  1067. self.research_direction = research_direction
  1068. # Phase 1: 预处理(步骤1-3:解析 → 抽取 → 索引),带缓存复用
  1069. await self._preprocess_papers(
  1070. folder_path=folder_path,
  1071. paper_ids=paper_ids,
  1072. progress_callback=progress_callback,
  1073. )
  1074. # Phase 2: Plan 阶段(仅步骤4-7)
  1075. task_desc = folder_path or f"已上传的 {len(paper_ids or [])} 篇论文"
  1076. self.plan = await self.plan_task(task_desc)
  1077. # 过滤掉步骤1-3(已由预处理阶段完成)
  1078. self.plan = [
  1079. s for s in self.plan
  1080. if s.get("agent") not in ("PaperParser", "Extractor", "Indexer")
  1081. ]
  1082. # 若过滤后为空,使用默认步骤4-7
  1083. if not self.plan:
  1084. self.plan = [dict(s) for s in DEFAULT_PLAN if s.get("agent") not in ("PaperParser", "Extractor", "Indexer")]
  1085. # Phase 3: Execute 阶段(步骤4-7)
  1086. result = await self.execute_plan(
  1087. self.plan, progress_callback, post_step_hook
  1088. )
  1089. # 附加计划信息,供后续整合输出 Agent 使用
  1090. result["plan"] = self.plan
  1091. return result