🤖lauren-ai
← Home
Export this page

Tools

The @tool() decorator and runtime context.

tool

python
def tool(args: Any = (), name: str | None = None, description: str | None = None, requires_confirmation: bool = False, pre_hook: Callable[..., Any] | None = None, post_hook: Callable[..., Any] | None = None, error_hook: Callable[..., Any] | None = None, cache_ttl: int | None = None, cache_key_fn: Callable[..., Any] | None = None) -> Callable[[_T], _T]

Decorator that marks a function or class as a tool for AI agents.

Must be called with parentheses: @tool(). Using the bare form @tool (without parentheses) raises DecoratorUsageError.

Function-form (simple, stateless tools):

python
@tool()
async def my_tool(query: str) -> list[dict]:
    """One-line description.

    Args:
        query: What to search for.
    """
    ...

Class-form (stateful tools with DI constructor dependencies):

python
@tool()
@injectable(scope=Scope.SINGLETON)
class MyTool:
    """Description used as tool description."""

    def __init__(self, dep: SomeDep) -> None:
        self._dep = dep

    async def run(self, query: str) -> list[dict]:
        ...

Parameters:

NameTypeDescription
namestr | NoneOverride the inferred tool name (default: function/class name converted to snake_case).
descriptionstr | NoneOverride the description extracted from the docstring.
requires_confirmationboolWhen True, the executor emits a ToolPendingApprovalSignal before calling the tool, enabling a human-in-the-loop review step.
pre_hookCallable[..., Any] | NoneCallable invoked before the tool runs. Receives the tool call and ToolContext.
post_hookCallable[..., Any] | NoneCallable invoked after a successful tool run. Receives the ToolResult and ToolContext.
error_hookCallable[..., Any] | NoneCallable invoked when the tool raises an exception. Receives the exception and ToolContext.
cache_ttlint | NoneCache successful results for this many seconds. Requires a CacheBackend in the executor.
cache_key_fnCallable[..., Any] | NoneCustom factory that derives a cache key from the input dict.

Returns: Callable — The decorated function or class, with TOOL_META set on it.

Raises:

ExceptionDescription
DecoratorUsageErrorWhen called without parentheses (bare @tool).

ToolContext

python
class ToolContext(agent_context: Any, tool_use_id: str, turn: int, request: Any | None = None, execution_context: Any | None = None, metadata: dict[str, Any] = dict(), state: dict[str, Any] = dict())

Context injected into a tool function when a ctx: ToolContext param is declared.

Carries the owning agent context, the current turn number, a mutable state bag for per-call data, and the tool's static metadata (populated from @set_metadata decorators applied to the tool at definition time).

Parameters:

NameTypeDescription
agent_contextAnyThe AgentContext of the running agent (typed as Any to avoid a circular import; at runtime it is an AgentContext instance).
tool_use_idstrThe provider-assigned tool use identifier for this specific invocation.
turnintWhich agentic-loop iteration (0-based) triggered this call.
requestAny | NoneThe originating HTTP Request, if the agent was invoked from a web handler. None otherwise.
metadatadict[str, Any]Static metadata attached to this tool via @set_metadata(key, value) at decoration time. Readable via get_metadata().
statedict[str, Any]Mutable per-call state bag for tool-local storage.

ToolContext.get_metadata

python
def get_metadata(self, key: str, default: Any = None) -> Any

Return metadata by key, checking tool-level then agent-level.

Lookup order:

  1. Tool-level static metadata — key-value pairs attached at decoration time via @set_metadata(key, value) on the tool.
  2. Agent-level runtime metadata — the metadata dict supplied to ~lauren_ai.AgentRunnerBase.run() (e.g. runner.run(agent, prompt, metadata={"scope": "admin"})), delegated through agent_context.get_metadata.

Parameters:

NameTypeDescription
keystrMetadata key to look up.
defaultAnyValue returned when the key is absent in both layers.

Returns: Any — Metadata value or default.

ToolResult

python
class ToolResult(tool_use_id: str, content: str | list[Any], is_error: bool = False)

The result of executing a single tool call.

Parameters:

NameTypeDescription
tool_use_idstrThe provider-assigned identifier echoed back to the model so it can correlate the result with its own tool-use request.
contentstr | list[Any]The tool output. Either a plain string or a list of content blocks (e.g. for image responses).
is_errorboolTrue when the tool raised an exception or returned an explicit error payload.

ToolResult.ok

python
def ok(cls, content: Any, tool_use_id: str) -> ToolResult

Create a successful ToolResult.

Non-string content is serialised to a JSON string automatically.

Parameters:

NameTypeDescription
contentAnyThe tool return value. Strings are passed through unchanged; everything else is serialised via json.dumps.
tool_use_idstrMatching provider tool-use identifier.

Returns: ToolResult — A new ToolResult with is_error=False.

ToolResult.error

python
def error(cls, message: str, tool_use_id: str) -> ToolResult

Create an error ToolResult.

Parameters:

NameTypeDescription
messagestrHuman-readable error description.
tool_use_idstrMatching provider tool-use identifier.

Returns: ToolResult — A new ToolResult with is_error=True.