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
PassClientTools to your conversation:
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: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
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
Use async for I/O operations
Use async for I/O operations
Always use async tools for network requests, database queries, or file I/O to avoid blocking the main conversation thread.
Validate parameters
Validate parameters
Always validate tool parameters before processing to provide clear error messages.
Return user-friendly messages
Return user-friendly messages
Tool return values are sent to the agent, so make them clear and actionable.
Handle errors gracefully
Handle errors gracefully
Catch and handle errors to provide meaningful feedback to users.
Keep tools focused
Keep tools focused
Each tool should do one thing well. Break complex operations into multiple tools.