如何为Runnable设置默认调用参数:优化LangChain中的操作序列

77 阅读3分钟

如何为Runnable设置默认调用参数:优化LangChain中的操作序列

引言

在使用LangChain进行复杂任务处理时,常常需要使用RunnableSequence来创建精细的操作链。有时候,我们希望在这些链中的某个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"))

假设我们想要使用某些停止词(stopwords)来缩短输出,例如各种提示技术中常用的场景。我们可以通过bind()方法传递运行时参数,如下所示:

runnable = (
    {"equation_statement": RunnablePassthrough()}
    | prompt
    | model.bind(stop="SOLUTION")  # 绑定停止词参数
    | StrOutputParser()
)

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

附加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:

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)

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

# 执行调用
print(runnable.invoke("x raised to the third plus seven equals 12"))

常见问题和解决方案

  1. 参数绑定后无效: 确保你绑定的参数名称和相应的方法签名是一致的。
  2. 网络访问问题: 某些地区可能会遇到访问限制,建议使用API代理服务提升访问的稳定性。

总结和进一步学习资源

在LangChain中绑定参数为构建灵活而强大的操作序列提供了重要的支持。通过提前设置默认参数,可以更高效地构建和调用Runnable对象。对于进一步的学习,建议参考LangChain的其他操作指南和文档,以充分发挥该框架的潜力。

参考资料

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

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

---END---