Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,211 +1,210 @@
|
|
| 1 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool,
|
| 2 |
import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
-
|
|
|
|
| 7 |
from Gradio_UI import GradioUI
|
| 8 |
|
| 9 |
-
#
|
| 10 |
@tool
|
| 11 |
-
def
|
| 12 |
-
"""
|
|
|
|
| 13 |
Args:
|
| 14 |
-
|
| 15 |
"""
|
| 16 |
try:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
# Calculator Tool
|
| 35 |
@tool
|
| 36 |
def calculate(expression: str) -> str:
|
| 37 |
-
"""
|
|
|
|
| 38 |
Args:
|
| 39 |
expression: A mathematical expression as a string (e.g., '2 + 2', '10 * 5 + 3')
|
| 40 |
"""
|
| 41 |
try:
|
| 42 |
-
# Safe evaluation
|
| 43 |
allowed_chars = set('0123456789+-*/(). ')
|
| 44 |
if not all(c in allowed_chars for c in expression):
|
| 45 |
-
return "Error: Expression contains invalid characters
|
| 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 |
-
#
|
| 53 |
@tool
|
| 54 |
-
def
|
| 55 |
-
"""
|
|
|
|
| 56 |
Args:
|
| 57 |
-
|
| 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 |
-
|
| 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 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
| 74 |
else:
|
| 75 |
-
return "
|
| 76 |
except Exception as e:
|
| 77 |
-
return f"Error
|
| 78 |
|
| 79 |
-
#
|
| 80 |
@tool
|
| 81 |
-
def
|
| 82 |
-
"""
|
|
|
|
| 83 |
Args:
|
| 84 |
-
|
| 85 |
"""
|
| 86 |
try:
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 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
|
| 104 |
|
| 105 |
-
#
|
| 106 |
@tool
|
| 107 |
-
def
|
| 108 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
try:
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 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
|
| 118 |
|
| 119 |
-
#
|
| 120 |
@tool
|
| 121 |
-
def
|
| 122 |
-
"""
|
|
|
|
| 123 |
Args:
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
"""
|
| 128 |
try:
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 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
|
| 146 |
|
| 147 |
-
#
|
| 148 |
@tool
|
| 149 |
-
def
|
| 150 |
-
"""
|
|
|
|
| 151 |
Args:
|
| 152 |
-
|
| 153 |
"""
|
| 154 |
try:
|
| 155 |
-
|
|
|
|
| 156 |
if response.status_code == 200:
|
| 157 |
-
|
| 158 |
-
return f"
|
| 159 |
else:
|
| 160 |
-
return "
|
| 161 |
except Exception as e:
|
| 162 |
-
return f"Error: {str(e)}"
|
| 163 |
|
|
|
|
| 164 |
@tool
|
| 165 |
-
def
|
| 166 |
-
"""
|
|
|
|
| 167 |
Args:
|
| 168 |
-
|
| 169 |
"""
|
| 170 |
try:
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
| 174 |
except Exception as e:
|
| 175 |
-
return f"Error
|
| 176 |
|
| 177 |
-
# Initialize tools
|
| 178 |
final_answer = FinalAnswerTool()
|
| 179 |
-
search_tool = DuckDuckGoSearchTool()
|
| 180 |
|
| 181 |
-
model =
|
| 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 |
-
#
|
| 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 |
-
|
| 200 |
-
|
| 201 |
calculate,
|
|
|
|
|
|
|
|
|
|
| 202 |
convert_currency,
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
convert_time_between_timezones,
|
| 207 |
-
shorten_url,
|
| 208 |
-
image_generation_tool
|
| 209 |
],
|
| 210 |
max_steps=6,
|
| 211 |
verbosity_level=1,
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
|
| 2 |
import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
+
import json
|
| 7 |
+
from tools.final_answer import FinalAnswerTool
|
| 8 |
from Gradio_UI import GradioUI
|
| 9 |
|
| 10 |
+
# Web Search Tool
|
| 11 |
@tool
|
| 12 |
+
def web_search(query: str) -> str:
|
| 13 |
+
"""Search the web using DuckDuckGo for current information.
|
| 14 |
+
|
| 15 |
Args:
|
| 16 |
+
query: The search query string
|
| 17 |
"""
|
| 18 |
try:
|
| 19 |
+
search_tool = DuckDuckGoSearchTool()
|
| 20 |
+
results = search_tool(query)
|
| 21 |
+
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
except Exception as e:
|
| 23 |
+
return f"Error performing web search: {str(e)}"
|
| 24 |
+
|
| 25 |
+
# Time and Date Tool
|
| 26 |
+
@tool
|
| 27 |
+
def get_current_time_in_timezone(timezone: str) -> str:
|
| 28 |
+
"""Get the current local time in a specified timezone.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
timezone: A valid timezone string (e.g., 'America/New_York', 'Europe/London', 'Asia/Tokyo')
|
| 32 |
+
"""
|
| 33 |
+
try:
|
| 34 |
+
tz = pytz.timezone(timezone)
|
| 35 |
+
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S %Z")
|
| 36 |
+
return f"The current local time in {timezone} is: {local_time}"
|
| 37 |
+
except Exception as e:
|
| 38 |
+
return f"Error: Invalid timezone '{timezone}'. {str(e)}"
|
| 39 |
|
| 40 |
# Calculator Tool
|
| 41 |
@tool
|
| 42 |
def calculate(expression: str) -> str:
|
| 43 |
+
"""Evaluate a mathematical expression safely.
|
| 44 |
+
|
| 45 |
Args:
|
| 46 |
expression: A mathematical expression as a string (e.g., '2 + 2', '10 * 5 + 3')
|
| 47 |
"""
|
| 48 |
try:
|
| 49 |
+
# Safe evaluation using only numbers and basic operators
|
| 50 |
allowed_chars = set('0123456789+-*/(). ')
|
| 51 |
if not all(c in allowed_chars for c in expression):
|
| 52 |
+
return "Error: Expression contains invalid characters"
|
| 53 |
|
| 54 |
result = eval(expression, {"__builtins__": {}}, {})
|
| 55 |
return f"Result: {result}"
|
| 56 |
except Exception as e:
|
| 57 |
return f"Error calculating expression: {str(e)}"
|
| 58 |
|
| 59 |
+
# Weather Tool
|
| 60 |
@tool
|
| 61 |
+
def get_weather(city: str) -> str:
|
| 62 |
+
"""Get current weather information for a city using wttr.in service.
|
| 63 |
+
|
| 64 |
Args:
|
| 65 |
+
city: Name of the city to get weather for
|
|
|
|
|
|
|
| 66 |
"""
|
| 67 |
try:
|
| 68 |
+
url = f"https://wttr.in/{city}?format=j1"
|
|
|
|
| 69 |
response = requests.get(url, timeout=10)
|
|
|
|
| 70 |
if response.status_code == 200:
|
| 71 |
data = response.json()
|
| 72 |
+
current = data['current_condition'][0]
|
| 73 |
+
temp_c = current['temp_C']
|
| 74 |
+
temp_f = current['temp_F']
|
| 75 |
+
weather_desc = current['weatherDesc'][0]['value']
|
| 76 |
+
humidity = current['humidity']
|
| 77 |
+
wind_speed = current['windspeedKmph']
|
| 78 |
+
|
| 79 |
+
return f"Weather in {city}: {weather_desc}, Temperature: {temp_c}°C ({temp_f}°F), Humidity: {humidity}%, Wind Speed: {wind_speed} km/h"
|
| 80 |
else:
|
| 81 |
+
return f"Could not fetch weather for {city}"
|
| 82 |
except Exception as e:
|
| 83 |
+
return f"Error fetching weather: {str(e)}"
|
| 84 |
|
| 85 |
+
# File Reader Tool
|
| 86 |
@tool
|
| 87 |
+
def read_file(filepath: str) -> str:
|
| 88 |
+
"""Read and return the contents of a text file.
|
| 89 |
+
|
| 90 |
Args:
|
| 91 |
+
filepath: Path to the file to read
|
| 92 |
"""
|
| 93 |
try:
|
| 94 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 95 |
+
content = f.read()
|
| 96 |
+
return f"File content:\n{content}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
except Exception as e:
|
| 98 |
+
return f"Error reading file: {str(e)}"
|
| 99 |
|
| 100 |
+
# File Writer Tool
|
| 101 |
@tool
|
| 102 |
+
def write_file(filepath: str, content: str) -> str:
|
| 103 |
+
"""Write content to a text file.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
filepath: Path where the file should be written
|
| 107 |
+
content: Content to write to the file
|
| 108 |
+
"""
|
| 109 |
try:
|
| 110 |
+
with open(filepath, 'w', encoding='utf-8') as f:
|
| 111 |
+
f.write(content)
|
| 112 |
+
return f"Successfully wrote to {filepath}"
|
|
|
|
|
|
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
+
return f"Error writing file: {str(e)}"
|
| 115 |
|
| 116 |
+
# Currency Converter Tool
|
| 117 |
@tool
|
| 118 |
+
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
|
| 119 |
+
"""Convert an amount from one currency to another using live exchange rates.
|
| 120 |
+
|
| 121 |
Args:
|
| 122 |
+
amount: The amount to convert
|
| 123 |
+
from_currency: The source currency code (e.g., 'USD', 'EUR', 'GBP')
|
| 124 |
+
to_currency: The target currency code (e.g., 'USD', 'EUR', 'GBP')
|
| 125 |
"""
|
| 126 |
try:
|
| 127 |
+
url = f"https://api.exchangerate-api.com/v4/latest/{from_currency.upper()}"
|
| 128 |
+
response = requests.get(url, timeout=10)
|
| 129 |
+
if response.status_code == 200:
|
| 130 |
+
data = response.json()
|
| 131 |
+
rate = data['rates'].get(to_currency.upper())
|
| 132 |
+
if rate:
|
| 133 |
+
converted = amount * rate
|
| 134 |
+
return f"{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()}"
|
| 135 |
+
else:
|
| 136 |
+
return f"Currency code '{to_currency}' not found"
|
| 137 |
+
else:
|
| 138 |
+
return "Error fetching exchange rates"
|
|
|
|
|
|
|
|
|
|
| 139 |
except Exception as e:
|
| 140 |
+
return f"Error converting currency: {str(e)}"
|
| 141 |
|
| 142 |
+
# Wikipedia Summary Tool
|
| 143 |
@tool
|
| 144 |
+
def get_wikipedia_summary(topic: str) -> str:
|
| 145 |
+
"""Get a brief summary from Wikipedia about a topic.
|
| 146 |
+
|
| 147 |
Args:
|
| 148 |
+
topic: The topic to search for on Wikipedia
|
| 149 |
"""
|
| 150 |
try:
|
| 151 |
+
url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic.replace(' ', '_')}"
|
| 152 |
+
response = requests.get(url, timeout=10)
|
| 153 |
if response.status_code == 200:
|
| 154 |
+
data = response.json()
|
| 155 |
+
return f"Wikipedia Summary: {data.get('extract', 'No summary available')}"
|
| 156 |
else:
|
| 157 |
+
return f"Could not find Wikipedia article for '{topic}'"
|
| 158 |
except Exception as e:
|
| 159 |
+
return f"Error fetching Wikipedia summary: {str(e)}"
|
| 160 |
|
| 161 |
+
# List Available Timezones Tool
|
| 162 |
@tool
|
| 163 |
+
def list_common_timezones(region: str = "all") -> str:
|
| 164 |
+
"""List common timezones, optionally filtered by region.
|
| 165 |
+
|
| 166 |
Args:
|
| 167 |
+
region: Region to filter by (e.g., 'America', 'Europe', 'Asia', 'all')
|
| 168 |
"""
|
| 169 |
try:
|
| 170 |
+
if region.lower() == "all":
|
| 171 |
+
timezones = pytz.common_timezones[:20] # First 20 for brevity
|
| 172 |
+
return f"Common timezones (first 20): {', '.join(timezones)}"
|
| 173 |
+
else:
|
| 174 |
+
filtered = [tz for tz in pytz.common_timezones if tz.startswith(region)]
|
| 175 |
+
return f"Timezones in {region}: {', '.join(filtered[:30])}"
|
| 176 |
except Exception as e:
|
| 177 |
+
return f"Error listing timezones: {str(e)}"
|
| 178 |
|
|
|
|
| 179 |
final_answer = FinalAnswerTool()
|
|
|
|
| 180 |
|
| 181 |
+
model = HfApiModel(
|
| 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 |
+
# Load image generation tool from Hub
|
| 189 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 190 |
|
|
|
|
| 191 |
with open("prompts.yaml", 'r') as stream:
|
| 192 |
prompt_templates = yaml.safe_load(stream)
|
| 193 |
+
|
| 194 |
agent = CodeAgent(
|
| 195 |
model=model,
|
| 196 |
tools=[
|
| 197 |
final_answer,
|
| 198 |
+
web_search,
|
| 199 |
+
get_current_time_in_timezone,
|
| 200 |
calculate,
|
| 201 |
+
get_weather,
|
| 202 |
+
read_file,
|
| 203 |
+
write_file,
|
| 204 |
convert_currency,
|
| 205 |
+
get_wikipedia_summary,
|
| 206 |
+
list_common_timezones,
|
| 207 |
+
image_generation_tool,
|
|
|
|
|
|
|
|
|
|
| 208 |
],
|
| 209 |
max_steps=6,
|
| 210 |
verbosity_level=1,
|