Spaces:
Sleeping
Sleeping
File size: 8,110 Bytes
9bf390e 9b5b26a c19d193 a870cc3 6aae614 9b5b26a 8c01ffb a870cc3 8c01ffb a870cc3 ae7a494 a870cc3 ae7a494 a870cc3 8c01ffb a870cc3 9bf390e a870cc3 9bf390e a870cc3 8c01ffb 9b5b26a a870cc3 8c01ffb a870cc3 861422e 9b5b26a 8c01ffb 8fe992b a870cc3 8c01ffb 861422e 8fe992b 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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
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
@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:
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)}"
@tool
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)}"
@tool
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)}"
@tool
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)}"
@tool
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"
@tool
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)}"
@tool
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}"
@tool
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)}"
@tool
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() |