Skip to main content

Overview

ClientTools allows you to register custom functions that your AI agent can call during conversations. Tools can be synchronous or asynchronous and run in a dedicated event loop to ensure non-blocking operation.

Basic Tool Registration

Register a simple synchronous tool:

Async Tools

Register asynchronous tools for I/O operations:

Using Tools in Conversations

Pass ClientTools to your conversation:
When the agent calls get_account_balance, the tool executes and returns the result to the agent.

Tool Parameters

Tools receive a dictionary of parameters:

Parameter Structure

str
Unique identifier for this tool invocation (automatically added)
any
Any additional parameters sent by the agent when calling the tool

Error Handling

Handle errors gracefully in your tools:
When a tool raises an exception, the error message is sent to the agent with is_error=True.

Custom Event Loops

For advanced use cases involving context propagation or resource reuse, provide a custom asyncio event loop:

Custom Loop Parameters

asyncio.AbstractEventLoop
Custom event loop to use for tool execution. If not provided, a new loop is created in a separate thread.

Benefits of Custom Event Loops

Context Propagation

Maintain request-scoped state across async operations

Resource Reuse

Share async resources like HTTP sessions or database pools

Loop Management

Prevent “different event loop” runtime errors

Performance

Better control over async task scheduling and execution
When using a custom loop, you’re responsible for its lifecycle. Don’t close the loop while ClientTools are still using it.

Complex Tool Example

Here’s a complete example with database access and error handling:

Tool Registration Reference

register()

str
required
Unique identifier for the tool. Must match the tool name configured in the agent.
Callable
required
Function that implements the tool logic. Can be sync or async.
bool
required
Whether the handler is an async function

Lifecycle Methods

method
Starts the event loop for tool execution. Called automatically when the conversation starts.
method
Stops the event loop and cleans up resources. Called automatically when the conversation ends.

Best Practices

Always use async tools for network requests, database queries, or file I/O to avoid blocking the main conversation thread.
Always validate tool parameters before processing to provide clear error messages.
Tool return values are sent to the agent, so make them clear and actionable.
Catch and handle errors to provide meaningful feedback to users.
Each tool should do one thing well. Break complex operations into multiple tools.

Complete Example