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