Skip to content

5.2 提示词模板系统

🎯 学习目标:构建智能提示词模板系统,实现动态、上下文感知的AI交互
⏱️ 预计时间:40分钟
📊 难度等级:⭐⭐⭐⭐

🤔 为什么需要提示词模板?

想象一下这样的场景:你的AI助手需要帮助用户分析不同类型的数据,每次都要重新写提示词会很繁琐。而且,好的提示词往往需要包含:

  • 📋 明确的任务描述
  • 🎯 具体的输出格式
  • 📊 相关的上下文信息
  • 🚫 边界条件和限制

提示词模板系统就是为了解决这些问题而设计的!

🏗️ 提示词模板系统架构

🎯 核心组件实现

📝 提示词模板基础框架

python
"""
prompt_templates.py - 提示词模板系统
"""

from abc import ABC, abstractmethod
from typing import Dict, List, Any, Optional, Union, Callable
from dataclasses import dataclass, field
from enum import Enum
import asyncio
import json
import re
from datetime import datetime
from pathlib import Path
import yaml
from jinja2 import Environment, FileSystemLoader, Template, meta
from jinja2.exceptions import TemplateError
from loguru import logger

class PromptType(Enum):
    """提示词类型"""
    SYSTEM = "system"
    USER = "user"
    ASSISTANT = "assistant"
    FUNCTION = "function"
    CONTEXT = "context"

class TemplateFormat(Enum):
    """模板格式"""
    JINJA2 = "jinja2"
    STRING = "string"
    YAML = "yaml"
    JSON = "json"

@dataclass
class PromptVariable:
    """提示词变量定义"""
    name: str
    type: str
    description: str
    required: bool = True
    default: Any = None
    validator: Optional[Callable] = None
    examples: List[Any] = field(default_factory=list)

@dataclass
class PromptTemplate:
    """提示词模板"""
    id: str
    name: str
    description: str
    template_content: str
    prompt_type: PromptType
    format: TemplateFormat = TemplateFormat.JINJA2
    variables: List[PromptVariable] = field(default_factory=list)
    tags: List[str] = field(default_factory=list)
    version: str = "1.0"
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)
    usage_count: int = 0
    rating: float = 0.0
    
    def get_variable_names(self) -> List[str]:
        """获取模板中的变量名"""
        return [var.name for var in self.variables]
    
    def validate_variables(self, variables: Dict[str, Any]) -> List[str]:
        """验证变量"""
        errors = []
        
        for var in self.variables:
            if var.required and var.name not in variables:
                errors.append(f"必需变量 '{var.name}' 缺失")
                continue
            
            if var.name in variables and var.validator:
                try:
                    if not var.validator(variables[var.name]):
                        errors.append(f"变量 '{var.name}' 验证失败")
                except Exception as e:
                    errors.append(f"变量 '{var.name}' 验证错误: {e}")
        
        return errors

@dataclass
class PromptContext:
    """提示词上下文"""
    user_id: Optional[str] = None
    session_id: Optional[str] = None
    conversation_history: List[Dict[str, Any]] = field(default_factory=list)
    user_preferences: Dict[str, Any] = field(default_factory=dict)
    current_task: Optional[str] = None
    environment: Dict[str, Any] = field(default_factory=dict)
    timestamp: datetime = field(default_factory=datetime.now)

class TemplateRenderer(ABC):
    """模板渲染器抽象基类"""
    
    @abstractmethod
    async def render(self, template: PromptTemplate, variables: Dict[str, Any], context: PromptContext) -> str:
        """渲染模板"""
        pass

