Langchain文档 为聊天模型提供的少样本案例

270 阅读1分钟

这个笔记本涵盖了如何在聊天模型中使用Few-shot示例。目前还没有就如何最好地进行Few-shot提示达成一致。因此,我们暂时不会对此进行任何抽象处理,而是使用现有的抽象处理方法。

交替的人工智能/人类消息

进行Few-shot提示的第一种方式是使用交替的人工智能/人类消息。以下是一个示例:

from langchain.chat_models import ChatOpenAI
from langchain import PromptTemplate, LLMChain
from langchain.prompts.chat import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    AIMessagePromptTemplate,
    HumanMessagePromptTemplate,
)
from langchain.schema import AIMessage, HumanMessage, SystemMessage

chat = ChatOpenAI(temperature=0)
template = "You are a helpful assistant that translates english to pirate."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
example_human = HumanMessagePromptTemplate.from_template("Hi")
example_ai = AIMessagePromptTemplate.from_template("Argh me mateys")
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages(
    [system_message_prompt, example_human, example_ai, human_message_prompt])
chain = LLMChain(llm=chat, prompt=chat_prompt)

# 从格式化的消息中获取聊天完成
chain.run("I love programming.")

系统消息

OpenAI提供了一个可选的name参数,他们还建议与系统消息一起使用来进行Few-shot提示。以下是如何使用name参数的示例:

template = "You are a helpful assistant that translates english to pirate."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
example_human = SystemMessagePromptTemplate.from_template("Hi", additional_kwargs={"name": "example_user"})
example_ai = SystemMessagePromptTemplate.from_template("Argh me mateys", additional_kwargs={"name": "example_assistant"})
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages(
    [system_message_prompt, example_human, example_ai, human_message_prompt])
chain = LLMChain(llm=chat, prompt=chat_prompt)

# 从格式化的消息中获取聊天完成
chain.run("I love programming.")
"I be lovin' programmin', me hearty."