Weather_Agent / app.py
Rishabh12j's picture
Update app.py
6cf5366 verified
import os
import requests
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
import streamlit as st
def main():
st.set_page_config(page_title="Weather Reporter", layout="centered")
st.header("🌤️ Get your City's Weather Report")
# Input validation
city_input = st.text_input(
"Please enter your city name",
placeholder="e.g., London, New York, Dublin"
)
if st.button("Get Weather Report", type="primary"):
if not city_input.strip():
st.error("❌ Please enter a city name")
return
try:
with st.spinner(f"Fetching weather data for {city_input}..."):
response = agent(city_input)
st.success("✅ Weather Report Generated!")
st.markdown("---")
st.write(response)
except ValueError as e:
st.error(f"❌ Error: {str(e)}")
except Exception as e:
st.error(f"❌ Unexpected error: {str(e)}")
def get_weather(city):
"""
Fetch weather data from OpenWeatherMap API
Returns a dictionary with weather metrics
"""
# Validate API keys exist
openweather_key = os.getenv("openweather")
if not openweather_key:
raise ValueError("Missing 'openweather' environment variable")
# Use params instead of string concatenation
url = "http://api.openweathermap.org/data/2.5/weather"
params = {
"q": city,
"appid": openweather_key,
"units": "metric"
}
try:
response = requests.get(url, params=params, timeout=5)
response.raise_for_status() # Raise error for bad status codes
except requests.exceptions.RequestException as e:
raise ValueError(f"Failed to fetch weather data: {str(e)}")
data = response.json()
# Check if city was found
if response.status_code == 200 and "main" in data:
weather_data = {
"humidity": data.get("main", {}).get("humidity"),
"pressure": data.get("main", {}).get("pressure"),
"wind": data.get("wind", {}).get("speed"),
"description": data.get("weather", [{}])[0].get("description", "unknown"),
"temp": data.get("main", {}).get("temp"),
"city": data.get("name", city)
}
return weather_data
else:
raise ValueError(f"City '{city}' not found. Please check the spelling and try again.")
def agent(city_input):
"""
Generate a weather report using LangChain and Groq LLM
"""
# Validate API key
groq_api_key = os.getenv("groq")
if not groq_api_key:
raise ValueError("Missing 'groq' environment variable")
# Get weather data
weather_data = get_weather(city_input)
# Extract weather values
temp = weather_data["temp"]
humidity = weather_data["humidity"]
pressure = weather_data["pressure"]
wind = weather_data["wind"]
description = weather_data["description"]
city_name = weather_data["city"]
# Create a clean system prompt
system_prompt = f"""You are a helpful meteorological expert for {city_name}.
Based on the following weather data, compile a professional and detailed weather summary:
Current Conditions:
- Temperature: {temp}°C
- Humidity: {humidity}%
- Atmospheric Pressure: {pressure} hPa
- Wind Speed: {wind} m/s
- Description: {description}
Provide insights on how these conditions might affect daily activities and any weather-related recommendations."""
# Create prompt template
prompt = ChatPromptTemplate.from_messages([
("system", system_prompt),
("human", "Generate a comprehensive weather report for {city}")
])
# Initialize LLM
chat = ChatGroq(
api_key=groq_api_key,
model_name="llama-3.3-70b-versatile",
temperature=0.7
)
# Create and invoke chain
chain = prompt | chat | StrOutputParser()
output = chain.invoke({"city": city_name})
return output
if __name__ == "__main__":
main()