agent.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. """论文撰写助手协调器
  2. 五个专职 Agent:
  3. - PaperPlannerAgent 章节规划
  4. - LiteratureSearchAgent 学术检索 + PDF 下载 + RAG 索引
  5. - SectionWriterAgent 章节撰写(检索论文原文)
  6. - PaperReviewAgent 论文审校
  7. - ReportAssemblerAgent 最终论文汇总
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import re
  12. from pathlib import Path
  13. from typing import Any, Optional
  14. from hello_agents import HelloAgentsLLM, ToolAwareSimpleAgent
  15. from hello_agents.tools import MemoryTool, NoteTool, ToolRegistry
  16. from agents.literature_search import LiteratureSearchAgent
  17. from config import Configuration
  18. from models import PaperState, PaperStateOutput
  19. from prompts import (
  20. paper_planner_system_prompt,
  21. paper_reviewer_system_prompt,
  22. report_assembler_system_prompt,
  23. section_writer_system_prompt,
  24. )
  25. from services.assembler import ReportAssemblyService
  26. from services.planner import PlanningService
  27. from services.reviewer import ReviewService
  28. from services.tool_events import ToolCallTracker
  29. from services.writer import SectionWritingService
  30. from tools import PaperLibraryAskTool, PaperLibrarySearchTool
  31. logger = logging.getLogger(__name__)
  32. class PaperAssistantAgent:
  33. """论文撰写助手协调器"""
  34. def __init__(self, config: Optional[Configuration] = None) -> None:
  35. self.config = config or Configuration.from_env()
  36. self.llm = self._init_llm()
  37. # ---------- 内置工具 ----------
  38. self.note_tool = (
  39. NoteTool(workspace=self.config.notes_workspace)
  40. if self.config.enable_notes else None
  41. )
  42. self.memory_tool = (
  43. MemoryTool(user_id=self.config.memory_user_id)
  44. if self.config.enable_memory else None
  45. )
  46. # ---------- 工具调用追踪 ----------
  47. self._tool_tracker = ToolCallTracker(
  48. notes_workspace=self.config.notes_workspace
  49. if self.config.enable_notes else None
  50. )
  51. # ---------- 五个专职 Agent ----------
  52. self.planner_agent = self._make_agent(
  53. "论文规划专家", paper_planner_system_prompt.strip()
  54. )
  55. self.writer_agent = self._make_agent(
  56. "章节撰写专家", section_writer_system_prompt.strip()
  57. )
  58. self.reviewer_agent = self._make_agent(
  59. "论文审校专家", paper_reviewer_system_prompt.strip()
  60. )
  61. self.assembler_agent = self._make_agent(
  62. "报告汇总专家", report_assembler_system_prompt.strip()
  63. )
  64. # ---------- 文献检索 Agent ----------
  65. self.search_agent = LiteratureSearchAgent(
  66. llm=self.llm,
  67. config=self.config,
  68. tool_tracker=self._tool_tracker,
  69. )
  70. # ---------- 为写作 Agent 装配论文库检索工具(通过 add_tool) ----------
  71. self.writer_agent.add_tool(
  72. PaperLibrarySearchTool(self.search_agent.library)
  73. )
  74. self.writer_agent.add_tool(
  75. PaperLibraryAskTool(self.search_agent.library)
  76. )
  77. # ---------- 服务封装 ----------
  78. self.planner = PlanningService(self.planner_agent, self.config)
  79. self.writer = SectionWritingService(
  80. lambda: self.writer_agent, self.config
  81. )
  82. self.reviewer = ReviewService(
  83. lambda: self.reviewer_agent, self.config
  84. )
  85. self.assembler = ReportAssemblyService(
  86. lambda: self.assembler_agent, self.config
  87. )
  88. # ------------------------------------------------------------------
  89. def _init_llm(self) -> HelloAgentsLLM:
  90. """初始化 LLM 客户端
  91. 直接交给 HelloAgentsLLM 的自动检测机制处理:
  92. - 参数优先,环境变量兜底;
  93. - 读取 LLM_PROVIDER / LLM_API_KEY / LLM_BASE_URL / LLM_MODEL_ID,
  94. 或 OPENAI_API_KEY / DEEPSEEK_API_KEY / DASHSCOPE_API_KEY 等;
  95. - 根据 base_url 或 api_key 格式自动识别 provider。
  96. 应用层不感知 provider 细节,只设置业务相关参数(temperature=0.0)。
  97. """
  98. return HelloAgentsLLM(temperature=0.0)
  99. def _make_agent(self, name: str, system_prompt: str) -> ToolAwareSimpleAgent:
  100. """为每个 Agent 装配 NoteTool + MemoryTool(共享 registry)"""
  101. registry = ToolRegistry()
  102. if self.note_tool:
  103. registry.register_tool(self.note_tool)
  104. if self.memory_tool:
  105. registry.register_tool(self.memory_tool)
  106. return ToolAwareSimpleAgent(
  107. name=name,
  108. llm=self.llm,
  109. system_prompt=system_prompt,
  110. enable_tool_calling=True,
  111. tool_registry=registry,
  112. tool_call_listener=self._tool_tracker.record,
  113. )
  114. # ------------------------------------------------------------------
  115. def run(self, topic: str) -> PaperStateOutput:
  116. """执行完整论文撰写流程"""
  117. state = PaperState(
  118. research_topic=topic,
  119. paper_type=self._enum_value(self.config.paper_type),
  120. citation_style=self._enum_value(self.config.citation_style),
  121. )
  122. # 1) 记录研究主题到情景记忆
  123. if self.memory_tool:
  124. self.memory_tool.run({
  125. "action": "add",
  126. "content": f"开始撰写论文,研究主题:{topic}",
  127. "memory_type": "episodic",
  128. "importance": 0.9,
  129. })
  130. # 2) 章节规划
  131. logger.info("→ 规划章节大纲")
  132. sections = self.planner.plan_outline(state)
  133. if not sections:
  134. sections = PlanningService.create_fallback_sections()
  135. state.sections = sections
  136. self._drain_events()
  137. # 3) 逐章检索 + 撰写
  138. previous_context = ""
  139. for section in sections:
  140. logger.info("→ 章节 %d: %s", section.id, section.title)
  141. # 3.1 学术检索 + PDF 下载 + RAG 索引
  142. refs = self.search_agent.search_for_section(section)
  143. section.references = refs
  144. logger.info(" 检索到 %d 篇,其中 %d 篇已下载索引",
  145. len(refs), sum(1 for r in refs if r.get("indexed")))
  146. # 3.2 撰写章节(Writer Agent 可调用 search_paper_library 检索原文)
  147. content = self.writer.write_section(
  148. state, section, refs, previous_context
  149. )
  150. section.content = content
  151. section.status = "completed"
  152. previous_context += f"\n\n## {section.title}\n{content[:500]}"
  153. # 3.3 保存章节笔记(NoteTool)
  154. if self.note_tool:
  155. note_body = (
  156. f"## 章节意图\n{section.intent}\n\n"
  157. f"## 关键词\n{', '.join(section.keywords)}\n\n"
  158. f"## 章节正文(节选)\n{content[:1500]}\n\n"
  159. f"## 参考文献\n"
  160. + "\n".join(
  161. f"- {r.get('title', '')} "
  162. f"{'[已索引]' if r.get('indexed') else ''}"
  163. for r in refs
  164. )
  165. )
  166. resp = self.note_tool.run({
  167. "action": "create",
  168. "title": f"章节 {section.id}: {section.title}",
  169. "note_type": "conclusion",
  170. "tags": ["paper", f"section_{section.id}"],
  171. "content": note_body,
  172. })
  173. m = re.search(r"ID:\s*([^\n]+)", resp or "")
  174. if m:
  175. section.note_id = m.group(1).strip()
  176. if self.config.notes_workspace:
  177. section.note_path = str(
  178. Path(self.config.notes_workspace)
  179. / f"{section.note_id}.md"
  180. )
  181. self._drain_events()
  182. # 3.4 记录撰写事件到情景记忆
  183. if self.memory_tool:
  184. self.memory_tool.run({
  185. "action": "add",
  186. "content": f"完成章节「{section.title}」撰写",
  187. "memory_type": "episodic",
  188. "importance": 0.7,
  189. })
  190. # 4) 审校
  191. logger.info("→ 审校论文")
  192. full_draft = self._assemble_draft(state, sections)
  193. review_notes = self.reviewer.review(state, full_draft)
  194. state.review_notes = review_notes
  195. self._drain_events()
  196. # 5) 汇总
  197. logger.info("→ 汇总最终论文")
  198. final_paper = self.assembler.assemble(state, sections, review_notes)
  199. state.final_paper = final_paper
  200. self._drain_events()
  201. # 6) 保存终稿到笔记(NoteTool)
  202. if self.note_tool and final_paper:
  203. resp = self.note_tool.run({
  204. "action": "create",
  205. "title": f"论文终稿:{state.paper_title or topic}",
  206. "note_type": "conclusion",
  207. "tags": ["paper", "final"],
  208. "content": final_paper[:5000],
  209. })
  210. m = re.search(r"ID:\s*([^\n]+)", resp or "")
  211. if m:
  212. state.report_note_id = m.group(1).strip()
  213. if self.config.notes_workspace:
  214. state.report_note_path = str(
  215. Path(self.config.notes_workspace)
  216. / f"{state.report_note_id}.md"
  217. )
  218. # 7) 记录完成事件
  219. if self.memory_tool:
  220. total_refs = sum(len(s.references) for s in sections)
  221. indexed_refs = sum(
  222. 1 for s in sections for r in s.references if r.get("indexed")
  223. )
  224. self.memory_tool.run({
  225. "action": "add",
  226. "content": (
  227. f"论文《{state.paper_title or topic}》完成,"
  228. f"共 {len(sections)} 章,"
  229. f"{total_refs} 篇参考文献({indexed_refs} 篇已索引)"
  230. ),
  231. "memory_type": "episodic",
  232. "importance": 0.9,
  233. })
  234. return PaperStateOutput(
  235. paper_markdown=final_paper,
  236. sections=sections,
  237. references=[r for s in sections for r in s.references],
  238. review_notes=review_notes,
  239. library_stats=self.search_agent.library_stats(),
  240. )
  241. # ------------------------------------------------------------------
  242. def _assemble_draft(self, state: PaperState, sections) -> str:
  243. parts = [f"# {state.paper_title or state.research_topic}\n"]
  244. for s in sections:
  245. parts.append(f"## {s.title}\n\n{s.content or ''}\n")
  246. return "\n".join(parts)
  247. def _drain_events(self) -> list[dict[str, Any]]:
  248. return self._tool_tracker.drain()
  249. @staticmethod
  250. def _enum_value(v: Any) -> str:
  251. return v.value if hasattr(v, "value") else str(v)