Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,23 +1,13 @@
|
|
| 1 |
-
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
|
| 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 |
-
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
| 11 |
-
@tool
|
| 12 |
-
def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
|
| 13 |
-
#Keep this format for the description / args / args description but feel free to modify the tool
|
| 14 |
-
"""A tool that does nothing yet
|
| 15 |
-
Args:
|
| 16 |
-
arg1: the first argument
|
| 17 |
-
arg2: the second argument
|
| 18 |
-
"""
|
| 19 |
-
return "What magic will you build ?"
|
| 20 |
|
|
|
|
| 21 |
@tool
|
| 22 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 23 |
"""A tool that fetches the current local time in a specified timezone.
|
|
@@ -25,45 +15,150 @@ 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
model = HfApiModel(
|
| 43 |
-
max_tokens=2096,
|
| 44 |
-
temperature=0.5,
|
| 45 |
-
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
|
| 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,
|
| 62 |
planning_interval=None,
|
| 63 |
name=None,
|
| 64 |
description=None,
|
| 65 |
-
prompt_templates=prompt_templates
|
| 66 |
)
|
| 67 |
|
| 68 |
-
|
| 69 |
GradioUI(agent).launch()
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, 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 |
|
| 10 |
+
# ── Tool 1: Timezone checker ──────────────────────────────────────────────────
|
| 11 |
@tool
|
| 12 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 13 |
"""A tool that fetches the current local time in a specified timezone.
|
|
|
|
| 15 |
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
| 16 |
"""
|
| 17 |
try:
|
|
|
|
| 18 |
tz = pytz.timezone(timezone)
|
|
|
|
| 19 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 20 |
return f"The current local time in {timezone} is: {local_time}"
|
| 21 |
except Exception as e:
|
| 22 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 23 |
|
| 24 |
|
| 25 |
+
# ── Tool 2: Weather checker ───────────────────────────────────────────────────
|
| 26 |
+
@tool
|
| 27 |
+
def get_weather(city: str) -> str:
|
| 28 |
+
"""Fetches the current weather for a given city using the Open-Meteo API.
|
| 29 |
+
Args:
|
| 30 |
+
city: The name of the city to get weather for (e.g., 'London').
|
| 31 |
+
"""
|
| 32 |
+
try:
|
| 33 |
+
# Step 1: Geocode the city name to lat/lon
|
| 34 |
+
geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1"
|
| 35 |
+
geo_resp = requests.get(geo_url, timeout=10).json()
|
| 36 |
+
if not geo_resp.get("results"):
|
| 37 |
+
return f"Could not find location for city: {city}"
|
| 38 |
+
loc = geo_resp["results"][0]
|
| 39 |
+
lat, lon, name = loc["latitude"], loc["longitude"], loc["name"]
|
| 40 |
+
|
| 41 |
+
# Step 2: Fetch weather
|
| 42 |
+
weather_url = (
|
| 43 |
+
f"https://api.open-meteo.com/v1/forecast"
|
| 44 |
+
f"?latitude={lat}&longitude={lon}"
|
| 45 |
+
f"¤t_weather=true&hourly=relative_humidity_2m"
|
| 46 |
+
)
|
| 47 |
+
weather_resp = requests.get(weather_url, timeout=10).json()
|
| 48 |
+
cw = weather_resp.get("current_weather", {})
|
| 49 |
+
temp = cw.get("temperature", "N/A")
|
| 50 |
+
wind = cw.get("windspeed", "N/A")
|
| 51 |
+
code = cw.get("weathercode", "N/A")
|
| 52 |
+
return (
|
| 53 |
+
f"Weather in {name}:\n"
|
| 54 |
+
f" Temperature : {temp} °C\n"
|
| 55 |
+
f" Wind speed : {wind} km/h\n"
|
| 56 |
+
f" Weather code: {code} (WMO standard)"
|
| 57 |
+
)
|
| 58 |
+
except Exception as e:
|
| 59 |
+
return f"Error fetching weather: {str(e)}"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ── Tool 3: Unit converter ────────────────────────────────────────────────────
|
| 63 |
+
@tool
|
| 64 |
+
def convert_units(value: float, from_unit: str, to_unit: str) -> str:
|
| 65 |
+
"""Converts a value between common units (length, weight, temperature).
|
| 66 |
+
Args:
|
| 67 |
+
value: The numeric value to convert.
|
| 68 |
+
from_unit: The source unit (e.g., 'km', 'kg', 'celsius', 'miles', 'pounds', 'fahrenheit').
|
| 69 |
+
to_unit: The target unit (e.g., 'miles', 'pounds', 'fahrenheit').
|
| 70 |
+
"""
|
| 71 |
+
conversions = {
|
| 72 |
+
("km", "miles"): lambda x: x * 0.621371,
|
| 73 |
+
("miles", "km"): lambda x: x * 1.60934,
|
| 74 |
+
("kg", "pounds"): lambda x: x * 2.20462,
|
| 75 |
+
("pounds", "kg"): lambda x: x * 0.453592,
|
| 76 |
+
("meters", "feet"): lambda x: x * 3.28084,
|
| 77 |
+
("feet", "meters"): lambda x: x * 0.3048,
|
| 78 |
+
("celsius", "fahrenheit"): lambda x: x * 9 / 5 + 32,
|
| 79 |
+
("fahrenheit", "celsius"): lambda x: (x - 32) * 5 / 9,
|
| 80 |
+
("celsius", "kelvin"): lambda x: x + 273.15,
|
| 81 |
+
("kelvin", "celsius"): lambda x: x - 273.15,
|
| 82 |
+
("liters", "gallons"): lambda x: x * 0.264172,
|
| 83 |
+
("gallons", "liters"): lambda x: x * 3.78541,
|
| 84 |
+
}
|
| 85 |
+
key = (from_unit.lower(), to_unit.lower())
|
| 86 |
+
if key in conversions:
|
| 87 |
+
result = conversions[key](value)
|
| 88 |
+
return f"{value} {from_unit} = {round(result, 4)} {to_unit}"
|
| 89 |
+
return f"Conversion from '{from_unit}' to '{to_unit}' is not supported."
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# ── Tool 4: Day-of-week calculator ───────────────────────────────────────────
|
| 93 |
+
@tool
|
| 94 |
+
def get_day_of_week(date_str: str) -> str:
|
| 95 |
+
"""Returns the day of the week for a given date.
|
| 96 |
+
Args:
|
| 97 |
+
date_str: A date string in YYYY-MM-DD format (e.g., '2025-12-25').
|
| 98 |
+
"""
|
| 99 |
+
try:
|
| 100 |
+
date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d")
|
| 101 |
+
day_name = date_obj.strftime("%A")
|
| 102 |
+
return f"{date_str} falls on a {day_name}."
|
| 103 |
+
except ValueError:
|
| 104 |
+
return "Invalid date format. Please use YYYY-MM-DD (e.g., '2025-07-04')."
|
| 105 |
|
| 106 |
+
|
| 107 |
+
# ── Tool 5: Random joke fetcher ───────────────────────────────────────────────
|
| 108 |
+
@tool
|
| 109 |
+
def get_random_joke(category: str) -> str:
|
| 110 |
+
"""Fetches a random joke from the JokeAPI.
|
| 111 |
+
Args:
|
| 112 |
+
category: Joke category — one of 'Programming', 'Misc', 'Dark', 'Pun', 'Spooky', 'Christmas'.
|
| 113 |
+
"""
|
| 114 |
+
try:
|
| 115 |
+
url = f"https://v2.jokeapi.dev/joke/{category}?blacklistFlags=nsfw,racist,sexist"
|
| 116 |
+
resp = requests.get(url, timeout=10).json()
|
| 117 |
+
if resp.get("type") == "single":
|
| 118 |
+
return resp["joke"]
|
| 119 |
+
elif resp.get("type") == "twopart":
|
| 120 |
+
return f"{resp['setup']}\n... {resp['delivery']}"
|
| 121 |
+
return "Couldn't fetch a joke right now."
|
| 122 |
+
except Exception as e:
|
| 123 |
+
return f"Error fetching joke: {str(e)}"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# ── Model & agent setup ───────────────────────────────────────────────────────
|
| 127 |
+
final_answer = FinalAnswerTool()
|
| 128 |
|
| 129 |
model = HfApiModel(
|
| 130 |
+
max_tokens=2096,
|
| 131 |
+
temperature=0.5,
|
| 132 |
+
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
|
| 133 |
+
custom_role_conversions=None,
|
| 134 |
)
|
| 135 |
|
| 136 |
+
# Load image generation tool from the Hub
|
|
|
|
| 137 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 138 |
|
| 139 |
+
# Load system prompt
|
| 140 |
with open("prompts.yaml", 'r') as stream:
|
| 141 |
prompt_templates = yaml.safe_load(stream)
|
| 142 |
+
|
| 143 |
agent = CodeAgent(
|
| 144 |
model=model,
|
| 145 |
+
tools=[
|
| 146 |
+
final_answer,
|
| 147 |
+
DuckDuckGoSearchTool(), # Web search
|
| 148 |
+
image_generation_tool, # Text-to-image
|
| 149 |
+
get_current_time_in_timezone, # Timezone lookup
|
| 150 |
+
get_weather, # Live weather
|
| 151 |
+
convert_units, # Unit converter
|
| 152 |
+
get_day_of_week, # Date → weekday
|
| 153 |
+
get_random_joke, # Joke fetcher
|
| 154 |
+
],
|
| 155 |
max_steps=6,
|
| 156 |
verbosity_level=1,
|
| 157 |
grammar=None,
|
| 158 |
planning_interval=None,
|
| 159 |
name=None,
|
| 160 |
description=None,
|
| 161 |
+
prompt_templates=prompt_templates,
|
| 162 |
)
|
| 163 |
|
|
|
|
| 164 |
GradioUI(agent).launch()
|