Spaces:
Sleeping
Sleeping
File size: 6,044 Bytes
9b5b26a c19d193 949f50d 6aae614 949f50d 8fe992b 9b5b26a 949f50d 9b5b26a 949f50d 9b5b26a 949f50d 9b5b26a 8c01ffb 6aae614 949f50d ae7a494 e121372 bf6d34c 29ec968 fe328e0 13d500a 8c01ffb 9b5b26a 8c01ffb 861422e 9b5b26a 8c01ffb 8fe992b 949f50d 8c01ffb 861422e 8fe992b 9b5b26a 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 | 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 tools.visit_webpage import VisitWebpageTool
from tools.web_search import DuckDuckGoSearchTool as WebSearchTool
from Gradio_UI import GradioUI
@tool
def get_wikipedia_summary(topic: str) -> str:
"""Fetches a short summary from Wikipedia for a given topic.
Args:
topic: The topic to search for on Wikipedia (e.g., 'Python programming language').
"""
try:
url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + topic.replace(" ", "_")
response = requests.get(url, timeout=15)
if response.status_code == 200:
data = response.json()
title = data.get("title", topic)
extract = data.get("extract", "No summary available.")
page_url = data.get("content_urls", {}).get("desktop", {}).get("page", "")
return f"**{title}**\n\n{extract}\n\nRead more: {page_url}"
elif response.status_code == 404:
return f"No Wikipedia article found for '{topic}'. Try a different search term."
else:
return f"Error fetching Wikipedia summary (HTTP {response.status_code})."
except Exception as e:
return f"Error fetching Wikipedia summary for '{topic}': {str(e)}"
@tool
def get_random_fun_fact() -> str:
"""Fetches a random fun/useless fact from the uselessfacts API. No arguments needed.
"""
try:
response = requests.get("https://uselessfacts.jsph.pl/api/v2/facts/random", timeout=10)
if response.status_code == 200:
data = response.json()
return f"🎲 Fun fact: {data.get('text', 'No fact available.')}"
return "Could not fetch a fun fact right now. Try again later."
except Exception as e:
return f"Error fetching fun fact: {str(e)}"
@tool
def convert_units(value: float, from_unit: str, to_unit: str) -> str:
"""Converts a numeric value between common units of measurement.
Supports length (km, miles, m, ft, in, cm), weight (kg, lbs, g, oz),
and temperature (celsius, fahrenheit, kelvin).
Args:
value: The numeric value to convert.
from_unit: The unit to convert from (e.g., 'km', 'lbs', 'celsius').
to_unit: The unit to convert to (e.g., 'miles', 'kg', 'fahrenheit').
"""
conversions_to_base = {
# Length → meters
"km": ("length", lambda v: v * 1000),
"m": ("length", lambda v: v),
"cm": ("length", lambda v: v / 100),
"miles": ("length", lambda v: v * 1609.344),
"ft": ("length", lambda v: v * 0.3048),
"in": ("length", lambda v: v * 0.0254),
# Weight → grams
"kg": ("weight", lambda v: v * 1000),
"g": ("weight", lambda v: v),
"lbs": ("weight", lambda v: v * 453.592),
"oz": ("weight", lambda v: v * 28.3495),
# Temperature → celsius
"celsius": ("temp", lambda v: v),
"fahrenheit": ("temp", lambda v: (v - 32) * 5 / 9),
"kelvin": ("temp", lambda v: v - 273.15),
}
conversions_from_base = {
"km": lambda v: v / 1000, "m": lambda v: v, "cm": lambda v: v * 100,
"miles": lambda v: v / 1609.344, "ft": lambda v: v / 0.3048, "in": lambda v: v / 0.0254,
"kg": lambda v: v / 1000, "g": lambda v: v, "lbs": lambda v: v / 453.592, "oz": lambda v: v / 28.3495,
"celsius": lambda v: v, "fahrenheit": lambda v: v * 9 / 5 + 32, "kelvin": lambda v: v + 273.15,
}
fu = from_unit.lower().strip()
tu = to_unit.lower().strip()
if fu not in conversions_to_base or tu not in conversions_from_base:
return f"Unsupported unit(s): '{from_unit}' or '{to_unit}'. Supported: {list(conversions_to_base.keys())}"
cat_from, to_base = conversions_to_base[fu]
cat_to, _ = conversions_to_base[tu]
if cat_from != cat_to:
return f"Cannot convert between '{from_unit}' ({cat_from}) and '{to_unit}' ({cat_to}). Units must be in the same category."
base_value = to_base(value)
result = conversions_from_base[tu](base_value)
return f"{value} {from_unit} = {result:.4f} {to_unit}"
@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:
# Create timezone object
tz = pytz.timezone(timezone)
# Get current time in that 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)}"
final_answer = FinalAnswerTool()
web_search = WebSearchTool()
visit_webpage = VisitWebpageTool()
# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
custom_role_conversions=None,
)
# Import 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,
visit_webpage,
get_current_time_in_timezone,
get_wikipedia_summary,
get_random_fun_fact,
convert_units,
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() |