Tool Usage¶
This example demonstrates how to give your agents capabilities through tools.
Overview¶
Tools allow agents to interact with external systems, perform calculations, access data, and more.
flowchart LR
User -->|Message| Agent
Agent -->|Request| LLM
LLM -->|Tool Call| Agent
Agent -->|Execute| Tool
Tool -->|Result| Agent
Agent -->|Continue| LLM
LLM -->|Response| Agent
Agent -->|Answer| User
Basic Tool Definition¶
Define tools using Python functions with type hints:
- Simple tools can be synchronous functions with no arguments
- Tools with parameters should include docstrings describing the arguments
Tool.from_functionautomatically extracts name, description, and parameters from the function
Async Tools¶
For I/O operations, use async tools:
Tool with Complex Parameters¶
Tools can accept complex parameter types:
pydantic_tools.py
from pydantic import BaseModel, Field
from nagents import Tool
class EmailParams(BaseModel):
"""Parameters for sending an email."""
to: str = Field(description="Recipient email address")
subject: str = Field(description="Email subject line")
body: str = Field(description="Email body content")
priority: str = Field(
default="normal",
description="Email priority: low, normal, or high"
)
async def send_email(params: EmailParams) -> str:
"""Send an email with the specified parameters."""
# Simulate sending email
return f"Email sent to {params.to} with subject '{params.subject}'"
# Create tool with Pydantic model
email_tool = Tool.from_function(send_email)
dict_tools.py
from typing import Any
from nagents import Tool
def create_task(
title: str,
description: str,
priority: int = 1,
tags: list[str] | None = None,
) -> dict[str, Any]:
"""
Create a new task.
Args:
title: Task title
description: Detailed task description
priority: Priority level (1-5, default 1)
tags: Optional list of tags
"""
return {
"id": "task_123",
"title": title,
"description": description,
"priority": priority,
"tags": tags or [],
"status": "created",
}
task_tool = Tool.from_function(create_task)
Handling Tool Errors¶
Implement proper error handling in tools:
- Raise descriptive errors that help the LLM understand what went wrong
- Handle
tool_errorevents to inform the user about failures
Complete Example: Research Assistant¶
A full example combining multiple tools:
| research_assistant.py | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
Tool Configuration¶
Tool Options¶
| Option | Type | Description |
|---|---|---|
name |
str |
Tool name (auto-generated from function) |
description |
str |
Tool description (from docstring) |
parameters |
dict |
JSON Schema for parameters |
strict |
bool |
Enable strict parameter validation |
Manual Tool Definition¶
For advanced cases, define tools manually:
manual_tool.py
from nagents import Tool
# Manual tool definition with full control
manual_tool = Tool(
name="get_stock_price",
description="Get the current stock price for a ticker symbol",
parameters={
"type": "object",
"properties": {
"symbol": {
"type": "string",
"description": "Stock ticker symbol (e.g., AAPL, GOOGL)",
},
"currency": {
"type": "string",
"enum": ["USD", "EUR", "GBP"],
"default": "USD",
},
},
"required": ["symbol"],
},
function=lambda symbol, currency="USD": f"${symbol}: $150.00 {currency}",
)
Best Practices¶
Tool Design
- Keep tools focused on a single task
- Write clear descriptions - the LLM uses them to decide when to use tools
- Include parameter descriptions in docstrings
- Return structured data (JSON) for complex results
Security
- Validate all inputs before processing
- Limit file access to safe directories
- Set timeouts for network requests
- Never execute arbitrary code from tool inputs
Performance
- Use async tools for I/O operations
- Cache results when appropriate
- Set reasonable limits on returned data size
Tool Checklist
- Clear, descriptive name
- Detailed docstring with Args section
- Type hints for all parameters
- Input validation
- Error handling with descriptive messages
- Reasonable output size limits
- Security considerations addressed