class Jinja2Renderer(TemplateRenderer):
    """Jinja2模板渲染器"""
    
    def __init__(self, template_dirs: List[str] = None):
        self.template_dirs = template_dirs or []
        self.env = Environment(
            loader=FileSystemLoader(self.template_dirs) if self.template_dirs else None,
            autoescape=True,
            trim_blocks=True,
            lstrip_blocks=True
        )
        
        # 注册自定义函数和过滤器
        self._register_custom_functions()
        self._register_custom_filters()
    
    def _register_custom_functions(self):
        """注册自定义函数"""
        
        def now(format_str: str = "%Y-%m-%d %H:%M:%S") -> str:
            """获取当前时间"""
            return datetime.now().strftime(format_str)
        
        def format_list(items: List[Any], separator: str = ", ", last_separator: str = " and ") -> str:
            """格式化列表"""
            if not items:
                return ""
            if len(items) == 1:
                return str(items[0])
            if len(items) == 2:
                return f"{items[0]}{last_separator}{items[1]}"
            return separator.join(str(item) for item in items[:-1]) + last_separator + str(items[-1])
        
        def truncate_text(text: str, max_length: int = 100, suffix: str = "...") -> str:
            """截断文本"""
            if len(text) <= max_length:
                return text
            return text[:max_length - len(suffix)] + suffix
        
        def json_extract(data: Union[str, Dict], path: str) -> Any:
            """从JSON中提取数据"""
            if isinstance(data, str):
                try:
                    data = json.loads(data)
                except json.JSONDecodeError:
                    return None
            
            keys = path.split('.')
            current = data
            
            for key in keys:
                if isinstance(current, dict) and key in current:
                    current = current[key]
                else:
                    return None
            
            return current
        
        # 注册函数
        self.env.globals.update({
            'now': now,
            'format_list': format_list,
            'truncate_text': truncate_text,
            'json_extract': json_extract
        })
    
    def _register_custom_filters(self):
        """注册自定义过滤器"""
        
        def smart_truncate(text: str, max_length: int = 100) -> str:
            """智能截断(在单词边界)"""
            if len(text) <= max_length:
                return text
            
            truncated = text[:max_length]
            last_space = truncated.rfind(' ')
            
            if last_space > max_length * 0.8:  # 如果最后一个空格位置合理
                return truncated[:last_space] + "..."
            else:
                return truncated + "..."
        
        def highlight_keywords(text: str, keywords: List[str], tag: str = "**") -> str:
            """高亮关键词"""
            for keyword in keywords:
                pattern = re.compile(re.escape(keyword), re.IGNORECASE)
                text = pattern.sub(f"{tag}{keyword}{tag}", text)
            return text
        
        def format_number(value: Union[int, float], precision: int = 2) -> str:
            """格式化数字"""
            if isinstance(value, int):
                return f"{value:,}"
            else:
                return f"{value:,.{precision}f}"
        
        # 注册过滤器
        self.env.filters.update({
            'smart_truncate': smart_truncate,
            'highlight_keywords': highlight_keywords,
            'format_number': format_number
        })
    
    async def render(self, template: PromptTemplate, variables: Dict[str, Any], context: PromptContext) -> str:
        """渲染Jinja2模板"""
        try:
            # 创建模板对象
            if template.format == TemplateFormat.JINJA2:
                jinja_template = Template(template.template_content, environment=self.env)
            else:
                raise ValueError(f"不支持的模板格式: {template.format}")
            
            # 准备渲染变量
            render_vars = {
                **variables,
                'context': context,
                'template': template
            }
            
            # 渲染模板
            rendered = await asyncio.get_event_loop().run_in_executor(
                None, jinja_template.render, render_vars
            )
            
            return rendered.strip()
            
        except TemplateError as e:
            logger.error(f"模板渲染错误: {e}")
            raise ValueError(f"模板渲染失败: {e}")
        except Exception as e:
            logger.error(f"未知渲染错误: {e}")
            raise

