纲要
- 核心概念
Zero Shot:零样本推理,直接提问不含示例Few Shot:少样本推理,通过少量输入-输出示例引导模型行为FewShotChatMessagePromptTemplate:LangChain 中专用于构建 Few Shot 提示的消息模板
- 关键流程
- 准备示例数据集 → 定义示例格式化模板 → 组合最终提示词(含系统消息、示例、用户问题) → 提交至 LLM
- 涉及组件与版本
langchain_core.prompts:ChatPromptTemplate,FewShotChatMessagePromptTemplatelangchain_core.messages:消息类型(HumanMessage,AIMessage)langchain_community.chat_models.fake:FakeListChatModel(用于离线测试)- 适用版本:LangChain
>=0.1.0,langchain-core>=0.1.0
- 完整可运行代码:演示自定义运算符“小鸟”作为加法,包含示例构建、模板组合、模型调用(模拟)
引言
在提示词工程中,直接要求大模型处理从未见过的任务(如自定义符号运算、专有格式转换)时,模型常因缺乏上下文而产生无关或错误的输出。Few Shot 提示通过提供少量精心设计的“输入-输出”示例,使模型迅速习得任务模式,从而在新输入上生成更符合预期的结果。
本文将系统阐述 Few Shot 的核心思想,并基于 LangChain 框架,利用 FewShotChatMessagePromptTemplate 高效构建示例驱动的提示词模板,同时给出完整可运行的代码示例(含模拟模型),便于读者在没有 API Key 的情况下验证流程。
Zero Shot 与 Few Shot 对比
- Zero Shot(零样本):不提供任何示例,仅凭任务指令直接提问。该方法依赖模型自身的推理能力,对于已具备强推理链(CoT)能力的大型模型(如 GPT-4)仍可奏效,但对常规模型或非标准任务效果欠佳。
- Few Shot(少样本):在提示中包含若干(通常 1~5 个)完整示例,每个示例均包含输入和期望输出。模型通过类比学习,按照示例的格式和逻辑进行回答。示例的质量和与目标任务的关联性远比数量重要。
示例说明:若直接问模型 “2 小鸟 9”,Zero Shot 方式可能得到随机或无关回复;若先给出示例 “2 小鸟 2 = 4”、“2 小鸟 3 = 5”,模型则能推断“小鸟”代表加法,并正确回答 “2 小鸟 9 = 11”。
| 方式 | 示例数量 | 适用场景 | 对模型推理能力要求 |
|---|---|---|---|
| Zero Shot | 0 | 常识问答、通用任务 | 高 |
| Few Shot | ≥1 | 自定义规则、格式转换、非标准任务 | 较低(借助示例) |
LangChain 中的 Few Shot 实现
LangChain 提供 FewShotChatMessagePromptTemplate,它负责将一组示例与基础提示模板组合成最终的消息列表(适用于聊天模型)。整个流程如下图所示:
构建示例数据
示例通常以字典列表形式表示,每个字典包含 input 和 output 字段,分别对应人类问题和期望的 AI 响应内容。
定义示例模板
使用 ChatPromptTemplate.from_messages 定义如何将单个示例格式化为消息对:input 映射为 HumanMessage,output 映射为 AIMessage。
组合最终提示
将示例模板与完整提示模板(可包含系统消息、Few Shot 示例占位符及最终人类问题)结合,由 FewShotChatMessagePromptTemplate 统一注入示例消息。
完整可运行代码
以下代码演示如何使用 Few Shot 让模型理解自定义运算符“小鸟”代表加法,并利用 FakeListChatModel 模拟模型返回结果,无需真实 API Key。
环境准备(需 Python 3.8+):
pip install langchain>=0.1.0 langchain-core>=0.1.0 langchain-community>=0.1.0
核心脚本(保存为 few_shot_demo.py):
from langchain_core.prompts import (
ChatPromptTemplate,
FewShotChatMessagePromptTemplate,
)
from langchain_community.chat_models.fake import FakeListChatModel
# 1. 定义示例列表(每个示例包含 input 和 output)
examples = [
{"input": "2 小鸟 2", "output": "4"},
{"input": "2 小鸟 3", "output": "5"},
]
# 2. 构建示例模板:将每个示例格式化为 Human 和 AI 消息
example_prompt = ChatPromptTemplate.from_messages([
("human", "{input}"),
("ai", "{output}"),
])
# 3. 创建 FewShotChatMessagePromptTemplate 实例
few_shot_prompt = FewShotChatMessagePromptTemplate(
example_prompt=example_prompt,
examples=examples,
)
# 4. 构建最终提示词模板(系统指令 + few shot 示例占位 + 最终用户问题)
final_prompt = ChatPromptTemplate.from_messages([
("system", "你是一位神奇的数学奇才。"),
few_shot_prompt, # 此处会自动展开为多个 Human/AI 消息
("human", "{input}"),
])
# 5. 格式化并打印组合后的消息列表(便于调试)
formatted_messages = final_prompt.format_messages(input="2 小鸟 9")
print("组合后的消息列表:")
for msg in formatted_messages:
print(f" {msg.type}: {msg.content}")
# 6. 使用模拟模型(预设回答为 "11")
model = FakeListChatModel(responses=["11"])
chain = final_prompt | model
response = chain.invoke({"input": "2 小鸟 9"})
print(f"\n模型回答:{response.content}")
运行结果:控制台将依次打印出系统消息、两个示例消息(Human/AI 各两对)以及最后的用户问题,最终模型输出为 11,验证了 Few Shot 成功让模型习得“小鸟”为加法。
API 速览
本节梳理上述代码涉及的核心 API,便于读者按需调用。
ChatPromptTemplate.from_messages
- 所属库:
langchain_core.prompts - 方法签名:
from_messages(messages: List[Union[Tuple[str, str], BaseMessagePromptTemplate]]) -> ChatPromptTemplate - 参数:消息列表,支持元组
(角色, 内容)或已实例化的消息模板。 - 返回值:
ChatPromptTemplate对象,可调用format_messages(...)生成消息列表。
FewShotChatMessagePromptTemplate
- 所属库:
langchain_core.prompts - 构造函数:
FewShotChatMessagePromptTemplate(example_prompt: ChatPromptTemplate, examples: List[Dict[str, Any]], **kwargs) - 参数:
example_prompt:用于格式化单个示例的ChatPromptTemplate(通常包含 human 和 ai 角色)。examples:字典列表,每个字典的键应与example_prompt中的变量匹配。
- 行为:该实例作为消息模板,在最终提示中被展开为多条
HumanMessage和AIMessage。
FakeListChatModel
- 所属库:
langchain_community.chat_models.fake - 构造函数:
FakeListChatModel(responses: List[str], **kwargs) - 参数:
responses为预定义的响应字符串列表,按调用顺序依次返回。 - 返回值:实现
BaseChatModel接口,可被Runnable链式调用。
示例设计的注意事项
- 任务相关性:示例必须与目标任务同域同格式。例如,若要求模型生成唐诗,示例应为唐诗而非宋词。
- 质量优先:一两个精准、清晰的示例通常优于多个模糊或含噪声的示例。
- 格式一致性:确保示例的输入输出格式与最终用户问题的格式完全一致,以降低模型的迁移难度。
- 多样性覆盖:若任务包含多种边缘情况,可提供覆盖不同情形的示例,但总数不宜过多(通常 3~5 个即可)。
参考文档
官方文档
- LangChain Prompts 官方指南:https://python.langchain.com/docs/modules/model_io/prompts/
FewShotChatMessagePromptTemplateAPI 参考:https://python.langchain.com/api_reference/core/prompts/langchain_core.prompts.few_shot.FewShotChatMessagePromptTemplate.htmlChatPromptTemplate说明:https://python.langchain.com/api_reference/core/prompts/langchain_core.prompts.chat.ChatPromptTemplate.html
参考链接
- LangChain 官方 GitHub 仓库(示例与源码):https://github.com/langchain-ai/langchain
- 提示词工程指南(Few Shot 章节):https://www.promptingguide.ai/techniques/fewshot
总结
Few Shot 提示是一种高效、轻量的模型引导技术,尤其适用于需要快速适配新任务或自定义规则的场景。通过 LangChain 的 FewShotChatMessagePromptTemplate,开发者可以将示例管理、模板组合和消息生成标准化,显著提升提示词的可维护性和复用性。
本文提供的代码示例在 LangChain 0.1.x 环境下可直接运行,读者可将其作为基础模板,迁移至实际业务中。
439



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



