Skip to main content

Adding a tool

When building AI agents, you often need to extend their capabilities with external data or functionality. Timbal lets you pass tools to an agent using the tools parameter. Tools give agents a way to call specific functions, such as fetching data or performing calculations, to help answer a user's query.

Prerequisites

This example uses the openai model. Make sure to add OPENAI_API_KEY to your .env file.

.env
OPENAI_API_KEY=your_api_key_here

Creating a tool

This tool provides historical weather data for London, returning arrays of daily temperature, precipitation, wind speed, snowfall, and weather conditions from January 1st of the current year up to today. This structure makes it easy for agents to access and reason about recent weather trends.

import asyncio
import json
import urllib.request
from datetime import datetime
from typing import Any
from timbal.core import Tool
async def london_weather_tool() -> dict[str, Any]:
"""Returns year-to-date historical weather data for London."""
start_date = f"{datetime.now().year}-01-01"
end_date = datetime.now().strftime("%Y-%m-%d")
url = f"https://archive-api.open-meteo.com/v1/archive?latitude=51.5072&longitude=-0.1276&start_date={start_date}&end_date={end_date}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum,windspeed_10m_max,snowfall_sum&timezone=auto"
response = await asyncio.get_event_loop().run_in_executor(None, lambda: urllib.request.urlopen(url))
data = await asyncio.get_event_loop().run_in_executor(None, lambda: response.read())
weather_data = json.loads(data.decode())
daily = weather_data["daily"]
return {
"date": daily["time"],
"temp_max": daily["temperature_2m_max"],
"temp_min": daily["temperature_2m_min"],
"rainfall": daily["precipitation_sum"],
"windspeed": daily["windspeed_10m_max"],
"snowfall": daily["snowfall_sum"]
}
# Create the Tool instance
london_weather_tool_instance = Tool(
name="london_weather_tool",
description="Returns year-to-date historical weather data for London",
handler=london_weather_tool
)

Adding a tool to an agent

This agent uses the london_weather_tool_instance to answer questions about historical weather in London. It has clear instructions that guide it to use the tool for every query and limit its responses to data available for the current calendar year.

from timbal.core import Agent
london_weather_agent = Agent(
name="london-weather-agent",
system_prompt="""You are a helpful assistant with access to historical weather data for London.
- The data is limited to the current calendar year, from January 1st up to today's date.
- Use the provided tool (londonWeatherTool) to retrieve relevant data.
- Answer the user's question using that data.
- Keep responses concise, factual, and informative.
- If the question cannot be answered with available data, say so clearly.""",
model="openai/gpt-4o",
tools=[london_weather_tool_instance]
)

Example usage

Use the agent directly by calling it with a prompt message.

async def main():
# Call the agent directly
response = await london_weather_agent(prompt="How many times has it rained this year?").collect()
# Extract the text response
response_text = response.output.content[0].text
print(response_text)
if __name__ == "__main__":
asyncio.run(main())