API 参考¶
ToolRegistry 中所有类和方法的全面 API 文档,从源代码自动生成。
核心类¶
基础类和基本组件:
- ToolRegistry — 工具管理的中央协调器
- Tool — 包含元数据和执行逻辑的单个工具
- Executor — 可插拔的执行后端(线程/进程)
- Events — 变更事件类型和回调机制
- Permissions — 基于规则的授权框架
参见 核心类概览 了解架构图。
集成模块¶
框架和协议兼容性,用于工具注册:
- OpenAPI — 从 OpenAPI 规范生成 REST API 工具
- MCP — 模型上下文协议服务器通信
- LangChain — LangChain BaseTool 互操作性
- Native — Python 类方法注册
参见 集成模块概览 了解通用模式。
工具包装器¶
不同工具类型的适配器类:
- BaseToolWrapper — 抽象基类
- MCPToolWrapper — MCP 服务器工具包装器
- OpenAPIToolWrapper — OpenAPI/REST 工具包装器
- LangChainToolWrapper — LangChain 工具包装器
参见 工具包装器概览 了解执行模型。
辅助类¶
支持工具:
- 参数模型与工具函数 — 参数验证、工具名规范化、HTTP 客户端配置
类型定义¶
LLM API 格式兼容性类型:
- 类型 — 通用、OpenAI、Anthropic 和 Gemini 类型定义
完整模块概览¶
toolregistry ¶
ToolRegistry ¶
ToolRegistry(name: str | None = None, *, default_max_result_size: int | None = None, think_augment: bool = False, tool_discovery: bool = False)
Bases: AdminMixin, ExecutionLoggingMixin, PermissionsMixin, RegistrationMixin, EnableDisableMixin, NamespaceMixin, ChangeCallbackMixin
Central registry for managing tools (functions) and their metadata.
This class provides functionality to register, manage, and execute tools, as well as to interface with MCP servers, OpenAPI endpoints, and generate tool schemas.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the tool registry. |
Notes
Private attributes are used internally to manage registered tools and sub-registries. These attributes are not intended for external use.
Initialize an empty ToolRegistry.
This method initializes an empty ToolRegistry with a name and internal structures for storing tools and sub-registries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Name of the tool registry. Defaults to a random "reg_<4-char>" string. For instance, "reg_1a3c". |
None
|
default_max_result_size
|
int | None
|
Default maximum result size in characters
for all tools. Individual tools can override this via
|
None
|
think_augment
|
bool
|
Enable thought-augmented tool calling globally.
When |
False
|
tool_discovery
|
bool
|
Enable tool discovery on initialization.
When |
False
|
Notes
This class uses private attributes _tools and _sub_registries internally
to manage registered tools and sub-registries. These are not intended for
external use.
__contains__ ¶
Check if a tool with the given name is registered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the tool to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if tool is registered, False otherwise. |
__getitem__ ¶
Enable key-value access to retrieve callables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Name of the function. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any] | None
|
Optional[Callable[..., Any]]: The function to call, or None if not found. |
__repr__ ¶
Return the JSON representation of the registry for debugging purposes.
Returns:
| Name | Type | Description |
|---|---|---|
str |
JSON string representation of the registry. |
__str__ ¶
Return the JSON representation of the registry as a string.
Returns:
| Name | Type | Description |
|---|---|---|
str |
JSON string representation of the registry. |
build_tool_call_messages ¶
build_tool_call_messages(tool_calls: list[AnyToolCall], tool_responses: dict[str, str | list], api_format: API_FORMATS = 'openai-chat') -> list[dict[str, Any]]
Build conversation messages for a tool-calling round-trip.
Combines the assistant message (tool call requests) and the tool result messages into the format required by the next LLM turn.
This is a convenience method wrapping :func:build_assistant_message
and :func:build_tool_response. It handles Gemini-specific ID
alignment automatically (position-based remapping).
.. important::
Do **not** reorder ``tool_calls`` between
:meth:`execute_tool_calls` and this method. Gemini format
relies on positional alignment between ``tool_calls`` and
``tool_responses`` because Gemini does not provide tool call
IDs upstream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_calls
|
list[AnyToolCall]
|
Tool call objects in any supported format. |
required |
tool_responses
|
dict[str, str | list]
|
Mapping of tool call IDs to results,
as returned by :meth: |
required |
api_format
|
API_FORMATS
|
Target API format. Defaults to |
'openai-chat'
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
Conversation messages ready to extend the message history. |
list[dict[str, Any]]
|
When multimodal content is present, an additional user |
list[dict[str, Any]]
|
message is appended containing the expanded content. |
close_async
async
¶
Close all persistent connections (async).
Closes MCP and OpenAPI integrations that hold persistent connections or HTTP clients.
disable_think_augment ¶
Disable thought-augmented tool calling globally.
When disabled, the toolcall_reason property is stripped from
tool schemas produced by :meth:get_schemas, unless a tool
explicitly opts in via ToolMetadata.think_augment = True.
disable_tool_discovery ¶
Disable tool discovery and unregister the discovery tool.
enable_think_augment ¶
Enable thought-augmented tool calling globally.
When enabled, a toolcall_reason property is included in
every tool's schema (via :meth:get_schemas) so that LLMs can
articulate their rationale when calling tools. Individual tools
can still override this via ToolMetadata.think_augment.
Reference: https://arxiv.org/abs/2601.18282
enable_tool_discovery ¶
Enable tool discovery and register a discovery tool.
Creates a :class:ToolDiscoveryTool, registers its
:meth:~ToolDiscoveryTool.discover method as a callable tool
named discover_tools, and subscribes to registry change
events for automatic index rebuilds.
The discovery tool itself is never deferred (defer=False)
so that LLMs always see it in the initial schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_weights
|
dict[str, float] | None
|
Optional per-field BM25F boost weights. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
ToolDiscoveryTool
|
class: |
execute_tool_calls ¶
execute_tool_calls(tool_calls: list[AnyToolCall], execution_mode: Literal['process', 'thread'] | None = None) -> dict[str, str | list]
Execute tool calls with concurrency using cloudpickle for serialization.
Disabled tools are rejected with an error message instead of being executed. If logging is enabled, execution details are recorded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_calls
|
list[AnyToolCall]
|
List of tool calls to be executed in any supported format. |
required |
execution_mode
|
Literal['process', 'thread'] | None
|
Execution mode to use; defaults to the Executor's current mode. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str | list]
|
Dictionary mapping tool call IDs to their results. Values |
dict[str, str | list]
|
are |
dict[str, str | list]
|
multimodal results (e.g. images). |
get_deferred_summaries ¶
Get name and first-sentence description for deferred tools.
Useful for injecting into system prompts so the LLM knows which
additional tools are available via discover_tools.
Only enabled tools with ToolMetadata.defer=True are included.
Returns:
| Type | Description |
|---|---|
list[dict[str, str | None]]
|
List of dicts with keys: |
list[dict[str, str | None]]
|
|
list[dict[str, str | None]]
|
|
list[dict[str, str | None]]
|
|
get_schemas ¶
get_schemas(tool_name: str | None = None, *, api_format: API_FORMATS = 'openai-chat', tags: set[str | ToolTag] | None = None, exclude_tags: set[str | ToolTag] | None = None, sort: bool = True, include_deferred: bool = True) -> list[dict[str, Any]]
Get tool definitions as JSON Schema dicts for a target API format.
When no specific tool_name is given, only enabled tools are returned. Tools can be filtered by tags and sorted for deterministic ordering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_name
|
str | None
|
Optional name of specific tool to get schema for. When set, tag filtering and sorting are skipped. |
None
|
api_format
|
API_FORMATS
|
Target API format. Defaults to |
'openai-chat'
|
tags
|
set[str | ToolTag] | None
|
If set, only include tools matching ANY of these tags. |
None
|
exclude_tags
|
set[str | ToolTag] | None
|
Exclude tools matching ANY of these tags. |
None
|
sort
|
bool
|
If True (default), sort tools by name for deterministic ordering. Stable sorting improves prompt cache hit rates. |
True
|
include_deferred
|
bool
|
If False, exclude tools with
|
True
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
A list of tool definition dicts in the specified API format. |
get_tools_json ¶
get_tools_json(tool_name: str | None = None, *, api_format: API_FORMATS = 'openai-chat', tags: set[str | ToolTag] | None = None, exclude_tags: set[str | ToolTag] | None = None, sort: bool = True, include_deferred: bool = True) -> list[dict[str, Any]]
Deprecated: use :meth:get_schemas instead.
get_tools_status ¶
Get status information for all registered tools.
Returns a list of dictionaries containing status information for each tool, including enable/disable state, metadata summary, and tags.
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
list[dict[str, Any]]: List of tool status dictionaries, each containing:
|
Example
registry = ToolRegistry() registry.register(my_tool) registry.disable("my_tool", reason="Under maintenance") registry.get_tools_status() [ { "name": "my_tool", "enabled": False, "reason": "Under maintenance", "namespace": None, "tags": [], "locality": "any", "is_async": False, "think_augment": None, "defer": False, } ]
list_all_tools ¶
Deprecated: use list_tools(include_disabled=True) instead.
list_tools ¶
List registered tools.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_disabled
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: A list of tool names. |
recover_tool_call_assistant_message ¶
recover_tool_call_assistant_message(tool_calls: list[AnyToolCall], tool_responses: dict[str, str | list], api_format: API_FORMATS = 'openai-chat') -> list[dict[str, Any]]
Deprecated: use :meth:build_tool_call_messages instead.
set_default_execution_mode ¶
Set the default execution mode for parallel tasks.
This sets the default mode used by :meth:execute_tool_calls when no
per-call execution_mode override is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
Literal['thread', 'process']
|
The desired execution mode. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an invalid mode is provided. |
set_execution_mode ¶
Deprecated: use :meth:set_default_execution_mode instead.
Tool ¶
Bases: BaseModel
Base class representing an executable tool/function.
Provides core functionality for
- Function wrapping and metadata management
- Parameter validation using Pydantic
- Synchronous/asynchronous execution
- JSON schema generation
callable
class-attribute
instance-attribute
¶
The underlying function/method that implements the tool's logic.
This is excluded from serialization to prevent accidental exposure of sensitive implementation details.
description
class-attribute
instance-attribute
¶
Detailed description of the tool's functionality.
Should clearly explain what the tool does, its purpose, and any important usage considerations.
is_async
property
¶
Whether the tool requires async execution.
Backward-compatible proxy to metadata.is_async.
metadata
class-attribute
instance-attribute
¶
Behavioral and classification metadata for this tool.
Contains execution hints (is_async, is_concurrency_safe,
timeout) and classification tags (tags, custom_tags).
method_name
class-attribute
instance-attribute
¶
The original method/function name before namespace prefixing.
Preserved so that the base name can be recovered without
ambiguity even when the name field contains a namespace
prefix joined by - (which normalize_tool_name would
otherwise convert to _).
name
class-attribute
instance-attribute
¶
The name of the tool.
Used as the primary identifier when calling the tool. Must be unique within a tool registry.
namespace
class-attribute
instance-attribute
¶
The namespace this tool belongs to.
Used to group tools logically and avoid name collisions.
When set, the tool's name is typically prefixed as
{namespace}-{method_name}. This field stores the
original namespace string (after normalization) so that
downstream code can reliably determine group membership
without parsing the name field.
parameters
class-attribute
instance-attribute
¶
Parameter schema defining the tool's expected inputs.
Follows JSON Schema format. Automatically generated from the wrapped function's type hints when using from_function().
parameters_model
class-attribute
instance-attribute
¶
parameters_model: Any | None = Field(default=None, description='Pydantic Model for tool parameters')
Pydantic model used for parameter validation.
Automatically generated from the wrapped function's type hints when using from_function(). Can be None for tools without parameter validation.
qualified_name
property
¶
Return the fully-qualified tool name.
If a namespace is set, returns {namespace}-{method_name}.
Otherwise falls back to the name field.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The qualified name of the tool. |
arun
async
¶
Execute tool asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, Any]
|
Validated input parameters. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
Tool execution result. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If async execution unsupported. |
Exception
|
On execution failure. |
Note
Result size truncation (via max_result_size) is only applied
when tools are executed through
ToolRegistry.execute_tool_calls(). Direct calls to arun()
return raw results without truncation.
.. deprecated::
When an exception is caught, arun() returns an error string.
This behaviour is deprecated — use arun_raw() to get
exceptions directly. In a future version arun() will raise.
arun_raw
async
¶
Execute tool asynchronously, raising on failure.
Unlike arun(), this method does not catch exceptions — they
propagate to the caller, preserving full stack-trace information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
dict[str, Any]
|
Input parameters for the tool. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The tool execution result. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If async execution is unsupported. |
Exception
|
Any exception raised during validation or execution. |
Note
Result size truncation (via max_result_size) is only applied
when tools are executed through
ToolRegistry.execute_tool_calls(). Direct calls return raw
results without truncation.
describe ¶
Deprecated: use :meth:get_schema instead.
from_function
classmethod
¶
from_function(func: Callable[..., Any], name: str | None = None, description: str | None = None, namespace: str | None = None, method_name: str | None = None, metadata: ToolMetadata | None = None) -> Tool
Factory method to create Tool from callable.
Automatically
- Extracts function metadata
- Generates parameter schema
- Handles async/sync detection
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Function to convert to tool. |
required |
name
|
str | None
|
Override tool name (defaults to function name). |
None
|
description
|
str | None
|
Override description (defaults to docstring). |
None
|
namespace
|
str | None
|
Namespace the tool belongs to. |
None
|
method_name
|
str | None
|
Original method name of the tool. |
None
|
metadata
|
ToolMetadata | None
|
Optional ToolMetadata; |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Tool |
Tool
|
Configured Tool instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
For unnamed lambda functions. |
get_json_schema ¶
Deprecated: use :meth:get_schema instead.
get_schema ¶
get_schema(api_format: API_FORMATS = 'openai-chat', *, _think_augment: bool | None = None) -> dict[str, Any]
Generate schema representation of tool for a target API format.
All formats are produced via llm-rosetta converters, which also
apply schema sanitization (stripping unsupported JSON Schema
keywords like $ref, $schema, anyOf, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_format
|
API_FORMATS
|
Target API format. One of |
'openai-chat'
|
_think_augment
|
bool | None
|
Internal override for toolcall_reason injection.
When |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Provider-specific tool definition dict. |
model_post_init ¶
Inject toolcall_reason property into the tool's parameter schema.
Runs after every Tool (and subclass) construction, regardless
of whether the instance was created via from_function(), or
directly (MCP, OpenAPI, LangChain integrations).
The toolcall_reason field is only added when parameters
already contains a properties mapping.
run ¶
Execute tool synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
Dict[str, Any]
|
Validated input parameters. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
Tool execution result. |
Raises:
| Type | Description |
|---|---|
Exception
|
On execution failure. |
Note
Result size truncation (via max_result_size) is only applied
when tools are executed through
ToolRegistry.execute_tool_calls(). Direct calls to run()
return raw results without truncation.
.. deprecated::
When an exception is caught, run() returns an error string.
This behaviour is deprecated — use run_raw() to get
exceptions directly. In a future version run() will raise.
run_raw ¶
Execute tool synchronously, raising on failure.
Unlike run(), this method does not catch exceptions — they
propagate to the caller, preserving full stack-trace information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
dict[str, Any]
|
Input parameters for the tool. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The tool execution result. |
Raises:
| Type | Description |
|---|---|
Exception
|
Any exception raised during validation or execution. |
Note
Result size truncation (via max_result_size) is only applied
when tools are executed through
ToolRegistry.execute_tool_calls(). Direct calls return raw
results without truncation.
update_namespace ¶
Updates the namespace of a tool.
This method checks if the tool's name already contains a namespace (indicated by the presence of a separator character).
OpenAI requires that function names match the pattern ^[a-zA-Z0-9_-]+$. Some other providers allow dot (.) as separator.
If it does and force is True, the existing namespace is replaced with the provided namespace.
If force is False and an existing namespace is present, no changes are made.
If the tool's name does not contain a namespace, the namespace is prepended as a prefix to the tool's name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str
|
The new namespace to apply to the tool's name. |
required |
force
|
bool
|
If |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
This method modifies the |
Example
tool = Tool(name="example_tool")
tool.update_namespace("new_namespace")
tool.name # 'new_namespace-example_tool'
tool = Tool(name="old_namespace.example_tool")
tool.update_namespace("new_namespace", force=False)
tool.name # 'old_namespace-example_tool'
tool = Tool(name="old_namespace.example_tool")
tool.update_namespace("new_namespace", force=True, sep=".")
tool.name # 'new_namespace.example_tool'