Poojashetty357's picture
Update app.py
adadc2b verified
import os
import gradio as gr
import requests
from dotenv import load_dotenv
from langchain.agents import initialize_agent, AgentType, Tool
#from langchain_community.llms import OpenAI
from langchain_openai import ChatOpenAI
from langchain_community.utilities import SerpAPIWrapper
load_dotenv()
# Weather Tool
def get_weather_forecast(city):
api_key = os.getenv("OPENWEATHER_API_KEY")
url = f"https://api.openweathermap.org/data/2.5/forecast?q={city}&cnt=7&appid={api_key}&units=metric"
response = requests.get(url)
if response.status_code != 200:
return "Weather API error.", 35
data = response.json()
summaries = []
temps = []
for item in data["list"]:
date = item["dt_txt"]
condition = item["weather"][0]["description"]
temp = item["main"]["temp"]
temps.append(temp)
summaries.append(f"{date[:10]} - {condition}, {temp}ยฐC")
avg_temp = sum(temps) / len(temps) if temps else 35
return "\n".join(summaries), avg_temp
# Tools
weather_tool = Tool(
name="Weather Forecast",
func=lambda city: get_weather_forecast(city)[0],
description="Get weather forecast in a city."
)
search_tool = Tool(
name="Event Search",
func=SerpAPIWrapper().run,
description="Use this tool to search the internet for live events, kids competitions, or local programs happening now. Input: search query like 'kids events in Dubai July 2025'"
)
# Initialize LLM
llm = ChatOpenAI(
model="gpt-3.5-turbo", # or "gpt-4o" if available in your key
temperature=0,
openai_api_key=os.getenv("OPENAI_API_KEY")
)
agent = initialize_agent(
tools=[weather_tool, search_tool],
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
max_iterations=5, # limit to 3 steps
early_stopping_method="generate",
handle_parsing_errors=True
)
# Sample place listings for cities (expand as needed)
INDOOR_PLACES = {
"Dubai": [
"๐Ÿฐ IMG Worlds of Adventure โ€“ indoor theme park",
"๐Ÿงช OliOli Children's Museum โ€“ interactive play",
"๐Ÿ›๏ธ Dubai Museum โ€“ Al Fahidi Fort history",
"๐Ÿ›๏ธ KidZania โ€“ roleplay city inside Dubai Mall",
"๐ŸŽฎ VR Park โ€“ virtual reality experiences"
],
"Abu Dhabi": [
"๐ŸŽ๏ธ Ferrari World โ€“ indoor thrill rides",
"๐ŸŽญ Louvre Abu Dhabi โ€“ art museum",
"๐ŸŽฎ Fun City โ€“ indoor arcade for kids",
"๐ŸŽฒ Orange Wheels โ€“ indoor soft play"
]
}
OUTDOOR_PLACES = {
"Dubai": [
"๐Ÿ–๏ธ Jumeirah Beach โ€“ open beach access",
"๐ŸŒณ Zabeel Park โ€“ greenery + kids play area",
"๐Ÿฆ“ Dubai Safari Park โ€“ wildlife attraction",
"๐Ÿšœ The Desert Farm โ€“ animal feeding, pony rides",
"๐ŸŽ Al Marmoom Camel Racing Track"
],
"Abu Dhabi": [
"๐ŸŒด Corniche Beach โ€“ beach walks and water play",
"๐Ÿฆฉ Mangrove National Park โ€“ kayak tours",
"๐Ÿฆ’ Emirates Park Zoo โ€“ family-friendly zoo",
"๐ŸŒพ Al Ain Oasis โ€“ UNESCO site and palm groves"
]
}
# Gradio Function
def suggest_event(city, month, preference):
forecast, avg_temp = get_weather_forecast(city)
hot_weather = avg_temp >= 34
# Attractions
indoor = INDOOR_PLACES.get(city, [
"๐ŸŽจ Local museum", "๐Ÿงธ Indoor play area", "๐Ÿ›๏ธ Science center"
])
outdoor = OUTDOOR_PLACES.get(city, [
"๐ŸŒณ City park", "๐Ÿ–๏ธ Public beach", "๐Ÿฆ“ City zoo"
])
# Weather decision
if preference.lower() == "indoor" or hot_weather:
attraction_type = "Indoor"
recommended = indoor
condition_note = f"Since the average temperature is {avg_temp}ยฐC, it's advisable to stay indoors."
elif preference.lower() == "outdoor":
attraction_type = "Outdoor"
recommended = outdoor
condition_note = f"The weather is pleasant (avg {avg_temp}ยฐC), so outdoor activities are great."
else:
attraction_type = "Indoor or Outdoor"
recommended = indoor + outdoor
condition_note = f"The weather is manageable (avg {avg_temp}ยฐC), so both indoor and outdoor activities are fine."
# Bullet format
attraction_list = "\n".join(f"โ€ข {place}" for place in recommended)
# Final prompt
prompt = f"""
You are a helpful family activity planner AI.
Goal: Create a weekend plan for families with kids in **{city}** during **{month}**.
Here's the weather forecast: **{forecast}**.
Step-by-step instructions:
1. Based on the forecast, determine whether **indoor**, **outdoor**, or **both** types of activities are most suitable. Clearly state your recommendation first.
2. Always include a list of **7โ€“8 indoor attractions** in {city} for kids.
3. If the weather permits or if the user prefers, also include **7โ€“8 outdoor attractions** in {city} for kids. These may include:
- public parks
- water parks
- farms
- natural places like lakes, gardens, walking trails
- beaches (if applicable to location)
Avoid listing categories that are not relevant to the city's geography.
4. Use the `Event Search` tool to find **real, ongoing events for kids and families** in {city} during {month}, including:
- kids competitions
- seasonal festivals
- live shows, exhibitions, workshops
- fun fairs and city-wide programs
(Only include event names and descriptions. Do not include clickable links or images.)
5. End with a checklist of suggested items to carry for the outing (consider weather).
Output must follow this format:
### Final Answer:
**Weather Recommendation:**
Indoor / Outdoor / Both โ€“ include a brief reason based on temperature, rain, etc.
**Indoor Attractions in {city}:**
- Place Name โ€“ short description
...
**Outdoor Attractions in {city}:**
- Place Name โ€“ short description
...
**Live Events in {city} for {month}:**
- Event Title โ€“ brief description
...
**What to Carry:**
- โœ… item 1
- โœ… item 2
...
๐Ÿ“Œ Do not guess event or location names. Only include events if returned by the Event Search tool.
"""
try:
result = agent.run(prompt)
return result
except Exception as e:
return f"Agent Error: {str(e)}"
# Define city and month options
city_options = [
"Dubai", "Abu Dhabi", "Sharjah", "Ajman", "Al Ain", "Fujairah",
"Doha", "Riyadh", "Jeddah", "Manama", "Kuwait City", "Muscat",
"Cairo", "Amman", "Istanbul", "Delhi", "Bangalore", "Singapore"
]
month_options = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]
# SOLUTION 1: Inline CSS (Recommended)
custom_css = """
.main-wrapper {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 15px;
padding: 20px;
margin: 10px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
#banner-image {
border-radius: 10px;
margin-bottom: 20px;
max-height: 200px;
object-fit: cover;
}
.gradio-container {
background: #f8f9fa;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.gr-button {
background: linear-gradient(45deg, #ff6b6b, #ee5a24);
border: none;
border-radius: 25px;
color: white;
font-weight: bold;
padding: 12px 24px;
transition: all 0.3s ease;
}
.gr-button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}
.gr-dropdown, .gr-radio {
border-radius: 10px;
border: 2px solid #e9ecef;
}
.gr-markdown {
background: rgba(255, 255, 255, 0.9);
border-radius: 10px;
padding: 15px;
margin: 10px 0;
}
h1 {
color: #2c3e50;
text-align: center;
margin-bottom: 20px;
}
"""
with gr.Blocks(css=custom_css, title="Family Event Planner Agent") as demo:
with gr.Group(elem_classes=["main-wrapper"]):
# SOLUTION 2: Use a local image or remove the external dependency
# Option A: Remove the banner image if not essential
# Option B: Use a placeholder or local image
gr.Markdown("""
# ๐ŸŽ‰ Family Event Planner Agent
Plan kid-friendly indoor/outdoor activities based on weather, city, and preferences. Get real events, suggestions, and a checklist to carry!
""")
with gr.Row():
city = gr.Dropdown(choices=city_options, label="Select City", value="Dubai")
month = gr.Dropdown(choices=month_options, label="Select Month", value="July")
preference = gr.Radio(["Indoor", "Outdoor", "Either"], label="Event Type Preference", value="Either")
submit_btn = gr.Button("๐Ÿงญ Suggest Weekend Plan")
output = gr.Markdown()
def run_with_feedback(city, month, preference):
yield "โณ Generating your personalized family weekend plan..."
result = suggest_event(city, month, preference)
yield result
submit_btn.click(fn=run_with_feedback, inputs=[city, month, preference], outputs=output)
if __name__ == "__main__":
demo.launch(share=True)