06. LangChain 提示词模板和提示词工程

提示词模板基础概念

提示词模板就像是智能对话的配方,它们定义了如何结构化地与AI模型交流,确保获得一致且高质量的回复。

为什么需要提示词模板?

传统提示词问题 = '''
❌ 不一致: 每次手动写的提示词可能不同
❌ 难维护: 修改提示词需要找遍所有代码
❌ 难复用: 无法在不同场景重复使用
❌ 难测试: 无法系统性地优化提示词
❌ 难扩展: 添加新功能需要重写提示词
'''

提示词模板优势 = '''
✅ 一致性: 统一的提示词格式和标准
✅ 可维护: 集中管理,一处修改全局生效
✅ 可复用: 模板化设计,多场景复用
✅ 可测试: 可以A/B测试不同模板效果
✅ 可扩展: 参数化设计,灵活扩展功能
'''

基础提示词模板

1. 简单提示词模板

from langchain.prompts import PromptTemplate

# 基础模板
basic_template = PromptTemplate(
    input_variables=["topic", "style"],
    template="请用{style}的风格介绍{topic}"
)

# 使用模板
prompt = basic_template.format(
    topic="人工智能",
    style="通俗易懂"
)
print(prompt)
# 输出: 请用通俗易懂的风格介绍人工智能

# 另一个例子
story_template = PromptTemplate(
    input_variables=["character", "setting", "genre"],
    template="""
    请创作一个{genre}类型的故事:
    
    主角:{character}
    场景:{setting}
    
    要求:
    1. 故事要有趣且引人入胜
    2. 包含冲突和解决方案
    3. 结尾要有意义
    """
)

# 生成故事提示词
story_prompt = story_template.format(
    character="一位年轻的程序员",
    setting="未来的科技城市",
    genre="科幻冒险"
)
print(story_prompt)

2. 带验证的提示词模板

from langchain.prompts import PromptTemplate
from typing import Dict, Any

class ValidatedPromptTemplate:
    def __init__(self, template: str, variables: list, validators: Dict[str, Any]):
        self.template = PromptTemplate(
            input_variables=variables,
            template=template
        )
        self.validators = validators
    
    def format(self, **kwargs):
        """格式化并验证输入"""
        # 验证输入参数
        for var, validator in self.validators.items():
            if var in kwargs:
                value = kwargs[var]
                
                # 类型验证
                if 'type' in validator and not isinstance(value, validator['type']):
                    raise ValueError(f"{var} 必须是 {validator['type'].__name__} 类型")
                
                # 范围验证
                if 'range' in validator:
                    min_val, max_val = validator['range']
                    if not min_val <= value <= max_val:
                        raise ValueError(f"{var} 必须在 {min_val}{max_val} 之间")
                
                # 选项验证
                if 'choices' in validator and value not in validator['choices']:
                    raise ValueError(f"{var} 必须是 {validator['choices']} 中的一个")
        
        return self.template.format(**kwargs)

# 创建带验证的模板
validated_template = ValidatedPromptTemplate(
    template="请为{age}岁的{gender}推荐{category}产品,预算{budget}元",
    variables=["age", "gender", "category", "budget"],
    validators={
        "age": {"type": int, "range": (1, 120)},
        "gender": {"type": str, "choices": ["男性", "女性", "其他"]},
        "category": {"type": str, "choices": ["电子产品", "服装", "食品", "图书"]},
        "budget": {"type": (int, float), "range": (0, 100000)}
    }
)

# 正确使用
try:
    prompt = validated_template.format(
        age=25,
        gender="男性",
        category="电子产品",
        budget=5000
    )
    print("验证通过:", prompt)
except ValueError as e:
    print("验证失败:", e)

# 错误使用(会触发验证错误)
try:
    prompt = validated_template.format(
        age=150,  # 超出范围
        gender="男",  # 不在选项中
        category="汽车",  # 不在选项中
        budget=-100  # 负数
    )
except ValueError as e:
    print("验证错误:", e)

高级提示词模板

1. Few-Shot 提示词模板

from langchain.prompts import FewShotPromptTemplate

# 示例数据
examples = [
    {
        "input": " happy ",
        "output": "sad"
    },
    {
        "input": " tall ",
        "output": "short"
    },
    {
        "input": " fast ",
        "output": "slow"
    },
    {
        "input": " hot ",
        "output": "cold"
    }
]

