from smolagents import CodeAgent, HfApiModel, load_tool, tool import datetime import requests import pytz import yaml import os from tools.final_answer import FinalAnswerTool from Gradio_UI import GradioUI # ========================= # 🌦 WEATHER TOOL # ========================= @tool def get_weather(city: str) -> str: """ A tool that fetches the current weather for a given city using OpenWeather API. Args: city: Name of the city (e.g., 'London', 'Bangalore') """ try: api_key = os.getenv("OPENWEATHER_API_KEY") # safer method if not api_key: return "OpenWeather API key not found. Please set OPENWEATHER_API_KEY." url = ( f"http://api.openweathermap.org/data/2.5/weather?" f"q={city}&appid={api_key}&units=metric" ) response = requests.get(url) data = response.json() if response.status_code != 200: return f"Error fetching weather: {data.get('message', 'Unknown error')}" temperature = data["main"]["temp"] description = data["weather"][0]["description"] humidity = data["main"]["humidity"] wind_speed = data["wind"]["speed"] return ( f"Weather in {city}:\n" f"Temperature: {temperature}°C\n" f"Condition: {description}\n" f"Humidity: {humidity}%\n" f"Wind Speed: {wind_speed} m/s" ) except Exception as e: return f"Error occurred: {str(e)}" # ========================= # 🕒 TIME TOOL # ========================= @tool def get_current_time_in_timezone(timezone: str) -> str: """ A tool that fetches the current local time in a specified timezone. Args: timezone: A valid timezone (e.g., 'Asia/Kolkata') """ try: tz = pytz.timezone(timezone) local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") return f"Current time in {timezone}: {local_time}" except Exception as e: return f"Error fetching time: {str(e)}" # ========================= # 🎯 FINAL ANSWER TOOL # ========================= final_answer = FinalAnswerTool() # ========================= # 🤖 MODEL SETUP # ========================= model = HfApiModel( max_tokens=2096, temperature=0.5, model_id="Qwen/Qwen2.5-Coder-32B-Instruct", custom_role_conversions=None, ) # ========================= # 📜 LOAD PROMPTS # ========================= with open("prompts.yaml", "r") as stream: prompt_templates = yaml.safe_load(stream) # ========================= # 🧠 AGENT SETUP # ========================= agent = CodeAgent( model=model, tools=[ get_weather, get_current_time_in_timezone, final_answer ], max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name="smart_assistant_agent", description="An AI agent that can fetch weather and time information.", prompt_templates=prompt_templates, ) # ========================= # 🚀 LAUNCH UI # ========================= GradioUI(agent).launch()