import requests import streamlit as st import json from dotenv import load_dotenv import os from groq import Groq load_dotenv() # Get GROQ API key from environment variable client = Groq( api_key=os.getenv("GROQ_API_KEY"), ) # Get OpenWeatherMap API key from environment variable weather_api_key = os.getenv("OPENWEATHERMAP_API_KEY") # OpenWeatherMap API endpoint API_URL = "http://api.openweathermap.org/data/2.5/weather" def get_current_weather(location): """Get the current weather in a given location""" params = { "q": location, "appid": weather_api_key, "units": "metric" } response_data = requests.get(API_URL, params=params) if response_data.status_code == 200: data = response_data.json() print("data-", data) location_resp = data['name'] weather = data['weather'][0]['main'] temperature = round(data['main']['temp'], 2) description = data['weather'][0]['description'] humidity = data['main']['humidity'] pressure = data['main']['pressure'] wind = data['wind']['speed'] report = (f"We have an update on the weather for {location_resp} location. Currently, it is {weather} " f"({description}) with a temperature of {temperature} °C. There's {humidity}% humidity, " f"atmospheric pressure is {pressure} hPa, and winds are blowing at {wind} m/s.") return report else: return f"Uh oh! We're unable to retrieve weather data for {location}. Please try again later." def define_tools(): """Define tools for the OpenAI API call""" tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, }, "required": ["location"], }, }, } ] return tools st.title("Weather App") location = st.text_input("Enter a location (city and state):") if st.button("Get Weather"): tools = define_tools() response = client.chat.completions.create( model="mixtral-8x7b-32768", messages=[ { "role": "user", "content": f"What is the weather like in {location}?", } ], temperature=0, max_tokens=300, tools=tools, tool_choice="auto" ) # Handle potential NoneType errors if response and response.choices and response.choices[0].message: groq_response = response.choices[0].message if groq_response and groq_response.tool_calls and groq_response.tool_calls[0].function.arguments: args = json.loads(groq_response.tool_calls[0].function.arguments) weather_report = get_current_weather(**args) st.write("**Weather Report:**") st.write(weather_report) else: st.write("Oops! There seems to be an issue retrieving the weather data. Please check the location provided " "correctly") else: st.write("Oops! There seems to be an issue retrieving the weather data. Please try again later.")