paper_library_tool.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """论文库检索/问答工具(包装 RAGTool,返回 str)"""
  2. from typing import Any, Dict, List
  3. from hello_agents.tools import Tool, ToolParameter
  4. class PaperLibrarySearchTool(Tool):
  5. """检索已索引的论文库(PDF 原文分块)"""
  6. def __init__(self, library_service):
  7. super().__init__(
  8. name="search_paper_library",
  9. description=(
  10. "在本地论文库中检索与查询最相关的原文片段。"
  11. "所有片段来自已下载的学术论文 PDF"
  12. "(经 MarkItDown 转换 → 智能分块 → 向量化)。"
  13. "撰写章节正文时获取论文细节的主要方式。"
  14. ),
  15. )
  16. self._library = library_service
  17. def get_parameters(self) -> List[ToolParameter]:
  18. return [
  19. ToolParameter(name="query", type="string",
  20. description="英文检索查询", required=True),
  21. ToolParameter(name="limit", type="integer",
  22. description="返回片段数,默认 5", required=False),
  23. ToolParameter(name="use_advanced", type="boolean",
  24. description="是否启用 MQE + HyDE 高级检索",
  25. required=False),
  26. ]
  27. def run(self, parameters: Dict[str, Any]) -> str:
  28. query = (parameters.get("query") or "").strip()
  29. if not query:
  30. return "❌ query 不能为空"
  31. try:
  32. text = self._library.search(
  33. query=query,
  34. limit=int(parameters.get("limit") or 5),
  35. enable_advanced=bool(parameters.get("use_advanced", False)),
  36. )
  37. return text or "未检索到相关论文片段"
  38. except Exception as exc:
  39. return f"❌ 论文库检索失败: {exc}"
  40. class PaperLibraryAskTool(Tool):
  41. """基于论文库直接回答(RAG 增强生成)"""
  42. def __init__(self, library_service):
  43. super().__init__(
  44. name="ask_paper_library",
  45. description=(
  46. "基于已索引论文库直接回答学术问题,"
  47. "返回带引用来源的回答。"
  48. ),
  49. )
  50. self._library = library_service
  51. def get_parameters(self) -> List[ToolParameter]:
  52. return [
  53. ToolParameter(name="question", type="string",
  54. description="学术问题", required=True),
  55. ToolParameter(name="limit", type="integer",
  56. description="检索片段数,默认 5", required=False),
  57. ]
  58. def run(self, parameters: Dict[str, Any]) -> str:
  59. question = (parameters.get("question") or "").strip()
  60. if not question:
  61. return "❌ question 不能为空"
  62. try:
  63. answer = self._library.ask(
  64. question=question,
  65. limit=int(parameters.get("limit") or 5),
  66. )
  67. return answer or "未得到回答"
  68. except Exception as exc:
  69. return f"❌ 论文库问答失败: {exc}"