@@ -95,6 +95,154 @@ export async function queryDuckDuckGo(query: string): Promise<string> {
9595 }
9696 }
9797
98+/**
99+ * Queries Open-Meteo's weather API for current weather and forecast information.
100+ *
101+ * @param location - The location name (e.g., "New York", "London", "Tokyo").
102+ * @returns A formatted string containing weather information.
103+ */
104+export async function queryWeather(location: string): Promise<string> {
105+ debug(`[Weather] Querying weather for: "${location}"`);
106+
107+ try {
108+ // First, geocode the location to get coordinates
109+ const geocodeUrl = "https://geocoding-api.open-meteo.com/v1/search";
110+ const geocodeParams = new URLSearchParams({
111+ name: location,
112+ count: "1",
113+ language: "en",
114+ format: "json",
115+ });
116+
117+ const geocodeResponse = await fetch(`${geocodeUrl}?${geocodeParams.toString()}`);
118+ if (!geocodeResponse.ok) {
119+ debug(`[Weather] Geocoding error: HTTP ${geocodeResponse.status}`);
120+ return `Error: Failed to geocode location "${location}" (${geocodeResponse.status})`;
121+ }
122+
123+ const geocodeData = await geocodeResponse.json();
124+ debug(`[Weather] Geocoding response:`, JSON.stringify(geocodeData, null, 2));
125+
126+ if (!geocodeData.results || geocodeData.results.length === 0) {
127+ return `Error: Could not find location "${location}". Please provide a more specific location name.`;
128+ }
129+
130+ const { latitude, longitude, name, country, admin1 } = geocodeData.results[0];
131+ const locationName = `${name}${admin1 ? `, ${admin1}` : ""}${country ? `, ${country}` : ""}`;
132+
133+ debug(`[Weather] Found location: ${locationName} (${latitude}, ${longitude})`);
134+
135+ // Now fetch weather data
136+ const weatherUrl = "https://api.open-meteo.com/v1/forecast";
137+ const weatherParams = new URLSearchParams({
138+ latitude: latitude.toString(),
139+ longitude: longitude.toString(),
140+ current: "temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m,wind_direction_10m",
141+ hourly: "temperature_2m,weather_code,precipitation_probability",
142+ daily: "temperature_2m_max,temperature_2m_min,weather_code,precipitation_sum",
143+ forecast_days: "3",
144+ timezone: "auto",
145+ });
146+
147+ const weatherResponse = await fetch(`${weatherUrl}?${weatherParams.toString()}`);
148+ if (!weatherResponse.ok) {
149+ debug(`[Weather] Weather API error: HTTP ${weatherResponse.status}`);
150+ return `Error: Failed to fetch weather data for "${locationName}" (${weatherResponse.status})`;
151+ }
152+
153+ const weatherData = await weatherResponse.json();
154+ debug(`[Weather] Weather API response:`, JSON.stringify(weatherData, null, 2));
155+
156+ // Format the response
157+ const parts: string[] = [];
158+ parts.push(`Weather for ${locationName}:`);
159+
160+ // Current conditions
161+ if (weatherData.current) {
162+ const current = weatherData.current;
163+ parts.push(`\nCurrent Conditions:`);
164+ parts.push(` Temperature: ${current.temperature_2m}°C`);
165+ parts.push(` Humidity: ${current.relative_humidity_2m}%`);
166+ parts.push(` Wind Speed: ${current.wind_speed_10m} km/h`);
167+ if (current.wind_direction_10m !== undefined) {
168+ parts.push(` Wind Direction: ${current.wind_direction_10m}°`);
169+ }
170+ if (current.weather_code !== undefined) {
171+ const weatherDesc = getWeatherDescription(current.weather_code);
172+ parts.push(` Conditions: ${weatherDesc}`);
173+ }
174+ }
175+
176+ // Daily forecast (next 3 days)
177+ if (weatherData.daily && weatherData.daily.time) {
178+ parts.push(`\n3-Day Forecast:`);
179+ for (let i = 0; i < Math.min(3, weatherData.daily.time.length); i++) {
180+ const date = new Date(weatherData.daily.time[i]);
181+ const dayName = date.toLocaleDateString("en-US", { weekday: "long" });
182+ const maxTemp = weatherData.daily.temperature_2m_max?.[i];
183+ const minTemp = weatherData.daily.temperature_2m_min?.[i];
184+ const weatherCode = weatherData.daily.weather_code?.[i];
185+ const precipitation = weatherData.daily.precipitation_sum?.[i];
186+
187+ parts.push(`\n ${dayName} (${date.toLocaleDateString()}):`);
188+ if (maxTemp !== undefined && minTemp !== undefined) {
189+ parts.push(` High: ${maxTemp}°C, Low: ${minTemp}°C`);
190+ }
191+ if (weatherCode !== undefined) {
192+ parts.push(` Conditions: ${getWeatherDescription(weatherCode)}`);
193+ }
194+ if (precipitation !== undefined && precipitation > 0) {
195+ parts.push(` Precipitation: ${precipitation} mm`);
196+ }
197+ }
198+ }
199+
200+ return parts.join("\n");
201+ } catch (error) {
202+ console.error("Weather query error:", error);
203+ return `Error querying weather: ${error instanceof Error ? error.message : "Unknown error"}`;
204+ }
205+}
206+
207+/**
208+ * Converts WMO weather code to human-readable description.
209+ * Based on WMO Weather interpretation codes (WW).
210+ */
211+function getWeatherDescription(code: number): string {
212+ const descriptions: { [key: number]: string } = {
213+ 0: "Clear sky",
214+ 1: "Mainly clear",
215+ 2: "Partly cloudy",
216+ 3: "Overcast",
217+ 45: "Foggy",
218+ 48: "Depositing rime fog",
219+ 51: "Light drizzle",
220+ 53: "Moderate drizzle",
221+ 55: "Dense drizzle",
222+ 56: "Light freezing drizzle",
223+ 57: "Dense freezing drizzle",
224+ 61: "Slight rain",
225+ 63: "Moderate rain",
226+ 65: "Heavy rain",
227+ 66: "Light freezing rain",
228+ 67: "Heavy freezing rain",
229+ 71: "Slight snow fall",
230+ 73: "Moderate snow fall",
231+ 75: "Heavy snow fall",
232+ 77: "Snow grains",
233+ 80: "Slight rain showers",
234+ 81: "Moderate rain showers",
235+ 82: "Violent rain showers",
236+ 85: "Slight snow showers",
237+ 86: "Heavy snow showers",
238+ 95: "Thunderstorm",
239+ 96: "Thunderstorm with slight hail",
240+ 99: "Thunderstorm with heavy hail",
241+ };
242+
243+ return descriptions[code] || `Weather code ${code}`;
244+}
245+
98246 /**
99247 * Defines the DuckDuckGo search tool for Ollama.
100248 */
@@ -116,6 +264,27 @@ export const duckDuckGoTool = {
116264 },
117265 };
118266
267+/**
268+ * Defines the weather query tool for Ollama.
269+ */
270+export const weatherTool = {
271+ type: "function" as const,
272+ function: {
273+ name: "query_weather",
274+ description: "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.",
275+ parameters: {
276+ type: "object",
277+ properties: {
278+ location: {
279+ type: "string",
280+ description: "The location name (e.g., 'New York', 'London', 'Tokyo', 'Paris'). Can be a city name, city with country, or more specific location.",
281+ },
282+ },
283+ required: ["location"],
284+ },
285+ },
286+};
287+
119288 /**
120289 * Executes a tool call and returns the result.
121290 *
@@ -145,6 +314,15 @@ async function executeToolCall(toolCall: {
145314 name: "query_duckduckgo",
146315 content: result,
147316 };
317+ case "query_weather":
318+ const weatherResult = await queryWeather(parsedArgs.location);
319+ debug(`[Tool] ${name} completed, result length: ${weatherResult.length} chars`);
320+ return {
321+ tool_call_id: toolCall.id,
322+ role: "tool",
323+ name: "query_weather",
324+ content: weatherResult,
325+ };
148326 default:
149327 debug(`[Tool] Unknown tool: ${name}`);
150328 return {
@@ -170,7 +348,7 @@ export async function fetchOllamaResponse(
170348 messages: OllamaMessageInput[],
171349 model = "gpt-oss"
172350 ): Promise<OllamaResponse> {
173- const tools = [duckDuckGoTool];
351+ const tools = [duckDuckGoTool, weatherTool];
174352 let totalDuration = 0;
175353 let currentMessages: OllamaMessage[] = messages.map((msg) => ({
176354 role: msg.role,