#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 提示词管理和构建模块 """ import os import logging import random from typing import Dict, Any, Optional, List from core.config import GenerateTopicConfig from .file_io import ResourceLoader logger = logging.getLogger(__name__) class PromptTemplate: """封装单个提示模板的逻辑""" def __init__(self, template_path: str): self.path = template_path self._content = None @property def content(self) -> str: """延迟加载提示内容""" if self._content is None: self._content = ResourceLoader.load_text_file(self.path) or "" return self._content def render(self, **kwargs) -> str: """使用提供的上下文渲染提示""" try: return self.content.format(**kwargs) except KeyError as e: logger.error(f"渲染提示 '{self.path}' 时缺少键: {e}") return self.content # 返回原始模板以避免崩溃 except Exception as e: logger.error(f"渲染提示 '{self.path}' 时发生错误: {e}") return self.content class TopicPromptBuilder: """构建用于生成选题的提示""" def __init__(self, config: GenerateTopicConfig): self.config = config self._cache: Dict[str, str] = {} self._preload_resources() def _load_resource(self, resource_type: str, file_paths: List[str]) -> str: """加载并合并指定类型的所有资源文件""" contents = [] for path in file_paths: if path not in self._cache: content = ResourceLoader.load_text_file(path) if content: self._cache[path] = content if self._cache.get(path): contents.append(f"--- {resource_type}: {os.path.basename(path)} ---\n{self._cache[path]}") return "\n\n".join(contents) def _preload_resources(self): """预加载所有必需的资源""" logger.info("预加载选题生成所需资源...") self.style_content = self._load_resource("风格", self.config.style.paths) self.demand_content = self._load_resource("需求", self.config.demand.paths) self.refer_content = self._load_resource("参考", self.config.refer.paths) self.object_content = self._load_resource("对象", self.config.object.paths) self.product_content = self._load_resource("产品", self.config.product.paths) logger.info("资源预加载完成.") def build_prompts(self) -> Dict[str, str]: """构建系统和用户提示""" system_template = PromptTemplate(self.config.topic_system_prompt) user_template = PromptTemplate(self.config.topic_user_prompt) # 准备渲染上下文 context = { "num_topics": self.config.topic.num, "date_range": self.config.topic.date, "style": self.style_content, "demand": self.demand_content, "refer": self.refer_content, "object": self.object_content, "product": self.product_content, } system_prompt = system_template.render(**context) user_prompt = user_template.render(**context) return { "system": system_prompt, "user": user_prompt } class JudgerPromptBuilder: """构建用于审核内容的提示""" def __init__(self, system_prompt_path: str): self.system_template = PromptTemplate(system_prompt_path) def build_prompts(self, product_info: str, generated_content: str) -> Dict[str, str]: """ 构建审核提示 Args: product_info: 产品资料 generated_content: 已生成的内容 Returns: 包含 "system" 和 "user" 提示的字典 """ user_prompt = ( "请根据以下信息审核文案:\n\n" f"--- 产品资料 ---\n{product_info}\n\n" f"--- 待审核文案 ---\n{generated_content}" ) system_prompt = self.system_template.content return { "system": system_prompt, "user": user_prompt, }