[LangChain] 学习笔记(05):提示词模板(Prompt)与少样本注入(Few-Shot)实战

📌 核心结论(TL;DR)

  1. 模板化 :ChatPromptTemplate 使用 {} 占位符实现提示词与数据的解耦,配合 LCEL 管道符,是 LangChain 应用的基础。

  2. 少样本注入(Few-Shot):提供 2-3 个标准的"输入-输出"示例,比千言万语的规则描述更能约束大模型的输出格式。

  3. 思维链(CoT):在示例中提供推导过程,能极大激活模型逻辑推理能力,解决复杂数学和逻辑问题。

  4. 示例选择器 :当示例库过大时,通过 LengthBasedExampleSelector(按长度)或 SemanticSimilarityExampleSelector(按语义相似)动态挑选最合适的示例,控制 Token 消耗。

🔍 一、 原理图解与核心概念

1. 为什么要用模板?

  • 原始痛点 :手写 SystemMessage,改一个变量要全局搜索替换。

  • 模板方案 :定义 "将 {source} 翻译成 {target}",传入字典 {"source": "英文", "target": "中文"},瞬间生成。

2. 少样本与 CoT 的威力

  • Few-Shot:大模型是模仿大师。给几个完美的示例,它就能照葫芦画瓢。

  • Few-Shot CoT:不仅要给答案,还要给过程(例如:先算消耗,再算买入,最后求和)。模型会模仿你的推理路径,大幅降低错误率。

💻 二、 精选核心代码片段

1. 基础模板与 LCEL

python 复制代码
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate([
    ("system", "你是一个精通{domain}的专家。"),
    ("user", "解释什么是{concept}?")
])
chain = prompt | model
result = chain.invoke({"domain": "物理", "concept": "量子纠缠"})

2. 少样本注入(Few-Shot Chat)

python 复制代码
from langchain_core.prompts import FewShotChatMessagePromptTemplate, ChatPromptTemplate

examples = [
    {"text": "hi", "output": "你好"},
    {"text": "bye", "output": "再见"},
]
example_prompt = ChatPromptTemplate([("human", "{text}"), ("ai", "{output}")])

few_shot_prompt = FewShotChatMessagePromptTemplate(
    example_prompt=example_prompt,
    examples=examples,
)

# 拼接成最终模板
final_prompt = ChatPromptTemplate([
    ("system", "中英翻译"),
    few_shot_prompt,
    ("human", "{input}")
])

3. 长度示例选择器(防止 Token 爆炸)

python 复制代码
from langchain_core.example_selectors import LengthBasedExampleSelector

selector = LengthBasedExampleSelector(
    examples=examples,
    example_prompt=example_prompt,
    max_length=25, # 限制提示词最大长度
)

dynamic_prompt = FewShotPromptTemplate(
    example_selector=selector, # 动态选择示例
    example_prompt=example_prompt,
    prefix="给出反义词:",
    suffix="Input: {adjective}\nOutput: ",
    input_variables=["adjective"],
)

在使用 LengthBasedExampleSelector 时,如果输入的中文文本非常长,会占满 max_length 的额度,导致所有少样本示例被裁剪掉 。

此时,Few-Shot 退化为 Zero-Shot,大模型会失去格式约束,返回长篇大论(例如:输入"非常非常大的",模型返回了一大段解释和超长的反义词,而不是单纯的单词)。

解决方案 :对中文场景,建议改用 SemanticSimilarityExampleSelector(基于向量语义匹配)来动态挑选示例,或者适当调大 max_length 并缩小 chunk_size。

(完整的包含思维链与多种示例选择器的代码已上传至 Gitee 仓库)

⚠️ 三、 踩坑排查排雷

  1. 大括号转义坑 :在 Prompt 中输出原生 JSON(如 {"name": "Bob"}),会报 KeyError。排查 :必须双写大括号 {``{"name": "Bob"}}。

  2. LengthBasedExampleSelector 对中文支持不佳 :默认按空格切分单词计算长度。排查 :生产环境更推荐使用 SemanticSimilarityExampleSelector,基于向量检索匹配最相似示例。

  3. 少样本过拟合 :示例太多(如超过 5 个)且高度相似,会导致模型只会死板复读,丧失泛化能力。排查:保留 2-3 个具有代表性的示例,且尽量覆盖不同边界情况。

相关推荐
CodeYp201912 分钟前
第5讲:Socket 编程 TCP
linux·socket·tcp
天天被压力16 分钟前
【A股分钟级高频数据完全手册 #10】股票实时行情数据接口Python:公开源实时交易取数
java·人工智能·python
深蓝AI20 分钟前
Vercel 把浏览器做成命令行:agent-browser 十个月 4.6 万星,给每个元素发一个编号
人工智能·程序员
咔_21 分钟前
有IPv6地址,为什么外面还是连不进来?让同一台服务分别卡在四个位置
linux·计算机网络
唐老板36 分钟前
最会审代码的 AI,也只挑得出三分之一
人工智能·ai编程
CodeYp201937 分钟前
第3讲:网络命令
linux·网络·命令
kaixin_啊啊8 小时前
【零基础学AI】第 25 章课后练习与答案
人工智能
水如烟9 小时前
孤能子视角:逆溯法与传统方法比较
人工智能