LangChain提示词模板简介
LangChain的提示词模板(PromptTemplate)是一种结构化生成提示词(prompt)的工具,用于将动态变量注入固定文本模板,从而标准化与大模型交互的输入格式。通过模板化提示词,可以提升代码复用性并减少手动拼接字符串的复杂度。
核心功能
- 变量插值:支持通过
{{variable}}语法将动态值嵌入模板。 - 多模态适配:适用于聊天、问答、代码生成等多种场景。
- 格式控制:可定义输出格式(如JSON、纯文本等)。
基本用法示例
from langchain.prompts import PromptTemplate
# 定义包含变量的模板
template = "请用中文解释以下概念:{{concept}}"
prompt = PromptTemplate(
input_variables=["concept"],
template=template
)
# 填充变量生成最终提示词
filled_prompt = prompt.format(concept="机器学习")
print(filled_prompt)
输出结果:
请用中文解释以下概念:机器学习
高级模板类型
1. 聊天提示模板 适用于多轮对话场景,可区分系统消息、用户消息和AI回复:
from langchain.prompts import ChatPromptTemplate
from langchain.prompts.chat import SystemMessagePromptTemplate, HumanMessagePromptTemplate
system_template = "你是一位精通{{subject}}的教授"
human_template = "用简单的话解释{{topic}}"
system_prompt = SystemMessagePromptTemplate.from_template(system_template)
human_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_prompt, human_prompt])
result = chat_prompt.format_prompt(subject="物理学", topic="量子纠缠").to_messages()
2. 少量示例模板 包含示例的few-shot模板:
from langchain.prompts import FewShotPromptTemplate
examples = [
{"input": "高兴", "output": "情绪状态:积极"},
{"input": "愤怒", "output": "情绪状态:消极"}
]
example_template = "输入: {{input}}\n输出: {{output}}"
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template=example_template
)
few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix="根据示例分类情绪",
suffix="输入: {{query}}\n输出:",
input_variables=["query"]
)
print(few_shot_prompt.format(query="悲伤"))
模板组合技巧
-
部分填充:使用
partial()预填充部分变量from langchain.prompts import PromptTemplate template = "{{foo}}{{bar}}" prompt = PromptTemplate(template=template, input_variables=["foo", "bar"]) partial_prompt = prompt.partial(foo="固定前缀") print(partial_prompt.format(bar="动态内容")) -
模板继承:通过组合多个子模板构建复杂提示
from langchain.prompts import PipelinePromptTemplate full_template = """{intro}\n\n{example}\n\n{start}""" full_prompt = PromptTemplate.from_template(full_template) intro_template = "你是一个擅长{{domain}}的AI" intro_prompt = PromptTemplate.from_template(intro_template) example_template = "示例:{{example}}" example_prompt = PromptTemplate.from_template(example_template) pipeline_prompt = PipelinePromptTemplate( final_prompt=full_prompt, pipeline_prompts=[ ("intro", intro_prompt), ("example", example_prompt) ] )
最佳实践
- 变量校验:始终指定
input_variables避免运行时错误 - 模板库管理:将常用模板存储为独立文件或数据库记录
- 版本控制:对重要业务提示模板进行版本跟踪
通过合理使用提示模板,可以实现以下效果:
- 保持不同环境(开发/生产)提示词一致性
- 支持A/B测试不同提示版本
- 降低提示词维护成本
507

被折叠的 条评论
为什么被折叠?



