在LangChain中处理复杂的运行逻辑时,能够预先绑定一些常量参数到一个Runnable
可以为我们减少冗余代码并提高可维护性。本指南将介绍如何使用Runnable.bind()
方法来提前设置这些参数,使得在一个RunnableSequence
中调用时,既不需要依赖于前一个Runnable
的输出,也不需要使用者提供。
技术背景介绍
本指南假定您已熟悉以下概念:
- LangChain表达式语言(LCEL)
- Runnables的链式调用
- 工具调用
LangChain是一个支持可配置步骤和工具调用的强大框架,为顺序执行和复杂业务逻辑提供了支持。
核心原理解析
当我们需要在RunnableSequence
中调用一个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链
runnable = (
{"equation_statement": RunnablePassthrough()} | prompt | model | StrOutputParser()
)
# 调用Runnable
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_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?")
应用场景分析
这种参数绑定方法在多种场合下都非常有效,例如在对话模型中需要固定的结束条件,或者在工具调用中需要一致的参数格式。
实践建议
- 利用
bind()
方法可以减少重复配置,提高代码的可读性和可维护性。 - 在复杂的步骤链中使用参数绑定,可以简化输入并保持一定的灵活性。
如果遇到问题欢迎在评论区交流。
—END—