deconstruct.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. """解构:给知识片段补上阶段(灵感/选题/脚本)和作用域(五棵树)。"""
  2. from __future__ import annotations
  3. from typing import Optional
  4. from creation_knowledge.integrations.llm import ChatFn, default_chat
  5. from creation_knowledge.models import Deconstruction, KnowledgeItem, Scope
  6. from creation_knowledge.prompts import load_prompt
  7. SYSTEM = "你是严谨的创作知识解构器,按阶段和五棵分类树归类。"
  8. VALID_STAGES = {"灵感", "选题", "脚本"}
  9. VALID_SCOPES = {"substance", "form", "feeling", "effect", "intent"}
  10. def deconstruct_item(
  11. item: KnowledgeItem,
  12. *,
  13. chat: Optional[ChatFn] = None,
  14. env_file: str = ".env",
  15. ) -> Deconstruction:
  16. chat = chat or default_chat(env_file)
  17. user = load_prompt("deconstruct").format(
  18. item=item.model_dump_json(indent=2)
  19. )
  20. data = chat(SYSTEM, user)
  21. stages = [s for s in (data.get("stages") or []) if s in VALID_STAGES]
  22. scopes = [
  23. Scope(scope_type=s["scope_type"], value=str(s["value"]).strip())
  24. for s in (data.get("scopes") or [])
  25. if isinstance(s, dict) and s.get("scope_type") in VALID_SCOPES and s.get("value")
  26. ]
  27. return Deconstruction(
  28. stages=stages,
  29. scopes=scopes,
  30. stage_reason=str(data.get("stage_reason") or ""),
  31. scope_reason=str(data.get("scope_reason") or ""),
  32. )