from openai import OpenAI import os from dotenv import load_dotenv import requests import json # Load environment variables from .env file load_dotenv() # Initialize the OpenAI client client = OpenAI(api_key=os.getenv('OPEN_AI_API_KEY')) # Define the body for the API request print("Welcome to the Weather Chat App!") print("Open API Key is set:", os.getenv('OPEN_AI_API_KEY') is not None) def get_weather(city,unit='celsius'): if unit == 'celsius': units = 'metric' elif unit == 'fahrenheit': units = 'imperial' else: raise ValueError("Invalid unit. Use 'celsius' or 'fahrenheit'.") api_key = os.getenv('OPENWEATHER_API_KEY') response = requests.get(f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units={units}") if response.status_code == 200: data= response.json() return{ "location": city, "temperature": data['main']['temp'], "weather": data['weather'][0]['description'] } else: raise Exception(f"Error fetching weather data: {response.status_code} - {response.text}") functions = [ { "name": "get_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city, e.g. San Francisco" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } ] def weather_chat_app(user_input): try: client = OpenAI(api_key=os.getenv('OPEN_AI_API_KEY')) messages =[] messages.append({"role":"user","content":user_input}) messages.append({"role":"system","content": ( "You are a friendly weather assistant. " "When replying to the user, always use emojis and a creative tone. " "Describe the weather in a short, cheerful sentence. " "Examples: " "☀️ Sunny and hot, perfect for outdoor plans! " "🌧️ Rainy and cool, don’t forget an umbrella!" ) }) response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, functions=functions, temperature=0.2, max_tokens=200, top_p=0.3, stream=False, ) message = response.choices[0].message # Extract the arguments string # message is a ChatCompletionMessage object arguments_str = message.function_call.arguments arguments = json.loads(arguments_str) location = arguments["location"] weather_data = get_weather(location) print(f"Current temperature in {location}: {weather_data['temperature']}°C Sky: {weather_data['weather']} ") messages.append({"role":"assistant","content":None,"function_call":{"name":"get_weather","arguments":json.dumps(arguments)}}) messages.append({"role":"function","name":"get_weather","content":json.dumps(weather_data)}) response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, temperature=1.0, max_tokens=200, top_p=0.3, stream=False, ) print(response.choices[0].message.content) return response.choices[0].message.content except Exception as e: print("An error occurred:", str(e)) return "Sorry, I couldn't fetch the weather data at the moment. Please try again later." if __name__ == "__main__": city = "What is the weather in Gudauri ?" weather_data = weather_chat_app(city) #print(weather_data) # print(json.dumps(weather_data,indent=4)) # data = json.loads(json.dumps(weather_data,indent=4)) # print(f"Current temperature in {city}: {data['main']['temp']}°C Sky: {data['weather'][0]['description']} ") # print(f"Wind Speed: {data['wind']['speed']} km/h Humidity: {data['main']['humidity']}%")