# 掌握LangChain中的Runnable:轻松绑定默认参数,提升AI任务效率
## 引言
在构建复杂的AI应用程序时,常常需要将多个任务串联起来。在LangChain中,`Runnable`是一个强大的工具,可以帮助我们构建这样的任务链。然而,有时候我们希望在任务链运行时为某些`Runnable`设置固定参数,这些参数既不依赖于用户输入,也不从前一个任务的输出中获得。本文将介绍如何使用`Runnable.bind()`方法来为`Runnable`预先设置这些参数。
## 主要内容
### 1. 绑定停止序列
在LangChain中,结合`Prompt`与`Model`的任务链非常常见。假设我们有一个简单的任务链,用于将数学方程式转化为代数表达式并求解:
```python
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"))
假设我们希望在生成的输出中截去SOLUTION部分,可以通过bind()方法在运行时绑定一个停止词:
runnable = (
{"equation_statement": RunnablePassthrough()}
| prompt
| model.bind(stop="SOLUTION") # 使用API代理服务提高访问稳定性
| StrOutputParser()
)
print(runnable.invoke("x raised to the third plus seven equals 12"))
2. 绑定工具调用
LangChain还支持工具调用,特别是对于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) # 使用API代理服务提高访问稳定性
model.invoke("What's the weather in SF, NYC and LA?")
代码示例
如上述代码片段所示,我们可以通过bind()方法轻松为Runnable设置默认参数,确保在运行时对输出进行精确控制。
常见问题和解决方案
-
网络无法访问API端点:由于某些地区的网络限制,您可能需要考虑使用API代理服务来提高访问稳定性。
-
参数绑定不生效:确保参数名称和数据类型与API要求一致,否则可能无法正确绑定。
总结和进一步学习资源
通过学习使用Runnable.bind()方法,您可以在LangChain任务链中更灵活地控制参数设定,从而提高任务的可控性和有效性。接下来,您可以查阅LangChain的其他指南,学习如何使用可配置字段和替代步骤在运行时更改任务链的参数。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---