# 示例模板
example_template = """
输入: {input}
输出: {output}
"""

# 创建示例提示词模板
example_prompt = PromptTemplate(
    input_variables=["input", "output"],
    template=example_template
)

# 创建 Few-Shot 提示词模板
few_shot_template = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    prefix="请找出每个输入词的反义词:",
    suffix="输入: {adjective}\n输出:",
    input_variables=["adjective"],
    example_separator="\n"
)

# 使用模板
prompt = few_shot_template.format(adjective="big")
print(prompt)

2. 动态示例选择

from langchain.prompts import FewShotPromptTemplate
from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma

# 更大的示例库
large_examples = [
    {"input": "happy", "output": "sad"},
    {"input": "tall", "output": "short"},
    {"input": "fast", "output": "slow"},
    {"input": "hot", "output": "cold"},
    {"input": "bright", "output": "dark"},
    {"input": "heavy", "output": "light"},
    {"input": "loud", "output": "quiet"},
    {"input": "rough", "output": "smooth"},
    {"input": "expensive", "output": "cheap"},
    {"input": "difficult", "output": "easy"}
]

# 创建语义相似度选择器
example_selector = SemanticSimilarityExampleSelector.from_examples(
    examples=large_examples,
    embeddings=OpenAIEmbeddings(),
    vectorstore_cls=Chroma,
    k=3  # 选择最相似的3个示例
)

# 创建动态 Few-Shot 模板
dynamic_template = FewShotPromptTemplate(
    example_selector=example_selector,
    example_prompt=PromptTemplate(
        input_variables=["input", "output"],
        template="输入: {input}\n输出: {output}"
    ),
    prefix="根据示例,找出输入词的反义词:",
    suffix="输入: {input}\n输出:",
    input_variables=["input"],
    example_separator="\n\n"
)

# 使用动态模板
test_words = ["large", "soft", "complex"]
for word in test_words:
    prompt = dynamic_template.format(input=word)
    print(f"\n=== 测试词: {word} ===")
    print(prompt)

3. 条件提示词模板

from langchain.prompts import ConditionalPromptTemplate

class ConditionalPromptTemplate:
    def __init__(self, templates: dict, condition_func):
        self.templates = templates
        self.condition_func = condition_func
    
    def format(self, **kwargs):
        """根据条件选择合适的模板"""
        condition = self.condition_func(**kwargs)
        template = self.templates.get(condition, self.templates.get("default"))
        
        if template:
            return template.format(**kwargs)
        else:
            raise ValueError(f"未找到条件 '{condition}' 对应的模板")

# 条件函数:根据用户水平选择模板
def select_template_by_level(**kwargs):
    experience = kwargs.get("experience", "beginner")
    if experience == "beginner":
        return "simple"
    elif experience == "intermediate":
        return "detailed"
    elif experience == "expert":
        return "technical"
    else:
        return "default"

# 定义不同复杂度的模板
templates = {
    "simple": PromptTemplate(
        input_variables=["concept"],
        template="请用简单的语言解释什么是{concept},就像给小学生讲课一样。"
    ),
    "detailed": PromptTemplate(
        input_variables=["concept"],
        template="请详细解释{concept}的概念、原理和应用,适合有一定基础的读者。"
    ),
    "technical": PromptTemplate(
        input_variables=["concept"],
        template="请从技术角度深入分析{concept},包括算法原理、实现细节和性能优化。"
    ),
    "default": PromptTemplate(
        input_variables=["concept"],
        template="请解释{concept}的基本概念。"
    )
}

# 创建条件模板
conditional_template = ConditionalPromptTemplate(
    templates=templates,
    condition_func=select_template_by_level
)

# 测试不同水平的提示词
concepts = ["机器学习", "区块链", "量子计算"]
levels = ["beginner", "intermediate", "expert"]

for concept in concepts:
    for level in levels:
        prompt = conditional_template.format(
            concept=concept,
            experience=level
        )
        print(f"\n=== {concept} - {level} ===")
        print(prompt)

聊天提示词模板

1. 基础聊天模板

from langchain.prompts import ChatPromptTemplate
from langchain.schema import SystemMessage, HumanMessage, AIMessage

