Skip to main content
Open In Colab在 GitHub 上打开

如何在聊天模型中使用少数镜头示例

先决条件

本指南假定您熟悉以下概念:

本指南介绍如何使用示例输入和输出提示聊天模型。为模型提供一些这样的示例称为 few-shotting,这是一种简单而强大的方法,可以指导生成,在某些情况下可以显著提高模型性能。

关于如何最好地进行 few-shot 提示似乎没有坚实的共识,并且最佳提示编译可能会因模型而异。因此,我们提供了 FewShotChatMessagePromptTemplate 等小镜头提示模板作为灵活的起点,您可以根据需要修改或替换它们。

小样本提示模板的目标是根据输入动态选择示例,然后在最终提示中格式化示例以提供模型。

注意:以下代码示例仅适用于聊天模型,因为FewShotChatMessagePromptTemplates旨在输出格式化的聊天消息,而不是纯字符串。有关与完成模型 (LLM) 兼容的纯字符串模板的类似小镜头提示示例,请参阅小镜头提示模板指南。

修复示例

最基本(也是最常见的)小镜头提示技术是使用固定提示示例。这样,您就可以选择链条,对其进行评估,并避免担心生产中的额外活动部件。

该模板的基本组件包括:

  • examples:要包含在最终提示中的词典示例列表。
  • example_prompt:通过其format_messages方法。一个常见的示例是将每个示例转换为一个人工消息和一个 AI 消息响应,或者将人工消息后跟函数调用消息。

下面是一个简单的演示。首先,定义要包含的示例。让我们给 LLM 一个不熟悉的数学运算符,用 “” 🦜 表情符号表示:

%pip install -qU langchain langchain-openai langchain-chroma

import os
from getpass import getpass

if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass()

如果我们尝试询问模型这个表达式的结果是什么,它会失败:

from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o-mini", temperature=0.0)

model.invoke("What is 2 🦜 9?")
API 参考:ChatOpenAI
AIMessage(content='The expression "2 🦜 9" is not a standard mathematical operation or equation. It appears to be a combination of the number 2 and the parrot emoji 🦜 followed by the number 9. It does not have a specific mathematical meaning.', response_metadata={'token_usage': {'completion_tokens': 54, 'prompt_tokens': 17, 'total_tokens': 71}, 'model_name': 'gpt-4o-mini', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-aad12dda-5c47-4a1e-9949-6fe94e03242a-0', usage_metadata={'input_tokens': 17, 'output_tokens': 54, 'total_tokens': 71})

现在让我们看看如果我们给 LLM 一些示例来使用会发生什么。我们将在下面定义一些:

from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate

examples = [
{"input": "2 🦜 2", "output": "4"},
{"input": "2 🦜 3", "output": "5"},
]

接下来,将它们组合到少数镜头提示模板中。

# This is a prompt template used to format each individual example.
example_prompt = ChatPromptTemplate.from_messages(
[
("human", "{input}"),
("ai", "{output}"),
]
)
few_shot_prompt = FewShotChatMessagePromptTemplate(
example_prompt=example_prompt,
examples=examples,
)

print(few_shot_prompt.invoke({}).to_messages())
[HumanMessage(content='2 🦜 2'), AIMessage(content='4'), HumanMessage(content='2 🦜 3'), AIMessage(content='5')]

最后,我们按照如下所示组装最终的提示符,将few_shot_prompt直接进入from_messagesfactory 方法,并将其与模型一起使用:

final_prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a wondrous wizard of math."),
few_shot_prompt,
("human", "{input}"),
]
)

现在让我们向模型提出初始问题,看看它是如何运作的:

from langchain_openai import ChatOpenAI

chain = final_prompt | model

