literature_search.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. """文献检索 Agent(基于 Paper Search MCP)
  2. 链路:
  3. LLM 调用 papersearch_search_papers → 返回 JSON(含 source + paper_id)
  4. Python 层逐篇调用 MCPTool.run({action: call_tool, ...}) → 直接调用 download_with_fallback
  5. 下载成功的 PDF → PaperLibraryService.index_paper(内部走 RAGTool)
  6. """
  7. from __future__ import annotations
  8. import hashlib
  9. import json
  10. import logging
  11. import re
  12. from pathlib import Path
  13. from typing import Any, Dict, List, Optional
  14. from hello_agents import HelloAgentsLLM, ToolAwareSimpleAgent
  15. from config import Configuration
  16. from models import PaperSection
  17. from prompts import literature_search_system_prompt
  18. from services.paper_library import PaperLibraryService
  19. from services.tool_events import ToolCallTracker
  20. from tools import create_paper_search_mcp_tool
  21. logger = logging.getLogger(__name__)
  22. class LiteratureSearchAgent:
  23. """文献检索 Agent:检索 → 下载 → RAG 索引"""
  24. def __init__(
  25. self,
  26. llm: HelloAgentsLLM,
  27. config: Configuration,
  28. tool_tracker: Optional[ToolCallTracker] = None,
  29. ):
  30. self._config = config
  31. self._tracker = tool_tracker
  32. self._prefix = config.paper_search_mcp_prefix
  33. self._mcp_tool = None # ★ 保存原始 MCPTool 引用
  34. # 1. 论文库服务(复用第八章 RAGTool)
  35. self.library = PaperLibraryService(
  36. library_path=config.paper_library_path,
  37. rag_namespace=config.paper_library_rag_namespace,
  38. pdf_dir=str(config.paper_library_path.rstrip("/") + "/pdfs"),
  39. )
  40. # 2. Agent(参照第十四章 ToolAwareSimpleAgent 用法)
  41. self._agent = ToolAwareSimpleAgent(
  42. name="文献检索专家",
  43. llm=llm,
  44. system_prompt="你是一名学术文献检索专家。",
  45. enable_tool_calling=True,
  46. tool_registry=None,
  47. tool_call_listener=self._tracker.record if self._tracker else None,
  48. )
  49. # 3. 装配 Paper Search MCP
  50. self._register_mcp_tool()
  51. # 4. 刷新系统提示
  52. self._agent.system_prompt = self._build_system_prompt()
  53. # ------------------------------------------------------------------
  54. def _register_mcp_tool(self) -> None:
  55. """装配 Paper Search MCP"""
  56. command = self._config.resolve_paper_search_mcp_command()
  57. if not command:
  58. logger.warning("未配置 PAPER_SEARCH_MCP_COMMAND,文献检索能力不可用")
  59. return
  60. try:
  61. mcp_tool = create_paper_search_mcp_tool(
  62. server_command=command,
  63. prefix=self._prefix,
  64. )
  65. self._agent.add_tool(mcp_tool)
  66. self._mcp_tool = mcp_tool # ★ 保存引用,供直接调用
  67. logger.info("Paper Search MCP 已装配: %s", command)
  68. except Exception as exc:
  69. logger.exception("Paper Search MCP 装配失败: %s", exc)
  70. def _build_system_prompt(self) -> str:
  71. """★ 补回此方法:把工具清单注入检索提示词"""
  72. tools_desc = (
  73. self._agent.tool_registry.get_tools_description()
  74. if self._agent.tool_registry else "暂无可用工具"
  75. )
  76. return literature_search_system_prompt.format(
  77. tools_placeholder=tools_desc,
  78. prefix=self._prefix,
  79. )
  80. # ------------------------------------------------------------------
  81. def search_for_section(self, section: PaperSection) -> List[Dict[str, Any]]:
  82. """对单个章节执行检索 → 下载 → 索引"""
  83. keywords = section.keywords or [section.title]
  84. query = " ".join(keywords)
  85. limit = self._config.max_references_per_section
  86. # ------ 步骤 1: 让 LLM 调用 papersearch_search_papers 完成检索 ------
  87. prompt = (
  88. f"请为以下论文章节检索 {limit} 篇高质量学术论文。\n\n"
  89. f"章节标题:{section.title}\n"
  90. f"章节意图:{section.intent}\n"
  91. f"检索关键词:{query}\n\n"
  92. f"## 操作指令\n"
  93. f"调用一次 `{self._prefix}_search_papers`,参数:\n"
  94. f"```json\n"
  95. f'{{"query": "{query}", '
  96. f'"sources": "arxiv,semantic,crossref,openalex,dblp", '
  97. f'"max_results_per_source": {limit}}}\n'
  98. f"```\n\n"
  99. f"## 返回要求\n"
  100. f"检索完成后,**只输出 JSON**,格式如下(不要任何解释文字):\n"
  101. f'{{"papers": ['
  102. f'{{"title":"...","authors":[...],"year":...,'
  103. f'"venue":"...","doi":"...","source":"arxiv",'
  104. f'"paper_id":"..."}}]}}\n'
  105. f"注意:source 与 paper_id 必填,用于后续下载。"
  106. )
  107. response = self._agent.run(prompt)
  108. # ===== 诊断 1:检索 Agent 原始输出 =====
  109. print("=" * 70)
  110. print("【诊断】检索 Agent 原始输出:")
  111. print(response[:2000])
  112. print("=" * 70)
  113. papers = self._parse_papers(response)
  114. papers = self._deduplicate(papers)[:limit]
  115. # ===== 诊断 2:解析出的 papers 列表 =====
  116. print("=" * 70)
  117. print(f"【诊断】解析出 {len(papers)} 篇论文:")
  118. for i, p in enumerate(papers, 1):
  119. print(f" [{i}] title : {(p.get('title') or '')[:60]}")
  120. print(f" source : {p.get('source')!r}")
  121. print(f" paper_id : {p.get('paper_id')!r}")
  122. print(f" arxiv_id : {p.get('arxiv_id')!r}")
  123. print(f" doi : {p.get('doi')!r}")
  124. print(f" 所有字段 : {list(p.keys())}")
  125. print("=" * 70)
  126. # ------ 步骤 2: Python 层逐篇调用 download_with_fallback ------
  127. for p in papers:
  128. self._download_paper(p)
  129. # ------ 步骤 3: 已下载的 PDF 加入 RAG 索引 ------
  130. for p in papers:
  131. self._index_if_downloaded(p)
  132. logger.info(
  133. "章节「%s」检索 %d 篇,已下载 %d 篇,已索引 %d 篇",
  134. section.title, len(papers),
  135. sum(1 for p in papers if p.get("pdf_path")),
  136. sum(1 for p in papers if p.get("indexed")),
  137. )
  138. return papers
  139. # ------------------------------------------------------------------
  140. def _download_paper(self, paper: Dict[str, Any]) -> None:
  141. """调用 download_with_fallback 下载单篇论文
  142. 直接调用底层 MCPTool.run(),避免经过 wrapper 的参数包装。
  143. """
  144. source = (paper.get("source") or "").strip()
  145. paper_id = (paper.get("paper_id") or "").strip()
  146. if not source or not paper_id:
  147. logger.debug("论文《%s》缺少 source/paper_id,跳过下载",
  148. (paper.get("title") or "")[:60])
  149. paper["pdf_path"] = None
  150. return
  151. unsupported = {"google_scholar", "dblp", "ssrn", "unpaywall"}
  152. if source in unsupported:
  153. logger.debug("源 %s 不支持全文下载,跳过", source)
  154. paper["pdf_path"] = None
  155. return
  156. if self._mcp_tool is None:
  157. logger.warning("MCPTool 未装配,无法下载")
  158. paper["pdf_path"] = None
  159. return
  160. save_path = str(self.library.pdf_dir)
  161. # ===== 诊断 =====
  162. print("=" * 70)
  163. print("【诊断】直接调用 MCPTool.run() 下载:")
  164. print(f" source : {source!r}")
  165. print(f" paper_id : {paper_id!r}")
  166. print(f" save_path: {save_path!r}")
  167. print("=" * 70)
  168. # ★ 关键:直接调用 MCPTool,参数不经过 wrapper 的 {"input": ...} 包装
  169. try:
  170. result = self._mcp_tool.run({
  171. "action": "call_tool",
  172. "tool_name": "download_with_fallback",
  173. "arguments": {
  174. "source": source,
  175. "paper_id": paper_id,
  176. "doi": paper.get("doi", "") or "",
  177. "title": paper.get("title", "") or "",
  178. "save_path": save_path,
  179. "use_scihub": False,
  180. },
  181. })
  182. except Exception as exc:
  183. logger.warning("下载工具调用失败 source=%s paper_id=%s: %s",
  184. source, paper_id, exc)
  185. paper["pdf_path"] = None
  186. return
  187. # ===== 诊断 =====
  188. print("=" * 70)
  189. print("【诊断】download_with_fallback 返回值(全文):")
  190. print(str(result))
  191. print("=" * 70)
  192. pdf_path = self._extract_pdf_path(str(result))
  193. paper["pdf_path"] = pdf_path
  194. if pdf_path:
  195. logger.info("下载成功: %s", pdf_path)
  196. else:
  197. logger.debug("未能从下载结果中提取 PDF 路径: %s", str(result)[:200])
  198. @staticmethod
  199. def _extract_pdf_path(result_text: str) -> Optional[str]:
  200. """从 download_with_fallback 的返回值里提取 PDF 路径
  201. 典型返回值:
  202. 工具 'download_with_fallback' 执行结果:
  203. workspace\\paper_library\\pdfs/2502.00632v2.pdf
  204. 提取规则:
  205. 1. 逐行从后往前找以 .pdf 结尾的行,去掉 "xxx:" 前缀
  206. 2. 若整行就是路径,直接返回
  207. 3. 兜底:抓取任何含目录分隔符且以 .pdf 结尾的片段
  208. """
  209. if not result_text:
  210. return None
  211. text = result_text.strip()
  212. # 1. 整段就是纯路径
  213. if text.endswith(".pdf") and "\n" not in text:
  214. return text
  215. # 2. 逐行从后往前找
  216. for line in reversed(text.splitlines()):
  217. line = line.strip()
  218. if not line:
  219. continue
  220. # 去掉 "工具 'xxx' 执行结果:" 之类的中英文冒号前缀
  221. line = re.sub(r'^[^:\n]*[::]\s*', '', line)
  222. if line.endswith(".pdf"):
  223. return line
  224. # 行末包含路径的情况,如 "Downloaded to: xxx.pdf"
  225. m = re.search(r'([^\s:"\']+\.pdf)\s*$', line)
  226. if m:
  227. return m.group(1)
  228. # 3. 兜底:任何含目录分隔符且以 .pdf 结尾的片段
  229. # 要求路径里至少出现一个 \ 或 / 且不是开头就 /
  230. m = re.search(
  231. r'([A-Za-z]:[\\/][^\s:"\']+\.pdf' # Windows 绝对路径
  232. r'|[^\s:"\'/\\]+[\\/][^\s:"\']+\.pdf)' # 相对路径(至少一级目录)
  233. , text
  234. )
  235. if m:
  236. return m.group(1)
  237. return None
  238. def _index_if_downloaded(self, paper: Dict[str, Any]) -> None:
  239. """若已下载 PDF,则加入 RAG 索引"""
  240. pdf_path = paper.get("pdf_path")
  241. if not pdf_path or not Path(pdf_path).exists():
  242. paper["indexed"] = False
  243. return
  244. doi = (paper.get("doi") or "").strip()
  245. title = (paper.get("title") or "").strip()
  246. paper_id = (paper.get("paper_id") or "").strip()
  247. stable_id = self._make_stable_id(doi, paper_id, title)
  248. if not stable_id:
  249. paper["indexed"] = False
  250. return
  251. paper["stable_id"] = stable_id
  252. index_result = self.library.index_paper(
  253. pdf_path=pdf_path,
  254. paper_id=stable_id,
  255. metadata={
  256. "title": title,
  257. "doi": doi,
  258. "source": paper.get("source"),
  259. "source_id": paper_id,
  260. "year": paper.get("year"),
  261. "venue": paper.get("venue"),
  262. },
  263. )
  264. paper["indexed"] = bool(index_result.get("success"))
  265. paper["chunks"] = index_result.get("chunks", 0)
  266. @staticmethod
  267. def _make_stable_id(doi: str, source_id: str, title: str) -> Optional[str]:
  268. if doi:
  269. return f"doi_{hashlib.md5(doi.lower().encode()).hexdigest()[:16]}"
  270. if source_id:
  271. safe = re.sub(r"[^\w\-]", "_", source_id)[:40]
  272. return f"sid_{safe}"
  273. if title:
  274. return f"title_{hashlib.md5(title.lower().encode()).hexdigest()[:16]}"
  275. return None
  276. # ------------------------------------------------------------------
  277. @staticmethod
  278. def _parse_papers(response: str) -> List[Dict[str, Any]]:
  279. if not response:
  280. return []
  281. try:
  282. data = json.loads(response)
  283. if isinstance(data, dict) and isinstance(data.get("papers"), list):
  284. return [p for p in data["papers"] if isinstance(p, dict)]
  285. except json.JSONDecodeError:
  286. pass
  287. start, end = response.find("{"), response.rfind("}")
  288. if start != -1 and end > start:
  289. try:
  290. data = json.loads(response[start:end + 1])
  291. if isinstance(data, dict) and isinstance(data.get("papers"), list):
  292. return [p for p in data["papers"] if isinstance(p, dict)]
  293. except json.JSONDecodeError:
  294. pass
  295. m = re.search(r"```json\s*(\{.*?\})\s*```", response, re.DOTALL)
  296. if m:
  297. try:
  298. data = json.loads(m.group(1))
  299. if isinstance(data, dict) and isinstance(data.get("papers"), list):
  300. return [p for p in data["papers"] if isinstance(p, dict)]
  301. except json.JSONDecodeError:
  302. pass
  303. logger.warning("未能从检索 Agent 输出中解析 papers")
  304. return []
  305. @staticmethod
  306. def _deduplicate(papers: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  307. seen, unique = set(), []
  308. for p in papers:
  309. doi = (p.get("doi") or "").strip().lower()
  310. title = re.sub(r"\s+", " ", (p.get("title") or "").strip().lower())
  311. key = doi or title
  312. if not key or key in seen:
  313. continue
  314. seen.add(key)
  315. unique.append(p)
  316. return unique
  317. # ------------------------------------------------------------------
  318. def list_tools(self) -> List[str]:
  319. return self._agent.list_tools() if self._agent else []
  320. def library_stats(self) -> Dict[str, Any]:
  321. return self.library.stats()