import openai import requests import gradio as gr # Set up your OpenAI API key openai.api_key = "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" # Function to get weather data from Open-Meteo API def get_weather_data(city): geocode_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1" geocode_response = requests.get(geocode_url) if geocode_response.status_code == 200 and geocode_response.json().get("results"): location_data = geocode_response.json()["results"][0] latitude = location_data["latitude"] longitude = location_data["longitude"] else: return {"error": "City not found or API issue"} weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t_weather=true" weather_response = requests.get(weather_url) if weather_response.status_code == 200: weather_data = weather_response.json()["current_weather"] weather_info = { "city": location_data["name"], "temperature": weather_data["temperature"], "description": "Clear skies" if weather_data["weathercode"] == 0 else "Cloudy or other conditions" } return weather_info else: return {"error": "Weather data not available"} # Function to use GPT Turbo with RAG (external weather data) def ask_gpt_with_weather_rag(city): weather_data = get_weather_data(city) if "error" in weather_data: return weather_data["error"] weather_info_str = ( f"The current weather in {weather_data['city']} is " f"{weather_data['temperature']}°C with {weather_data['description']}." ) prompt = ( f"You are a helpful assistant. Based on the following weather information:\n\n" f"{weather_info_str}\n\n" f"Can you recommend an activity suitable for this weather?" ) response = openai.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are an assistant knowledgeable about weather and activities."}, {"role": "user", "content": prompt} ] ) return response.choices[0].message.content # Gradio Interface def weather_activity(city): return ask_gpt_with_weather_rag(city) interface = gr.Interface( fn=weather_activity, inputs=gr.Textbox(label="Enter City Name"), outputs=gr.Textbox(label="Suggested Activity"), title="Weather-Based Activity Recommendation", description="Enter a city name to get the current weather and GPT-based activity suggestions." ) # Launch the Gradio interface if __name__ == "__main__": interface.launch(debug=True)