Weather-Openai / app.py
GenAiPA's picture
Update app.py
c9d8e3f verified
import gradio as gr
import openai
import json
import os
import requests
# Initialize OpenAI client your openai key
openai.api_key = os.getenv('yek_oaipen')
weather_api_key = os.getenv('openweather')
def get_current_weather(location, unit='celsius'):
base_url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={weather_api_key}&units=metric"
response = requests.get(base_url)
data = response.json()
weather_description = data['weather'][0]['description']
return {
"location": location,
"temperature": data['main']['temp'],
"weather": weather_description
}
functions = [
{
"name": "get_current_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"]
}
}
]
#Function Definition and Initial Message Handling
def weather_chat(user_message):
messages=[]
messages.append({"role": "user", "content": user_message})
messages.append({"role": "assistant", "content": "You are a weather bot . Answer only in Celsius."})
# Sending Initial Message to OpenAI
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
temperature = 0,
max_tokens=256,
top_p=0.5,
frequency_penalty=0,
presence_penalty=0,
messages=messages,
functions=functions
)
#Handling Function Calls and Fetching Weather Data
try:
function_call = response['choices'][0]['message']['function_call']
arguments = eval(function_call['arguments'])
# Fetch weather data using the extracted arguments
weather_data = get_current_weather(arguments['location'])
# Append the function call and weather data to the messages
messages.append({"role": "assistant", "content": None, "function_call": {"name": "get_current_weather", "arguments": str(arguments)}})
messages.append({"role": "function", "name": "get_current_weather", "content": str(weather_data)})
#magic of llm
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
return response['choices'][0]['message']['content']
except Exception as e:
return "I'm here to provide weather updates. Please ask me questions related to weather."
# Define Gradio interface
iface = gr.Interface(
fn=weather_chat,
inputs=gr.Textbox(label="Weather Queries"),
outputs=gr.Textbox(label="Weather Updates"),
title = "Weather Bot",
description = "Ask me anything about weather!"
)
# Launch the Gradio interface
iface.launch(share="True")