import requests import re # Function to get weather information def get_weather_info(location): """Fetch weather information for the specified location.""" url = f"http://api.weatherapi.com/v1/current.json" params = { "key": weather_api_key, # Use the secret key "q": location, "aqi": "no" } response = requests.get(url, params=params) if response.status_code == 200: data = response.json() weather = data["current"]["condition"]["text"] temp = data["current"]["temp_c"] return f"The current weather in {location} is {weather} with a temperature of {temp}°C." else: return "Sorry, I couldn't fetch the weather information." def preprocess_query(user_input): """Process user input for weather queries or normal conversation.""" # Check if the user is asking about the weather if "weather" in user_input.lower(): # Try to extract a location from the user's input (if provided) location = extract_location(user_input) return get_weather_info(location) else: # Continue with the regular conversation return user_input def extract_location(user_input): """Try to extract a location from the user's input.""" # Define a simple regex to match common location patterns (e.g., 'weather in London', 'What is the weather in New York?') match = re.search(r"weather in (\w+|\w+\s\w+)", user_input, re.IGNORECASE) if match: # If a location is found, return it return match.group(1) else: # If no location is specified, return a default (e.g., "London") return "London"