【Agent智能体项目实战六】FewShot提示词模板

3 阅读3分钟

一、前言

在使用大模型时,有些任务只靠描述很难让模型理解规则,比如:反义词、分类、格式转换等。 这时就可以用小样本学习(Few-Shot):给模型看几个示例,它就能立刻学会规则。

LangChain 提供了 FewShotPromptTemplate 专门用于构建带示例的提示词,本文用反义词生成完整演示。


二、依赖安装

pip install langchain langchain-core langchain-community dashscope

三、完整可运行代码

import os

from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_community.llms.tongyi import Tongyi

# 定义示例数据模板
prompt_template = PromptTemplate.from_template(
    "单词:{word},反义词{antonym}"
)

# 定义示例数据列表
examples = [
    {"word": "上", "antonym": "下"},
    {"word": "坏", "antonym": "好"},
    {"word": "粗", "antonym": "细"},
]

# 定义FewShotPromptTemplate对象
prompt = FewShotPromptTemplate(
    example_prompt=prompt_template,  # 示例数据模板
    examples=examples,  # 示例数据列表 list内套字典
    prefix="告知我单词的反义词,我提供的如下示例:",  # 前缀提示词
    suffix="基于上面的示例,请根据{input_word}单词,生成其反义词",  # 后缀提示词
    input_variables=["input_word"],  # 输入需要注入的变量
)

# 调用invoke方法,传入参数
prompt_text = prompt.invoke({"input_word": "酸"}).to_string()

# 设置 dashscope api key
os.environ["DASHSCOPE_API_KEY"] = "sk-你的API_KEY"

# 创建一个聊天模型对象
model = Tongyi(
    model="qwen-max"
)

print(model.invoke(input=prompt_text))

四、代码逐行解析

1. 导入模块

import os
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_community.llms.tongyi import Tongyi
  • PromptTemplate:普通提示词模板
  • FewShotPromptTemplate小样本提示词模板
  • Tongyi:通义千问大模型封装

2. 定义示例的格式

prompt_template = PromptTemplate.from_template(
    "单词:{word},反义词{antonym}"
)

作用:规定每个示例长什么样。 比如: 单词:上,反义词:下


3. 提供示例数据

examples = [
    {"word": "上", "antonym": "下"},
    {"word": "坏", "antonym": "好"},
    {"word": "粗", "antonym": "细"},
]

这是给模型看的学习样本,模型会根据这些示例理解任务规则。


4. 构建 FewShotPromptTemplate

prompt = FewShotPromptTemplate(
    example_prompt=prompt_template,   # 示例格式
    examples=examples,               # 示例列表
    prefix="告知我单词的反义词,我提供的如下示例:",  # 开头引导
    suffix="基于上面的示例,请根据{input_word}单词,生成其反义词", # 结尾任务
    input_variables=["input_word"],   # 要传入的变量
)

这是核心:

  • prefix:提示词开头,告诉模型任务是什么
  • examples:自动把示例按格式拼进去
  • suffix:最后提出真正的问题
  • input_variables:需要动态替换的参数

最终拼接出来的提示词类似:

告知我单词的反义词,我提供的如下示例:
单词:上,反义词下
单词:坏,反义词好
单词:粗,反义词细
基于上面的示例,请根据酸单词,生成其反义词

5. 生成最终提示词

prompt_text = prompt.invoke({"input_word": "酸"}).to_string()
  • 传入 input_word="酸"
  • 自动填充到 suffix
  • to_string() 把提示对象转成字符串

6. 调用通义千问

os.environ["DASHSCOPE_API_KEY"] = "sk-xxxx"
model = Tongyi(model="qwen-max")
print(model.invoke(input=prompt_text))

模型根据示例,输出:


五、运行结果示例


六、核心知识点总结

  1. FewShotPromptTemplate = 前缀 + 示例 + 后缀
  2. 必须搭配 example_prompt 规定示例格式
  3. 示例用 list[dict] 格式
  4. 适合:反义词、分类、格式转换、逻辑推理
  5. 比普通 PromptTemplate 效果更稳定、更易理解任务

七、适用场景

  • 反义词/近义词生成
  • 文本分类
  • 固定格式输出
  • 简单逻辑推理
  • 翻译、抽取、改写