跳到主要內容
Open In ColabOpen on GitHub

如何在聊天模型中使用少量範例

先決條件

本指南假設您熟悉以下概念

本指南涵蓋如何使用範例輸入和輸出來提示聊天模型。為模型提供一些此類範例稱為少量樣本學習,這是一種簡單但功能強大的方法,可用於引導生成,並在某些情況下顯著提高模型效能。

關於如何最好地進行少量樣本提示,似乎沒有確鑿的共識,最佳提示編譯可能會因模型而異。因此,我們提供了少量樣本提示範本,例如 FewShotChatMessagePromptTemplate 作為彈性的起點,您可以根據需要修改或替換它們。

少量樣本提示範本的目標是根據輸入動態選擇範例,然後將範例格式化為最終提示以提供給模型。

注意: 以下程式碼範例僅適用於聊天模型,因為 FewShotChatMessagePromptTemplates 旨在輸出格式化的聊天訊息,而不是純字串。如需與完成模型 (LLM) 相容的純字串範本的類似少量樣本提示範例,請參閱少量樣本提示範本指南。

固定範例

最基本 (且常見) 的少量樣本提示技術是使用固定提示範例。這樣您就可以選擇鏈、評估它,並避免擔心生產中的其他移動部件。

範本的基本組件包括

  • examples:要包含在最終提示中的字典範例列表。
  • example_prompt:透過其 format_messages 方法將每個範例轉換為 1 個或多個訊息。一個常見的範例是將每個範例轉換為一個人類訊息和一個 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_messages 工廠方法中,並將其與模型一起使用

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})

我們可以發現模型現在已經從給定的少量樣本範例中推斷出鸚鵡表情符號表示加法!

動態少量樣本提示

有時您可能只想根據輸入從您的整體集合中選擇幾個範例來顯示。為此,您可以將傳遞到 FewShotChatMessagePromptTemplate 中的 examples 替換為 example_selector。其他組件與上面保持不變!我們的動態少量樣本提示範本如下所示

  • example_selector:負責為給定輸入選擇少量樣本範例 (以及它們傳回的順序)。這些實作了 BaseExampleSelector 介面。一個常見的範例是由向量儲存庫支援的 SemanticSimilarityExampleSelector
  • example_prompt:透過其 format_messages 方法將每個範例轉換為 1 個或多個訊息。一個常見的範例是將每個範例轉換為一個人類訊息和一個 AI 訊息回應,或一個人類訊息後跟一個函式呼叫訊息。

這些可以再次與其他訊息和聊天範本組合,以組裝您的最終提示。

讓我們逐步了解使用 SemanticSimilarityExampleSelector 的範例。由於此實作使用向量儲存庫根據語義相似度選擇範例,因此我們將首先填充儲存庫。由於這裡的基本概念是我們想要搜尋並傳回與文字輸入最相似的範例,因此我們嵌入提示範例的 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

建立向量儲存庫後,我們可以建立 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')]

我們可以將此少量樣本聊天訊息提示範本傳遞到另一個聊天提示範本中

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')]

與聊天模型搭配使用

最後,您可以將模型連接到少量樣本提示。

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})

後續步驟

您現在已了解如何將少量樣本範例新增至您的聊天提示。

接下來,查看本節中關於提示範本的其他操作指南、關於使用文字完成模型進行少量樣本學習的相關操作指南,或其他的範例選擇器操作指南


此頁面是否有幫助?