# 基础聊天模板
chat_template = ChatPromptTemplate.from_messages([
    SystemMessage(content="你是一个专业的AI助手"),
    HumanMessage(content="{user_question}")
])

# 使用模板
messages = chat_template.format_messages(
    user_question="什么是人工智能?"
)
print("消息列表:")
for msg in messages:
    print(f"{type(msg).__name__}: {msg.content}")

# 带变量的聊天模板
advanced_chat_template = ChatPromptTemplate.from_messages([
    ("system", "你是一个{role},擅长{expertise}"),
    ("human", "请{action}关于{topic}的内容"),
    ("ai", "我来为您{action}关于{topic}的内容"),
    ("human", "{follow_up_question}")
])

# 使用高级模板
messages = advanced_chat_template.format_messages(
    role="Python编程专家",
    expertise="数据分析和机器学习",
    action="详细解释",
    topic="pandas库的使用",
    follow_up_question="如何处理缺失值?"
)

print("\n=== 高级聊天模板 ===")
for msg in messages:
    role = "系统" if isinstance(msg, SystemMessage) else \
           "用户" if isinstance(msg, HumanMessage) else "AI"
    print(f"{role}: {msg.content}")

2. 动态聊天模板

class DynamicChatTemplate:
    def __init__(self, base_messages=None):
        self.base_messages = base_messages or []
        self.message_templates = {
            "system": ("system", "{content}"),
            "human": ("human", "{content}"),
            "ai": ("ai", "{content}"),
            "function": ("function", "{content}", "{name}")
        }
    
    def add_message(self, role: str, content: str, **kwargs):
        """添加消息模板"""
        if role in self.message_templates:
            template = self.message_templates[role]
            if len(template) == 2:
                self.base_messages.append(template)
            else:
                self.base_messages.append(template[:2])
    
    def format_messages(self, **kwargs):
        """格式化消息"""
        formatted_messages = []
        
        for template in self.base_messages:
            role, content_template = template
            content = content_template.format(**kwargs)
            
            if role == "system":
                formatted_messages.append(SystemMessage(content=content))
            elif role == "human":
                formatted_messages.append(HumanMessage(content=content))
            elif role == "ai":
                formatted_messages.append(AIMessage(content=content))
        
        return formatted_messages
    
    def create_conversation_flow(self, flow_config: list):
        """创建对话流程"""
        for step in flow_config:
            role = step.get("role")
            content = step.get("content", "")
            variables = step.get("variables", [])
            
            # 创建动态内容模板
            content_template = content
            for var in variables:
                content_template = content_template.replace(
                    f"{{{var}}}", 
                    f"{{{var}}}"
                )
            
            self.add_message(role, content_template)

# 创建动态聊天模板
dynamic_template = DynamicChatTemplate()

# 定义对话流程
conversation_flow = [
    {
        "role": "system",
        "content": "你是一个{expertise}专家,请用{style}的风格回答",
        "variables": ["expertise", "style"]
    },
    {
        "role": "human",
        "content": "请{action}关于{topic}的内容",
        "variables": ["action", "topic"]
    },
    {
        "role": "ai",
        "content": "我来为您{action}关于{topic}的内容",
        "variables": ["action", "topic"]
    }
]

# 创建对话流程
dynamic_template.create_conversation_flow(conversation_flow)

# 使用动态模板
messages = dynamic_template.format_messages(
    expertise="Python编程",
    style="通俗易懂",
    action="详细解释",
    topic="装饰器"
)

print("=== 动态聊天模板 ===")
for msg in messages:
    role = "系统" if isinstance(msg, SystemMessage) else \
           "用户" if isinstance(msg, HumanMessage) else "AI"
    print(f"{role}: {msg.content}")

提示词工程最佳实践

1. 提示词设计原则

提示词设计原则 = '''
1. 清晰性原则:
   - 明确任务目标和要求
   - 避免模糊和歧义
   - 使用具体的描述

2. 结构化原则:
   - 使用清晰的格式和结构
   - 分步骤说明复杂任务
   - 使用标题和列表

3. 上下文原则:
   - 提供充分的背景信息
   - 设定合适的角色和场景
   - 明确约束条件

4. 示例原则:
   - 提供具体的例子
   - 展示期望的输出格式
   - 说明质量标准

5. 迭代原则:
   - 持续优化提示词
   - 根据结果调整模板
   - A/B测试不同版本
'''

