planner.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """章节规划服务"""
  2. import json
  3. import logging
  4. from typing import Any, List
  5. from hello_agents import ToolAwareSimpleAgent
  6. from config import Configuration
  7. from models import PaperSection, PaperState
  8. from prompts import get_current_date, paper_planner_instructions
  9. from utils import strip_thinking_tokens, strip_tool_calls
  10. logger = logging.getLogger(__name__)
  11. class PlanningService:
  12. """封装规划 Agent,产出结构化章节列表"""
  13. def __init__(self, planner_agent: ToolAwareSimpleAgent, config: Configuration):
  14. self._agent = planner_agent
  15. self._config = config
  16. def plan_outline(self, state: PaperState) -> List[PaperSection]:
  17. prompt = paper_planner_instructions.format(
  18. current_date=get_current_date(),
  19. research_topic=state.research_topic,
  20. paper_type=state.paper_type,
  21. target_sections=self._config.target_sections,
  22. target_words_per_section=self._config.target_words_per_section,
  23. )
  24. response = self._agent.run(prompt)
  25. self._agent.clear_history()
  26. logger.info("Planner raw output (truncated): %s", response[:500])
  27. payload = self._extract_payload(response)
  28. if payload.get("paper_title"):
  29. state.paper_title = str(payload["paper_title"]).strip()
  30. sections: List[PaperSection] = []
  31. for idx, item in enumerate(payload.get("sections") or [], start=1):
  32. if not isinstance(item, dict):
  33. continue
  34. title = str(item.get("title") or f"章节{idx}").strip()
  35. intent = str(item.get("intent") or "").strip()
  36. keywords = item.get("keywords") or []
  37. if isinstance(keywords, str):
  38. keywords = [keywords]
  39. target_words = int(item.get("target_words")
  40. or self._config.target_words_per_section)
  41. sections.append(PaperSection(
  42. id=idx, title=title, intent=intent,
  43. keywords=list(keywords), target_words=target_words,
  44. ))
  45. return sections
  46. @staticmethod
  47. def create_fallback_sections() -> List[PaperSection]:
  48. """规划失败时的回退章节(参照第十四章 create_fallback_task)"""
  49. defaults = [
  50. ("Introduction", "介绍研究背景、问题与贡献", ["background", "motivation"]),
  51. ("Related Work", "梳理领域已有研究与差距", ["related work", "survey"]),
  52. ("Method", "阐述研究方法与实现细节",
  53. ["method", "approach", "algorithm"]),
  54. ("Experiments", "呈现实验设计与结果分析",
  55. ["experiment", "evaluation", "benchmark"]),
  56. ("Conclusion", "总结贡献与未来方向",
  57. ["conclusion", "future work"]),
  58. ]
  59. return [
  60. PaperSection(id=i + 1, title=t, intent=it, keywords=kw)
  61. for i, (t, it, kw) in enumerate(defaults)
  62. ]
  63. def _extract_payload(self, response: str) -> dict[str, Any]:
  64. """从 Agent 响应中提取 JSON(参照第十四章 PlanningService._extract_json)"""
  65. text = response.strip()
  66. if self._config.strip_thinking_tokens:
  67. text = strip_thinking_tokens(text)
  68. text = strip_tool_calls(text).strip()
  69. start = text.find("{")
  70. end = text.rfind("}")
  71. if start != -1 and end > start:
  72. try:
  73. return json.loads(text[start:end + 1])
  74. except json.JSONDecodeError:
  75. pass
  76. return {}