writer.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """章节撰写服务"""
  2. import logging
  3. from typing import Any, Callable, Dict, List
  4. from hello_agents import ToolAwareSimpleAgent
  5. from config import Configuration
  6. from models import PaperSection, PaperState
  7. from utils import strip_thinking_tokens, strip_tool_calls
  8. logger = logging.getLogger(__name__)
  9. class SectionWritingService:
  10. """调用写作 Agent 完成章节草稿"""
  11. def __init__(
  12. self,
  13. agent_factory: Callable[[], ToolAwareSimpleAgent],
  14. config: Configuration,
  15. ):
  16. self._agent_factory = agent_factory
  17. self._config = config
  18. def write_section(
  19. self,
  20. state: PaperState,
  21. section: PaperSection,
  22. references: List[Dict[str, Any]],
  23. previous_context: str = "",
  24. ) -> str:
  25. refs_block = self._format_references(references)
  26. prompt = (
  27. f"论文题目:{state.paper_title or state.research_topic}\n"
  28. f"章节标题:{section.title}\n"
  29. f"章节意图:{section.intent}\n"
  30. f"目标字数:{section.target_words}\n\n"
  31. f"## 可用文献(引用必须来自以下列表)\n{refs_block}\n\n"
  32. f"## 已完成章节的上下文\n{previous_context[-800:]}\n\n"
  33. f"## 撰写要求\n"
  34. f"1. 写作过程中如需了解论文原文细节,**调用 search_paper_library 工具**;\n"
  35. f"2. 引用必须来自上方文献列表,禁止引入网页链接;\n"
  36. f"3. 使用 format_citation 生成规范引用条目;\n"
  37. f"4. 撰写完成后将章节草稿写入笔记(note 工具)。"
  38. )
  39. agent = self._agent_factory()
  40. try:
  41. response = agent.run(prompt)
  42. finally:
  43. agent.clear_history()
  44. content = response.strip()
  45. if self._config.strip_thinking_tokens:
  46. content = strip_thinking_tokens(content)
  47. return strip_tool_calls(content).strip()
  48. @staticmethod
  49. def _format_references(references: List[Dict[str, Any]]) -> str:
  50. if not references:
  51. return "(暂无检索到的文献)"
  52. lines = []
  53. for i, ref in enumerate(references, start=1):
  54. lines.append(
  55. f"[{i}] {ref.get('title', '')} "
  56. f"({ref.get('year', '')}) — {ref.get('venue', '')} "
  57. f"DOI: {ref.get('doi', '')} "
  58. f"PDF: {'已索引' if ref.get('indexed') else '未下载'}"
  59. )
  60. return "\n".join(lines)