API 参考¶
ToolRegistry 中所有类和方法的全面 API 文档,从源代码自动生成。
核心类¶
基础类和基本组件:
- ToolRegistry — 工具管理的中央协调器
- Tool — 包含元数据和执行逻辑的单个工具
- Executor — 可插拔的执行后端(线程/进程)
- 出站地址策略 — 拒绝主机非全球可达的 URL
- Events — 变更事件类型和回调机制
- Permissions — 基于规则的授权框架
参见 核心类概览 了解架构图。
集成模块¶
框架和协议兼容性,用于工具注册:
- OpenAPI — 从 OpenAPI 规范生成 REST API 工具
- MCP — 模型上下文协议服务器通信
- LangChain — LangChain BaseTool 互操作性
- Native — Python 类方法注册
参见 集成模块概览 了解通用模式。
工具包装器¶
不同工具类型的适配器类:
- BaseToolWrapper — 抽象基类
- MCPToolWrapper — MCP 服务器工具包装器
- OpenAPIToolWrapper — OpenAPI/REST 工具包装器
- LangChainToolWrapper — LangChain 工具包装器
参见 工具包装器概览 了解执行模型。
辅助类¶
支持工具:
- 参数模型与工具函数 — 参数验证、工具名规范化、HTTP 客户端配置
校验错误¶
工具在运行前会校验参数。相关异常可以直接从包根导入,调用方无需访问私有模块即可将它们映射到自己的错误格式:
from toolregistry import ErrorDetail, SchemaValidationError, ValidationError
try:
tool.validate_parameters(arguments)
except ValidationError as exc:
for detail in exc.errors: # ErrorDetail(path, expected, actual, message)
print(detail.path, detail.message)
ValidationError/ErrorDetail—— 由Tool.validate_parameters()抛出,用于按签名生成的工具对照其参数模型进行校验。SchemaValidationError/SchemaErrorDetail—— 在按原始 JSON Schema 校验数据时抛出,代理工具(MCP / OpenAPI / LangChain)走这条路径。
两者捕获的就是库实际抛出的类;这些名字是再导出,而非包装。
类型定义¶
LLM API 格式兼容性类型:
- 类型 — 通用、OpenAI、Anthropic 和 Gemini 类型定义
完整模块概览¶
toolregistry ¶
ToolRegistry ¶
ToolRegistry(name: str | None = None, *, default_max_result_size: int | None = DEFAULT_MAX_RESULT_SIZE, default_max_result_tokens: int | None = None, persist_large_results: bool = False, result_store: ResultStore | None = None, result_ttl_seconds: float = DEFAULT_RESULT_TTL_SECONDS, result_idle_ttl_seconds: float | None = DEFAULT_RESULT_IDLE_TTL_SECONDS, result_quota_bytes: int = DEFAULT_RESULT_QUOTA_BYTES, result_scope_policy: ResultScopePolicy = DEFAULT_RESULT_SCOPE_POLICY, result_scope_provider: Callable[[], ResultScope | None] | None = None, think_augment: bool = False, tool_discovery: bool = False, name_sep: Literal['-', '.'] = '-', derive_output_schemas: bool = False)
Bases: AdminMixin, ExecutionLoggingMixin, PermissionsMixin, RegistrationMixin, SkillsMixin, 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
|
DEFAULT_MAX_RESULT_SIZE
|
default_max_result_tokens
|
int | None
|
Default maximum result size in tokens
for all tools, converted to characters with
:data: |
None
|
persist_large_results
|
bool
|
Store each truncated full result in a
private per-run directory and register a |
False
|
result_store
|
ResultStore | None
|
A prepared store to use instead of building one
from the retention arguments. Supplying a store enables
persistence even when persist_large_results is |
None
|
result_ttl_seconds
|
float
|
Hard lifetime of a persisted result, in seconds, measured from creation. Reads never extend it. |
DEFAULT_RESULT_TTL_SECONDS
|
result_idle_ttl_seconds
|
float | None
|
Sliding lifetime measured from the last
successful read. |
DEFAULT_RESULT_IDLE_TTL_SECONDS
|
result_quota_bytes
|
int
|
Total bytes the result directory may hold. Older results are evicted first, but the result being written is retained even when it alone is over quota. |
DEFAULT_RESULT_QUOTA_BYTES
|
result_scope_policy
|
ResultScopePolicy
|
|
DEFAULT_RESULT_SCOPE_POLICY
|
result_scope_provider
|
Callable[[], ResultScope | None] | None
|
Callable that returns the
:class: |
None
|
think_augment
|
bool
|
Enable thought-augmented tool calling globally.
When |
False
|
tool_discovery
|
bool
|
Enable tool discovery on initialization.
When |
False
|
name_sep
|
Literal['-', '.']
|
Separator character used when combining namespace and
method name into a tool name (e.g. |
'-'
|
derive_output_schemas
|
bool
|
Derive each registered tool's output schema
from its return annotation and store it in
|
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.
name_sep
property
writable
¶
Separator used between a namespace and a tool name.
Registration paths use this to derive the key a tool will be stored under, without reaching into the private attribute.
ptc
property
¶
PTC (Programmatic Tool Calling) controller.
Use registry.ptc.enable() to register a code_execution
tool that lets LLMs write Python code with registered tools
callable in the namespace.
Example::
registry.ptc.enable(timeout=30)
registry.ptc.disable()
registry.ptc.enabled # bool
registry.ptc.last_invocation_id # str | None
tool_discovery_enabled
property
¶
Whether tool discovery is enabled.
True once discover_tools and call_deferred are
registered, until :meth:disable_tool_discovery removes them again.
tool_discovery_mode
property
¶
How tool discovery tracks the registry.
"auto" (the default) keeps discovery on exactly while at least one
enabled tool is deferred, so a model can always retrieve a tool the
schema hides. "on" and "off" are explicit choices that later
registrations do not override; :meth:enable_tool_discovery and
:meth:disable_tool_discovery set them.
__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. |
aexecute_tool_calls
async
¶
aexecute_tool_calls(tool_calls: list[Any], execution_mode: Literal['process', 'thread'] | None = None) -> ResultList
Async counterpart to :meth:execute_tool_calls.
Runs concurrency-safe calls concurrently via asyncio.gather
over the per-tool async pipeline: inline tools (MCP/OpenAPI and
async natives) overlap on the caller's loop, while pool-backed
tools run off-loop and are awaited via result_async. If any
tool is not concurrency-safe, all calls run sequentially.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_calls
|
list[Any]
|
Tool calls in any supported format. |
required |
execution_mode
|
Literal['process', 'thread'] | None
|
Optional backend override. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ResultList
|
class: |
ainvoke
async
¶
ainvoke(tool_name: str, kwargs: dict[str, Any], *, invocation_id: str | None = None, execution_mode: Literal['thread', 'process'] | None = None) -> ToolCallResult | ErrorResult
Async counterpart to :meth:invoke.
For inline-resolved tools (the default, including MCP/OpenAPI),
awaits tool.arun() directly on the caller's loop — the tool's
async transport stays on the running loop without blocking it.
For thread/process backends, submits and awaits
handle.result_async().
Returns a :class:ToolCallResult on success or an
:class:ErrorResult on any failure. Never raises for
access-control failures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_name
|
str
|
Name of the registered tool. |
required |
kwargs
|
dict[str, Any]
|
Keyword arguments to pass to the tool. |
required |
invocation_id
|
str | None
|
Optional grouping ID; auto-generated
( |
None
|
execution_mode
|
Literal['thread', 'process'] | None
|
Optional backend override. |
None
|
Returns:
| Type | Description |
|---|---|
ToolCallResult | ErrorResult
|
|
apply_metadata_config ¶
Apply tool_metadata overrides from a loaded ToolConfig.
Accepts dict[str, ToolMetadataOverride] (as returned by
ToolConfig.tool_metadata) or plain dict[str, dict].
Silently skips tool names not present in the registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
overrides
|
dict[str, Any]
|
Mapping of exact tool name → metadata override.
Each value must provide |
required |
Note
None here means "skip this field" — the already-registered
value is kept. That differs from the config loader, where
None means "no override was declared", and from
:meth:update_tool_metadata, where title=None clears the
field. An explicit False is always applied, never treated
as "unset".
build_tool_call_messages ¶
build_tool_call_messages(tool_calls: list[Any], results: list[Any], 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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_calls
|
list[Any]
|
Tool call objects in any supported format (as received from the LLM). |
required |
results
|
list[Any]
|
Structured results from :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 ¶
Close all persistent connections and execution resources (sync).
Closes MCP and OpenAPI integrations, then shuts down the thread and
process execution backends. With wait=False (the default)
shutdown is non-blocking and work already running or queued is
abandoned; with wait=True it drains that work before returning.
The backends recreate their pools lazily, so the registry remains
usable; calling this repeatedly is safe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wait
|
bool
|
Drain in-flight and queued execution before returning. |
False
|
close_async
async
¶
Close all persistent connections and execution resources (async).
Closes MCP and OpenAPI integrations that hold persistent
connections or HTTP clients, then shuts down the thread and process
execution backends. With wait=False (the default) shutdown is
non-blocking and work already running or queued is abandoned; with
wait=True it drains that work before returning. The backends
recreate their pools lazily, so the registry remains usable; calling
this repeatedly is safe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wait
|
bool
|
Drain in-flight and queued execution before returning. |
False
|
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 tools.
The mode is pinned to "off", so registering a deferred tool does
not bring discovery back. One UNREGISTER change event is emitted
per removed tool: transports listen for it to refresh what they
advertise (an MCP client receives tools/list_changed).
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(field_weights: dict[str, float] | None = None, min_score_ratio: float | None = None, max_df_ratio: float | None = None) -> ToolDiscoveryTool
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.
Discovery is enabled once per registry. A repeated call returns the
existing :class:~toolregistry.llm.discovery.ToolDiscoveryTool
unchanged; options that differ from its live configuration are
reported with a :class:UserWarning. Call
:meth:disable_tool_discovery first to reconfigure.
The call also pins :attr:tool_discovery_mode to "on": an
operator who asked for discovery keeps it even when the last
deferred tool goes away. Use :meth:set_tool_discovery_mode with
"auto" to follow the deferred set again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_weights
|
dict[str, float] | None
|
Optional per-field BM25F boost weights. |
None
|
min_score_ratio
|
float | None
|
Drop fuzzy hits scoring below this fraction of
the best hit. |
None
|
max_df_ratio
|
float | None
|
Drop query tokens present in at least this fraction
of indexed tools. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
ToolDiscoveryTool
|
class: |
execute_tool_calls ¶
execute_tool_calls(tool_calls: list[Any], execution_mode: Literal['process', 'thread'] | None = None) -> ResultList
Execute tool calls and return structured results.
Disabled tools are rejected with an :class:ErrorResult instead
of being executed. If logging is enabled, execution details are
recorded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_calls
|
list[Any]
|
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 |
|---|---|
ResultList
|
List of results in the same order as tool_calls. Each |
ResultList
|
element is a :class: |
ResultList
|
class: |
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, "title": None, "execution_hints": {}, } ]
invoke ¶
invoke(tool_name: str, kwargs: dict[str, Any], *, invocation_id: str | None = None, execution_mode: Literal['thread', 'process'] | None = None) -> ToolCallResult | ErrorResult
Execute a single tool and return a structured result.
Canonical single-tool entry point. Runs the full pipeline
(permissions, execution via the resolved backend, logging) and
returns a :class:ToolCallResult on success or an
:class:ErrorResult on any failure — including access-control
failures (missing/disabled/denied). Never raises for those
conditions, mirroring :meth:execute_tool_calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_name
|
str
|
Name of the registered tool. |
required |
kwargs
|
dict[str, Any]
|
Keyword arguments to pass to the tool. |
required |
invocation_id
|
str | None
|
Optional ID to group related calls. If
|
None
|
execution_mode
|
Literal['thread', 'process'] | None
|
Optional backend override
( |
None
|
Returns:
| Type | Description |
|---|---|
ToolCallResult | ErrorResult
|
|
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. |
read_result ¶
Read a slice of a stored, truncated tool result.
Access is checked against the scope this registry resolves for the
current caller. In library mode that scope is None and any
valid id is readable, which preserves the old behavior. Server
adapters bind either a scope provider on the registry or a
per-request read_result handler, so one agent cannot read
another agent's result.
When invoked through the tool machinery, the registry resolves the caller's scope on the dispatching thread and runs the read on the thread backend, even if a process backend was requested: the result directory is process-local and the registry cannot be pickled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
str
|
Opaque result id from a truncation header ( |
required |
offset
|
int
|
Character offset to start at. |
0
|
limit
|
int
|
Maximum number of characters to return. |
DEFAULT_READ_RESULT_LIMIT
|
Returns:
| Type | Description |
|---|---|
str
|
The requested slice of the full result. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the id is not a valid result id, is unknown, is not owned by the caller's scope, has expired, is corrupt, or offset/limit is not a non-negative integer. |
RuntimeError
|
If result persistence is not enabled. |
recover_tool_call_assistant_message ¶
recover_tool_call_assistant_message(tool_calls: list[Any], results: list[Any], 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.
set_tool_discovery_mode ¶
Choose how discovery is controlled and apply the choice at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mode
|
Literal['auto', 'on', 'off']
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
The |
ToolDiscoveryTool | None
|
class: |
ToolDiscoveryTool | None
|
otherwise |
Raises:
| Type | Description |
|---|---|
ValueError
|
If mode is not |
Tool
dataclass
¶
Tool(*, name: str, description: str, parameters: dict[str, Any], callable: Callable[..., Any], metadata: ToolMetadata | None = None, parameters_model: Any | None = None, namespace: str | None = None, method_name: str | None = None, is_async: bool | None = None)
Base class representing an executable tool/function.
Provides core functionality for
- Function wrapping and metadata management
- Parameter validation
- Synchronous/asynchronous execution
- JSON schema generation
Note
Frozen semantics are shallow — field reassignment is prevented
but mutable containers (parameters dict, metadata.tags
set) can still be modified in place. Mutation should only occur
during __init__.
callable
instance-attribute
¶
The tool's callable, always a :class:BaseToolWrapper at runtime.
Use call_sync() / call_async() for sync/async transparent
execution.
declared_execution_hints
property
¶
Explicitly declared execution hints, excluding tag-derived values.
Convenience proxy to :attr:ToolMetadata.declared_execution_hints;
transports should publish this mapping rather than the resolved one.
description
instance-attribute
¶
Detailed description of the tool's functionality.
Should clearly explain what the tool does, its purpose, and any important usage considerations.
execution_hints
property
¶
Resolved execution hints from :attr:metadata.
Convenience proxy to metadata.execution_hints; see
:attr:ToolMetadata.execution_hints for the tri-state contract
and tag-derivation rule. title is not part of this mapping;
read :attr:ToolMetadata.title for the display name.
fn
property
¶
Return the underlying unwrapped function.
For native tools (registered via from_function), returns the
original Python function. For integration tools (MCP, OpenAPI,
LangChain), returns the wrapper itself.
is_async
property
¶
Whether the tool requires async execution.
Backward-compatible proxy to metadata.is_async.
metadata
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
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
instance-attribute
¶
The name of the tool.
Used as the primary identifier when calling the tool. Must be unique within a tool registry.
namespace
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
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
instance-attribute
¶
Type 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.
name is authoritative: registration and every namespace operation
rebuild it from namespace, method_name and the registry
separator (see :meth:requalify). The property therefore simply
exposes name.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The qualified name of the tool. |
__getstate__ ¶
Avoid pickling the dynamically created TypedDict on Python 3.11+.
__setstate__ ¶
Restore native parameter validation after deserialization.
Regeneration can fail for annotations that no longer resolve in the
loading process (local classes, optional dependencies). The tool is
then restored without parameter validation and a UserWarning
says so, matching Tool.from_function. With warnings escalated
to errors (python -W error) that warning raises and the tool
still fails to load.
arun
async
¶
Execute tool asynchronously.
Delegates to callable.call_async() which handles sync/async
callable transparency. Exceptions propagate directly.
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.
arun_raw
async
¶
Deprecated alias for arun().
.. deprecated:: 0.12.0
Use arun() instead. arun_raw will be removed in a
future version.
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, sep: NameSeparator = '-', *, localns: Mapping[str, Any] | None = None, derive_output_schema: bool = False) -> Tool
Factory method to create Tool from callable.
Automatically
- Extracts function metadata
- Generates parameter schema
- Optionally derives the output schema from the return annotation
- 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
|
sep
|
NameSeparator
|
Separator between namespace and the tool name. Pass the
registry's |
'-'
|
localns
|
Mapping[str, Any] | None
|
Names visible only to the function that defined the
annotations, typically |
None
|
derive_output_schema
|
bool
|
Derive a JSON Schema from the return
annotation and store it in
|
False
|
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.
Parameters are already flattened and sanitized at construction
(see :meth:_normalize_parameters). This method wraps them in
the target provider format and optionally injects a
toolcall_reason property for think-augmented calling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_format
|
API_FORMATS
|
Target API format. One of |
'openai-chat'
|
_think_augment
|
bool | None
|
Override for toolcall_reason injection.
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Provider-specific tool definition dict. |
requalify ¶
Return a copy whose name is rebuilt from namespace and method_name.
name is derived, never parsed: the unqualified name comes from
:attr:method_name (falling back to the current name for tools built
before that field existed), then it is recombined with namespace using
sep. Passing namespace=None drops the namespace and keeps only the
method name.
This is the primitive behind spinoff, reduce_namespace and
separator conversion during merge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str | None
|
Namespace to apply, or |
required |
sep
|
NameSeparator
|
Separator between namespace and method name. |
'-'
|
Returns:
| Type | Description |
|---|---|
_ToolT
|
A copy with consistent |
run ¶
Execute tool synchronously.
Delegates to callable.call_sync() which handles sync/async
callable transparency. Exceptions propagate directly.
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.
run_raw ¶
Deprecated alias for run().
.. deprecated:: 0.12.0
Use run() instead. run_raw will be removed in a
future version.
update_namespace ¶
Return a copy of the tool with an updated namespace.
Names are always derived from namespace, method_name and sep;
the tool is never renamed by parsing its current name. OpenAI requires
function names to match ^[a-zA-Z0-9_-]+$; some other providers allow
dot (.) as separator.
If a namespace prefix already exists and force is True, the
existing namespace is replaced. If force is False, a tool that is
already qualified is returned unchanged (both name and
namespace are preserved). A name containing either - or .
counts as already qualified; registration normalizes separators away, so
this heuristic only affects hand-built Tool instances. If no
namespace exists, the new namespace is applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
str | None
|
The new namespace to apply to the tool's name. |
required |
force
|
bool
|
If |
False
|
sep
|
NameSeparator
|
Separator character between namespace and method name. |
'-'
|
Returns:
| Type | Description |
|---|---|
_ToolT
|
A new |
_ToolT
|
|
_ToolT
|
|
Example
tool = Tool(name="example_tool", ...)
tool = tool.update_namespace("new_namespace")
tool.name # 'new_namespace-example_tool'
tool = Tool(name="old_namespace-example_tool", ...)
tool = tool.update_namespace("new_namespace", force=False)
tool.name # 'old_namespace-example_tool'
tool = Tool(name="old_namespace.example_tool", ...)
tool = tool.update_namespace("new_namespace", force=True, sep=".")
tool.name # 'new_namespace.example_tool'
validate_parameters ¶
Validate parameters against tool schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
dict[str, Any]
|
Raw input parameters. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Validated and normalized parameters. |
with_parameters ¶
Return a copy with a new parameter schema and a recomputed hash.
dataclasses.replace(tool, parameters=...) reuses the existing
metadata, so the fingerprint would keep describing the old schema.
This is the supported replacement path.
The new copy validates its arguments only when a parameters_model
is supplied. Without one, validate_parameters() is a pass-through:
it neither checks types nor required nor unknown keys, so payloads
that violate the published schema are accepted. Dropping the old model
is still the safe default, because it describes the old schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameters
|
dict[str, Any]
|
New JSON Schema, normally |
required |
parameters_model
|
Any | None
|
Validation type for the new parameters. The
default |
None
|
Returns:
| Type | Description |
|---|---|
_ToolT
|
A copy of the tool with the new schema and its hash. |
with_refreshed_at ¶
Return a copy with last_refreshed_at updated.