Spaces:
Sleeping
Sleeping
Update app.py
Browse filesUpdated the browser tool
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
from smolagents import (
|
| 2 |
CodeAgent,
|
| 3 |
DuckDuckGoSearchTool,
|
| 4 |
-
VisitWebpageTool,
|
| 5 |
HfApiModel,
|
| 6 |
load_tool,
|
| 7 |
tool,
|
|
@@ -26,6 +25,7 @@ def get_weather(city: str) -> str:
|
|
| 26 |
city: the name of the city (e.g. 'Paris', 'New York').
|
| 27 |
"""
|
| 28 |
try:
|
|
|
|
| 29 |
geo = requests.get(
|
| 30 |
"https://geocoding-api.open-meteo.com/v1/search",
|
| 31 |
params={"name": city, "count": 1, "language": "en", "format": "json"},
|
|
@@ -36,6 +36,7 @@ def get_weather(city: str) -> str:
|
|
| 36 |
loc = geo["results"][0]
|
| 37 |
lat, lon = loc["latitude"], loc["longitude"]
|
| 38 |
|
|
|
|
| 39 |
weather = requests.get(
|
| 40 |
"https://api.open-meteo.com/v1/forecast",
|
| 41 |
params={
|
|
@@ -52,6 +53,7 @@ def get_weather(city: str) -> str:
|
|
| 52 |
windspeed = cur.get("windspeed")
|
| 53 |
wmo = cur.get("weathercode", 0)
|
| 54 |
|
|
|
|
| 55 |
descriptions = {
|
| 56 |
0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast",
|
| 57 |
45: "fog", 48: "depositing rime fog",
|
|
@@ -121,61 +123,101 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 121 |
|
| 122 |
# ---------------------------------------------------------------------------
|
| 123 |
# Custom tool 4: Browse a webpage and return readable text
|
| 124 |
-
# (A robust replacement / companion for VisitWebpageTool)
|
| 125 |
# ---------------------------------------------------------------------------
|
| 126 |
@tool
|
| 127 |
-
def browse_webpage(url: str
|
| 128 |
-
"""Fetch a web page and return its
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
Args:
|
| 132 |
-
url: The full URL of the page to read
|
| 133 |
-
max_chars: Maximum number of characters to return (default 4000).
|
| 134 |
"""
|
|
|
|
|
|
|
| 135 |
headers = {
|
| 136 |
"User-Agent": (
|
| 137 |
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 138 |
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 139 |
"Chrome/122.0.0.0 Safari/537.36"
|
| 140 |
),
|
|
|
|
| 141 |
"Accept-Language": "en-US,en;q=0.9",
|
| 142 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
try:
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
|
| 148 |
-
resp.raise_for_status()
|
| 149 |
-
content_type = resp.headers.get("Content-Type", "")
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
| 155 |
|
|
|
|
|
|
|
| 156 |
soup = BeautifulSoup(resp.text, "html.parser")
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
tag.decompose()
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
-
|
| 167 |
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
|
| 180 |
|
| 181 |
final_answer = FinalAnswerTool()
|
|
@@ -202,15 +244,14 @@ agent = CodeAgent(
|
|
| 202 |
tools=[
|
| 203 |
final_answer, # don't remove
|
| 204 |
DuckDuckGoSearchTool(), # 🔍 search the web
|
| 205 |
-
|
| 206 |
-
browse_webpage, # 🌐 custom: read any page cleanly
|
| 207 |
image_generation_tool, # 🎨 text-to-image
|
| 208 |
get_current_time_in_timezone, # 🕒 current time in any timezone
|
| 209 |
get_weather, # 🌤️ real-time weather
|
| 210 |
convert_currency, # 💱 currency conversion
|
| 211 |
],
|
| 212 |
-
max_steps=
|
| 213 |
-
verbosity_level=
|
| 214 |
grammar=None,
|
| 215 |
planning_interval=None,
|
| 216 |
name=None,
|
|
|
|
| 1 |
from smolagents import (
|
| 2 |
CodeAgent,
|
| 3 |
DuckDuckGoSearchTool,
|
|
|
|
| 4 |
HfApiModel,
|
| 5 |
load_tool,
|
| 6 |
tool,
|
|
|
|
| 25 |
city: the name of the city (e.g. 'Paris', 'New York').
|
| 26 |
"""
|
| 27 |
try:
|
| 28 |
+
# 1) Geocode the city name into lat/lon
|
| 29 |
geo = requests.get(
|
| 30 |
"https://geocoding-api.open-meteo.com/v1/search",
|
| 31 |
params={"name": city, "count": 1, "language": "en", "format": "json"},
|
|
|
|
| 36 |
loc = geo["results"][0]
|
| 37 |
lat, lon = loc["latitude"], loc["longitude"]
|
| 38 |
|
| 39 |
+
# 2) Fetch current weather at that location
|
| 40 |
weather = requests.get(
|
| 41 |
"https://api.open-meteo.com/v1/forecast",
|
| 42 |
params={
|
|
|
|
| 53 |
windspeed = cur.get("windspeed")
|
| 54 |
wmo = cur.get("weathercode", 0)
|
| 55 |
|
| 56 |
+
# Map WMO weather codes to readable descriptions
|
| 57 |
descriptions = {
|
| 58 |
0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast",
|
| 59 |
45: "fog", 48: "depositing rime fog",
|
|
|
|
| 123 |
|
| 124 |
# ---------------------------------------------------------------------------
|
| 125 |
# Custom tool 4: Browse a webpage and return readable text
|
|
|
|
| 126 |
# ---------------------------------------------------------------------------
|
| 127 |
@tool
|
| 128 |
+
def browse_webpage(url: str) -> str:
|
| 129 |
+
"""Fetch a web page and return its readable text content.
|
| 130 |
+
|
| 131 |
+
Use this tool AFTER a web search to read the full content of a specific
|
| 132 |
+
result URL. Returns the page title plus its main article text, with
|
| 133 |
+
scripts, navigation, ads, and footers stripped out.
|
| 134 |
|
| 135 |
Args:
|
| 136 |
+
url: The full URL of the web page to read, starting with http:// or https://.
|
|
|
|
| 137 |
"""
|
| 138 |
+
MAX_CHARS = 5000 # hardcoded — avoids confusing the tool schema
|
| 139 |
+
|
| 140 |
headers = {
|
| 141 |
"User-Agent": (
|
| 142 |
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
| 143 |
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
| 144 |
"Chrome/122.0.0.0 Safari/537.36"
|
| 145 |
),
|
| 146 |
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
| 147 |
"Accept-Language": "en-US,en;q=0.9",
|
| 148 |
}
|
| 149 |
+
|
| 150 |
+
if not url.startswith(("http://", "https://")):
|
| 151 |
+
url = "https://" + url
|
| 152 |
+
|
| 153 |
+
# --- Network request ---------------------------------------------------
|
| 154 |
try:
|
| 155 |
+
resp = requests.get(url, headers=headers, timeout=20, allow_redirects=True)
|
| 156 |
+
except requests.exceptions.Timeout:
|
| 157 |
+
return f"Error: request to '{url}' timed out."
|
| 158 |
+
except requests.exceptions.RequestException as e:
|
| 159 |
+
return f"Error: could not reach '{url}': {e}"
|
| 160 |
+
|
| 161 |
+
if resp.status_code != 200:
|
| 162 |
+
return (
|
| 163 |
+
f"Error: '{url}' returned HTTP {resp.status_code}. "
|
| 164 |
+
f"The site may be blocking automated access — try a different URL."
|
| 165 |
+
)
|
| 166 |
|
| 167 |
+
content_type = resp.headers.get("Content-Type", "").lower()
|
|
|
|
|
|
|
| 168 |
|
| 169 |
+
# Plain text / JSON endpoints
|
| 170 |
+
if "json" in content_type or "text/plain" in content_type:
|
| 171 |
+
text = resp.text
|
| 172 |
+
if len(text) > MAX_CHARS:
|
| 173 |
+
text = text[:MAX_CHARS] + "\n\n[...truncated...]"
|
| 174 |
+
return f"Source: {url}\n\n{text}"
|
| 175 |
|
| 176 |
+
# --- Parse HTML --------------------------------------------------------
|
| 177 |
+
try:
|
| 178 |
soup = BeautifulSoup(resp.text, "html.parser")
|
| 179 |
+
except Exception as e:
|
| 180 |
+
return f"Error parsing HTML from '{url}': {e}"
|
| 181 |
+
|
| 182 |
+
# Title (safe: get_text() never raises on nested tags)
|
| 183 |
+
title = url
|
| 184 |
+
if soup.title is not None:
|
| 185 |
+
title_text = soup.title.get_text(strip=True)
|
| 186 |
+
if title_text:
|
| 187 |
+
title = title_text
|
| 188 |
+
|
| 189 |
+
# Strip noise
|
| 190 |
+
for tag_name in (
|
| 191 |
+
"script", "style", "noscript", "header", "footer",
|
| 192 |
+
"nav", "aside", "form", "iframe", "svg", "button",
|
| 193 |
+
):
|
| 194 |
+
for tag in soup.find_all(tag_name):
|
| 195 |
tag.decompose()
|
| 196 |
|
| 197 |
+
# Prefer main content — explicit `is not None` checks (NOT `or`)
|
| 198 |
+
main = soup.find("main")
|
| 199 |
+
if main is None:
|
| 200 |
+
main = soup.find("article")
|
| 201 |
+
if main is None:
|
| 202 |
+
main = soup.find(id="content") or soup.find(class_="content")
|
| 203 |
+
if main is None:
|
| 204 |
+
main = soup.body
|
| 205 |
+
if main is None:
|
| 206 |
+
main = soup
|
| 207 |
|
| 208 |
+
text = main.get_text(separator="\n", strip=True)
|
| 209 |
|
| 210 |
+
# Collapse blank lines
|
| 211 |
+
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
|
| 212 |
+
cleaned = "\n".join(lines)
|
| 213 |
|
| 214 |
+
if not cleaned:
|
| 215 |
+
return f"Could not extract readable text from '{url}'."
|
| 216 |
|
| 217 |
+
if len(cleaned) > MAX_CHARS:
|
| 218 |
+
cleaned = cleaned[:MAX_CHARS] + "\n\n[...content truncated...]"
|
| 219 |
+
|
| 220 |
+
return f"# {title}\nSource: {url}\n\n{cleaned}"
|
| 221 |
|
| 222 |
|
| 223 |
final_answer = FinalAnswerTool()
|
|
|
|
| 244 |
tools=[
|
| 245 |
final_answer, # don't remove
|
| 246 |
DuckDuckGoSearchTool(), # 🔍 search the web
|
| 247 |
+
browse_webpage, # 🌐 read a result URL
|
|
|
|
| 248 |
image_generation_tool, # 🎨 text-to-image
|
| 249 |
get_current_time_in_timezone, # 🕒 current time in any timezone
|
| 250 |
get_weather, # 🌤️ real-time weather
|
| 251 |
convert_currency, # 💱 currency conversion
|
| 252 |
],
|
| 253 |
+
max_steps=10,
|
| 254 |
+
verbosity_level=2,
|
| 255 |
grammar=None,
|
| 256 |
planning_interval=None,
|
| 257 |
name=None,
|