2. 提示词优化技巧

class PromptOptimizer:
    def __init__(self):
        self.optimization_strategies = {
            "clarity": self.optimize_clarity,
            "structure": self.optimize_structure,
            "context": self.optimize_context,
            "examples": self.optimize_examples
        }
    
    def optimize_clarity(self, prompt: str):
        """优化清晰度"""
        clarity_checks = [
            ("是否明确说明了任务?", "请在提示词开头明确说明任务目标"),
            ("是否指定了输出格式?", "请添加输出格式要求"),
            ("是否设定了质量标准?", "请说明质量评判标准"),
            ("是否避免了模糊词汇?", "请使用具体、可量化的描述")
        ]
        
        suggestions = []
        for check, suggestion in clarity_checks:
            if not self.check_prompt_quality(prompt, check):
                suggestions.append(suggestion)
        
        return suggestions
    
    def optimize_structure(self, prompt: str):
        """优化结构"""
        structure_improvements = []
        
        if "步骤" not in prompt and "流程" not in prompt:
            structure_improvements.append("考虑将任务分解为清晰的步骤")
        
        if len(prompt.split("\n")) < 3:
            structure_improvements.append("使用多行格式,提高可读性")
        
        if "要求" not in prompt and "注意" not in prompt:
            structure_improvements.append("添加明确的要求或注意事项部分")
        
        return structure_improvements
    
    def check_prompt_quality(self, prompt: str, criterion: str):
        """检查提示词质量"""
        # 简化的质量检查逻辑
        quality_indicators = {
            "是否明确说明了任务?": ["请", "任务", "目标", "要求"],
            "是否指定了输出格式?": ["格式", "结构", "样式", "模板"],
            "是否设定了质量标准?": ["质量", "标准", "要求", "评判"],
            "是否避免了模糊词汇?": ["具体", "明确", "详细", "清晰"]
        }
        
        indicators = quality_indicators.get(criterion, [])
        return any(indicator in prompt for indicator in indicators)
    
    def generate_optimized_version(self, original_prompt: str, focus_areas: list):
        """生成优化版本"""
        suggestions = []
        
        for area in focus_areas:
            if area in self.optimization_strategies:
                area_suggestions = self.optimization_strategies[area](original_prompt)
                suggestions.extend(area_suggestions)
        
        return {
            "original": original_prompt,
            "suggestions": suggestions,
            "optimized": self.apply_suggestions(original_prompt, suggestions)
        }
    
    def apply_suggestions(self, prompt: str, suggestions: list):
        """应用优化建议"""
        # 简化的优化应用逻辑
        optimized = prompt
        
        if "明确说明任务目标" in str(suggestions):
            optimized = f"任务目标:{optimized}"
        
        if "添加输出格式要求" in str(suggestions):
            optimized += "\n\n输出格式要求:\n- 使用清晰的结构\n- 提供具体的例子\n- 给出详细的解释"
        
        if "说明质量评判标准" in str(suggestions):
            optimized += "\n\n质量要求:回复应该准确、详细、易懂,并提供实际例子。"
        
        return optimized

# 使用提示词优化器
optimizer = PromptOptimizer()

# 原始提示词
original_prompt = "解释一下机器学习"

# 生成优化版本
optimization_result = optimizer.generate_optimized_version(
    original_prompt,
    focus_areas=["clarity", "structure"]
)

print("=== 提示词优化示例 ===")
print(f"原始提示词: {optimization_result['original']}")
print(f"\n优化建议: {optimization_result['suggestions']}")
print(f"\n优化版本: {optimization_result['optimized']}")

3. 提示词测试和评估

