LangChain FewShotPromptTemplate 少样本提示模板
2026/7/21 16:43:54 网站建设 项目流程
# 💡 Concept: # Few-shot templates teach the AI by showing examples. The AI learns the pattern from examples and applies it to new inputs. # 🧠 Pattern Learning Process: # Example 1: happy → sad ✓ # Example 2: tall → short ✓ # New Input: hot → ??? # AI Prediction: hot → cold 🎯 from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate # Define examples that teach the pattern examples = [ {"input": "happy", "output": "sad"}, {"input": "tall", "output": "short"}, {"input": "fast", "output": "slow"}, {"input": "hot", "output": "cold"} ] # Template for each example example_template = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}" ) # Few-shot template few_shot_template = FewShotPromptTemplate( examples=examples, example_prompt=example_template, prefix="Find the opposite of each word:", suffix="Input: {word}\nOutput:", input_variables=["word"] ) # Test the pattern learning test_words = ["big", "light", "expensive", "difficult"] print("🎯 Few-Shot Learning in Action:") print("=" * 40) for word in test_words: prompt = few_shot_template.format(word=word) print(f"\n📝 Generated Prompt for '{word}':") print(prompt) print("-" * 30) # Advanced: Dynamic example selection print("\n🔄 Advanced: Selective Examples") selected_examples = examples[:2] # Use only first 2 examples dynamic_template = FewShotPromptTemplate( examples=selected_examples, example_prompt=example_template, prefix="Learn the pattern from these examples:", suffix="Input: {word}\nOutput:", input_variables=["word"] ) prompt = dynamic_template.format(word="bright") print(prompt) # with open('/root/few-shot-templates.txt', 'w') as f: # f.write("FEW_SHOT_TEMPLATES_COMPLETE")

完整代码逐行详解:LangChain FewShotPromptTemplate 少样本提示模板

一、核心概念前置注释翻译

python

运行

# 💡 Concept: # Few-shot templates teach the AI by showing examples. The AI learns the pattern from examples and applies it to new inputs. # 核心概念:少样本提示模板通过提供样例教会AI执行任务。模型从样例中总结规律,再套用在全新输入上。 # 🧠 Pattern Learning Process: # Example 1: happy → sad ✓ # Example 2: tall → short ✓ # New Input: hot → ??? # AI Prediction: hot → cold 🎯 # 规律学习流程: # 样例1:开心 → 悲伤 # 样例2:高 → 矮 # 新输入:热 → ? # AI推理输出:热 → 冷

专业名词

  • Few-shot(少样本):给模型少量示例,不用微调模型权重,仅靠 Prompt 引导输出格式 / 逻辑
  • Zero-shot:不给任何样例;One-shot:1 个样例;Few-shot:多个样例

二、导入模块

python

运行

from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate
  1. PromptTemplate:基础单条文本模板,用于定义单组输入输出样例的格式
  2. FewShotPromptTemplate:少样本专用模板,负责把多条示例、任务说明、用户新问题拼接成完整 Prompt

注意:langchain_core是 LangChain 新版拆分包,区别于旧版langchain.prompts

三、定义样例数据集 examples

python

运行

examples = [ {"input": "happy", "output": "sad"}, {"input": "tall", "output": "short"}, {"input": "fast", "output": "slow"}, {"input": "hot", "output": "cold"} ]
  • 存储多条输入 - 标准答案配对,每条是字典
  • 任务目标:输入形容词,输出它的反义词
  • 这些示例会全部塞进 Prompt,给模型做参考标准

四、单条示例格式化模板 example_template

python

运行

example_template = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}" )
  1. input_variables=["input", "output"]:声明模板内两个占位变量
  2. template:规定每一条样例的固定排版 渲染后单条样例:

    plaintext

    Input: happy Output: sad

作用:统一所有示例的展示格式,避免排版混乱、模型识别出错

五、组装完整少样本模板 few_shot_template(核心)

python

运行

few_shot_template = FewShotPromptTemplate( examples=examples, # 传入全部样例数据 example_prompt=example_template, # 指定每条样例用什么格式渲染 prefix="Find the opposite of each word:", # 样例前面的任务总说明(前缀) suffix="Input: {word}\nOutput:", # 样例之后,放用户新问题(后缀) input_variables=["word"] # 最终留给用户传入的变量名 )

五大参数拆解

  1. examples:样例列表
  2. example_prompt:单条样例的渲染模板
  3. prefix:全局任务指令,写在所有示例最前面,告诉模型整体要做什么
  4. suffix:示例结束后拼接用户待预测的新输入,{word}是待填充变量
  5. input_variables:模板末尾后缀需要接收的外部变量(用户新词)

拼接完成后的完整 Prompt 结构

plaintext

Find the opposite of each word: Input: happy Output: sad Input: tall Output: short Input: fast Output: slow Input: hot Output: cold Input: big Output:

模型读到这段文本,就会明白任务是找反义词,并按Output: xxx格式给出答案。

六、批量测试基础版模板

python

运行

# Test the pattern learning test_words = ["big", "light", "expensive", "difficult"] print("🎯 Few-Shot Learning in Action:") print("=" * 40) for word in test_words: prompt = few_shot_template.format(word=word) print(f"\n📝 Generated Prompt for '{word}':") print(prompt) print("-" * 30)
  1. test_words:批量待预测单词
  2. .format(word=word):把循环里的单词填充到模板{word}占位符,生成完整可发给 LLM 的字符串 Prompt
  3. 循环打印每个单词对应的完整提示词,直观查看拼接效果

七、进阶:动态选取部分样例 Dynamic Example Selection

python

运行

# Advanced: Selective examples print("\n🔄 Advanced: Selective Examples") selected_examples = examples[:2] # 只截取前2条样例:happy/sad、tall/short dynamic_template = FewShotPromptTemplate( examples=selected_examples, example_prompt=example_template, prefix="Learn the pattern from these examples:", suffix="Input: {word}\nOutput:", input_variables=["word"] ) prompt = dynamic_template.format(word="bright") print(prompt)

核心知识点

  • examples[:2]:切片只取前 2 个示例,减少 Prompt 长度、降低 token 消耗
  • 实际工程中可搭配SemanticSimilarityExampleSelector,根据用户问题语义自动挑选最相关样例,不用固定截取,适合 RAG、问答场景

输出效果(仅 2 条样例)

plaintext

Learn the pattern from these examples: Input: happy Output: sad Input: tall Output: short Input: bright Output:

三、完整代码核心用途总结

  1. 工程价值:统一管理提示词样例,不用手动拼接超长字符串,便于维护、修改样例
  2. 适用场景:分类、翻译、抽取、格式生成、问答等需要固定输出格式的任务
  3. 优势对比 Zero-shot:少量样例能大幅约束 LLM 输出格式,减少乱回答、格式错乱
  4. 扩展方向
    • 语义动态选样例 ExampleSelector
    • 搭配 ChatPromptTemplate 实现对话式少样本
    • 和 RAG 结合,把检索文档作为 Few-shot 示例注入 Prompt

四、补充运行依赖

执行代码前必须安装库:

bash

运行

pip install langchain-core

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询