趋近智
大型语言模型(LLM)具有很强的能力,但相比只被告知做什么,当被展示如何完成任务时,它们的表现通常更好。少量样本提示就派上用场了。少量样本提示是一种直接在提示中包含几个完成任务的示例(样本)的技术。这与零样本提示不同,零样本提示是一种只提供指令而没有任何示例的方法。
可以把它看作是在要求模型解决新问题之前,给它一个迷你教程。这些示例作为演示,引导模型达到预期的输出格式、风格或推理过程。这种方法对于期望输出结构具体明确的任务,或者当任务本身需要某种模式而仅凭指令无法立即看出时,尤其有效。
让我们明确一下这些区别:
Translate to French: Hello worldTranslate to French:
sea otter => loutre de mer
Hello world =>
Translate to French:
sea otter => loutre de mer
cheese => fromage
blue sky => ciel bleu
Hello world =>
提供多个示例有以下几个好处:
在Python中,您可以使用简单的字符串格式化方法,或者使用LangChain等库的更结构化方法来构建少量样本提示。
您可以使用f-strings或str.format()来动态构建提示。
# 输入/输出对的示例
examples = [
{"input": "A friendly water mammal.", "output": "sea otter"},
{"input": "A dairy product made from milk.", "output": "cheese"},
{"input": "The color of the atmosphere on a clear day.", "output": "blue sky"}
]
# 我们希望模型处理的新输入
new_input = "A large, gray animal with a trunk."
# 构建提示字符串
prompt_parts = ["Identify the object from the description.\n"]
for example in examples:
prompt_parts.append(f"Description: {example['input']}")
prompt_parts.append(f"Object: {example['output']}\n") # 添加换行符用于分隔
# 添加最终输入
prompt_parts.append(f"Description: {new_input}")
prompt_parts.append("Object:") # 提示模型给出最终输出
final_prompt = "\n".join(prompt_parts)
print(final_prompt)
# 预期输出:
# Identify the object from the description.
#
# Description: A friendly water mammal.
# Object: sea otter
#
# Description: A dairy product made from milk.
# Object: cheese
#
# Description: The color of the atmosphere on a clear day.
# Object: blue sky
#
# Description: A large, gray animal with a trunk.
# Object:
这个final_prompt字符串随后会被发送到LLM API。模型会识别示例中的模式,并很可能输出“elephant”。
像LangChain这样的框架提供了管理提示的方法,特别是少量样本提示。您可以使用FewShotPromptTemplate之类的类。(我们已经在第4章了解了PromptTemplate;FewShotPromptTemplate在此基础上构建)。
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
# 定义示例
examples = [
{"input": "happy", "output": "sad"},
{"input": "tall", "output": "short"},
]
# 定义每个示例的格式模板
example_prompt = PromptTemplate.from_template("Input: {input}\nOutput: {output}")
# 定义整体的少量样本提示模板
few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
prefix="Give the antonym of the input word.",
suffix="Input: {user_input}\nOutput:", # {user_input} 是最终输入的变量
input_variables=["user_input"], # 指定最终输入的变量名
example_separator="\n\n" # 示例之间的分隔符
)
# 为新输入格式化提示
final_prompt = few_shot_prompt.format(user_input="hot")
print(final_prompt)
# 预期输出:
# Give the antonym of the input word.
#
# Input: happy
# Output: sad
#
# Input: tall
# Output: short
#
# Input: hot
# Output:
使用FewShotPromptTemplate可以使示例管理、格式化和整体提示结构更清晰,尤其当提示变得更复杂时。
示例的质量非常重要。糟糕的示例可能会让模型困惑或导致它重复错误。请记住以下几点:
少量样本提示在以下情况中特别有效:
少量样本提示虽然功能强大,但也有一些方面需要考虑:
少量样本提示是实际提示工程中的一种基本方法。通过在提示中提供具体示例,您可以大大增强引导LLM行为的能力,并获得更可靠、准确且格式正确的结果,尤其是在使用Python以编程方式实现这些提示时。
简洁的语法。内置调试功能。从第一天起就可投入生产。
为 ApX 背后的 AI 系统而构建
这部分内容有帮助吗?
FewShotPromptTemplate 官方文档,详细介绍了其使用方法、参数以及在 Python 中编程构建少样本提示的示例。© 2026 ApX Machine Learning用心打造