# -*- coding: utf-8 -*- import gradio as gr import os import requests import openai from dotenv import load_dotenv # Load environment variables load_dotenv() # Initialize OpenAI client your openai key openai.api_key = os.getenv('OPENAI_API_KEY') def get_current_weather(location, unit='celsius'): weather_api_key = userdata.get('WEATHER_API_KEY') 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 } #print(get_current_weather("fremont")) # format is referred from opeai Function Chat->Tools->Add->Function->get_weather() 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"] } } ] functions #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 and answer only related to weather related questions. If user asks other than weather then politely decline it"}) # Sending Initial Message to OpenAI response = openai.ChatCompletion.create( model="gpt-3.5-turbo", temperature = 0, max_tokens=256, top_p=0.2, frequency_penalty=0, presence_penalty=0, messages=messages, functions=functions ) #print(f'response1 is : {response}') #Handling Function Calls and Fetching Weather Data try: function_call = response['choices'][0]['message']['function_call'] #print(f'function_call : {function_call}') # Extract function name and arguments arguments = eval(function_call['arguments']) # we are passing locatioon in arguments. this line of code is taking the string representation of the arguments returned by the OpenAI API and converting it into a usable Python dictionary, which you then use to call your get_current_weather function. #print(f'arguments : {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)}) #print(f'message : {messages}') #magic of llm response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=messages ) #print(f'response2 : {response}') 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." #import gradio as gr # Define Gradio interface # iface = gr.Interface( # fn=weather_chat, # inputs=gr.Textbox(label="Weather Queries"), # outputs=gr.Textbox(label="Weather Updates", lines=5), # title = "Weather Bot", # description = "Ask me anything about weather!" # ) # Launch the Gradio interface #iface.launch(share="True") # To create a customized Gradio Interference, following is the prompt. # import gradio as gr # # Define Gradio interface # iface = gr.Interface( # fn=weather_chat, # inputs=gr.Textbox(label="Weather Queries"), # outputs=gr.Textbox(label="Weather Updates", lines=5), # title = "Weather Bot", # description = "Ask me anything about weather!" # ) # # Launch the Gradio interface # iface.launch(share="True") # make the above gradio app more professional, use blocks and add 2 columns format, give option for famous cities in a drop down or give a option of manually submitting the city, also add the logo # https://github.com/Decoding-Data-Science/airesidency/blob/main/dds_logo.jpg # List of famous cities for the dropdown FAMOUS_CITIES = [ "New York", "London", "Tokyo", "Paris", "Dubai", "Singapore", "Hong Kong", "Sydney", "Mumbai", "Toronto", "Los Angeles", "Chicago", "San Francisco", "Berlin", "Madrid", "Rome", "Barcelona", "Amsterdam", "Bangkok", "Seoul", "Shanghai", "Beijing", "Istanbul", "Moscow", "Mexico City" ] def process_weather_query(city_dropdown, custom_city, query): """ Process weather query based on city selection and custom input """ # Determine which city to use city = custom_city.strip() if custom_city.strip() else city_dropdown # Combine city with query if query exists if query.strip(): full_query = f"{query} in {city}" else: full_query = f"What's the weather in {city}?" # Call your weather_chat function response = weather_chat(full_query) return response # Create the Gradio Blocks interface with gr.Blocks(theme=gr.themes.Soft(), title="Weather Bot") as iface: # Header with logo with gr.Row(): gr.Image( #"https://github.com/Decoding-Data-Science/airesidency/blob/main/dds_logo.jpg?raw=true", "weather_bot.jpg", label=None, show_label=False, height=100, width=200, show_download_button=False, container=False ) # Title and description gr.Markdown( """ # 🌤️ Weather Bot ### Get real-time weather information for any city around the world """ ) # Main content with two columns with gr.Row(): # Left Column - Input Section with gr.Column(scale=1): gr.Markdown("### 📍 Select or Enter City") city_dropdown = gr.Dropdown( choices=FAMOUS_CITIES, value="New York", label="Choose from Popular Cities", info="Select a city from the dropdown" ) gr.Markdown("**OR**") custom_city = gr.Textbox( label="Enter Custom City", placeholder="Type any city name...", info="Leave empty to use the dropdown selection" ) query_input = gr.Textbox( label="Additional Query (Optional)", placeholder="e.g., temperature, forecast, humidity...", lines=2, info="Ask specific weather questions" ) with gr.Row(): submit_btn = gr.Button("Get Weather 🌍", variant="primary", size="lg") clear_btn = gr.Button("Clear 🔄", variant="secondary") # Right Column - Output Section with gr.Column(scale=1): gr.Markdown("### 🌡️ Weather Information") output = gr.Textbox( label="Weather Updates", lines=12, placeholder="Weather information will appear here...", show_copy_button=True ) # Example queries gr.Markdown("### 💡 Example Queries") gr.Examples( examples=[ ["London", "", "What's the current temperature?"], ["", "Seattle", "Will it rain today?"], ["Tokyo", "", "7-day forecast"], ["", "Mumbai", "humidity levels"], ["Paris", "", ""] ], inputs=[city_dropdown, custom_city, query_input], label="Try these examples" ) # Event handlers submit_btn.click( fn=process_weather_query, inputs=[city_dropdown, custom_city, query_input], outputs=output ) clear_btn.click( fn=lambda: ("New York", "", "", ""), inputs=None, outputs=[city_dropdown, custom_city, query_input, output] ) # Footer gr.Markdown( """ ---

Powered by AI | Built with Gradio

""" ) # Launch the interface if __name__ == "__main__": iface.launch(share=True)