content_service.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """正文生成服务。"""
  2. from typing import Any, AsyncGenerator
  3. from ..utils.openai_util import OpenAIUtil
  4. from ..utils.prompts.content_prompts import build_chapter_content_messages
  5. class ContentService:
  6. """负责目录叶子章节的正文生成。"""
  7. def __init__(self, ai: OpenAIUtil | None = None):
  8. self.ai = ai or OpenAIUtil()
  9. async def stream_chapter_content(
  10. self,
  11. chapter: dict[str, Any],
  12. parent_chapters: list[dict[str, Any]] | None = None,
  13. sibling_chapters: list[dict[str, Any]] | None = None,
  14. project_overview: str = "",
  15. ) -> AsyncGenerator[str, None]:
  16. """流式生成单章节内容。"""
  17. messages = build_chapter_content_messages(
  18. chapter=chapter,
  19. parent_chapters=parent_chapters,
  20. sibling_chapters=sibling_chapters,
  21. project_overview=project_overview,
  22. )
  23. async for chunk in self.ai.stream_chat_completion(messages, temperature=0.7):
  24. yield chunk
  25. async def generate_chapter_content(
  26. self,
  27. chapter: dict[str, Any],
  28. parent_chapters: list[dict[str, Any]] | None = None,
  29. sibling_chapters: list[dict[str, Any]] | None = None,
  30. project_overview: str = "",
  31. ) -> str:
  32. """生成单章节完整正文。"""
  33. return await self.ai.collect_chat_completion(
  34. build_chapter_content_messages(
  35. chapter=chapter,
  36. parent_chapters=parent_chapters,
  37. sibling_chapters=sibling_chapters,
  38. project_overview=project_overview,
  39. ),
  40. temperature=0.7,
  41. )