class TemplateRegistry:
    """模板注册表"""
    
    def __init__(self):
        self.templates: Dict[str, PromptTemplate] = {}
        self.categories: Dict[str, List[str]] = {}
        self.template_files: Dict[str, str] = {}  # 模板ID -> 文件路径
    
    def register_template(self, template: PromptTemplate):
        """注册模板"""
        self.templates[template.id] = template
        
        # 按标签分类
        for tag in template.tags:
            if tag not in self.categories:
                self.categories[tag] = []
            if template.id not in self.categories[tag]:
                self.categories[tag].append(template.id)
        
        logger.info(f"模板已注册: {template.id}")
    
    def get_template(self, template_id: str) -> Optional[PromptTemplate]:
        """获取模板"""
        return self.templates.get(template_id)
    
    def list_templates(self, tag: Optional[str] = None, prompt_type: Optional[PromptType] = None) -> List[PromptTemplate]:
        """列出模板"""
        templates = list(self.templates.values())
        
        if tag:
            templates = [t for t in templates if tag in t.tags]
        
        if prompt_type:
            templates = [t for t in templates if t.prompt_type == prompt_type]
        
        return templates
    
    def search_templates(self, query: str) -> List[PromptTemplate]:
        """搜索模板"""
        query_lower = query.lower()
        results = []
        
        for template in self.templates.values():
            if (query_lower in template.name.lower() or 
                query_lower in template.description.lower() or
                any(query_lower in tag.lower() for tag in template.tags)):
                results.append(template)
        
        return results
    
    def load_from_directory(self, directory: str):
        """从目录加载模板"""
        template_dir = Path(directory)
        if not template_dir.exists():
            logger.warning(f"模板目录不存在: {directory}")
            return
        
        for file_path in template_dir.rglob("*.yaml"):
            try:
                self._load_template_file(file_path)
            except Exception as e:
                logger.error(f"加载模板文件失败 {file_path}: {e}")
    
    def _load_template_file(self, file_path: Path):
        """加载单个模板文件"""
        with open(file_path, 'r', encoding='utf-8') as f:
            data = yaml.safe_load(f)
        
        # 解析模板定义
        template_data = data.get('template', {})
        
        # 解析变量定义
        variables = []
        for var_data in data.get('variables', []):
            variable = PromptVariable(
                name=var_data['name'],
                type=var_data.get('type', 'string'),
                description=var_data.get('description', ''),
                required=var_data.get('required', True),
                default=var_data.get('default'),
                examples=var_data.get('examples', [])
            )
            variables.append(variable)
        
        # 创建模板对象
        template = PromptTemplate(
            id=template_data['id'],
            name=template_data['name'],
            description=template_data.get('description', ''),
            template_content=template_data['content'],
            prompt_type=PromptType(template_data.get('type', 'user')),
            format=TemplateFormat(template_data.get('format', 'jinja2')),
            variables=variables,
            tags=template_data.get('tags', []),
            version=template_data.get('version', '1.0')
        )
        
        self.register_template(template)
        self.template_files[template.id] = str(file_path)
        
        logger.info(f"从文件加载模板: {template.id} <- {file_path}")

class PromptTemplateEngine:
    """提示词模板引擎"""
    
    def __init__(self, template_dirs: List[str] = None):
        self.registry = TemplateRegistry()
        self.renderer = Jinja2Renderer(template_dirs)
        self.context_providers: List[Callable] = []
    
    def register_context_provider(self, provider: Callable):
        """注册上下文提供者"""
        self.context_providers.append(provider)
    
    async def render_template(self, 
                            template_id: str,
                            variables: Dict[str, Any],
                            context: Optional[PromptContext] = None) -> str:
        """渲染模板"""
        # 获取模板
        template = self.registry.get_template(template_id)
        if not template:
            raise ValueError(f"模板不存在: {template_id}")
        
        # 验证变量
        validation_errors = template.validate_variables(variables)
        if validation_errors:
            raise ValueError(f"变量验证失败: {', '.join(validation_errors)}")
        
        # 使用默认值填充缺失的可选变量
        complete_variables = variables.copy()
        for var in template.variables:
            if not var.required and var.name not in complete_variables and var.default is not None:
                complete_variables[var.name] = var.default
        
        # 构建上下文
        if context is None:
            context = PromptContext()
        
        # 调用上下文提供者
        for provider in self.context_providers:
            try:
                additional_context = await provider(template_id, variables, context)
                if additional_context:
                    context.environment.update(additional_context)
            except Exception as e:
                logger.warning(f"上下文提供者执行失败: {e}")
        
        # 渲染模板
        rendered = await self.renderer.render(template, complete_variables, context)
        
        # 更新使用统计
        template.usage_count += 1
        template.updated_at = datetime.now()
        
        return rendered
    
    async def batch_render(self, 
                          requests: List[Dict[str, Any]]) -> List[str]:
        """批量渲染模板"""
        tasks = []
        
        for request in requests:
            task = self.render_template(
                template_id=request['template_id'],
                variables=request.get('variables', {}),
                context=request.get('context')
            )
            tasks.append(task)
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        # 处理异常
        processed_results = []
        for i, result in enumerate(results):
            if isinstance(result, Exception):
                logger.error(f"批量渲染失败 (索引 {i}): {result}")
                processed_results.append(f"渲染失败: {result}")
            else:
                processed_results.append(result)
        
        return processed_results
    
    def create_template_from_text(self,
                                template_id: str,
                                name: str,
                                content: str,
                                prompt_type: PromptType = PromptType.USER,
                                variables: List[Dict[str, Any]] = None) -> PromptTemplate:
        """从文本创建模板"""
        
        # 自动检测变量
        detected_vars = self._detect_variables(content)
        
        # 构建变量定义
        template_variables = []
        variable_configs = {var['name']: var for var in (variables or [])}
        
        for var_name in detected_vars:
            var_config = variable_configs.get(var_name, {})
            variable = PromptVariable(
                name=var_name,
                type=var_config.get('type', 'string'),
                description=var_config.get('description', f'变量: {var_name}'),
                required=var_config.get('required', True),
                default=var_config.get('default')
            )
            template_variables.append(variable)
        
        template = PromptTemplate(
            id=template_id,
            name=name,
            description=f"从文本创建的模板: {name}",
            template_content=content,
            prompt_type=prompt_type,
            variables=template_variables
        )
        
        self.registry.register_template(template)
        return template
    
    def _detect_variables(self, content: str) -> List[str]:
        """检测模板中的变量"""
        try:
            # 使用Jinja2的meta模块检测变量
            env = Environment()
            ast = env.parse(content)
            variables = meta.find_undeclared_variables(ast)
            return list(variables)
        except Exception as e:
            logger.warning(f"变量检测失败: {e}")
            
            # 回退到正则表达式检测
            pattern = r'\{\{\s*(\w+)\s*\}\}'
            matches = re.findall(pattern, content)
            return list(set(matches))

