RETRIEVAL-AUGMENTED GENERATION · 05
整理少样本提示、对话提示模板、Chat Model Few-shot 与 Chain 补充知识。
- Few-shot
- ChatPromptTemplate
本文目录
- 17.1 Zero-shot 与 Few-shot 区别
- Zero-shot
- Few-shot
- 17.2 FewShotPromptTemplate
- examples
- example_prompt
- prefix
- suffix
- input_variables
- 17.3 Few-shot 数据流
- 十八、ChatPromptTemplate
- 18.1 为什么需要 ChatPromptTemplate?
- 18.2 基础代码
- 18.3 ChatPromptTemplate 数据流
- 十九、Chat Model Few-shot
- 19.1 为什么使用 HumanMessage + AIMessage?
- 19.2 Few-shot 与多轮对话区别
- 多轮对话
- Few-shot
- 19.3 FewShotChatMessagePromptTemplate
Few-shot 与 ChatPromptTemplate
本章节补充 LangChain Prompt 模块中之前未整理的 Few-shot 内容。
17.1 Zero-shot 与 Few-shot 区别
Zero-shot
不提供任务示例,只告诉模型:
- 要完成什么任务
- 输出要求是什么
例如:
请判断下面评论属于正面、负面还是中性。
评论:
这个手机很好用。
请只输出分类结果。
特点:
任务说明
+
用户输入
没有示例。
Few-shot
在 Prompt 中增加少量示例,让模型学习输入输出模式。
例如:
问题:1+1
答案:2
问题:2+3
答案:5
问题:10+20
答案:
模型通过示例理解:
输入形式 → 输出形式
注意:
Few-shot 不会修改模型参数。
它:
- 不是训练
- 不是微调
- 只是通过上下文示例引导模型生成
17.2 FewShotPromptTemplate
普通 LLM 的 Few-shot 使用:
FewShotPromptTemplate
它负责:
将示例数据按照指定格式拼接成完整 Prompt。
核心组成:
examples
+
example_prompt
+
prefix
+
suffix
+
input_variables
examples
作用:
提供示例内容。
例如:
examples = [
{
"input":"1+1",
"output":"2"
},
{
"input":"2+3",
"output":"5"
}
]
example_prompt
作用:
定义每个示例如何展示。
例如:
example_prompt = PromptTemplate.from_template(
"问题:{input}\n答案:{output}"
)
生成:
问题:1+1
答案:2
prefix
作用:
示例之前的任务说明。
例如:
请参考下面的例子回答数学问题:
suffix
作用:
示例之后真正需要模型处理的新问题。
例如:
suffix="问题:{input}\n答案:"
其中:
{input}
来自用户真实输入。
input_variables
作用:
声明最终调用时需要外部传入的变量。
例如:
input_variables=["input"]
表示:
调用:
prompt.invoke({
"input":"10+20"
})
时需要提供 input。
17.3 Few-shot 数据流
完整过程:
examples
↓
example_prompt格式化
↓
生成示例文本
prefix
↓
任务说明
suffix
↓
用户当前问题
↓
完整 Prompt
↓
LLM
十八、ChatPromptTemplate
18.1 为什么需要 ChatPromptTemplate?
PromptTemplate 生成:
字符串
适合:
PromptTemplate
↓
LLM
但是 Chat Model 输入:
SystemMessage
HumanMessage
AIMessage
因此需要:
ChatPromptTemplate
它负责生成消息列表。
18.2 基础代码
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"你是一个专业AI老师"
),
(
"human",
"请解释{topic}"
)
]
)
调用:
prompt.invoke({
"topic":"RAG"
})
生成:
SystemMessage:
你是一个专业AI老师
HumanMessage:
请解释RAG
18.3 ChatPromptTemplate 数据流
用户变量
↓
ChatPromptTemplate
↓
SystemMessage
+
HumanMessage
↓
Chat Model
↓
AIMessage
十九、Chat Model Few-shot
19.1 为什么使用 HumanMessage + AIMessage?
Chat Model 天然理解:
HumanMessage
+
AIMessage
这种结构。
因此 Few-shot 示例可以表示:
Human:
这个手机很好用
AI:
正面
告诉模型:
输入
↓
应该如何输出
19.2 Few-shot 与多轮对话区别
两者形式相似:
HumanMessage + AIMessage
但是目的不同。
多轮对话
作用:
保存真实历史上下文。
例如:
Human:
我叫小明
AI:
你好小明
Human:
我叫什么?
Few-shot
作用:
提供人为设计的任务示例。
例如:
Human:
这个手机很好用
AI:
正面
Human:
物流太慢
AI:
负面
19.3 FewShotChatMessagePromptTemplate
用于:
Chat Model Few-shot
作用:
根据 examples 自动生成 HumanMessage + AIMessage 示例。
逻辑:
examples
↓
example_prompt
↓
HumanMessage
+
AIMessage
↓
ChatPromptTemplate
↓
Chat Model