Spaces:
Sleeping
Sleeping
File size: 7,060 Bytes
fbba536 9b5b26a c19d193 fbba536 9b5b26a fbba536 9b5b26a fbba536 9b5b26a fbba536 9b5b26a 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 9b5b26a fbba536 9b5b26a fbba536 9b5b26a fbba536 9b5b26a fbba536 9b5b26a fbba536 8c01ffb 6aae614 ae7a494 fbba536 5511e5c 13d500a 8c01ffb fbba536 9b5b26a 8c01ffb 861422e fbba536 8c01ffb 8fe992b 5511e5c fbba536 5511e5c fbba536 5511e5c fbba536 5511e5c 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 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
import json
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
# Web Search Tool
@tool
def web_search(query: str) -> str:
"""Search the web using DuckDuckGo for current information.
Args:
query: The search query string
"""
try:
search_tool = DuckDuckGoSearchTool()
results = search_tool(query)
return results
except Exception as e:
return f"Error performing web search: {str(e)}"
# Time and Date Tool
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""Get the current local time in a specified timezone.
Args:
timezone: A valid timezone string (e.g., 'America/New_York', 'Europe/London', 'Asia/Tokyo')
"""
try:
tz = pytz.timezone(timezone)
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S %Z")
return f"The current local time in {timezone} is: {local_time}"
except Exception as e:
return f"Error: Invalid timezone '{timezone}'. {str(e)}"
# Calculator Tool
@tool
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression safely.
Args:
expression: A mathematical expression as a string (e.g., '2 + 2', '10 * 5 + 3')
"""
try:
# Safe evaluation using only numbers and basic operators
allowed_chars = set('0123456789+-*/(). ')
if not all(c in allowed_chars for c in expression):
return "Error: Expression contains invalid characters"
result = eval(expression, {"__builtins__": {}}, {})
return f"Result: {result}"
except Exception as e:
return f"Error calculating expression: {str(e)}"
# Weather Tool
@tool
def get_weather(city: str) -> str:
"""Get current weather information for a city using wttr.in service.
Args:
city: Name of the city to get weather for
"""
try:
url = f"https://wttr.in/{city}?format=j1"
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
current = data['current_condition'][0]
temp_c = current['temp_C']
temp_f = current['temp_F']
weather_desc = current['weatherDesc'][0]['value']
humidity = current['humidity']
wind_speed = current['windspeedKmph']
return f"Weather in {city}: {weather_desc}, Temperature: {temp_c}°C ({temp_f}°F), Humidity: {humidity}%, Wind Speed: {wind_speed} km/h"
else:
return f"Could not fetch weather for {city}"
except Exception as e:
return f"Error fetching weather: {str(e)}"
# File Reader Tool
@tool
def read_file(filepath: str) -> str:
"""Read and return the contents of a text file.
Args:
filepath: Path to the file to read
"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
return f"File content:\n{content}"
except Exception as e:
return f"Error reading file: {str(e)}"
# File Writer Tool
@tool
def write_file(filepath: str, content: str) -> str:
"""Write content to a text file.
Args:
filepath: Path where the file should be written
content: Content to write to the file
"""
try:
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
return f"Successfully wrote to {filepath}"
except Exception as e:
return f"Error writing file: {str(e)}"
# Currency Converter Tool
@tool
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
"""Convert an amount from one currency to another using live exchange rates.
Args:
amount: The amount to convert
from_currency: The source currency code (e.g., 'USD', 'EUR', 'GBP')
to_currency: The target currency code (e.g., 'USD', 'EUR', 'GBP')
"""
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()}"
else:
return f"Currency code '{to_currency}' not found"
else:
return "Error fetching exchange rates"
except Exception as e:
return f"Error converting currency: {str(e)}"
# Wikipedia Summary Tool
@tool
def get_wikipedia_summary(topic: str) -> str:
"""Get a brief summary from Wikipedia about a topic.
Args:
topic: The topic to search for on Wikipedia
"""
try:
url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic.replace(' ', '_')}"
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
return f"Wikipedia Summary: {data.get('extract', 'No summary available')}"
else:
return f"Could not find Wikipedia article for '{topic}'"
except Exception as e:
return f"Error fetching Wikipedia summary: {str(e)}"
# List Available Timezones Tool
@tool
def list_common_timezones(region: str = "all") -> str:
"""List common timezones, optionally filtered by region.
Args:
region: Region to filter by (e.g., 'America', 'Europe', 'Asia', 'all')
"""
try:
if region.lower() == "all":
timezones = pytz.common_timezones[:20] # First 20 for brevity
return f"Common timezones (first 20): {', '.join(timezones)}"
else:
filtered = [tz for tz in pytz.common_timezones if tz.startswith(region)]
return f"Timezones in {region}: {', '.join(filtered[:30])}"
except Exception as e:
return f"Error listing timezones: {str(e)}"
final_answer = FinalAnswerTool()
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
# Load image generation 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,
web_search,
get_current_time_in_timezone,
calculate,
get_weather,
read_file,
write_file,
convert_currency,
get_wikipedia_summary,
list_common_timezones,
image_generation_tool,
],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch() |