File size: 4,263 Bytes
761b9c2
 
 
 
 
 
 
 
837f371
761b9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
837f371
761b9c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
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']}%")