Spaces:
Sleeping
Sleeping
| from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| import json | |
| import re | |
| from tools.final_answer import FinalAnswerTool | |
| from Gradio_UI import GradioUI | |
| 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: | |
| tz = pytz.timezone(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)}" | |
| def calculate_time_difference(timezone1: str, timezone2: str) -> str: | |
| """Calculate the time difference between two timezones. | |
| Args: | |
| timezone1: First timezone (e.g., 'America/New_York') | |
| timezone2: Second timezone (e.g., 'Asia/Tokyo') | |
| """ | |
| try: | |
| tz1 = pytz.timezone(timezone1) | |
| tz2 = pytz.timezone(timezone2) | |
| now = datetime.datetime.now(pytz.UTC) | |
| offset1 = now.astimezone(tz1).utcoffset().total_seconds() / 3600 | |
| offset2 = now.astimezone(tz2).utcoffset().total_seconds() / 3600 | |
| diff = offset2 - offset1 | |
| return f"Time difference: {timezone2} is {diff:+.1f} hours ahead of {timezone1}" | |
| except Exception as e: | |
| return f"Error calculating time difference: {str(e)}" | |
| def get_weather_info(city: str) -> str: | |
| """Fetch current weather information for a city using wttr.in service. | |
| Args: | |
| city: Name of the city (e.g., 'London', 'Paris', 'Tokyo') | |
| """ | |
| try: | |
| response = requests.get(f"https://wttr.in/{city}?format=j1", timeout=10) | |
| if response.status_code == 200: | |
| data = response.json() | |
| current = data['current_condition'][0] | |
| temp_c = current['temp_C'] | |
| feels_like = current['FeelsLikeC'] | |
| desc = current['weatherDesc'][0]['value'] | |
| humidity = current['humidity'] | |
| wind_speed = current['windspeedKmph'] | |
| return f"Weather in {city}: {desc}, {temp_c}°C (feels like {feels_like}°C), Humidity: {humidity}%, Wind: {wind_speed} km/h" | |
| else: | |
| return f"Could not fetch weather for {city}" | |
| except Exception as e: | |
| return f"Error fetching weather: {str(e)}" | |
| def convert_currency(amount: float, from_currency: str, to_currency: str) -> str: | |
| """Convert currency using live exchange rates from an API. | |
| Args: | |
| amount: Amount to convert | |
| from_currency: Source currency code (e.g., 'USD') | |
| to_currency: Target currency code (e.g., 'EUR') | |
| """ | |
| try: | |
| url = f"https://api.exchangerate-api.com/v4/latest/{from_currency.upper()}" | |
| response = requests.get(url, timeout=10) | |
| if response.status_code == 200: | |
| data = response.json() | |
| rate = data['rates'].get(to_currency.upper()) | |
| if rate: | |
| converted = amount * rate | |
| return f"{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()} (Rate: {rate:.4f})" | |
| else: | |
| return f"Currency {to_currency} not found" | |
| else: | |
| return "Error fetching exchange rates" | |
| except Exception as e: | |
| return f"Error converting currency: {str(e)}" | |
| def extract_urls_from_text(text: str) -> str: | |
| """Extract all URLs from a given text. | |
| Args: | |
| text: The text to extract URLs from | |
| """ | |
| url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+' | |
| urls = re.findall(url_pattern, text) | |
| if urls: | |
| return f"Found {len(urls)} URL(s): " + ", ".join(urls) | |
| else: | |
| return "No URLs found in the text" | |
| def countdown_to_date(target_date: str) -> str: | |
| """Calculate countdown to a specific date. | |
| Args: | |
| target_date: Date in format 'YYYY-MM-DD' (e.g., '2025-12-31') | |
| """ | |
| try: | |
| target = datetime.datetime.strptime(target_date, "%Y-%m-%d") | |
| now = datetime.datetime.now() | |
| diff = target - now | |
| if diff.days < 0: | |
| return f"The date {target_date} has already passed ({abs(diff.days)} days ago)" | |
| days = diff.days | |
| hours = diff.seconds // 3600 | |
| minutes = (diff.seconds % 3600) // 60 | |
| return f"Countdown to {target_date}: {days} days, {hours} hours, {minutes} minutes" | |
| except Exception as e: | |
| return f"Error parsing date: {str(e)}" | |
| def generate_random_password(length: int, include_symbols: bool = True) -> str: | |
| """Generate a random secure password. | |
| Args: | |
| length: Length of the password (minimum 8) | |
| include_symbols: Whether to include special symbols | |
| """ | |
| import random | |
| import string | |
| if length < 8: | |
| return "Password length must be at least 8 characters" | |
| chars = string.ascii_letters + string.digits | |
| if include_symbols: | |
| chars += "!@#$%^&*()_+-=[]{}|;:,.<>?" | |
| password = ''.join(random.choice(chars) for _ in range(length)) | |
| return f"Generated password (length {length}): {password}" | |
| def calculate_age_from_birthdate(birthdate: str) -> str: | |
| """Calculate age from birthdate. | |
| Args: | |
| birthdate: Date in format 'YYYY-MM-DD' (e.g., '1990-05-15') | |
| """ | |
| try: | |
| birth = datetime.datetime.strptime(birthdate, "%Y-%m-%d") | |
| today = datetime.datetime.now() | |
| age = today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day)) | |
| next_birthday = datetime.datetime(today.year, birth.month, birth.day) | |
| if next_birthday < today: | |
| next_birthday = datetime.datetime(today.year + 1, birth.month, birth.day) | |
| days_to_birthday = (next_birthday - today).days | |
| return f"Age: {age} years old. Next birthday in {days_to_birthday} days." | |
| except Exception as e: | |
| return f"Error calculating age: {str(e)}" | |
| def list_available_timezones(region: str = "all") -> str: | |
| """List available timezones for a specific region. | |
| Args: | |
| region: Region name (e.g., 'America', 'Europe', 'Asia') or 'all' for common timezones | |
| """ | |
| if region.lower() == "all": | |
| common_tz = [ | |
| "UTC", "America/New_York", "America/Los_Angeles", "America/Chicago", | |
| "Europe/London", "Europe/Paris", "Europe/Berlin", "Asia/Tokyo", | |
| "Asia/Shanghai", "Asia/Dubai", "Australia/Sydney", "Pacific/Auckland" | |
| ] | |
| return "Common timezones: " + ", ".join(common_tz) | |
| else: | |
| timezones = [tz for tz in pytz.all_timezones if tz.startswith(region)] | |
| if timezones: | |
| return f"Timezones in {region}: " + ", ".join(timezones[:20]) + ("..." if len(timezones) > 20 else "") | |
| else: | |
| return f"No timezones found for region '{region}'" | |
| final_answer = FinalAnswerTool() | |
| # Use HfApiModel instead of InferenceClientModel | |
| model = HfApiModel( | |
| model_id='Qwen/Qwen2.5-Coder-32B-Instruct', | |
| token=None # Will use HF_TOKEN from environment if available | |
| ) | |
| # Import tool from Hub | |
| image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) | |
| search_tool = DuckDuckGoSearchTool() | |
| # Load system prompt from prompt.yaml file | |
| 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, | |
| calculate_time_difference, | |
| get_weather_info, | |
| convert_currency, | |
| extract_urls_from_text, | |
| countdown_to_date, | |
| generate_random_password, | |
| calculate_age_from_birthdate, | |
| list_available_timezones, | |
| 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() |