Tool¶
表示 ToolRegistry 生态系统中具有元数据和执行逻辑的单个工具。
概览¶
Tool 类是 ToolRegistry 系统中所有工具的基础抽象。它封装了可执行逻辑以及工具发现、参数验证和在 LLM 应用中执行所需的元数据。
主要特性¶
- 元数据管理:全面的工具描述、参数和执行元数据
- 参数验证:内置参数模式验证和类型检查
- 执行抽象:同步和异步执行的统一接口
- 命名空间支持:与命名空间组织集成,用于工具分组
- 可调用集成:通过可调用接口直接执行
架构¶
Tool 类遵循数据传输对象模式,包含以下关键组件:
核心属性¶
- name:工具的唯一标识符
- description:人类可读的工具功能描述
- parameters:定义预期参数的 JSON Schema
- callable:实际的可执行函数或包装器
- is_async:指示异步执行能力的标志
- namespace:可选的组织命名空间(存储规范化后的原始命名空间字符串)
- method_name:可选的命名空间前缀添加前的原始方法/函数名称(保留用于无歧义的基础名称恢复)
计算属性¶
- qualified_name:返回完全限定的工具名称。如果同时设置了
namespace和method_name,则返回{namespace}-{method_name};否则回退到name字段。
设计理念¶
- 不可变性:Tool 实例设计为创建后不可变
- 模式驱动:基于 JSON Schema 标准的参数验证
- 执行灵活性:支持同步和异步执行模式
- 元数据保留:完整保留工具元数据以供 LLM 使用
API 参考¶
toolregistry.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 tool's callable, always a :class:BaseToolWrapper at runtime.
Typed as Callable for Pydantic compatibility (Pydantic cannot
generate a schema for BaseToolWrapper). Use call_sync() /
call_async() for sync/async transparent execution.
Excluded from serialization to prevent accidental exposure of 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.
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
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.
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) -> 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.
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 ¶
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'
使用示例¶
基本工具创建¶
from toolregistry import Tool
def calculate_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle."""
return length * width
# Create a Tool instance
area_tool = Tool(
name="calculate_area",
description="Calculate the area of a rectangle",
parameters={
"type": "object",
"properties": {
"length": {"type": "number", "description": "Length of rectangle"},
"width": {"type": "number", "description": "Width of rectangle"}
},
"required": ["length", "width"]
},
callable=calculate_area,
is_async=False
)
带命名空间的工具¶
from toolregistry import Tool
# Create a tool with namespace and method_name fields
math_tool = Tool(
name="math_ops-multiply",
description="Multiply two numbers",
parameters={
"type": "object",
"properties": {
"a": {"type": "number"},
"b": {"type": "number"}
},
"required": ["a", "b"]
},
callable=lambda a, b: a * b,
is_async=False,
namespace="math_ops",
method_name="multiply",
)
# Access the qualified name
print(math_tool.qualified_name) # Output: "math_ops-multiply"
print(math_tool.namespace) # Output: "math_ops"
print(math_tool.method_name) # Output: "multiply"
通过函数创建带命名空间的工具¶
from toolregistry import Tool
def multiply(a: float, b: float) -> float:
"""Multiply two numbers."""
return a * b
# Create a tool with namespace using from_function()
tool = Tool.from_function(multiply, namespace="math_ops")
print(tool.name) # Output: "math_ops-multiply"
print(tool.namespace) # Output: "math_ops"
print(tool.method_name) # Output: "multiply"
print(tool.qualified_name) # Output: "math_ops-multiply"
# You can also provide a custom method_name
tool2 = Tool.from_function(multiply, namespace="math_ops", method_name="mul")
print(tool2.name) # Output: "math_ops-mul"
print(tool2.method_name) # Output: "mul"
更新命名空间¶
from toolregistry import Tool
# Create a tool without namespace
math_tool = Tool.from_function(lambda a, b: a * b, name="multiply")
# Update with namespace
math_tool.update_namespace("math_operations")
print(math_tool.name) # Output: "math_operations-multiply"
print(math_tool.namespace) # Output: "math_operations"
print(math_tool.method_name) # Output: "multiply"
print(math_tool.qualified_name) # Output: "math_operations-multiply"
异步工具¶
import asyncio
from toolregistry import Tool
async def fetch_data(url: str) -> dict:
"""Fetch data from a URL asynchronously."""
# Async implementation
return {"url": url, "data": "sample"}
# Create async tool
async_tool = Tool(
name="fetch_data",
description="Fetch data from URL",
parameters={
"type": "object",
"properties": {
"url": {"type": "string", "description": "URL to fetch from"}
},
"required": ["url"]
},
callable=fetch_data,
is_async=True
)
执行工具¶
Tool 类提供同步和异步两种执行方式:
run(parameters)— 同步执行。失败时直接抛出异常。arun(parameters)— 异步执行。失败时直接抛出异常。
两个方法都自动处理 sync/async callable 的透明转换。同步工具可通过 arun() 调用(通过 asyncio.to_thread() 分发),异步工具可通过 run() 调用(通过 asyncio.run() 分发)。
from toolregistry import Tool
def divide(a: float, b: float) -> float:
"""Divide a by b."""
return a / b
tool = Tool.from_function(divide)
# 同步执行
try:
result = tool.run({"a": 10, "b": 0})
except ZeroDivisionError:
print("不能除以零!")
# 异步执行
result = await tool.arun({"a": 10, "b": 2}) # 返回 5.0
run_raw() / arun_raw() 已废弃
这些方法现在是 run() / arun() 的别名,调用时会发出
DeprecationWarning。请直接使用 run() / arun()。
访问底层函数¶
使用 tool.fn 属性获取原始未包装的函数:
tool = Tool.from_function(my_func)
tool.fn # → my_func(原始函数)
tool.callable # → _FunctionToolWrapper(包装器,内部使用)
参数模式格式¶
Tool 类使用 JSON Schema 格式进行参数验证:
{
"type": "object",
"properties": {
"param_name": {
"type": "string|number|boolean|array|object",
"description": "Parameter description",
"default": "default_value"
}
},
"required": ["param1", "param2"]
}
与 ToolRegistry 集成¶
工具主要通过 ToolRegistry 使用:
from toolregistry import ToolRegistry, Tool
registry = ToolRegistry()
# Register tool with registry
registry.register(tool_instance)
# Execute tool through registry
result = registry.execute_tool("tool_name", param1="value1", param2="value2")
Tool 类为 ToolRegistry 生态系统中的所有工具操作提供了基础,确保在不同工具来源和执行环境中具有一致的行为。