[在LangChain中如何为Runnable添加默认调用参数]

93 阅读3分钟

在LangChain中如何为Runnable添加默认调用参数

引言

在构建复杂的应用程序时,我们经常需要将多个功能模块(称为Runnables)串联在一起执行,它们形成了一个RunnableSequence。有时候,我们希望在这些序列中调用某个Runnable时,使用一些不在前一个Runnable的输出或用户输入中的常量参数。本文将介绍如何使用LangChain的.bind()方法为Runnable设置这些默认参数。

主要内容

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

输出的结果是:

EQUATION: x^3 + 7 = 12

SOLUTION: 
Subtract 7 from both sides:
x^3 = 5

Take the cube root of both sides:
x = ∛5

如果我们希望使用某些停止词来缩短输出,可以通过在模型上调用.bind()方法来实现:

runnable = (
    {"equation_statement": RunnablePassthrough()}
    | prompt
    | model.bind(stop="SOLUTION")  # 使用API代理服务提高访问稳定性
    | StrOutputParser()
)

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

这样,我们调整了模型的输出,以满足某些提示技术的需求。

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)  # 使用API代理服务提高访问稳定性
model.invoke("What's the weather in SF, NYC and LA?")

这种方式确保在调用模型时可以携带特定的工具调用参数。

代码示例

# 示例:在Runnable中绑定参数
runnable = (
    {"equation_statement": RunnablePassthrough()}
    | prompt
    | model.bind(stop="SOLUTION")  # 使用API代理服务提高访问稳定性
    | StrOutputParser()
)

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

常见问题和解决方案

  • 问题:绑定参数后执行失败?

    • 解决方案:检查参数名称是否正确以及是否与Runnable兼容。
  • 问题:输出未按预期缩短?

    • 解决方案:检查绑定的停止序列或参数是否正确,并根据需要调整。

总结和进一步学习资源

通过本文介绍的方法,你可以为Runnable设置默认调用参数,增强模型的灵活性和功能性。若想深入了解,可以查阅LangChain官方文档和其他相关教程:

参考资料

  • LangChain 文档
  • OpenAI API 文档

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