chain.invoke({"input": "What is 2 🦜 9?"})
API 参考:ChatOpenAI
AIMessage(content='11', response_metadata={'token_usage': {'completion_tokens': 1, 'prompt_tokens': 60, 'total_tokens': 61}, 'model_name': 'gpt-4o-mini', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-5ec4e051-262f-408e-ad00-3f2ebeb561c3-0', usage_metadata={'input_tokens': 60, 'output_tokens': 1, 'total_tokens': 61})

我们可以看到,模型现在已经从给定的少数镜头示例中推断出鹦鹉表情符号的含义是加法!

动态 few-shot 提示

有时,您可能希望从整个集合中仅选择几个示例,以根据输入进行显示。为此,您可以将examples传递到FewShotChatMessagePromptTemplate替换为example_selector.其他组件与上述相同!我们的动态 few-shot 提示模板如下所示:

  • example_selector:负责为给定输入选择小样本样本(以及它们的返回顺序)。这些实现 BaseExampleSelector 接口。一个常见的示例是 vectorstore 支持的 SemanticSimilarityExampleSelector
  • example_prompt:通过其format_messages方法。一个常见的示例是将每个示例转换为一个人工消息和一个 AI 消息响应,或者将人工消息后跟函数调用消息。

这些可以再次与其他消息和聊天模板组成,以组合您的最终提示。

让我们来看一个带有SemanticSimilarityExampleSelector.由于此实现使用 vectorstore 根据语义相似性选择示例,因此我们需要首先填充 store。由于这里的基本思想是,我们想要搜索并返回与文本输入最相似的示例,因此我们将values而不是考虑键:

from langchain_chroma import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_openai import OpenAIEmbeddings

examples = [
{"input": "2 🦜 2", "output": "4"},
{"input": "2 🦜 3", "output": "5"},
{"input": "2 🦜 4", "output": "6"},
{"input": "What did the cow say to the moon?", "output": "nothing at all"},
{
"input": "Write me a poem about the moon",
"output": "One for the moon, and one for me, who are we to talk about the moon?",
},
]

to_vectorize = [" ".join(example.values()) for example in examples]
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_texts(to_vectorize, embeddings, metadatas=examples)

创建example_selector

创建 vectorstore 后,我们可以创建example_selector.在这里,我们将孤立地调用它,并设置k以仅获取最接近输入的两个示例。

example_selector = SemanticSimilarityExampleSelector(
vectorstore=vectorstore,
k=2,
)

# The prompt template will load examples by passing the input do the `select_examples` method
example_selector.select_examples({"input": "horse"})
[{'input': 'What did the cow say to the moon?', 'output': 'nothing at all'},
{'input': '2 🦜 4', 'output': '6'}]

创建提示模板

现在,我们使用example_selector在上面创建。

from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate

# Define the few-shot prompt.
few_shot_prompt = FewShotChatMessagePromptTemplate(
# The input variables select the values to pass to the example_selector
input_variables=["input"],
example_selector=example_selector,
# Define how each example will be formatted.
# In this case, each example will become 2 messages:
# 1 human, and 1 AI
example_prompt=ChatPromptTemplate.from_messages(
[("human", "{input}"), ("ai", "{output}")]
),
)

print(few_shot_prompt.invoke(input="What's 3 🦜 3?").to_messages())
[HumanMessage(content='2 🦜 3'), AIMessage(content='5'), HumanMessage(content='2 🦜 4'), AIMessage(content='6')]

而我们可以将这个 few-shot 的聊天消息提示模板传递到另一个聊天提示模板中:

final_prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a wondrous wizard of math."),
few_shot_prompt,
("human", "{input}"),
]
)

print(few_shot_prompt.invoke(input="What's 3 🦜 3?"))
messages=[HumanMessage(content='2 🦜 3'), AIMessage(content='5'), HumanMessage(content='2 🦜 4'), AIMessage(content='6')]

与聊天模型一起使用

最后,您可以将模型连接到 few-shot 提示符。

chain = final_prompt | ChatOpenAI(model="gpt-4o-mini", temperature=0.0)

chain.invoke({"input": "What's 3 🦜 3?"})
AIMessage(content='6', response_metadata={'token_usage': {'completion_tokens': 1, 'prompt_tokens': 60, 'total_tokens': 61}, 'model_name': 'gpt-4o-mini', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-d1863e5e-17cd-4e9d-bf7a-b9f118747a65-0', usage_metadata={'input_tokens': 60, 'output_tokens': 1, 'total_tokens': 61})

后续步骤

您现在已经学习了如何将 few-shot 示例添加到您的聊天提示中。

接下来,查看本节中关于提示模板的其他操作指南,关于使用文本完成模型进行少数拍摄的相关操作指南,或其他示例选择器操作指南