Spaces:
Sleeping
Sleeping
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) | |