class PromptEvaluator:
    def __init__(self):
        self.evaluation_criteria = {
            "relevance": "回复是否与问题相关",
            "accuracy": "信息是否准确",
            "completeness": "是否回答了所有方面",
            "clarity": "表达是否清晰易懂",
            "usefulness": "对用户是否有用"
        }
    
    def create_test_cases(self, prompt_template, test_scenarios: list):
        """创建测试用例"""
        test_cases = []
        
        for scenario in test_scenarios:
            test_case = {
                "name": scenario.get("name", "未命名测试"),
                "input": scenario.get("input", {}),
                "expected": scenario.get("expected", ""),
                "criteria": scenario.get("criteria", ["relevance", "accuracy"])
            }
            test_cases.append(test_case)
        
        return test_cases
    
    def evaluate_response(self, response: str, test_case: dict):
        """评估回复质量"""
        evaluation = {
            "test_name": test_case["name"],
            "response": response,
            "scores": {},
            "overall_score": 0
        }
        
        # 简化的评分逻辑(实际应用中可能需要人工评估或更复杂的自动评估)
        for criterion in test_case["criteria"]:
            if criterion in self.evaluation_criteria:
                # 这里使用模拟评分,实际应用中需要真实的评估逻辑
                score = self.simulate_evaluation(response, criterion)
                evaluation["scores"][criterion] = score
                evaluation["overall_score"] += score
        
        evaluation["overall_score"] /= len(test_case["criteria"])
        
        return evaluation
    
    def simulate_evaluation(self, response: str, criterion: str):
        """模拟评估(实际应用中需要真实评估逻辑)"""
        # 基于关键词的简单评估逻辑
        quality_indicators = {
            "relevance": ["相关", "针对", "回答"],
            "accuracy": ["正确", "准确", "事实"],
            "completeness": ["全面", "完整", "详细"],
            "clarity": ["清晰", "易懂", "明确"],
            "usefulness": ["有用", "实用", "帮助"]
        }
        
        indicators = quality_indicators.get(criterion, [])
        score = 0
        
        for indicator in indicators:
            if indicator in response:
                score += 0.2
        
        return min(score, 1.0)  # 最高1分
    
    def run_evaluation_suite(self, prompt_template, test_scenarios: list, chat_model):
        """运行完整的评估套件"""
        test_cases = self.create_test_cases(prompt_template, test_scenarios)
        results = []
        
        print("=== 开始提示词模板评估 ===")
        
        for test_case in test_cases:
            print(f"\n运行测试: {test_case['name']}")
            
            # 生成提示词
            prompt = prompt_template.format(**test_case["input"])
            
            # 获取模型回复
            try:
                from langchain.schema import HumanMessage
                response = chat_model([HumanMessage(content=prompt)])
                response_text = response.content
            except Exception as e:
                print(f"获取回复时出错: {e}")
                continue
            
            # 评估回复
            evaluation = self.evaluate_response(response_text, test_case)
            results.append(evaluation)
            
            print(f"整体评分: {evaluation['overall_score']:.2f}")
            print(f"详细评分: {evaluation['scores']}")
        
        # 生成评估报告
        report = self.generate_evaluation_report(results)
        return report
    
    def generate_evaluation_report(self, results: list):
        """生成评估报告"""
        if not results:
            return "没有评估结果"
        
        total_tests = len(results)
        avg_score = sum(result["overall_score"] for result in results) / total_tests
        
        report = f"""
=== 提示词模板评估报告 ===
总测试数: {total_tests}
平均评分: {avg_score:.2f}

详细结果:
"""
        
        for result in results:
            report += f"""
测试名称: {result['test_name']}
整体评分: {result['overall_score']:.2f}
详细评分: {result['scores']}
回复预览: {result['response'][:100]}...
"""
        
        # 改进建议
        if avg_score < 0.7:
            report += "\n改进建议:\n"
            report += "- 考虑优化提示词的清晰度\n"
            report += "- 添加更多的上下文信息\n"
            report += "- 提供更具体的示例\n"
        
        return report

# 使用评估器
evaluator = PromptEvaluator()

# 定义测试场景
test_scenarios = [
    {
        "name": "基础概念解释",
        "input": {"concept": "机器学习"},
        "expected": "包含定义、原理、应用",
        "criteria": ["relevance", "accuracy", "completeness"]
    },
    {
        "name": "技术细节询问",
        "input": {"concept": "神经网络"},
        "expected": "包含结构、工作原理、类型",
        "criteria": ["relevance", "accuracy", "clarity"]
    },
    {
        "name": "实际应用咨询",
        "input": {"concept": "深度学习在医疗中的应用"},
        "expected": "包含具体应用、案例、效果",
        "criteria": ["relevance", "completeness", "usefulness"]
    }
]

