from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool import requests import pytz import yaml from datetime import datetime, timedelta from tools.final_answer import FinalAnswerTool from Gradio_UI import GradioUI # Below is an example of a tool that does nothing. Amaze us with your creativity ! @tool def get_time_difference(location: str) -> str: """ Calculates and returns the time difference between a specified location and U.S. Eastern Time. This tool fetches the current time for the given location and for the U.S. Eastern Time zone (America/New_York), then presents a fun, easy-to-read comparison. Args: location: The city or timezone to get the local time for (e.g., "London", "Asia/Tokyo", "Europe/Paris"). """ def get_time_data(timezone: str): """Helper function to fetch time data from the World Time API.""" api_url = f"http://worldtimeapi.org/api/timezone/{timezone}" try: response = requests.get(api_url) # Raise an exception for bad status codes (4xx or 5xx) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: # This handles network errors, bad status codes, etc. print(f"API request failed for {timezone}: {e}") return None # Step 1: Get U.S. Eastern Time et_data = get_time_data("America/New_York") if not et_data: return "Oops! I couldn't connect to get the U.S. Eastern Time right now. Please try again later." # Step 2: Get time for the user-specified location # The API can be picky. We'll try the user's input directly first. # If it fails, we'll try to find a matching timezone. location_data = get_time_data(location) if not location_data: # Try to find a timezone that contains the location string try: all_timezones_response = requests.get("http://worldtimeapi.org/api/timezone") all_timezones_response.raise_for_status() all_timezones = all_timezones_response.json() # Find the first timezone that ends with the location name found_timezone = next((tz for tz in all_timezones if tz.lower().endswith(f"/{location.lower()}")), None) if found_timezone: print(f"Found matching timezone: {found_timezone}") location_data = get_time_data(found_timezone) else: return f"Sorry, I couldn't find a timezone for '{location}'. Try a major city or a standard timezone format like 'Europe/London'." except requests.exceptions.RequestException: return "Sorry, I'm having trouble searching for that location right now." if not location_data: return f"I tried my best, but I still couldn't find the time for '{location}'. Are you sure it's spelled correctly?" # Step 3: Parse the datetime objects from the API responses try: et_time = datetime.fromisoformat(et_data['datetime']) location_time = datetime.fromisoformat(location_data['datetime']) location_timezone_name = location.replace('_', ' ').title() et_timezone_name = "U.S. Eastern Time" except (ValueError, KeyError): return "There was an issue processing the time data. It might be a temporary problem." # Step 4: Calculate the difference # We compare based on UTC offset to get the pure time difference et_offset_str = et_data['utc_offset'] location_offset_str = location_data['utc_offset'] et_offset = timedelta(hours=int(et_offset_str[1:3]), minutes=int(et_offset_str[4:6])) if et_offset_str[0] == '-': et_offset = -et_offset location_offset = timedelta(hours=int(location_offset_str[1:3]), minutes=int(location_offset_str[4:6])) if location_offset_str[0] == '-': location_offset = -location_offset time_difference = location_offset - et_offset # Step 5: Format the output string in a fun way diff_total_seconds = time_difference.total_seconds() diff_hours = int(diff_total_seconds / 3600) diff_minutes = int((diff_total_seconds % 3600) / 60) comparison = "" if diff_total_seconds == 0: comparison = f"{location_timezone_name} is in the same timezone as {et_timezone_name}!" else: ahead_or_behind = "ahead of" if diff_total_seconds > 0 else "behind" # Format the hours and minutes for readability hour_str = f"{abs(diff_hours)} hour{'s' if abs(diff_hours) != 1 else ''}" minute_str = f"{abs(diff_minutes)} minute{'s' if abs(diff_minutes) != 1 else ''}" if diff_hours != 0 and diff_minutes != 0: comparison = f"{location_timezone_name} is {hour_str} and {minute_str} {ahead_or_behind} {et_timezone_name}." elif diff_hours != 0: comparison = f"{location_timezone_name} is {hour_str} {ahead_or_behind} {et_timezone_name}." else: # Only minutes are different comparison = f"{location_timezone_name} is {minute_str} {ahead_or_behind} {et_timezone_name}." return (f"Time check! Right now, it's {et_time.strftime('%-I:%M %p')} in {et_timezone_name}, " f"which means it's {location_time.strftime('%-I:%M %p')} in {location_timezone_name}. " f"{comparison}") @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.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)}" final_answer = FinalAnswerTool() # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder: # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' model = HfApiModel( max_tokens=2096, temperature=0.5, model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded custom_role_conversions=None, ) # Import tool from Hub image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) with open("prompts.yaml", 'r') as stream: prompt_templates = yaml.safe_load(stream) agent = CodeAgent( model=model, tools=[final_answer, image_generation_tool, get_time_difference], ## add your tools here (don't remove final answer) max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) GradioUI(agent).launch()