【LangChain】P10 LangChain 提示词模板深度解析(一):Prompt Template
目录
- 什么是 Prompt Template?
- 核心特性
- Prompt Template 的类型
- PromptTemplate 实例化方法
- 方法一:使用构造函数
- 方法二:使用 from_template() 方法(推荐)
- 高级特性:两种特殊结构
- 部分提示词模板(Partial Prompt Template)
- 定义方式一:在构造时使用 partial_variables
- 定义方式二:使用 partial() 方法动态固定
- 定义方式三:链式调用(最优雅)
- 组合提示词(Composed Prompts)
- 变量赋值的两种方式
- format() 方法:直接返回字符串
- invoke() 方法:返回 PromptValue 对象(推荐)
- 实战:结合大模型使用
- 总结
在大模型应用开发中,提示词(Prompt)的质量直接决定了模型输出的效果。然而,硬编码的固定提示词往往缺乏灵活性,难以适应不同场景的需求。LangChain 的 Prompt Template(提示词模板)正是为解决这一问题而生,它通过模板化管理大模型输入,让我们能够优雅地构建可复用、可维护的提示词系统。
什么是 Prompt Template?
Prompt Template 是 LangChain 框架中的核心概念之一,它的作用是接收用户的动态输入,通过模板渲染生成最终传递给大语言模型(LLM)的提示词。
核心特性
- 模板化管理:将固定文本与动态变量分离,提高代码复用性
- 灵活输入:以字典形式传入参数,每个键对应模板中的一个变量
- 标准输出:返回 PromptValue 对象,可转换为字符串或消息列表
这种设计模式在实际开发中极为实用。例如,你可以创建一个通用的"角色扮演"模板,根据不同场景动态指定角色身份和任务需求。
Prompt Template 的类型
LangChain 提供了多种提示词模板类型以适应不同场景。本文重点介绍最常用的 PromptTemplate,即面向字符串的提示模板。后续一篇博文将详细介绍包含 ChatPromptTemplate、FewShotPromptTemplate、PipelinePrompt 等内容。
PromptTemplate 是用于生成字符串提示的基础模板类,它利用 Python 的字符串格式化机制来实现变量替换。这种模板特别适合与传统 LLM 交互,或需要生成纯文本提示的场景。
PromptTemplate 实例化方法
创建 PromptTemplate 实例有两种主要方式,各有适用场景。
方法一:使用构造函数
这种方式需要显式指定 input_variables
和 template
参数,适合需要精确控制模板行为的场景。
from langchain_core.prompts import PromptTemplate# 创建 PromptTemplate 实例
prompt_template = PromptTemplate(template="你是一个{role},你的名字叫{name}",input_variables=["role", "name"]
)# 填充变量并生成提示词
prompt = prompt_template.format(role="人工智能专家", name="小智")
print(prompt)
# 输出: 你是一个人工智能专家,你的名字叫小智
方法二:使用 from_template() 方法(推荐)
这是更简洁的创建方式,LangChain 会自动从模板字符串中识别变量,无需手动指定 input_variables
from langchain_core.prompts import PromptTemplate# 一行代码创建模板
prompt_template = PromptTemplate.from_template(template="你是一个{role},你的名字叫{name}"
)# 填充变量
prompt = prompt_template.format(role="人工智能专家", name="小智")
print(prompt)
推荐理由: 代码更简洁,减少冗余,降低出错概率。
高级特性:两种特殊结构
在实际应用中,我们常常需要更灵活的模板管理方式。LangChain 提供了 部分提示词模板 和 组合提示词 两种高级特性。
部分提示词模板(Partial Prompt Template)
部分提示词模板允许你预先固定某些变量的值,这在构建智能体(Agent)或需要复用模板时特别有用。
定义方式一:在构造时使用 partial_variables
# 在创建时就固定某些变量
prompt_template = PromptTemplate(template="你是一个{role},你的名字叫{name}",input_variables=["role", "name"],partial_variables={"name": "小智"}
)# 或结合 from_template() 方法
prompt_template = PromptTemplate.from_template(template="你是一个{role},你的名字叫{name}",partial_variables={"name": "小智"}
)
定义方式二:使用 partial() 方法动态固定
# 先创建完整模板
base_template = PromptTemplate.from_template(template="你是一个{role},你的名字叫{name}"
)# 后续固定某个变量
prompt_template = base_template.partial(name="小智")
定义方式三:链式调用(最优雅)
# 一行代码完成创建和部分固定
prompt_template = PromptTemplate.from_template(template="你是一个{role},你的名字叫{name}"
).partial(name="小智")
应用场景: 在构建多轮对话系统时,可以固定系统角色,只需动态修改任务描述。
组合提示词(Composed Prompts)
通过 +
操作符可以将多个模板片段组合成一个完整的提示词,这种方式让复杂提示的构建更加模块化。
from langchain_core.prompts import PromptTemplate# 组合多个模板片段
template = (PromptTemplate.from_template(template="Tell me a joke about {topic}")+ ", make it funny"+ "\n\nand in {language}"
)prompt = template.format(topic="sports", language="Python")
print(prompt)
# 输出:
# Tell me a joke about sports, make it funny
#
# and in Python
优势: 将长提示词拆分为多个可维护的片段,提高代码可读性。
变量赋值的两种方式
PromptTemplate 提供了两种给变量赋值的方法,它们在返回类型和应用场景上有所区别。
format() 方法:直接返回字符串
from langchain_core.prompts import PromptTemplatetemplate = PromptTemplate.from_template(template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。"
)# 使用关键字参数传值
prompt = template.format(product="智能手机",aspect1="电池续航",aspect2="拍照质量"
)print(prompt)
print(type(prompt)) # <class 'str'>
invoke() 方法:返回 PromptValue 对象(推荐)
from langchain_core.prompts import PromptTemplatetemplate = PromptTemplate.from_template(template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。"
)# 使用字典传值
prompt = template.invoke(input={"product": "智能手机","aspect1": "电池续航","aspect2": "拍照质量"
})print(prompt)
print(type(prompt)) # <class 'langchain_core.prompt_values.StringPromptValue'>
关键区别:
format()
返回纯字符串,适合简单场景invoke()
返回 PromptValue 对象,与 LangChain 生态深度集成,支持链式调用
实战:结合大模型使用
下面是一个完整的示例,展示如何将 PromptTemplate 与大语言模型结合使用。
import os
import dotenv
from langchain_openai import ChatOpenAI
from langchain_core.prompts import PromptTemplate# 加载环境变量
dotenv.load_dotenv()
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
os.environ["OPENAI_BASE_URL"] = os.getenv("OPENAI_BASE_URL")# 1. 初始化大模型
chat_model = ChatOpenAI(model="deepseek-chat",temperature=0.7,max_tokens=200
)# 2. 创建提示词模板
template = PromptTemplate.from_template(template="请评价{product}的优缺点,包括{aspect1}和{aspect2}。"
)# 3. 填充模板变量
prompt = template.invoke(input={"product": "智能手机","aspect1": "电池续航","aspect2": "拍照质量"
})
print(f"生成的提示词:\n{prompt}\n")# 4. 调用大模型
response = chat_model.invoke(prompt)
print(f"模型响应:\n{response.content}")
print(f"\n响应类型: {type(response)}")
代码解析
- 环境配置: 使用
dotenv
管理 API 密钥,避免硬编码敏感信息 - 模型初始化: 配置模型参数,
temperature
控制创造性,max_tokens
限制输出长度 - 模板创建: 定义结构化的提示词模板
- 变量填充: 使用
invoke()
方法填充变量,返回 PromptValue 对象 - 模型调用: 将 PromptValue 直接传递给模型,LangChain 会自动处理格式转换
总结
Prompt Template 是 LangChain 中不可或缺的工具,它通过模板化管理解决了固定提示词的局限性。从基础的 PromptTemplate 到部分模板、组合模板等高级特性,LangChain 提供了完整的提示词工程解决方案。
掌握 Prompt Template 的使用,不仅能提高代码质量和可维护性,更能帮助我们构建更加灵活、强大的 AI 应用。随着对 LangChain 的深入学习,你会发现提示词模板是构建复杂 AI 工作流的基石。
下一篇博文,将围绕提示词模板的其余类型展开。
2025.10.03 吉林·扶余