跳到主要内容

Prompt 提示词模板

提示词模板有助于将用户输入和参数转换为语言模型的指令。这可以用于指导模型的响应,帮助其理解上下文并生成相关且连贯的输出。

两种类型

类型说明适用场景
字符串提示词模板格式化单个字符串简单输入
聊天提示词模板格式化消息列表对话场景

PromptTemplate

用于简单文本提示,模板变量用 {} 包裹:

from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o-mini")

# 1. 定义模板
prompt = PromptTemplate.from_template(
"为生产{product}的公司起5个好名字?"
)

# 2. 格式化变量
formatted = prompt.format(product="智能水杯")
print(formatted) # 输出:为生产智能水杯的公司起5个好名字?

# 3. 调用模型
response = model.invoke(formatted)
print(response.content)

与 LLM 组成链

from langchain_core.prompts import PromptTemplate
from langchain_demo.my_llm import llm

# 所有的可执行对象都可以应用到 langchain 的 LCEL 中
# LCEL 中链接的就是一个个的 Runnable 对象
# 只要是通过 langchain 的代码得到的提示词模板,就是一个可执行对象
# Runnable 对象都可以通过 invoke 调用,Runnable 对象都可以放在 LCEL 的表达式语言中

prompt_template = PromptTemplate.from_template("帮我生成一个简短的,关于{topic}的报幕词。")

# 组成一个链(使用 | 运算符)
chain = prompt_template | llm

result = chain.invoke({"topic": "相声"})
print(result.content)
# 输出: '各位亲爱的观众朋友们,大家好!欢迎来到今天的相声晚会!...'

模板组合

# 提示词模板可以随意组合
prompts = (
prompt_template
+ '要求:1、内容搞笑一点;'
+ '要求:2、输出的内容采用{language}'
)

chain2 = prompts | llm
result = chain2.invoke({"topic": "相声", "language": "en"})
# 输出英文相声报幕词

ChatPromptTemplate

用于聊天场景,支持多轮消息模板:

from langchain_core.prompts import ChatPromptTemplate

# 方式一:from_messages(推荐)
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个{role}专家。"),
("human", "{question}")
])

# 方式二:字符串模板
prompt = ChatPromptTemplate.from_template(
"你是一个{role}专家,请回答:{question}"
)

# 调用
response = prompt.invoke({
"role": "编程",
"question": "什么是 Python?"
})

print(response.to_messages())

与 LLM 组成链

# 创建聊天提示词模板
prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个幽默的电视台主持人!"),
("user", "帮我生成一个简短的,关于{topic}的报幕词。")
])

chain = prompt_template | llm
result = chain.invoke({"topic": "相声"})
print(result.content)
# 输出: '各位观众朋友们,欢迎来到今晚的相声盛宴!...'

消息角色说明

角色说明用途
system系统提示设置 AI 行为
human用户消息用户输入
aiAI 消息指定 AI 回复
tool工具消息工具调用结果

MessagesPlaceholder 消息占位符

MessagesPlaceholder 负责在特定位置插入消息列表,常用于对话历史。

插入消息列表

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage

prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个电视台,高端访谈节目的主持人!"),
MessagesPlaceholder("msgs") # 消息占位符
])

result = prompt_template.invoke({"msgs": [HumanMessage(content="你好,主持人!")]})
print(result)
# 输出: messages=[SystemMessage(...), HumanMessage(content='你好,主持人!')]

典型 Agent 格式

prompt = ChatPromptTemplate.from_messages([
('system', '你是一个智能助手,尽可能的调用工具回答用户的问题'),
MessagesPlaceholder(variable_name='chat_history', optional=True), # 可选:对话历史
('human', '{input}'), # 用户输入
MessagesPlaceholder(variable_name='agent_scratchpad', optional=True), # 可选:Agent 草稿板
])

组合使用

chain = prompt_template | llm

# 对话历史 + 当前问题
result = chain.invoke({
"chat_history": [HumanMessage(content="你好")],
"input": "今天天气怎么样?"
})

partial_variables 预填充变量

对于不变的部分,可以预先填充:

from langchain_core.prompts import PromptTemplate

# 定义模板
prompt = PromptTemplate.from_template(
"你是{role},请回答关于{topic}的问题。"
)

# 预填充 role
prompt_partial = prompt.partial(role="编程")

# 只需填充剩余变量
response = prompt_partial.invoke({"topic": "Python"})

In-Context Learning(ICL)

ICL 核心思想:通过提供少量示例作为上下文,让大模型直接从中学习并做出预测。

字符串形式的 ICL

使用 FewShotPromptTemplate,适合简单场景:

from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate
from langchain_demo.my_llm import llm

# 步骤一:准备示例(展示推理过程)
examples = [
{
"question": "穆罕默德·阿里和艾伦·图灵谁活得更久?",
"answer": """
是否需要后续问题:是。
后续问题:穆罕默德·阿里去世时多大?
中间答案:穆罕默德·阿里去世时74岁。
后续问题:艾伦·图灵去世时多大?
中间答案:艾伦·图灵去世时41岁。
所以最终答案是:穆罕默德·阿里
""",
},
{
"question": "乔治·华盛顿的外祖父是谁?",
"answer": """
是否需要后续问题:是。
后续问题:乔治·华盛顿的母亲是谁?
中间答案:乔治·华盛顿的母亲是玛丽·鲍尔·华盛顿。
后续问题:玛丽·鲍尔·华盛顿的父亲是谁?
中间答案:玛丽·鲍尔·华盛顿的父亲是约瑟夫·鲍尔。
所以最终答案是:约瑟夫·鲍尔
""",
},
]