📚 预定义模板集合

🎯 常用模板定义

创建模板配置文件 templates/common_templates.yaml

yaml
# templates/common_templates.yaml
# 数据分析模板
template:
  id: "data_analysis"
  name: "数据分析助手"
  description: "帮助用户分析各种类型的数据"
  type: "system"
  format: "jinja2"
  tags: ["analysis", "data", "insights"]
  content: |
    你是一个专业的数据分析专家。用户将提供{{ data_type }}类型的数据,你需要:
    
    1. **数据概览**: 分析数据的基本特征和结构
    2. **关键发现**: 识别重要的模式、趋势和异常值
    3. **深度洞察**: 提供有价值的业务洞察和建议
    4. **可视化建议**: 推荐适合的图表类型和可视化方式
    
    {% if analysis_focus %}
    **特别关注**: {{ analysis_focus }}
    {% endif %}
    
    {% if constraints %}
    **分析限制**: {{ constraints }}
    {% endif %}
    
    请用{{ output_language }}回答,保持专业但易懂的语调。
    
    {% if examples %}
    **参考示例**:
    {% for example in examples %}
    - {{ example }}
    {% endfor %}
    {% endif %}

variables:
  - name: "data_type"
    type: "string"
    description: "数据类型(如:销售数据、用户行为数据、财务数据等)"
    required: true
    examples: ["销售数据", "用户行为数据", "市场调研数据"]
  
  - name: "analysis_focus"
    type: "string"
    description: "分析重点"
    required: false
    examples: ["增长趋势", "用户画像", "成本优化"]
  
  - name: "constraints"
    type: "string"
    description: "分析限制或特殊要求"
    required: false
    examples: ["保护用户隐私", "只分析最近3个月", "关注移动端数据"]
  
  - name: "output_language"
    type: "string"
    description: "输出语言"
    required: false
    default: "中文"
    examples: ["中文", "英文", "中英双语"]
  
  - name: "examples"
    type: "list"
    description: "参考示例"
    required: false

---
# 代码审查模板
template:
  id: "code_review"
  name: "代码审查助手"
  description: "专业的代码审查和优化建议"
  type: "system"
  format: "jinja2"
  tags: ["code", "review", "programming"]
  content: |
    你是一个资深的{{ programming_language }}开发专家,正在进行代码审查。
    
    **审查标准**:
    {% for criterion in review_criteria %}
    - {{ criterion }}
    {% endfor %}
    
    **代码类型**: {{ code_type }}
    **项目上下文**: {{ project_context }}
    
    请按以下格式提供审查意见:
    
    ## 🎯 总体评价
    [整体代码质量评估]
    
    ## ✅ 做得好的地方
    [列出代码的优点]
    
    ## ⚠️ 需要改进的地方
    [具体的问题和建议]
    
    ## 🚀 优化建议
    [性能和最佳实践建议]
    
    ## 📝 具体修改建议
    [提供具体的代码修改示例]
    
    {% if security_focus %}
    ## 🔒 安全性检查
    [安全相关的审查意见]
    {% endif %}

