Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,22 +1,165 @@
|
|
| 1 |
-
from smolagents import CodeAgent,DuckDuckGoSearchTool,
|
| 2 |
import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
from tools.final_answer import FinalAnswerTool
|
| 7 |
-
|
| 8 |
from Gradio_UI import GradioUI
|
| 9 |
|
| 10 |
-
#
|
| 11 |
@tool
|
| 12 |
-
def
|
| 13 |
-
|
| 14 |
-
"""A tool that does nothing yet
|
| 15 |
Args:
|
| 16 |
-
|
| 17 |
-
arg2: the second argument
|
| 18 |
"""
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
@tool
|
| 22 |
def get_current_time_in_timezone(timezone: str) -> str:
|
|
@@ -25,37 +168,45 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 25 |
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
| 26 |
"""
|
| 27 |
try:
|
| 28 |
-
# Create timezone object
|
| 29 |
tz = pytz.timezone(timezone)
|
| 30 |
-
# Get current time in that timezone
|
| 31 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 32 |
return f"The current local time in {timezone} is: {local_time}"
|
| 33 |
except Exception as e:
|
| 34 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 35 |
|
| 36 |
-
|
| 37 |
final_answer = FinalAnswerTool()
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
temperature=0.5,
|
| 45 |
-
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
|
| 46 |
-
custom_role_conversions=None,
|
| 47 |
)
|
| 48 |
|
| 49 |
-
|
| 50 |
# Import tool from Hub
|
| 51 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 52 |
|
|
|
|
| 53 |
with open("prompts.yaml", 'r') as stream:
|
| 54 |
prompt_templates = yaml.safe_load(stream)
|
| 55 |
|
| 56 |
agent = CodeAgent(
|
| 57 |
model=model,
|
| 58 |
-
tools=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
max_steps=6,
|
| 60 |
verbosity_level=1,
|
| 61 |
grammar=None,
|
|
@@ -65,5 +216,4 @@ agent = CodeAgent(
|
|
| 65 |
prompt_templates=prompt_templates
|
| 66 |
)
|
| 67 |
|
| 68 |
-
|
| 69 |
GradioUI(agent).launch()
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool
|
| 2 |
import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
from tools.final_answer import FinalAnswerTool
|
|
|
|
| 7 |
from Gradio_UI import GradioUI
|
| 8 |
|
| 9 |
+
# Weather Tool
|
| 10 |
@tool
|
| 11 |
+
def get_weather(city: str) -> str:
|
| 12 |
+
"""Fetches current weather information for a specified city.
|
|
|
|
| 13 |
Args:
|
| 14 |
+
city: The name of the city to get weather for (e.g., 'London', 'New York')
|
|
|
|
| 15 |
"""
|
| 16 |
+
try:
|
| 17 |
+
# Using wttr.in API which doesn't require authentication
|
| 18 |
+
response = requests.get(f"https://wttr.in/{city}?format=j1", timeout=10)
|
| 19 |
+
if response.status_code == 200:
|
| 20 |
+
data = response.json()
|
| 21 |
+
current = data['current_condition'][0]
|
| 22 |
+
weather_desc = current['weatherDesc'][0]['value']
|
| 23 |
+
temp_c = current['temp_C']
|
| 24 |
+
feels_like = current['FeelsLikeC']
|
| 25 |
+
humidity = current['humidity']
|
| 26 |
+
wind_speed = current['windspeedKmph']
|
| 27 |
+
|
| 28 |
+
return f"Weather in {city}: {weather_desc}, Temperature: {temp_c}°C (feels like {feels_like}°C), Humidity: {humidity}%, Wind: {wind_speed} km/h"
|
| 29 |
+
else:
|
| 30 |
+
return f"Could not fetch weather data for {city}"
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return f"Error fetching weather: {str(e)}"
|
| 33 |
+
|
| 34 |
+
# Calculator Tool
|
| 35 |
+
@tool
|
| 36 |
+
def calculate(expression: str) -> str:
|
| 37 |
+
"""Evaluates a mathematical expression safely.
|
| 38 |
+
Args:
|
| 39 |
+
expression: A mathematical expression as a string (e.g., '2 + 2', '10 * 5 + 3')
|
| 40 |
+
"""
|
| 41 |
+
try:
|
| 42 |
+
# Safe evaluation of mathematical expressions
|
| 43 |
+
allowed_chars = set('0123456789+-*/(). ')
|
| 44 |
+
if not all(c in allowed_chars for c in expression):
|
| 45 |
+
return "Error: Expression contains invalid characters. Only numbers and basic operators (+, -, *, /, parentheses) are allowed."
|
| 46 |
+
|
| 47 |
+
result = eval(expression, {"__builtins__": {}}, {})
|
| 48 |
+
return f"Result: {result}"
|
| 49 |
+
except Exception as e:
|
| 50 |
+
return f"Error calculating expression: {str(e)}"
|
| 51 |
+
|
| 52 |
+
# Currency Converter Tool
|
| 53 |
+
@tool
|
| 54 |
+
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
|
| 55 |
+
"""Converts an amount from one currency to another using live exchange rates.
|
| 56 |
+
Args:
|
| 57 |
+
amount: The amount to convert
|
| 58 |
+
from_currency: Source currency code (e.g., 'USD', 'EUR', 'GBP')
|
| 59 |
+
to_currency: Target currency code (e.g., 'USD', 'EUR', 'GBP')
|
| 60 |
+
"""
|
| 61 |
+
try:
|
| 62 |
+
# Using exchangerate-api.com free tier
|
| 63 |
+
url = f"https://api.exchangerate-api.com/v4/latest/{from_currency.upper()}"
|
| 64 |
+
response = requests.get(url, timeout=10)
|
| 65 |
+
|
| 66 |
+
if response.status_code == 200:
|
| 67 |
+
data = response.json()
|
| 68 |
+
if to_currency.upper() in data['rates']:
|
| 69 |
+
rate = data['rates'][to_currency.upper()]
|
| 70 |
+
converted = amount * rate
|
| 71 |
+
return f"{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()} (Rate: {rate:.4f})"
|
| 72 |
+
else:
|
| 73 |
+
return f"Currency code '{to_currency}' not found"
|
| 74 |
+
else:
|
| 75 |
+
return "Error fetching exchange rates"
|
| 76 |
+
except Exception as e:
|
| 77 |
+
return f"Error converting currency: {str(e)}"
|
| 78 |
+
|
| 79 |
+
# Text Analysis Tool
|
| 80 |
+
@tool
|
| 81 |
+
def analyze_text(text: str) -> str:
|
| 82 |
+
"""Analyzes text and provides statistics like word count, character count, and reading time.
|
| 83 |
+
Args:
|
| 84 |
+
text: The text to analyze
|
| 85 |
+
"""
|
| 86 |
+
try:
|
| 87 |
+
words = text.split()
|
| 88 |
+
word_count = len(words)
|
| 89 |
+
char_count = len(text)
|
| 90 |
+
char_count_no_spaces = len(text.replace(' ', ''))
|
| 91 |
+
sentence_count = text.count('.') + text.count('!') + text.count('?')
|
| 92 |
+
|
| 93 |
+
# Average reading speed is ~200 words per minute
|
| 94 |
+
reading_time_minutes = word_count / 200
|
| 95 |
+
|
| 96 |
+
return f"""Text Analysis:
|
| 97 |
+
- Words: {word_count}
|
| 98 |
+
- Characters (with spaces): {char_count}
|
| 99 |
+
- Characters (without spaces): {char_count_no_spaces}
|
| 100 |
+
- Sentences: {sentence_count}
|
| 101 |
+
- Estimated reading time: {reading_time_minutes:.1f} minutes"""
|
| 102 |
+
except Exception as e:
|
| 103 |
+
return f"Error analyzing text: {str(e)}"
|
| 104 |
+
|
| 105 |
+
# Random Fact Generator
|
| 106 |
+
@tool
|
| 107 |
+
def get_random_fact() -> str:
|
| 108 |
+
"""Fetches a random interesting fact."""
|
| 109 |
+
try:
|
| 110 |
+
response = requests.get("https://uselessfacts.jsph.pl/random.json?language=en", timeout=10)
|
| 111 |
+
if response.status_code == 200:
|
| 112 |
+
fact = response.json()['text']
|
| 113 |
+
return f"Random Fact: {fact}"
|
| 114 |
+
else:
|
| 115 |
+
return "Could not fetch a random fact at this time."
|
| 116 |
+
except Exception as e:
|
| 117 |
+
return f"Error fetching random fact: {str(e)}"
|
| 118 |
+
|
| 119 |
+
# Timezone Converter
|
| 120 |
+
@tool
|
| 121 |
+
def convert_time_between_timezones(time_str: str, from_timezone: str, to_timezone: str) -> str:
|
| 122 |
+
"""Converts a time from one timezone to another.
|
| 123 |
+
Args:
|
| 124 |
+
time_str: Time in format 'HH:MM' (24-hour format)
|
| 125 |
+
from_timezone: Source timezone (e.g., 'America/New_York')
|
| 126 |
+
to_timezone: Target timezone (e.g., 'Asia/Tokyo')
|
| 127 |
+
"""
|
| 128 |
+
try:
|
| 129 |
+
# Parse time
|
| 130 |
+
time_obj = datetime.datetime.strptime(time_str, "%H:%M").time()
|
| 131 |
+
|
| 132 |
+
# Get current date
|
| 133 |
+
today = datetime.datetime.now().date()
|
| 134 |
+
|
| 135 |
+
# Create datetime object with source timezone
|
| 136 |
+
from_tz = pytz.timezone(from_timezone)
|
| 137 |
+
dt_from = from_tz.localize(datetime.datetime.combine(today, time_obj))
|
| 138 |
+
|
| 139 |
+
# Convert to target timezone
|
| 140 |
+
to_tz = pytz.timezone(to_timezone)
|
| 141 |
+
dt_to = dt_from.astimezone(to_tz)
|
| 142 |
+
|
| 143 |
+
return f"{time_str} in {from_timezone} is {dt_to.strftime('%H:%M')} in {to_timezone}"
|
| 144 |
+
except Exception as e:
|
| 145 |
+
return f"Error converting time: {str(e)}"
|
| 146 |
+
|
| 147 |
+
# URL Shortener (using is.gd)
|
| 148 |
+
@tool
|
| 149 |
+
def shorten_url(url: str) -> str:
|
| 150 |
+
"""Shortens a long URL using a URL shortening service.
|
| 151 |
+
Args:
|
| 152 |
+
url: The URL to shorten
|
| 153 |
+
"""
|
| 154 |
+
try:
|
| 155 |
+
response = requests.get(f"https://is.gd/create.php?format=simple&url={url}", timeout=10)
|
| 156 |
+
if response.status_code == 200:
|
| 157 |
+
short_url = response.text
|
| 158 |
+
return f"Shortened URL: {short_url}"
|
| 159 |
+
else:
|
| 160 |
+
return "Error shortening URL"
|
| 161 |
+
except Exception as e:
|
| 162 |
+
return f"Error: {str(e)}"
|
| 163 |
|
| 164 |
@tool
|
| 165 |
def get_current_time_in_timezone(timezone: str) -> str:
|
|
|
|
| 168 |
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
| 169 |
"""
|
| 170 |
try:
|
|
|
|
| 171 |
tz = pytz.timezone(timezone)
|
|
|
|
| 172 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 173 |
return f"The current local time in {timezone} is: {local_time}"
|
| 174 |
except Exception as e:
|
| 175 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 176 |
|
| 177 |
+
# Initialize tools
|
| 178 |
final_answer = FinalAnswerTool()
|
| 179 |
+
search_tool = DuckDuckGoSearchTool()
|
| 180 |
|
| 181 |
+
model = InferenceClientModel(
|
| 182 |
+
max_tokens=2096,
|
| 183 |
+
temperature=0.5,
|
| 184 |
+
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
|
| 185 |
+
custom_role_conversions=None,
|
|
|
|
|
|
|
|
|
|
| 186 |
)
|
| 187 |
|
|
|
|
| 188 |
# Import tool from Hub
|
| 189 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 190 |
|
| 191 |
+
# Load system prompt from prompt.yaml file
|
| 192 |
with open("prompts.yaml", 'r') as stream:
|
| 193 |
prompt_templates = yaml.safe_load(stream)
|
| 194 |
|
| 195 |
agent = CodeAgent(
|
| 196 |
model=model,
|
| 197 |
+
tools=[
|
| 198 |
+
final_answer,
|
| 199 |
+
search_tool,
|
| 200 |
+
get_weather,
|
| 201 |
+
calculate,
|
| 202 |
+
convert_currency,
|
| 203 |
+
analyze_text,
|
| 204 |
+
get_random_fact,
|
| 205 |
+
get_current_time_in_timezone,
|
| 206 |
+
convert_time_between_timezones,
|
| 207 |
+
shorten_url,
|
| 208 |
+
image_generation_tool
|
| 209 |
+
],
|
| 210 |
max_steps=6,
|
| 211 |
verbosity_level=1,
|
| 212 |
grammar=None,
|
|
|
|
| 216 |
prompt_templates=prompt_templates
|
| 217 |
)
|
| 218 |
|
|
|
|
| 219 |
GradioUI(agent).launch()
|