2025-09-21 11:02:31 -07:00
|
|
|
import { tool } from "ai";
|
|
|
|
|
import { z } from "zod";
|
2025-01-23 01:19:48 +05:30
|
|
|
|
2025-10-09 19:28:04 +01:00
|
|
|
async function geocodeCity(city: string): Promise<{ latitude: number; longitude: number } | null> {
|
|
|
|
|
try {
|
|
|
|
|
const response = await fetch(
|
|
|
|
|
`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=1&language=en&format=json`
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
if (!response.ok) return null;
|
|
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
|
|
if (!data.results || data.results.length === 0) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const result = data.results[0];
|
|
|
|
|
return {
|
|
|
|
|
latitude: result.latitude,
|
|
|
|
|
longitude: result.longitude,
|
|
|
|
|
};
|
|
|
|
|
} catch {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-23 01:19:48 +05:30
|
|
|
export const getWeather = tool({
|
2025-10-09 19:28:04 +01:00
|
|
|
description: "Get the current weather at a location. You can provide either coordinates or a city name.",
|
2025-10-31 21:49:43 -07:00
|
|
|
inputSchema: z.object({
|
|
|
|
|
latitude: z.number().optional(),
|
|
|
|
|
longitude: z.number().optional(),
|
|
|
|
|
city: z.string().describe("City name (e.g., 'San Francisco', 'New York', 'London')").optional(),
|
|
|
|
|
}),
|
2025-10-09 19:28:04 +01:00
|
|
|
execute: async (input) => {
|
|
|
|
|
let latitude: number;
|
|
|
|
|
let longitude: number;
|
|
|
|
|
|
2025-10-31 21:49:43 -07:00
|
|
|
if (input.city) {
|
2025-10-09 19:28:04 +01:00
|
|
|
const coords = await geocodeCity(input.city);
|
|
|
|
|
if (!coords) {
|
|
|
|
|
return {
|
|
|
|
|
error: `Could not find coordinates for "${input.city}". Please check the city name.`,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
latitude = coords.latitude;
|
|
|
|
|
longitude = coords.longitude;
|
2025-10-31 21:49:43 -07:00
|
|
|
} else if (input.latitude !== undefined && input.longitude !== undefined) {
|
2025-10-09 19:28:04 +01:00
|
|
|
latitude = input.latitude;
|
|
|
|
|
longitude = input.longitude;
|
2025-10-31 21:49:43 -07:00
|
|
|
} else {
|
|
|
|
|
return {
|
|
|
|
|
error: "Please provide either a city name or both latitude and longitude coordinates.",
|
|
|
|
|
};
|
2025-10-09 19:28:04 +01:00
|
|
|
}
|
|
|
|
|
|
2025-01-23 01:19:48 +05:30
|
|
|
const response = await fetch(
|
2025-09-21 11:02:31 -07:00
|
|
|
`https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m&hourly=temperature_2m&daily=sunrise,sunset&timezone=auto`
|
2025-01-23 01:19:48 +05:30
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const weatherData = await response.json();
|
2025-10-09 19:28:04 +01:00
|
|
|
|
|
|
|
|
if ("city" in input) {
|
|
|
|
|
weatherData.cityName = input.city;
|
|
|
|
|
}
|
|
|
|
|
|
2025-01-23 01:19:48 +05:30
|
|
|
return weatherData;
|
|
|
|
|
},
|
|
|
|
|
});
|