# 创建提示词模板
concept_template = PromptTemplate(
    input_variables=["concept"],
    template="请详细解释什么是{concept},包括定义、原理、应用和实际例子。"
)

# 注意:实际运行需要配置好聊天模型
# report = evaluator.run_evaluation_suite(concept_template, test_scenarios, chat_model)
# print(report)

实际应用案例

1. 内容生成系统

class ContentGenerationSystem:
    def __init__(self):
        self.templates = {
            "blog": self.create_blog_template(),
            "social": self.create_social_template(),
            "email": self.create_email_template(),
            "product": self.create_product_template()
        }
    
    def create_blog_template(self):
        """创建博客文章模板"""
        return PromptTemplate(
            input_variables=["topic", "audience", "length", "tone"],
            template="""
            请写一篇关于{topic}的博客文章。
            
            目标读者:{audience}
            文章长度:{length}
            写作风格:{tone}
            
            文章结构要求:
            1. 引人入胜的开头
            2. 清晰的逻辑结构
            3. 实用的内容
            4. 有力的结尾
            
            请确保内容:
            - 信息准确且有用
            - 语言流畅自然
            - 适合目标读者
            - 包含实际例子
            
            文章:
            """
        )
    
    def create_social_template(self):
        """创建社交媒体模板"""
        return PromptTemplate(
            input_variables=["platform", "topic", "goal", "hashtags"],
            template="""
            请为{platform}平台创作一条关于{topic}的社交媒体内容。
            
            发布目的:{goal}
            相关标签:{hashtags}
            
            内容要求:
            1. 吸引眼球的开头
            2. 简洁有力的表达
            3. 适合平台特点
            4. 包含行动号召
            
            内容:
            """
        )
    
    def create_email_template(self):
        """创建邮件模板"""
        return PromptTemplate(
            input_variables=["purpose", "recipient", "tone", "key_points"],
            template="""
            请写一封{purpose}的邮件。
            
            收件人:{recipient}
            邮件语气:{tone}
            关键要点:{key_points}
            
            邮件要求:
            1. 清晰的主题行
            2. 礼貌的称呼
            3. 简洁的正文
            4. 专业的结尾
            
            邮件内容:
            """
        )
    
    def create_product_template(self):
        """创建产品描述模板"""
        return PromptTemplate(
            input_variables=["product", "features", "benefits", "target_audience"],
            template="""
            请为以下产品撰写产品描述:
            
            产品名称:{product}
            主要特性:{features}
            用户收益:{benefits}
            目标用户:{target_audience}
            
            描述要求:
            1. 突出产品优势
            2. 解决用户痛点
            3. 包含使用场景
            4. 有说服力的语言
            
            产品描述:
            """
        )
    
    def generate_content(self, content_type: str, **kwargs):
        """生成内容"""
        if content_type not in self.templates:
            raise ValueError(f"不支持的内容类型: {content_type}")
        
        template = self.templates[content_type]
        prompt = template.format(**kwargs)
        
        return {
            "type": content_type,
            "prompt": prompt,
            "parameters": kwargs
        }

# 使用内容生成系统
content_system = ContentGenerationSystem()

# 生成博客文章
blog_content = content_system.generate_content(
    "blog",
    topic="人工智能在医疗领域的应用",
    audience="医疗行业从业者",
    length="1000-1500字",
    tone="专业但易懂"
)

print("=== 博客文章生成 ===")
print(blog_content["prompt"])

# 生成社交媒体内容
social_content = content_system.generate_content(
    "social",
    platform="微博",
    topic="健康饮食",
    goal="提高品牌知名度",
    hashtags="#健康饮食 #营养生活 # wellness"
)

print("\n=== 社交媒体内容生成 ===")
print(social_content["prompt"])

2. 教育问答系统

