base.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. # -*- coding: utf-8 -*-
  2. """文档对话技能基类。"""
  3. from abc import ABC, abstractmethod
  4. from typing import Callable
  5. from core.document_chat.schemas import DocumentChatSkillInput, DocumentChatSkillOutput
  6. class BaseDocumentChatSkill(ABC):
  7. def __init__(self, name: str, function_name: str):
  8. self.name = name
  9. self.function_name = function_name
  10. @abstractmethod
  11. async def run(self, skill_input: DocumentChatSkillInput) -> DocumentChatSkillOutput:
  12. """执行技能并返回标准化输出。"""
  13. raise NotImplementedError
  14. async def run_stream(
  15. self,
  16. skill_input: DocumentChatSkillInput,
  17. on_chunk: Callable[[str], None],
  18. ) -> DocumentChatSkillOutput:
  19. """流式执行。每次生成一个 chunk 时调用 on_chunk,最终返回完整结果。
  20. 默认实现调用非流式 run(),将整个 answer 一次性传给 on_chunk,
  21. 子类可覆盖此方法实现真正的流式生成。
  22. """
  23. result = await self.run(skill_input)
  24. text = result.answer or result.proposed_content or ""
  25. if text:
  26. on_chunk(text)
  27. return result