@@ -16,172 +16,142 @@ const weatherRateLimiter = createRateLimiter({
1616 identifier: "weather",
1717 });
1818
19-/**
20- * Converts WMO weather code to human-readable description.
21- * Based on WMO Weather interpretation codes (WW).
22- */
23-function getWeatherDescription(code: number): string {
24- const descriptions: { [key: number]: string } = {
25- 0: "Clear sky",
26- 1: "Mainly clear",
27- 2: "Partly cloudy",
28- 3: "Overcast",
29- 45: "Foggy",
30- 48: "Depositing rime fog",
31- 51: "Light drizzle",
32- 53: "Moderate drizzle",
33- 55: "Dense drizzle",
34- 56: "Light freezing drizzle",
35- 57: "Dense freezing drizzle",
36- 61: "Slight rain",
37- 63: "Moderate rain",
38- 65: "Heavy rain",
39- 66: "Light freezing rain",
40- 67: "Heavy freezing rain",
41- 71: "Slight snow fall",
42- 73: "Moderate snow fall",
43- 75: "Heavy snow fall",
44- 77: "Snow grains",
45- 80: "Slight rain showers",
46- 81: "Moderate rain showers",
47- 82: "Violent rain showers",
48- 85: "Slight snow showers",
49- 86: "Heavy snow showers",
50- 95: "Thunderstorm",
51- 96: "Thunderstorm with slight hail",
52- 99: "Thunderstorm with heavy hail",
53- };
54-
55- return descriptions[code] || `Weather code ${code}`;
56-}
57-
5819 /**
5920 * Queries Open-Meteo's weather API for current weather and forecast information.
6021 * Results are cached for 6 hours.
6122 *
62- * @param location - The location name (e.g., 'New York', 'London', 'Tokyo').
23+ * @param query - The location name (e.g., 'New York', 'London', 'Tokyo').
24+ * @param timezone - Timezone (e.g., 'America/New_York', 'Europe/London', 'auto'). Defaults to 'auto'.
25+ * @param forecastDays - Number of forecast days (1-16). Defaults to 3.
6326 * @returns A formatted string containing weather information or an error message.
6427 */
65-export async function queryWeather(location: string): Promise<string> {
28+export async function queryWeather(
29+ query: string,
30+ timezone = "auto",
31+ forecastDays = 0
32+): Promise<string> {
33+ // Validate forecastDays (0 means no forecast, 1-16 for forecast days)
34+ const days = Math.max(0, Math.min(16, Math.round(forecastDays)));
35+
6636 // Check cache first
67- const cacheKey = `weather:${location.toLowerCase().trim()}`;
37+ const cacheKey = `weather:${query.toLowerCase().trim()}:${timezone}:${days}`;
6838 const cached = await getCache<string>(cacheKey);
6939 if (cached !== null) {
70- debug(`[Weather] Cache hit for: "${location}"`);
40+ debug(`[Weather] Cache hit for: "${query}"`);
7141 return cached;
7242 }
7343
74- debug(`[Weather] Querying weather for: "${location}"`);
44+ debug(
45+ `[Weather] Querying weather for: "${query}" (${days > 0 ? `${days} days` : "current only"}, ${timezone})`
46+ );
7547
7648 // Check rate limit before making the request
7749 const rateLimitCheck = await weatherRateLimiter.check();
7850 if (!rateLimitCheck.allowed) {
7951 const hoursRemaining = rateLimitCheck.hoursUntilReset || 0;
80- return `Error: Weather API rate limit exceeded. Maximum of 1000 requests per 24 hours has been reached. Please try again in approximately ${hoursRemaining} hour${hoursRemaining !== 1 ? "s" : ""}.`;
52+ throw new Error(
53+ `Weather API rate limit exceeded. Maximum of 1000 requests per 24 hours has been reached. Please try again in approximately ${hoursRemaining} hour${hoursRemaining !== 1 ? "s" : ""}.`
54+ );
8155 }
8256
83- try {
84- // Increment rate limit counter before making the request
85- // This ensures all API attempts are counted, not just successful ones
86- await weatherRateLimiter.increment();
87- // First, geocode the location to get coordinates
88- const geocodeUrl = "https://geocoding-api.open-meteo.com/v1/search";
89- const geocodeParams = new URLSearchParams({
90- name: location,
91- count: "1",
92- language: "en",
93- format: "json",
94- });
95-
96- const geocodeResponse = await fetch(`${geocodeUrl}?${geocodeParams.toString()}`);
97- if (!geocodeResponse.ok) {
98- debug(`[Weather] Geocoding error: HTTP ${geocodeResponse.status}`);
99- return `Error: Failed to geocode location "${location}" (${geocodeResponse.status})`;
100- }
57+ // Increment rate limit counter before making the request
58+ // This ensures all API attempts are counted, not just successful ones
59+ await weatherRateLimiter.increment();
60+ // First, geocode the location to get coordinates
61+ const geocodeUrl = "https://geocoding-api.open-meteo.com/v1/search";
62+ const geocodeParams = new URLSearchParams({
63+ name: query,
64+ count: "1",
65+ language: "en",
66+ format: "json",
67+ });
68+
69+ const geocodeResponse = await fetch(`${geocodeUrl}?${geocodeParams.toString()}`);
70+ if (!geocodeResponse.ok) {
71+ debug(`[Weather] Geocoding error: HTTP ${geocodeResponse.status}`);
72+ throw new Error(`Failed to geocode location "${query}" (${geocodeResponse.status})`);
73+ }
10174
102- const geocodeData = await geocodeResponse.json();
75+ const geocodeData = await geocodeResponse.json();
10376
104- if (!geocodeData.results || geocodeData.results.length === 0) {
105- return `Error: Could not find location "${location}". Please provide a more specific location name.`;
106- }
77+ if (!geocodeData.results || geocodeData.results.length === 0) {
78+ throw new Error(
79+ `Could not find location "${query}". Please provide a more specific location name.`
80+ );
81+ }
10782
108- const { latitude, longitude, name, country, admin1 } = geocodeData.results[0];
109- const locationName = `${name}${admin1 ? `, ${admin1}` : ""}${country ? `, ${country}` : ""}`;
110-
111- debug(`[Weather] Found location: ${locationName} (${latitude}, ${longitude})`);
112-
113- // Now fetch weather data
114- const weatherUrl = "https://api.open-meteo.com/v1/forecast";
115- const weatherParams = new URLSearchParams({
116- latitude: latitude.toString(),
117- longitude: longitude.toString(),
118- current: "temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m,wind_direction_10m",
119- hourly: "temperature_2m,weather_code,precipitation_probability",
120- daily: "temperature_2m_max,temperature_2m_min,weather_code,precipitation_sum",
121- forecast_days: "3",
122- timezone: "auto",
123- });
124-
125- const weatherResponse = await fetch(`${weatherUrl}?${weatherParams.toString()}`);
126- if (!weatherResponse.ok) {
127- debug(`[Weather] Weather API error: HTTP ${weatherResponse.status}`);
128- return `Error: Failed to fetch weather data for "${locationName}" (${weatherResponse.status})`;
129- }
83+ const { latitude, longitude, name, country, admin1 } = geocodeData.results[0];
84+ const locationName = `${name}${admin1 ? `, ${admin1}` : ""}${country ? `, ${country}` : ""}`;
13085
131- const weatherData = await weatherResponse.json();
132-
133- // Format the response
134- const parts: string[] = [];
135- parts.push(`Weather for ${locationName}:`);
136-
137- // Current conditions
138- if (weatherData.current) {
139- const current = weatherData.current;
140- parts.push(`\nCurrent Conditions:`);
141- parts.push(` Temperature: ${current.temperature_2m}°C`);
142- parts.push(` Humidity: ${current.relative_humidity_2m}%`);
143- parts.push(` Wind Speed: ${current.wind_speed_10m} km/h`);
144- if (current.wind_direction_10m !== undefined) {
145- parts.push(` Wind Direction: ${current.wind_direction_10m}°`);
146- }
147- if (current.weather_code !== undefined) {
148- const weatherDesc = getWeatherDescription(current.weather_code);
149- parts.push(` Conditions: ${weatherDesc}`);
150- }
86+ debug(`[Weather] Found location: ${locationName} (${latitude}, ${longitude})`);
87+
88+ // Now fetch weather data - focus on temperature and precipitation
89+ const weatherUrl = "https://api.open-meteo.com/v1/forecast";
90+ const weatherParams = new URLSearchParams({
91+ latitude: latitude.toString(),
92+ longitude: longitude.toString(),
93+ current: "temperature_2m,precipitation",
94+ timezone: timezone,
95+ });
96+
97+ // Only request daily forecast if forecastDays > 0
98+ if (days > 0) {
99+ weatherParams.append("daily", "temperature_2m_max,temperature_2m_min,precipitation_sum");
100+ weatherParams.append("forecast_days", days.toString());
101+ }
102+
103+ const weatherResponse = await fetch(`${weatherUrl}?${weatherParams.toString()}`);
104+ if (!weatherResponse.ok) {
105+ debug(`[Weather] Weather API error: HTTP ${weatherResponse.status}`);
106+ throw new Error(
107+ `Failed to fetch weather data for "${locationName}" (${weatherResponse.status})`
108+ );
109+ }
110+
111+ const weatherData = await weatherResponse.json();
112+
113+ // Format concise response focusing on temperature and precipitation
114+ const parts: string[] = [];
115+ parts.push(`${locationName}:`);
116+
117+ // Current conditions
118+ if (weatherData.current) {
119+ const current = weatherData.current;
120+ const temp = current.temperature_2m;
121+ const precip = current.precipitation;
122+ if (temp !== undefined) {
123+ parts.push(`Now: ${temp}°C${precip !== undefined && precip > 0 ? `, ${precip}mm rain` : ""}`);
151124 }
125+ }
152126
153- // Daily forecast (next 3 days)
154- if (weatherData.daily && weatherData.daily.time) {
155- parts.push(`\n3-Day Forecast:`);
156- for (let i = 0; i < Math.min(3, weatherData.daily.time.length); i++) {
157- const date = new Date(weatherData.daily.time[i]);
158- const dayName = date.toLocaleDateString("en-US", { weekday: "long" });
159- const maxTemp = weatherData.daily.temperature_2m_max?.[i];
160- const minTemp = weatherData.daily.temperature_2m_min?.[i];
161- const weatherCode = weatherData.daily.weather_code?.[i];
162- const precipitation = weatherData.daily.precipitation_sum?.[i];
163-
164- parts.push(`\n ${dayName} (${date.toLocaleDateString()}):`);
165- if (maxTemp !== undefined && minTemp !== undefined) {
166- parts.push(` High: ${maxTemp}°C, Low: ${minTemp}°C`);
167- }
168- if (weatherCode !== undefined) {
169- parts.push(` Conditions: ${getWeatherDescription(weatherCode)}`);
170- }
171- if (precipitation !== undefined && precipitation > 0) {
172- parts.push(` Precipitation: ${precipitation} mm`);
173- }
127+ // Daily forecast (only if forecastDays > 0)
128+ if (days > 0 && weatherData.daily && weatherData.daily.time) {
129+ for (let i = 0; i < Math.min(days, weatherData.daily.time.length); i++) {
130+ const date = new Date(weatherData.daily.time[i]);
131+ const dayName = date.toLocaleDateString("en-US", { weekday: "short" });
132+ const maxTemp = weatherData.daily.temperature_2m_max?.[i];
133+ const minTemp = weatherData.daily.temperature_2m_min?.[i];
134+ const precipitation = weatherData.daily.precipitation_sum?.[i];
135+
136+ const tempStr =
137+ maxTemp !== undefined && minTemp !== undefined
138+ ? `${minTemp}°/${maxTemp}°C`
139+ : maxTemp !== undefined
140+ ? `${maxTemp}°C`
141+ : "";
142+ const precipStr =
143+ precipitation !== undefined && precipitation > 0 ? `, ${precipitation}mm` : "";
144+
145+ if (tempStr) {
146+ parts.push(`${dayName}: ${tempStr}${precipStr}`);
174147 }
175148 }
176-
177- const result = parts.join("\n");
178- // Cache successful results
179- await setCache(cacheKey, result, CACHE_TTL_MS);
180- return result;
181- } catch (error) {
182- // Don't cache errors
183- return `Error querying weather: ${error instanceof Error ? error.message : "Unknown error"}`;
184149 }
150+
151+ const result = parts.join("\n");
152+ // Cache successful results
153+ await setCache(cacheKey, result, CACHE_TTL_MS);
154+ return result;
185155 }
186156
187157 /**
@@ -191,18 +161,28 @@ export const weatherTool = {
191161 type: "function" as const,
192162 function: {
193163 name: "query_weather",
194- description:
195- "Query Open-Meteo's weather API to get current weather conditions and 3-day forecast for a location. Use this when users ask about weather, temperature, forecast, or current conditions for any location worldwide.",
164+ description:
165+ "Query Open-Meteo's weather API to get current weather conditions and optionally forecast for a location. Returns temperature and precipitation data. By default returns only current weather. Use forecastDays parameter to include forecast. Use this when users ask about weather, temperature, forecast, or current conditions for any location worldwide.",
196166 parameters: {
197167 type: "object",
198168 properties: {
199- location: {
169+ query: {
200170 type: "string",
201171 description:
202- "The location name (e.g., 'New York', 'London', 'Tokyo', 'Paris'). Can be a city name, city with country, or more specific location.",
172+ "Location name (e.g., 'New York', 'London', 'Tokyo', 'Paris'). Can be a city name, city with country, or more specific location.",
173+ },
174+ timezone: {
175+ type: "string",
176+ description:
177+ "Timezone (e.g., 'America/New_York', 'Europe/London', 'Asia/Tokyo'). Use 'auto' to automatically detect. Defaults to 'auto'.",
178+ },
179+ forecastDays: {
180+ type: "number",
181+ description:
182+ "Number of forecast days (0-16). Use 0 for current weather only (default), or 1-16 for forecast days.",
203183 },
204184 },
205- required: ["location"],
185+ required: ["query"],
206186 },
207187 },
208188 };