variables:
  - name: "programming_language"
    type: "string"
    description: "编程语言"
    required: true
    examples: ["Python", "JavaScript", "Java", "Go", "TypeScript"]
  
  - name: "code_type"
    type: "string"
    description: "代码类型"
    required: true
    examples: ["Web应用", "API服务", "数据处理脚本", "机器学习模型"]
  
  - name: "project_context"
    type: "string"
    description: "项目背景"
    required: true
    examples: ["电商平台后端", "数据分析工具", "移动应用API"]
  
  - name: "review_criteria"
    type: "list"
    description: "审查标准"
    required: false
    default: ["代码可读性", "性能优化", "错误处理", "测试覆盖", "安全性"]
  
  - name: "security_focus"
    type: "boolean"
    description: "是否重点关注安全性"
    required: false
    default: false

---
# 文档生成模板
template:
  id: "documentation_generator"
  name: "文档生成器"
  description: "自动生成各种类型的技术文档"
  type: "user"
  format: "jinja2"
  tags: ["documentation", "technical", "writing"]
  content: |
    请为{{ document_type }}生成专业的技术文档。
    
    **项目信息**:
    - 名称: {{ project_name }}
    - 描述: {{ project_description }}
    - 目标用户: {{ target_audience }}
    
    {% if technical_details %}
    **技术细节**:
    {% for detail in technical_details %}
    - {{ detail }}
    {% endfor %}
    {% endif %}
    
    **文档要求**:
    - 结构清晰,层次分明
    - 包含代码示例和配置说明
    - 提供故障排除指南
    - 使用Markdown格式
    {% if include_diagrams %}
    - 包含必要的架构图和流程图
    {% endif %}
    
    **目标长度**: {{ document_length }}
    **技术水平**: {{ technical_level }}

variables:
  - name: "document_type"
    type: "string"
    description: "文档类型"
    required: true
    examples: ["API文档", "用户手册", "安装指南", "开发指南", "架构文档"]
  
  - name: "project_name"
    type: "string"
    description: "项目名称"
    required: true
  
  - name: "project_description"
    type: "string"
    description: "项目描述"
    required: true
  
  - name: "target_audience"
    type: "string"
    description: "目标用户"
    required: true
    examples: ["开发者", "系统管理员", "最终用户", "产品经理"]
  
  - name: "technical_details"
    type: "list"
    description: "技术细节列表"
    required: false
  
  - name: "include_diagrams"
    type: "boolean"
    description: "是否包含图表"
    required: false
    default: true
  
  - name: "document_length"
    type: "string"
    description: "文档长度"
    required: false
    default: "中等长度(2000-3000字)"
    examples: ["简短(500-1000字)", "中等长度(2000-3000字)", "详细(5000+字)"]
  
  - name: "technical_level"
    type: "string"
    description: "技术水平要求"
    required: false
    default: "中级"
    examples: ["初级", "中级", "高级", "专家级"]

🎨 动态模板生成器

python
"""
dynamic_templates.py - 动态模板生成器
"""

from typing import Dict, List, Any, Optional
import json
from datetime import datetime
from .prompt_templates import PromptTemplate, PromptVariable, PromptType, TemplateFormat

