AS AgentScopeAPI 手册 / API Reference
类class agentscope.tool

ToolMiddlewareBase

class ToolMiddlewareBase(ABC)
源码Source 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]
asyncabstractabstractmethod

处理工具调用事件。

Add pre-/post-logic around next_handler, rewrite the tool inputs by passing modified keyword arguments to next_handler, or transform the yielded chunks.

参数Parameters
名称Name类型Type说明Description
tool'ToolBase'工具(类型 `'ToolBase'`)。The tool instance being invoked.
input_kwargsdict[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_handlerCallable[..., 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.
返回Returns AsyncGenerator[ToolChunk, None]
以异步流的形式返回ToolChunk,None。`ToolChunk`:
源码Source agentscope/tool/_base.py:70–97
基于官方固定版本源码静态生成Generated from pinned official sources · Python 2.0.11 · Java 2.0.4
签名与文档为静态抽取;如有疑问请以源码为准。Signatures and docs are extracted statically; verify against the source when in doubt.