Tool calling
Code in slides
Weather R
library(httr)
library(ellmer)
library(dotenv)
# Load environment variables
load_dot_env()
# Define weather function
<- function(latitude, longitude) {
get_weather <- "https://api.open-meteo.com/v1/forecast"
base_url
tryCatch(
{<- GET(
response
base_url,query = list(
latitude = latitude,
longitude = longitude,
current = "temperature_2m,wind_speed_10m,relative_humidity_2m"
)
)rawToChar(response$content)
},error = function(e) {
paste("Error fetching weather data:", e$message)
}
)
}
# Create chat instance
<- chat_openai(
chat model = "gpt-4.1",
system_prompt = "You are a helpful assistant that can check the weather. Report results in imperial units."
)
# Register the weather tool
#
# Created using `ellmer::create_tool_def(get_weather)`
$register_tool(tool(
chat
get_weather,"Fetches weather information for a specified location given by latitude and
longitude.",
latitude = type_number(
"The latitude of the location for which weather information is requested."
),longitude = type_number(
"The longitude of the location for which weather information is requested."
)
))
# Test the chat
$chat("What is the weather in Seattle?") chat
Weather Python
import requests
from chatlas import ChatAnthropic
from dotenv import load_dotenv
# Loads OPENAI_API_KEY from the .env file
load_dotenv()
# Define a simple tool for getting the current weather
def get_weather(latitude: float, longitude: float):
"""
Get the current weather for a location using latitude and longitude.
"""
= "https://api.open-meteo.com/v1/forecast"
base_url = {
params "latitude": latitude,
"longitude": longitude,
"current": "temperature_2m,wind_speed_10m,relative_humidity_2m",
}
try:
= requests.get(base_url, params=params)
response # Raise an exception for bad status codes
response.raise_for_status() return response.text
except requests.RequestException as e:
return f"Error fetching weather data: {str(e)}"
= ChatAnthropic(
chat ="claude-3-5-sonnet-latest",
model=(
system_prompt"You are a helpful assistant that can check the weather. "
"Report results in imperial units."
),
)
chat.register_tool(get_weather)"What is the weather in Seattle?") chat.chat(