Description
Toolboxes extend the Davinci Agent’s capabilities by providing custom Python functions that can connect to external APIs, perform specialized operations, and retrieve real-time data. When you enable a toolbox, its tools become available to the agent, allowing it to call them when needed during conversations and task execution. Toolboxes are ideal for integrating third-party services (weather, databases, web APIs), automating data retrieval, performing specialized calculations, and extending agent functionality beyond built-in capabilities.Creating a Toolbox
Toolboxes are Python code objects that define one or more tools using thedavinci.tool() decorator. Each tool is an asynchronous function that the agent can call with specific parameters.
Basic Structure
A typical toolbox contains:- Imports: Required libraries (httpx for API calls, typing for type hints)
- Constants: API endpoints, configuration values
- Helper Functions: Internal functions that support tool operations
- Tool Functions: Functions marked with
davinci.tool()that the agent calls - Documentation: Docstrings that explain what each tool does
Defining Tools
The davinci.tool() Decorator
Placedavinci.tool() immediately before any async function you want to expose to the agent:
- Must be an
asyncfunction - Must have a docstring (agent uses this to understand the tool)
- Parameters should have type hints
- Return type should be specified
Function Documentation
The docstring is critical—the agent reads it to understand when and how to use your tool. Docstring format:- Description: First line(s) explain what the tool does
- Args: List each parameter with its purpose and format
- Return (optional): Describe what the tool returns
Write clear, concise docstrings. The agent uses them to decide when to call your tool and what arguments to provide.
Connecting to APIs
Toolboxes commonly use thehttpx library for making HTTP requests to external APIs.
Making API Requests
Usehttpx.AsyncClient() for asynchronous API calls:
- Always use
async withfor proper connection cleanup - Set appropriate timeouts (default: 30 seconds)
- Include a User-Agent header (some APIs require it)
- Use
raise_for_status()to catch HTTP errors - Handle exceptions gracefully
Error Handling
Wrap API calls in try-except blocks to handle failures:Enabling and Using Toolboxes
Activating a Toolbox
To make a toolbox available to the agent:- Open the toolbox in the Toolbox view
- Toggle the Active/Inactive switch in the header to “Active”
- The toolbox’s tools are now available to the agent
Only active toolboxes are available to the agent. Deactivate toolboxes you’re not using to reduce agent complexity.
How the Agent Uses Tools
When you interact with the agent, it:- Analyzes your request: Determines if any tools can help
- Selects appropriate tools: Chooses tools based on docstrings
- Calls tools with parameters: Invokes tools with extracted arguments
- Uses results: Incorporates tool output into its response
Updating Model Data from Tools
Tools can write data back to your model using the sameupdate() function as regular code:
Testing Toolboxes
Always test your toolbox before using it with the agent.Using the Test Interface
The right pane of the Toolbox view provides a testing area:- Type a natural language instruction (e.g., “Get weather alerts for Texas”)
- Click Run Test
- Review the output to verify your tool works correctly
- Valid inputs
- Edge cases (empty strings, unusual values)
- Error conditions (invalid API keys, network failures)
- Different parameter combinations
Thorough testing prevents agent failures during actual use. Test each tool with various inputs before activating the toolbox.
Example: Weather Data Toolbox
The default weather toolbox provides real-time weather data from the National Weather Service API. This example demonstrates API integration, error handling, and creating multiple related tools within one toolbox.Complete Script
Here’s the full example weather toolbox. We will break it down below to explain each section.Imports and Constants
typing.Any: Type hint for dictionaries with unknown structurehttpx: Async HTTP client library for API requests
NWS_API_BASE: Base URL for National Weather Service APIUSER_AGENT: Identifier for API requests (NWS requires this)
Helper Function: make_nws_request
async def: Asynchronous function (doesn’t block while waiting for API)url: str: Takes a URL string as input-> dict[str, Any] | None: Returns either a dictionary or None if it fails
User-Agent: Required by NWS API to identify the clientAccept: Tells API we want GeoJSON format response
async with: Ensures connection closes properly after usehttpx.AsyncClient(): Creates reusable HTTP client
await client.get(): Make GET request, wait for responsetimeout=30.0: Wait up to 30 seconds before giving upraise_for_status(): Throw error if response is 4xx or 5xxresponse.json(): Parse JSON response into Python dictionary
- Catch any exception (network error, timeout, invalid JSON)
- Return
Noneto indicate failure (caller checks for this)
Helper Function: format_alert
- Takes raw API data (
feature) and makes it human-readable
feature["properties"]: Get the properties section from API response
- Uses f-string with multi-line format
.get()method provides default values if fields are missing- Returns formatted string with event details
Tool 1: get_alerts
davinci.tool(): Marks this function as available to the agent
async def: Async function (can make API calls without blocking)get_alerts: Function name (agent sees this as tool name)state: str: Required parameter—a string state code-> str: Returns a string (formatted alert information)
- First line: Clear description of what the tool does
Args:section: Explains thestateparameter- Agent reads this to understand when/how to use the tool
- Uses f-string to insert state code into URL
- Example: For “CA”, creates
https://api.weather.gov/alerts/active/area/CA
- Calls helper function to fetch data
await: Wait for request to complete before continuingdatawill be dictionary (success) or None (failure)
- If
datais None or doesn’t have “features” key, API failed - Return error message to agent
- If “features” exists but is empty, no alerts are active
- Return informative message instead of empty response
- List comprehension: Process each alert in the data
format_alert(feature): Convert each raw alert to readable text- Creates list of formatted alert strings
"\n---\n".join(): Combine all alerts with separator lines- Returns single string with all formatted alerts
- Agent receives this string and can present it to the user
Tool 2: get_forecast
- Multi-step API calls (first get grid point, then get forecast)
- Handling latitude/longitude coordinates
- Processing nested API responses
- Limiting output (only 5 forecast periods)
- Formatting complex data structures
/points/ to get grid coordinates, then call the forecast URL from that response. The tool handles this complexity and returns simple formatted text.
Tips for Effective Toolboxes
Keep Tools Focused: Each tool should do one thing well. Multiple simple tools are better than one complex tool. Write Clear Docstrings: The agent’s ability to use your tools depends entirely on your descriptions. Be specific and include examples. Handle Errors Gracefully: Return error messages instead of crashing. The agent can communicate errors to users. Use Type Hints: They improve code clarity and help catch bugs during development. Test Thoroughly: Test with various inputs, including edge cases and error conditions. Limit Output Length: Don’t return megabytes of data. Summarize, truncate, or format data before returning it. Add Timeouts: Network requests can hang. Always specify reasonable timeouts.View Types
| View | Description |
|---|---|
| Toolbox | Edit tool code, view detected tools, and test functionality. |
| Properties | Edit the object’s properties, attributes, and metadata. |
Properties Fields
Name of the object.
Short name of the object.
Description of the object.
The Python code that defines the toolbox tools and connections.
A list of all Relationships this object has with other model objects.Read more about Relationships