from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool import datetime import requests import pytz import yaml import json from tools.final_answer import FinalAnswerTool from Gradio_UI import GradioUI # Weather API Tool @tool def get_weather(location: str) -> str: """A tool that fetches current weather for a specified location. Args: location: A string representing a city or location (e.g., 'New York', 'London, UK'). """ try: # Using open-meteo API which doesn't require API key # First get coordinates geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1" geocoding_response = requests.get(geocoding_url) geocoding_data = geocoding_response.json() if not geocoding_data.get("results"): return f"Could not find location: {location}" lat = geocoding_data["results"][0]["latitude"] lon = geocoding_data["results"][0]["longitude"] city_name = geocoding_data["results"][0]["name"] # Now get weather weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t=temperature_2m,wind_speed_10m,relative_humidity_2m,precipitation,weather_code" weather_response = requests.get(weather_url) weather_data = weather_response.json() current = weather_data["current"] temperature = current["temperature_2m"] wind_speed = current["wind_speed_10m"] humidity = current["relative_humidity_2m"] precipitation = current["precipitation"] # Weather code to text mapping weather_codes = { 0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast", 45: "Fog", 48: "Depositing rime fog", 51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle", 61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain", 71: "Slight snow fall", 73: "Moderate snow fall", 75: "Heavy snow fall", 80: "Slight rain showers", 81: "Moderate rain showers", 82: "Violent rain showers", 95: "Thunderstorm", 96: "Thunderstorm with slight hail", 99: "Thunderstorm with heavy hail" } weather_description = weather_codes.get(current["weather_code"], "Unknown") return f"Current weather in {city_name}: {weather_description}, {temperature}°C, {wind_speed}km/h wind, {humidity}% humidity, {precipitation}mm precipitation" except Exception as e: return f"Error fetching weather for '{location}': {str(e)}" @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 string representing a valid timezone (e.g., 'America/New_York'). """ try: # Create timezone object tz = pytz.timezone(timezone) # Get current time in that timezone local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") return f"The current local time in {timezone} is: {local_time}" except Exception as e: return f"Error fetching time for timezone '{timezone}': {str(e)}" @tool def currency_converter(amount: float, from_currency: str, to_currency: str) -> str: """A tool that converts an amount from one currency to another using latest exchange rates. Args: amount: The amount to convert from_currency: The source currency code (e.g., 'USD') to_currency: The target currency code (e.g., 'EUR') """ try: # Using ExchangeRate API url = f"https://open.er-api.com/v6/latest/{from_currency.upper()}" response = requests.get(url) data = response.json() if data["result"] != "success": return f"Error: Could not fetch exchange rates for {from_currency}" if to_currency.upper() not in data["rates"]: return f"Error: Target currency {to_currency} not found" rate = data["rates"][to_currency.upper()] converted_amount = amount * rate return f"{amount} {from_currency.upper()} = {converted_amount:.2f} {to_currency.upper()} (Rate: 1 {from_currency.upper()} = {rate} {to_currency.upper()})" except Exception as e: return f"Error converting currency: {str(e)}" @tool def stock_price_lookup(ticker: str) -> str: """A tool that looks up the latest stock price for a given ticker symbol. Args: ticker: The stock ticker symbol (e.g., 'AAPL' for Apple Inc.) """ try: # Using Alpha Vantage API (free tier, limited to 25 requests per day) # Note: In a production environment, you'd want to use a proper API key url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={ticker}&apikey=demo" response = requests.get(url) data = response.json() if "Global Quote" not in data or not data["Global Quote"]: return f"Could not find data for ticker: {ticker}" quote = data["Global Quote"] price = quote.get("05. price", "N/A") change = quote.get("09. change", "N/A") change_percent = quote.get("10. change percent", "N/A") return f"{ticker} current price: ${price} (Change: {change} / {change_percent})" except Exception as e: return f"Error looking up stock price for '{ticker}': {str(e)}" final_answer = FinalAnswerTool() model = HfApiModel( max_tokens=2096, temperature=0.5, model_id='Qwen/Qwen2.5-Coder-32B-Instruct', custom_role_conversions=None, ) # Import tool from Hub image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) search_tool = DuckDuckGoSearchTool() with open("prompts.yaml", 'r') as stream: prompt_templates = yaml.safe_load(stream) agent = CodeAgent( model=model, tools=[ final_answer, get_current_time_in_timezone, get_weather, currency_converter, stock_price_lookup, image_generation_tool, search_tool ], max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) GradioUI(agent).launch()