class EducationalQASystem:
    def __init__(self):
        self.difficulty_levels = {
            "elementary": "小学生",
            "middle": "初中生", 
            "high": "高中生",
            "university": "大学生",
            "professional": "专业人士"
        }
        
        self.subject_templates = {
            "math": self.create_math_template(),
            "science": self.create_science_template(),
            "history": self.create_history_template(),
            "language": self.create_language_template()
        }
    
    def create_math_template(self):
        """创建数学问题模板"""
        return PromptTemplate(
            input_variables=["question", "level", "topic"],
            template="""
            你是一个专业的数学教师,请为{level}学生解答以下数学问题。
            
            问题:{question}
            知识点:{topic}
            
            解答要求:
            1. 使用适合学生水平的语言
            2. 提供详细的解题步骤
            3. 解释相关的数学概念
            4. 给出类似问题的解题思路
            
            解答:
            """
        )
    
    def create_science_template(self):
        """创建科学问题模板"""
        return PromptTemplate(
            input_variables=["question", "level", "topic"],
            template="""
            你是一个科学教育专家,请为{level}学生解答以下科学问题。
            
            问题:{question}
            科学领域:{topic}
            
            解答要求:
            1. 用通俗易懂的语言解释科学原理
            2. 结合日常生活中的例子
            3. 鼓励学生思考和探索
            4. 可以安全进行的实验建议
            
            科学解答:
            """
        )
    
    def create_history_template(self):
        """创建历史问题模板"""
        return PromptTemplate(
            input_variables=["question", "level", "period"],
            template="""
            你是一个历史学者,请为{level}学生解答以下历史问题。
            
            问题:{question}
            历史时期:{period}
            
            解答要求:
            1. 提供准确的历史事实
            2. 分析历史背景和原因
            3. 联系现实,启发思考
            4. 培养历史思维能力
            
            历史解答:
            """
        )
    
    def create_language_template(self):
        """创建语言学习模板"""
        return PromptTemplate(
            input_variables=["question", "level", "aspect"],
            template="""
            你是一个语言教育专家,请为{level}学生解答以下语言问题。
            
            问题:{question}
            语言方面:{aspect}
            
            解答要求:
            1. 清晰的语法解释
            2. 提供丰富的例子
            3. 指出常见错误
            4. 给出练习建议
            
            语言解答:
            """
        )
    
    def create_explanation(self, subject: str, question: str, level: str, **kwargs):
        """创建解释"""
        if subject not in self.subject_templates:
            raise ValueError(f"不支持的学科: {subject}")
        
        if level not in self.difficulty_levels:
            raise ValueError(f"不支持的水平: {level}")
        
        template = self.subject_templates[subject]
        
        # 构建参数
        params = {
            "question": question,
            "level": self.difficulty_levels[level],
            **kwargs
        }
        
        prompt = template.format(**params)
        
        return {
            "subject": subject,
            "level": level,
            "question": question,
            "prompt": prompt,
            "parameters": params
        }

# 使用教育问答系统
edu_system = EducationalQASystem()

# 数学问题解答
math_explanation = edu_system.create_explanation(
    subject="math",
    question="如何解一元二次方程?",
    level="middle",
    topic="代数方程"
)

print("=== 数学问题解答 ===")
print(math_explanation["prompt"])

# 科学问题解答
science_explanation = edu_system.create_explanation(
    subject="science",
    question="为什么天空是蓝色的?",
    level="elementary",
    topic="光学现象"
)

print("\n=== 科学问题解答 ===")
print(science_explanation["prompt"])

小结

通过本章的学习,我们全面掌握了 LangChain 提示词模板和提示词工程

提示词模板核心概念

  1. 基础模板:掌握简单和带验证的提示词模板
  2. 高级模板:学会使用 Few-Shot、动态示例选择等高级功能
  3. 聊天模板:理解消息格式和对话流程设计
  4. 条件模板:实现智能化的模板选择

提示词工程技能

  1. 设计原则:掌握提示词设计的核心原则
  2. 优化技巧:学会系统性地优化提示词
  3. 测试评估:建立提示词质量评估体系
  4. 最佳实践:积累实际应用的宝贵经验

实际应用能力

  1. 内容生成:构建专业的内容生成系统
  2. 教育问答:开发智能教育辅助系统
  3. 模板复用:实现高效的模板管理和复用
  4. 质量优化:持续提升提示词效果

提示词工程是AI应用开发的核心技能,掌握它就像拥有了与AI高效沟通的魔法语言! 🎯✨

在下一章中,我们将深入学习LangChain的链(Chains)机制,掌握如何构建复杂的工作流程和任务处理系统!

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