Spaces:
Sleeping
Sleeping
File size: 7,003 Bytes
9b5b26a c19d193 19d3f03 6aae614 8fe992b 9b5b26a 5df72d6 9b5b26a 19d3f03 9b5b26a 19d3f03 9b5b26a 19d3f03 9b5b26a 19d3f03 9b5b26a 8c01ffb 6aae614 ae7a494 e121372 bf6d34c 29ec968 fe328e0 13d500a 8c01ffb 9b5b26a 8c01ffb 861422e 9b5b26a 8c01ffb 8fe992b b77d916 8c01ffb 861422e 8fe992b 9b5b26a 8c01ffb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
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() |