ArceusInception's picture
Update app.py
8fd69cb verified
raw
history blame
3.32 kB
import os
import json
import gradio as gr
import requests
from dotenv import load_dotenv
from groq import Groq # Correct import after installing groq module
# Load environment variables
load_dotenv()
# Groq client initialization
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
def preprocess_city_name_and_generate_insight(city_name):
tools = [
{
"type": "function",
"function": {
"name": "generate_city_insight",
"description": "Generate a short, interesting fact about a specified city",
"parameters": {
"type": "object",
"properties": {
"city_name": {
"type": "string",
"description": "The name of the city to generate insights for",
},
},
"required": ["city_name"],
},
},
}
]
# Simulate a user message asking for insights about a city
response = client.chat.completions.create(
model="mixtral-8x7b-32768",
messages=[
{
"role": "user",
"content": f"What interesting fact can you tell me about {city_name}?",
}
],
temperature=0,
max_tokens=300,
tools=tools,
tool_choice="auto"
)
# Extract and handle the response
groq_response = response.choices[0].message
args = json.loads(groq_response.tool_calls[0].function.arguments)
# Assuming generate_city_insight function is defined somewhere that returns an insight
insight = generate_city_insight(**args)
return city_name, insight
def get_weather(city_name):
corrected_city_name, city_insight = preprocess_city_name_and_generate_insight(city_name)
API_Key = os.getenv("OPENWEATHER_API_KEY")
if not API_Key:
return "API Key is not set. Please set the OPENWEATHER_API_KEY environment variable."
url = f'https://api.openweathermap.org/data/2.5/weather?q={corrected_city_name}&appid={API_Key}&units=metric'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
weather = data['weather'][0]['description']
temp = data['main']['temp']
humidity = data['main']['humidity']
weather_emoji = "☀️" if "clear" in weather else "☁️" if "cloud" in weather else "🌧️" if "rain" in weather else "❄️" if "snow" in weather else "🌫️"
return (f"In {corrected_city_name}, the weather is currently {weather} {weather_emoji}. "
f"The temperature is a comfy {temp}°C 🌡️. "
f"And the humidity levels are at {humidity}% 💧. "
f"Did you know? {city_insight}")
else:
return "Failed to retrieve data. Please check the city name and try again."
# Gradio interface definition
iface = gr.Interface(
fn=get_weather,
inputs=gr.Textbox(label="Enter City Name", placeholder="Type here..."),
outputs=gr.Textbox(label="Weather Update"),
title="WeatherAssistantApp",
description="Enter a city name to get a lively description of the current weather, temperature, and humidity."
)
# Launching the interface
iface.launch()