# 步骤二:创建单个示例的模板
base_template = PromptTemplate.from_template("问题:{question} \n {answer}")

# 步骤三:创建 FewShotPromptTemplate 实例
final_template = FewShotPromptTemplate(
examples=examples, # 传入示例列表
example_prompt=base_template, # 单个问题的提示词模板
suffix='问题:{input}', # 最后追加的问题模板
input_variables=['input'] # 指定输入变量
)

# 步骤四:组成链
chain = final_template | llm
result = chain.invoke({'input': '巴伦 特朗普的父亲是谁?'})
print(result.content)
# 模型学会了通过中间问题推理的方式回答

聊天消息形式的 ICL

使用 FewShotChatMessagePromptTemplate,适合对话场景:

from langchain_core.prompts import (
ChatPromptTemplate,
FewShotChatMessagePromptTemplate,
MessagesPlaceholder
)
from langchain_core.messages import HumanMessage
from langchain_demo.my_llm import llm

# 步骤一:准备示例(对话形式)
examples = [
{'input': '2 🦜 2', 'output': '4'},
{'input': '2 🦜 3', 'output': '5'},
]

# 步骤二:单个输入和 AI 回复的模板
example_prompt = ChatPromptTemplate.from_messages([
('human', '{input}'),
('ai', '{output}'),
])

# 步骤三:包含示例的模板
few_shot_template = FewShotChatMessagePromptTemplate(
examples=examples,
example_prompt=example_prompt,
)

# 步骤四:组合成最终的提示词模板
prompt_template = ChatPromptTemplate.from_messages([
('system', '你是一个智能 AI 助手'),
few_shot_template, # 示例
MessagesPlaceholder('msgs') # 用户当前问题
])

# 步骤五:组成链
chain = prompt_template | llm

# 测试 ICL 推理(🦜 = 2 + x)
result = chain.invoke({'msgs': [HumanMessage(content='2 🦜 9 的结果是多少?')]})
print(result.content)
# 输出: '2 🦜 9 的结果是 11。'

管道组合

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o-mini")

prompt = ChatPromptTemplate.from_template(
"用一句话解释{concept}。"
)

# 使用管道符组合
chain = prompt | model | StrOutputParser()

# 调用
result = chain.invoke({"concept": "机器学习"})
print(result)

LangChain Hub 模板库

从官方模板库拉取提示词:

from langchain import hub

# 获取热门提示词
prompt = hub.pull("rlb/rag-template")

# 查看内容
print(prompt.pretty_print())

完整代码汇总

# ========== 字符串提示词模板 ==========
from langchain_core.prompts import PromptTemplate
from langchain_demo.my_llm import llm

prompt_template = PromptTemplate.from_template("帮我生成一个简短的,关于{topic}的报幕词。")
chain = prompt_template | llm

# ========== 聊天提示词模板 ==========
from langchain_core.prompts import ChatPromptTemplate

prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个幽默的电视台主持人!"),
("user", "帮我生成一个简短的,关于{topic}的报幕词。")
])
chain = prompt_template | llm

# ========== 消息占位符 ==========
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage

prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个电视台,高端访谈节目的主持人!"),
MessagesPlaceholder("msgs")
])
result = prompt_template.invoke({"msgs": [HumanMessage(content="你好,主持人!")]})

# ========== ICL - 字符串形式 ==========
from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate

examples = [...] # 见上文
base_template = PromptTemplate.from_template("问题:{question} \n {answer}")
final_template = FewShotPromptTemplate(
examples=examples,
example_prompt=base_template,
suffix='问题:{input}',
input_variables=['input']
)
chain = final_template | llm

# ========== ICL - 聊天消息形式 ==========
from langchain_core.prompts import (
ChatPromptTemplate,
FewShotChatMessagePromptTemplate,
MessagesPlaceholder
)

examples = [{'input': '2 🦜 2', 'output': '4'}, ...]
example_prompt = ChatPromptTemplate.from_messages([('human', '{input}'), ('ai', '{output}')])
few_shot_template = FewShotChatMessagePromptTemplate(examples=examples, example_prompt=example_prompt)
prompt_template = ChatPromptTemplate.from_messages([('system', '...'), few_shot_template, MessagesPlaceholder('msgs')])
chain = prompt_template | llm

要点速记

概念关键点
PromptTemplate字符串模板,from_template() 创建
ChatPromptTemplate聊天模板,from_messages() 创建
MessagesPlaceholder消息占位符,插入对话历史
FewShotPromptTemplate字符串 ICL,传入 examples 列表
FewShotChatMessagePromptTemplate聊天 ICL,对话形式示例
partial_variables预填充不变部分
| 运算符组装 LCEL 链
invoke()执行 Runnable 对象

核心技巧:提示词模板化 = 可复用 + 易测试 + 参数化