跳转至

Tool

表示 ToolRegistry 生态系统中具有元数据和执行逻辑的单个工具。

概览

Tool 类是 ToolRegistry 系统中所有工具的基础抽象。它封装了可执行逻辑以及工具发现、参数验证和在 LLM 应用中执行所需的元数据。

主要特性

  • 元数据管理:全面的工具描述、参数和执行元数据
  • 参数验证:内置参数模式验证和类型检查
  • 执行抽象:同步和异步执行的统一接口
  • 命名空间支持:与命名空间组织集成,用于工具分组
  • 可调用集成:通过可调用接口直接执行

架构

Tool 类遵循数据传输对象模式,包含以下关键组件:

核心属性

  1. name:工具的唯一标识符
  2. description:人类可读的工具功能描述
  3. parameters:定义预期参数的 JSON Schema
  4. callable:实际的可执行函数或包装器
  5. is_async:指示异步执行能力的标志
  6. namespace:可选的组织命名空间(存储规范化后的原始命名空间字符串)
  7. method_name:可选的命名空间前缀添加前的原始方法/函数名称(保留用于无歧义的基础名称恢复)

计算属性

  • qualified_name:返回完全限定的工具名称。如果同时设置了 namespacemethod_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

callable: Callable[..., Any] = Field(exclude=True)

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

description: str = Field(description='Description of what the tool does')

Detailed description of the tool's functionality.

Should clearly explain what the tool does, its purpose, and any important usage considerations.

is_async property

is_async: bool

Whether the tool requires async execution.

Backward-compatible proxy to metadata.is_async.

metadata class-attribute instance-attribute

metadata: ToolMetadata = Field(default_factory=ToolMetadata)

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

method_name: str | None = Field(default=None, description='Original method name of the tool')

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

name: str = Field(description='Name of the tool')

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

namespace: str | None = Field(default=None, description='Namespace the tool belongs to')

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

parameters: dict[str, Any] = Field(description='JSON schema for tool parameters')

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

qualified_name: str

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

arun(parameters: dict[str, Any]) -> Any

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

arun_raw(parameters: dict[str, Any]) -> Any

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

describe(api_format: API_FORMATS = 'openai-chat') -> dict[str, Any]

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; is_async is always auto-detected and will override the value in metadata.

None

Returns:

Name Type Description
Tool Tool

Configured Tool instance.

Raises:

Type Description
ValueError

For unnamed lambda functions.

get_json_schema

get_json_schema(api_format: API_FORMATS = 'openai-chat') -> dict[str, Any]

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", "openai-response", "anthropic", "gemini".

'openai-chat'
_think_augment bool | None

Internal override for toolcall_reason injection. When None (default), falls back to self.metadata.think_augment. Used by :meth:ToolRegistry.get_schemas to pass the resolved effective value.

None

Returns:

Type Description
dict[str, Any]

Provider-specific tool definition dict.

model_post_init

model_post_init(__context: Any) -> None

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

run(parameters: dict[str, Any]) -> Any

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

run_raw(parameters: dict[str, Any]) -> Any

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

update_namespace(namespace: str | None, force: bool = False, sep: Literal['-', '.'] = '-') -> None

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 True, forces the replacement of an existing namespace. Defaults to False.

False

Returns:

Name Type Description
None None

This method modifies the tool.name attribute in place and does not return a value.

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
)

执行工具:run_raw()run()

Tool 类提供两组执行 API:

  • run_raw(parameters) / arun_raw(parameters) — 验证参数并执行工具。失败时直接抛出异常,允许程序化调用方捕获和处理错误。
  • run(parameters) / arun(parameters) (已弃用的错误吞没行为) — 委托给 run_raw()/arun_raw(),但会捕获异常并返回类似 "Error executing tool_name: ..." 的错误字符串。此行为会发出 DeprecationWarning;未来版本中 run() 也将直接抛出异常。
from toolregistry import Tool

def divide(a: float, b: float) -> float:
    """Divide a by b."""
    return a / b

tool = Tool.from_function(divide)

# 推荐:使用 run_raw() 进行程序化错误处理
try:
    result = tool.run_raw({"a": 10, "b": 0})
except ZeroDivisionError:
    print("不能除以零!")

# 遗留方式:run() 捕获异常并返回错误字符串(已弃用)
result = tool.run({"a": 10, "b": 0})
# result == "Error executing divide: division by zero"
# ^ 发出 DeprecationWarning

参数模式格式

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 生态系统中的所有工具操作提供了基础,确保在不同工具来源和执行环境中具有一致的行为。