class DynamicTemplateGenerator:
    """动态模板生成器"""
    
    def __init__(self, template_engine):
        self.template_engine = template_engine
        self.template_patterns = {
            'analysis': self._create_analysis_template,
            'comparison': self._create_comparison_template,
            'summarization': self._create_summarization_template,
            'explanation': self._create_explanation_template,
            'creative': self._create_creative_template,
            'problem_solving': self._create_problem_solving_template
        }
    
    async def generate_template(self, 
                              pattern: str,
                              domain: str,
                              requirements: Dict[str, Any]) -> PromptTemplate:
        """生成动态模板"""
        
        if pattern not in self.template_patterns:
            raise ValueError(f"不支持的模板模式: {pattern}")
        
        generator_func = self.template_patterns[pattern]
        template = await generator_func(domain, requirements)
        
        # 注册到模板引擎
        self.template_engine.registry.register_template(template)
        
        return template
    
    async def _create_analysis_template(self, domain: str, requirements: Dict[str, Any]) -> PromptTemplate:
        """创建分析类模板"""
        
        analysis_types = requirements.get('analysis_types', ['趋势分析', '模式识别', '异常检测'])
        output_format = requirements.get('output_format', '结构化报告')
        depth_level = requirements.get('depth_level', '深入')
        
        content = f"""
你是一个专业的{domain}分析专家。请对提供的{{{{ data_source }}}}进行全面分析。

**分析维度**:
{{% for analysis_type in analysis_types %}}
- {{{{ analysis_type }}}}
{{% endfor %}}

**分析深度**: {depth_level}
**输出格式**: {output_format}

{{% if specific_questions %}}
**重点关注问题**:
{{% for question in specific_questions %}}
- {{{{ question }}}}
{{% endfor %}}
{{% endif %}}

请按以下结构输出分析结果:

## 📊 数据概览
[数据基本情况和质量评估]

## 🔍 核心发现
[关键发现和模式]

## 📈 深度洞察
[深层次的分析和解释]

## 💡 建议和行动
[可执行的建议]

{{% if visualization_needed %}}
## 📊 可视化建议
[推荐的图表类型和数据展示方式]
{{% endif %}}
        """.strip()
        
        variables = [
            PromptVariable(
                name="data_source",
                type="string",
                description="数据来源描述",
                required=True
            ),
            PromptVariable(
                name="analysis_types",
                type="list",
                description="分析类型列表",
                required=False,
                default=analysis_types
            ),
            PromptVariable(
                name="specific_questions",
                type="list",
                description="特定问题列表",
                required=False
            ),
            PromptVariable(
                name="visualization_needed",
                type="boolean",
                description="是否需要可视化建议",
                required=False,
                default=True
            )
        ]
        
        template_id = f"dynamic_analysis_{domain}_{int(datetime.now().timestamp())}"
        
        return PromptTemplate(
            id=template_id,
            name=f"{domain}分析模板",
            description=f"动态生成的{domain}领域分析模板",
            template_content=content,
            prompt_type=PromptType.SYSTEM,
            variables=variables,
            tags=['dynamic', 'analysis', domain]
        )
    
    async def _create_comparison_template(self, domain: str, requirements: Dict[str, Any]) -> PromptTemplate:
        """创建比较类模板"""
        
        comparison_criteria = requirements.get('criteria', ['功能', '性能', '成本', '用户体验'])
        comparison_format = requirements.get('format', '表格对比')
        
        content = f"""
请对{{{{ items_to_compare }}}}进行专业的{domain}领域对比分析。

**对比维度**:
{{% for criterion in comparison_criteria %}}
- {{{{ criterion }}}}
{{% endfor %}}

**对比格式**: {comparison_format}

{{% if weighting_factors %}}
**权重考虑**:
{{% for factor, weight in weighting_factors.items() %}}
- {{{{ factor }}}}: {{{{ weight }}}}%
{{% endfor %}}
{{% endif %}}

请按以下结构进行对比:

## 🔍 对比概述
[简要说明对比对象和目的]

## 📊 详细对比
{{% if comparison_format == '表格对比' %}}
| 项目 | {' | '.join(comparison_criteria)} |
|------|{'----|' * len(comparison_criteria)}
{{% for item in items_to_compare %}}
| {{{{ item }}}} | [按标准填写] |
{{% endfor %}}
{{% else %}}
{{% for item in items_to_compare %}}
### {{{{ item }}}}
[详细分析]
{{% endfor %}}
{{% endif %}}

## 🎯 综合评价
[总体评价和推荐]

## 💡 选择建议
[基于不同需求的选择建议]
        """.strip()
        
        variables = [
            PromptVariable(
                name="items_to_compare",
                type="list",
                description="要对比的项目列表",
                required=True
            ),
            PromptVariable(
                name="comparison_criteria",
                type="list",
                description="对比标准",
                required=False,
                default=comparison_criteria
            ),
            PromptVariable(
                name="weighting_factors",
                type="dict",
                description="权重因子",
                required=False
            )
        ]
        
        template_id = f"dynamic_comparison_{domain}_{int(datetime.now().timestamp())}"
        
        return PromptTemplate(
            id=template_id,
            name=f"{domain}对比模板",
            description=f"动态生成的{domain}领域对比模板",
            template_content=content,
            prompt_type=PromptType.SYSTEM,
            variables=variables,
            tags=['dynamic', 'comparison', domain]
        )
    
    async def _create_creative_template(self, domain: str, requirements: Dict[str, Any]) -> PromptTemplate:
        """创建创意类模板"""
        
        creativity_level = requirements.get('creativity_level', '高')
        style_preferences = requirements.get('style', ['创新', '实用', '可行'])
        
        content = f"""
你是一个富有创意的{domain}专家,请为{{{{ creative_brief }}}}提供创新性的解决方案。

**创意要求**:
- 创新程度: {creativity_level}
- 风格偏好: {', '.join(style_preferences)}
{{% if constraints %}}
- 限制条件: {{{{ constraints }}}}
{{% endif %}}

{{% if inspiration_sources %}}
**灵感来源**:
{{% for source in inspiration_sources %}}
- {{{{ source }}}}
{{% endfor %}}
{{% endif %}}

请提供以下创意输出:

## 💡 核心创意
[主要的创新想法]

## 🎨 创意细节
[详细的实现方案]

## 🚀 实施步骤
[具体的执行计划]

## 🔍 可行性分析
[技术和资源可行性]

## 📊 预期效果
[预期的结果和影响]

{{% if alternatives_needed %}}
## 🔄 替代方案
[其他可选的创意方向]
{{% endif %}}
        """.strip()
        
        variables = [
            PromptVariable(
                name="creative_brief",
                type="string",
                description="创意简报",
                required=True
            ),
            PromptVariable(
                name="constraints",
                type="string",
                description="限制条件",
                required=False
            ),
            PromptVariable(
                name="inspiration_sources",
                type="list",
                description="灵感来源",
                required=False
            ),
            PromptVariable(
                name="alternatives_needed",
                type="boolean",
                description="是否需要替代方案",
                required=False,
                default=True
            )
        ]
        
        template_id = f"dynamic_creative_{domain}_{int(datetime.now().timestamp())}"
        
        return PromptTemplate(
            id=template_id,
            name=f"{domain}创意模板",
            description=f"动态生成的{domain}领域创意模板",
            template_content=content,
            prompt_type=PromptType.SYSTEM,
            variables=variables,
            tags=['dynamic', 'creative', domain]
        )
    
    # 其他模板生成方法...
    async def _create_summarization_template(self, domain: str, requirements: Dict[str, Any]) -> PromptTemplate:
        """创建总结类模板"""
        # 实现总结模板生成逻辑
        pass
    
    async def _create_explanation_template(self, domain: str, requirements: Dict[str, Any]) -> PromptTemplate:
        """创建解释类模板"""
        # 实现解释模板生成逻辑
        pass
    
    async def _create_problem_solving_template(self, domain: str, requirements: Dict[str, Any]) -> PromptTemplate:
        """创建问题解决类模板"""
        # 实现问题解决模板生成逻辑
        pass

🎯 本节小结

通过这一小节,你已经构建了一个强大的提示词模板系统:

灵活的模板引擎:支持Jinja2模板和自定义函数
动态模板生成:根据需求自动创建模板
变量验证机制:确保模板参数的正确性
上下文感知:智能整合用户和环境信息
批量处理能力:支持大规模模板渲染

🚀 使用示例

python
# 初始化模板引擎
template_engine = PromptTemplateEngine()

# 加载预定义模板
template_engine.registry.load_from_directory("templates/")

# 渲染数据分析模板
result = await template_engine.render_template(
    template_id="data_analysis",
    variables={
        "data_type": "销售数据",
        "analysis_focus": "季度增长趋势",
        "output_language": "中文"
    }
)

# 动态生成模板
generator = DynamicTemplateGenerator(template_engine)
custom_template = await generator.generate_template(
    pattern="analysis",
    domain="金融",
    requirements={
        "analysis_types": ["风险评估", "收益分析"],
        "depth_level": "专业级"
    }
)

现在你的MCP服务器具备了智能的提示词管理能力,可以为不同场景提供个性化的AI交互体验!


👉 下一小节:5.3 流式处理和实时通信