概述
LangChain Template 是 LangChain 提示工程的核心组件,用于动态生成模型的输入。
🎯 Template 的核心概念:
Template 本质是一个带有占位符的文本字符串,这些占位符会在运行时被具体的值填充。它的主要目的是将提示逻辑与业务数据分离。
模板分类
1. 🎯 基础模板类(Core Templates)
(1) PromptTemplate
最基础的文本模板
1from langchain.prompts import PromptTemplate 2 3# 创建模板的两种方式 4# 方式1: 使用 from_template (推荐) 5template = PromptTemplate.from_template("请把{text}翻译成{language}") 6result = template.format(text="Hello", language="中文") 7print(result) # 输出: "请把Hello翻译成中文" 8 9# 方式2: 传统创建方式 10template = PromptTemplate( 11 input_variables=["text", "language"], 12 template="请把{text}翻译成{language}" 13) 14 15# 实际应用示例 16translation_template = PromptTemplate.from_template( 17 "将以下{source_lang}文本翻译成{target_lang}:{text}" 18) 19translation_result = translation_template.format( 20 source_lang="英文", 21 target_lang="中文", 22 text="Hello, how are you?" 23) 24
(2) ChatPromptTemplate
聊天消息模板(最常用)
1from langchain.prompts import ChatPromptTemplate 2 3# 创建聊天提示模板 4chat_prompt = ChatPromptTemplate.from_messages([ 5 ("system", "你是一个{role}"), 6 ("human", "请回答:{question}") 7]) 8 9# 格式化模板 10messages = chat_prompt.format_messages( 11 role="数学老师", 12 question="什么是勾股定理?" 13) 14 15# 实际应用:客服机器人模板 16customer_service_prompt = ChatPromptTemplate.from_messages([ 17 ("system", "你是{company}的客服代表,专门处理{department}问题"), 18 ("human", "我遇到了一个问题:{issue_description}"), 19 ("ai", "我很理解您的情况,让我来帮您解决。"), 20 ("human", "具体的细节是:{details}") 21]) 22
2. 👥 消息模板类(Message Templates)
这些是 ChatPromptTemplate 的组成部分:
1from langchain.prompts import ( 2 SystemMessagePromptTemplate, 3 HumanMessagePromptTemplate, 4 AIMessagePromptTemplate, 5 FunctionMessagePromptTemplate 6) 7 8# 创建各种消息模板 9system_template = SystemMessagePromptTemplate.from_template( 10 "你是{role},具有{expertise}专业知识" 11) 12human_template = HumanMessagePromptTemplate.from_template( 13 "我的问题是:{question}" 14) 15ai_template = AIMessagePromptTemplate.from_template( 16 "根据我的知识,{answer}" 17) 18 19# 组合使用 20chat_prompt = ChatPromptTemplate.from_messages([ 21 system_template, 22 human_template, 23 ai_template 24]) 25 26# 完整示例:编程助手 27programming_prompt = ChatPromptTemplate.from_messages([ 28 SystemMessagePromptTemplate.from_template( 29 "你是{language}编程专家,擅长{domain}开发" 30 ), 31 HumanMessagePromptTemplate.from_template( 32 "请帮我解决这个编程问题:{problem}" 33 ), 34 AIMessagePromptTemplate.from_template( 35 "我会按照以下思路解决:{approach}" 36 ), 37 HumanMessagePromptTemplate.from_template( 38 "具体实现代码是?" 39 ) 40]) 41
3. 🎪 高级模板类(Advanced Templates)
(7) FewShotPromptTemplate
少样本学习模板
1from langchain.prompts import FewShotPromptTemplate, PromptTemplate 2 3# 定义示例数据 4examples = [ 5 { 6 "input": "The weather is nice today", 7 "output": "今天天气很好" 8 }, 9 { 10 "input": "I love programming", 11 "output": "我喜欢编程" 12 }, 13 { 14 "input": "The meeting starts at 3 PM", 15 "output": "会议下午三点开始" 16 } 17] 18 19# 定义单个示例的模板 20example_template = PromptTemplate.from_template( 21 "英文: {input}\n中文: {output}" 22) 23 24# 创建少样本提示模板 25few_shot_prompt = FewShotPromptTemplate( 26 examples=examples, 27 example_prompt=example_template, 28 prefix="请根据以下示例将英文翻译成中文:", 29 suffix="英文: {input}\n中文:", 30 input_variables=["input"] 31) 32 33# 使用示例 34result = few_shot_prompt.format(input="Thank you for your help") 35print("=== 生成的提示 ===") 36print(result) 37 38# 实际应用:情感分析少样本模板 39sentiment_examples = [ 40 {"text": "这个产品太棒了!", "sentiment": "正面"}, 41 {"text": "服务很差,很不满意", "sentiment": "负面"}, 42 {"text": "还可以,一般般", "sentiment": "中性"} 43] 44 45sentiment_template = FewShotPromptTemplate( 46 examples=sentiment_examples, 47 example_prompt=PromptTemplate.from_template( 48 "文本: {text}\n情感: {sentiment}" 49 ), 50 prefix="分析以下文本的情感倾向:", 51 suffix="文本: {text}\n情感:", 52 input_variables=["text"] 53) 54
(8) FewShotChatMessagePromptTemplate
聊天版的少样本模板
1from langchain.prompts import FewShotChatMessagePromptTemplate, ChatPromptTemplate 2 3# 定义聊天示例 4chat_examples = [ 5 { 6 "input": "今天的天气怎么样?", 7 "output": "我无法获取实时天气信息,请查看天气预报应用。" 8 }, 9 { 10 "input": "现在几点了?", 11 "output": "我无法获取当前时间,请查看您的设备时钟。" 12 }, 13 { 14 "input": "我的快递到哪里了?", 15 "output": "我无法查询物流信息,请使用快递公司的官方应用查询。" 16 } 17] 18 19# 创建示例模板 20example_prompt = ChatPromptTemplate.from_messages([ 21 ("human", "{input}"), 22 ("ai", "{output}") 23]) 24 25# 创建少样本聊天模板 26few_shot_chat = FewShotChatMessagePromptTemplate( 27 examples=chat_examples, 28 example_prompt=example_prompt 29) 30 31# 组合到完整提示中 32final_prompt = ChatPromptTemplate.from_messages([ 33 ("system", "你是一个有帮助的AI助手,请礼貌地回答用户问题。"), 34 few_shot_chat, 35 ("human", "{user_input}") 36]) 37 38# 使用示例 39messages = final_prompt.format_messages( 40 user_input="我的银行余额是多少?" 41) 42
4. 🧩 特殊用途模板
(9) MessagesPlaceholder
消息占位符(用于动态插入消息)
1from langchain.prompts import MessagesPlaceholder, ChatPromptTemplate 2 3# 创建带消息占位符的模板 4prompt_with_history = ChatPromptTemplate.from_messages([ 5 ("system", "你是专业的{expert_role}"), 6 MessagesPlaceholder(variable_name="chat_history"), 7 ("human", "{current_question}") 8]) 9 10# 模拟对话历史 11chat_history = [ 12 {"role": "human", "content": "什么是Python?"}, 13 {"role": "ai", "content": "Python是一种编程语言。"} 14] 15 16# 格式化模板 17messages = prompt_with_history.format_messages( 18 expert_role="编程教师", 19 chat_history=chat_history, 20 current_question="Python有什么特点?" 21) 22 23# 实际应用:带记忆的对话系统 24memory_prompt = ChatPromptTemplate.from_messages([ 25 ("system", """你是{assistant_name},具有以下特点: 26 - 专业领域: {expertise} 27 - 回答风格: {style} 28 - 语言: {language}"""), 29 30 MessagesPlaceholder(variable_name="conversation_history"), 31 ("human", "{current_input}") 32]) 33
🔗 Template 关系图谱
1PromptTemplate (基类) 2 │ 3 ├── ChatPromptTemplate (组合多个消息) 4 │ ├── SystemMessagePromptTemplate 5 │ ├── HumanMessagePromptTemplate 6 │ ├── AIMessagePromptTemplate 7 │ └── FunctionMessagePromptTemplate 8 │ 9 ├── FewShotPromptTemplate (包含example_prompt) 10 │ 11 └── FewShotChatMessagePromptTemplate (专门用于聊天) 12
🎯 核心关系说明
关系1:包含关系
1# FewShotPromptTemplate 包含 PromptTemplate 2examples = [ 3 {"input": "hello", "output": "你好"}, 4 {"input": "goodbye", "output": "再见"} 5] 6 7example_prompt = PromptTemplate.from_template( 8 "输入: {input}\n输出: {output}" 9) 10 11few_shot_prompt = FewShotPromptTemplate( 12 example_prompt=example_prompt, # 包含关系 13 examples=examples, 14 prefix="翻译任务:", 15 suffix="输入: {input}\n输出:", 16 input_variables=["input"] 17) 18 19# ChatPromptTemplate 包含 MessagePromptTemplates 20system_template = SystemMessagePromptTemplate.from_template("系统: {role}") 21human_template = HumanMessagePromptTemplate.from_template("用户: {question}") 22 23chat_prompt = ChatPromptTemplate.from_messages([ 24 system_template, # 包含关系 25 human_template # 包含关系 26]) 27
关系2:组合关系
1from langchain.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate 2 3# 创建少样本部分 4few_shot_examples = [ 5 {"input": "如何学习编程?", "output": "建议从基础语法开始..."}, 6 {"input": "最好的编程语言?", "output": "这取决于你的目标..."} 7] 8 9few_shot_section = FewShotChatMessagePromptTemplate( 10 example_prompt=ChatPromptTemplate.from_messages([ 11 ("human", "{input}"), 12 ("ai", "{output}") 13 ]), 14 examples=few_shot_examples 15) 16 17# FewShotChatMessagePromptTemplate 作为 ChatPromptTemplate 的一部分 18final_prompt = ChatPromptTemplate.from_messages([ 19 ("system", "你是{teacher_type}老师"), 20 few_shot_section, # 组合关系 21 MessagesPlaceholder(variable_name="history"), # 组合关系 22 HumanMessagePromptTemplate.from_template("{current_input}") 23]) 24 25# 使用组合模板 26formatted_messages = final_prompt.format_messages( 27 teacher_type="编程", 28 history=[], 29 current_input="如何调试代码?" 30) 31
🛠️ 实际使用场景对比
场景1:简单文本生成 → PromptTemplate
1# 诗歌生成 2poem_template = PromptTemplate.from_template(""" 3请以{style}风格写一首关于{topic}的诗。 4 5要求: 6- 意境: {mood} 7- 长度: {length} 8- 语言: {language} 9 10诗歌: 11""") 12 13poem_prompt = poem_template.format( 14 style="浪漫", 15 topic="春天", 16 mood="欢快", 17 length="八句", 18 language="中文" 19) 20
场景2:聊天对话 → ChatPromptTemplate + MessageTemplates
1# 专业咨询对话 2system_msg = SystemMessagePromptTemplate.from_template(""" 3你是{profession}顾问,具有以下资质: 4- 经验: {experience} 5- 专长: {specialization} 6- 认证: {certifications} 7""") 8 9human_msg = HumanMessagePromptTemplate.from_template(""" 10我的咨询问题是:{question} 11 12背景信息: 13{context} 14""") 15 16chat_prompt = ChatPromptTemplate.from_messages([system_msg, human_msg]) 17 18# 使用示例 19messages = chat_prompt.format_messages( 20 profession="法律", 21 experience="10年", 22 specialization="合同法", 23 certifications="律师执业证", 24 question="合同违约如何处理?", 25 context="甲方未按约定时间付款" 26) 27
场景3:示例学习 → FewShotPromptTemplate
1# 代码生成少样本学习 2code_examples = [ 3 { 4 "requirement": "计算列表平均值", 5 "code": "def calculate_average(numbers):\n return sum(numbers) / len(numbers)" 6 }, 7 { 8 "requirement": "反转字符串", 9 "code": "def reverse_string(s):\n return s[::-1]" 10 } 11] 12 13code_template = FewShotPromptTemplate( 14 examples=code_examples, 15 example_prompt=PromptTemplate.from_template( 16 "需求: {requirement}\n代码: {code}" 17 ), 18 prefix="请根据示例编写Python代码:", 19 suffix="需求: {requirement}\n代码:", 20 input_variables=["requirement"] 21) 22 23code_prompt = code_template.format( 24 requirement="检查字符串是否是回文" 25) 26
场景4:复杂聊天 + 示例 → 组合使用
1# 1. 创建少样本部分 2few_shot_examples = [ 3 { 4 "situation": "用户询问个人隐私信息", 5 "response": "出于安全考虑,我无法访问或提供个人隐私信息。" 6 }, 7 { 8 "situation": "用户要求违法帮助", 9 "response": "抱歉,我无法提供任何违法或不道德行为的帮助。" 10 } 11] 12 13few_shot_section = FewShotChatMessagePromptTemplate( 14 example_prompt=ChatPromptTemplate.from_messages([ 15 ("human", "情境: {situation}"), 16 ("ai", "回复: {response}") 17 ]), 18 examples=few_shot_examples 19) 20 21# 2. 创建完整聊天提示 22final_prompt = ChatPromptTemplate.from_messages([ 23 SystemMessagePromptTemplate.from_template(""" 24 你是{assistant_name},安全准则: 25 - {safety_guidelines} 26 - 始终遵守{regulations} 27 """), 28 29 few_shot_section, # 包含少样本示例 30 31 MessagesPlaceholder(variable_name="conversation_history"), # 动态历史 32 33 HumanMessagePromptTemplate.from_template("当前查询: {current_query}") 34]) 35 36# 使用示例 37messages = final_prompt.format_messages( 38 assistant_name="安全助手", 39 safety_guidelines="不分享个人信息,不提供违法建议", 40 regulations="AI使用规范", 41 conversation_history=[], 42 current_query="你能告诉我别人的电话号码吗?" 43) 44
📝 使用频率总结
| Template 类型 | 用途 | 使用频率 |
|---|---|---|
| PromptTemplate | 基础文本模板 | ⭐⭐⭐⭐ |
| ChatPromptTemplate | 聊天消息组合 | ⭐⭐⭐⭐⭐ |
| SystemMessagePromptTemplate | 系统消息 | ⭐⭐⭐⭐ |
| HumanMessagePromptTemplate | 用户消息 | ⭐⭐⭐⭐ |
| AIMessagePromptTemplate | AI消息 | ⭐⭐⭐ |
| FewShotPromptTemplate | 少样本学习 | ⭐⭐⭐ |
| FewShotChatMessagePromptTemplate | 聊天少样本 | ⭐⭐ |
| MessagesPlaceholder | 动态消息占位 | ⭐⭐ |
总结
LangChain Template 提供了强大而灵活的提示工程能力:
- 🎯 精准控制: 通过模板精确控制模型输入,确保提示的一致性
- ♻️ 可复用性: 一次创建,多处使用,提高开发效率
- 🔧 模块化: 像搭积木一样组合模板,支持复杂场景
- 🛡️ 可靠性: 类型安全和错误检查,减少运行时错误
- 🚀 高效开发: 加速 AI 应用开发流程,降低维护成本
掌握 LangChain Template 是构建高质量大模型应用的关键技能,它让提示工程从艺术走向工程化。
《Langchain Template 全面指南》 是转载文章,点击查看原文。
