prompt_loader.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # coding=utf-8
  2. """
  3. 提示词模板加载工具
  4. 从配置目录中加载 [system] / [user] 格式的提示词文件,
  5. 供 analyzer、translator、filter 等模块共享使用。
  6. """
  7. from pathlib import Path
  8. from typing import Tuple
  9. # 项目 config 根目录
  10. _CONFIG_ROOT = Path(__file__).parent.parent.parent / "config"
  11. def load_prompt_template(
  12. prompt_file: str,
  13. config_subdir: str = "",
  14. label: str = "AI",
  15. ) -> Tuple[str, str]:
  16. """
  17. 加载提示词模板文件,解析 [system] 和 [user] 部分。
  18. Args:
  19. prompt_file: 提示词文件名
  20. config_subdir: config 下的子目录(如 "ai_filter"),为空则直接在 config/ 下查找
  21. label: 日志标签,用于提示文件缺失时的打印
  22. Returns:
  23. (system_prompt, user_prompt_template) 元组
  24. """
  25. config_dir = _CONFIG_ROOT / config_subdir if config_subdir else _CONFIG_ROOT
  26. prompt_path = config_dir / prompt_file
  27. if not prompt_path.exists():
  28. print(f"[{label}] 提示词文件不存在: {prompt_path}")
  29. return "", ""
  30. content = prompt_path.read_text(encoding="utf-8")
  31. system_prompt = ""
  32. user_prompt = ""
  33. if "[system]" in content and "[user]" in content:
  34. parts = content.split("[user]")
  35. system_part = parts[0]
  36. user_part = parts[1] if len(parts) > 1 else ""
  37. if "[system]" in system_part:
  38. system_prompt = system_part.split("[system]")[1].strip()
  39. user_prompt = user_part.strip()
  40. else:
  41. user_prompt = content
  42. return system_prompt, user_prompt