agentscope.toolToolMiddlewareBase
class ToolMiddlewareBase(ABC)
agentscope/tool/_base.py:42–97工具中间件基类,让智能体以受控方式调用外部能力。位于 agentscope.tool 包,继承自 ABC。核心成员包括 on_tool_call。
A tool middleware wraps the execution of a tool in an onion fashion: the
first registered middleware is the outermost layer and runs its pre-logic
before any inner layer, then its post-logic after all inner layers have
completed. Subclass this and implement :meth:on_tool_call — the signature
is already spelled out, so second-party developers only need to fill in the
body without reasoning about the wrapping protocol.
Streaming and non-streaming tools are unified: next_handler always
returns an async generator, so a middleware never needs to know whether the
underlying tool yields a stream of chunks or returns a single chunk.
示例Example
class LoggingMiddleware(ToolMiddlewareBase):
async def on_tool_call(self, tool, input_kwargs, next_handler):
print(f"Calling {tool.name} with {input_kwargs}")
async for chunk in next_handler(**input_kwargs):
yield chunk
print(f"Finished {tool.name}")
tool = MyTool(middlewares=[LoggingMiddleware()])
方法摘要Method Summary
| 方法Method | 说明Description |
|---|---|
async def on_tool_call(tool: 'ToolBase', input_kwargs: dict[str, Any], next_handler: Callable[..., AsyncGenerator[ToolC…asyncabstractabstractmethod | 处理工具调用事件。 Intercept a single tool invocation. |
方法详情Method Detail
on_tool_call
async def on_tool_call(tool: 'ToolBase', input_kwargs: dict[str, Any], next_handler: Callable[..., AsyncGenerator[ToolChunk, None]]) -> AsyncGenerator[ToolChunk, None]
处理工具调用事件。
Add pre-/post-logic around next_handler, rewrite the tool inputs by passing modified keyword arguments to next_handler, or transform the yielded chunks.
| 名称Name | 类型Type | 说明Description |
|---|---|---|
tool | 'ToolBase' | 工具(类型 `'ToolBase'`)。The tool instance being invoked. |
input_kwargs | dict[str, Any] | 输入关键字参数(类型 `dict[str, Any]`)。The tool's input arguments for this invocation. Pass them on via `next_handler(**input_kwargs)`; mutate or replace them to change what the inner layers and the tool itself receive. |
next_handler | Callable[..., AsyncGenerator[ToolChunk, None]] | 下一个处理器(类型 `Callable[..., AsyncGenerator[ToolChunk, None]]`)。Call it as `next_handler(**input_kwargs)` to run the next layer. It always returns an async generator, regardless of whether the underlying tool is streaming or not. |
agentscope/tool/_base.py:70–97