Spaces:
Sleeping
Sleeping
Update app.py
Browse filesadded custom web search has a tool
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
|
| 2 |
from smolagents import (
|
| 3 |
CodeAgent,
|
| 4 |
DuckDuckGoSearchTool,
|
|
@@ -11,6 +10,7 @@ import datetime
|
|
| 11 |
import requests
|
| 12 |
import pytz
|
| 13 |
import yaml
|
|
|
|
| 14 |
from tools.final_answer import FinalAnswerTool
|
| 15 |
|
| 16 |
from Gradio_UI import GradioUI
|
|
@@ -26,7 +26,6 @@ def get_weather(city: str) -> str:
|
|
| 26 |
city: the name of the city (e.g. 'Paris', 'New York').
|
| 27 |
"""
|
| 28 |
try:
|
| 29 |
-
# 1) Geocode the city name into lat/lon
|
| 30 |
geo = requests.get(
|
| 31 |
"https://geocoding-api.open-meteo.com/v1/search",
|
| 32 |
params={"name": city, "count": 1, "language": "en", "format": "json"},
|
|
@@ -37,7 +36,6 @@ def get_weather(city: str) -> str:
|
|
| 37 |
loc = geo["results"][0]
|
| 38 |
lat, lon = loc["latitude"], loc["longitude"]
|
| 39 |
|
| 40 |
-
# 2) Fetch current weather at that location
|
| 41 |
weather = requests.get(
|
| 42 |
"https://api.open-meteo.com/v1/forecast",
|
| 43 |
params={
|
|
@@ -54,7 +52,6 @@ def get_weather(city: str) -> str:
|
|
| 54 |
windspeed = cur.get("windspeed")
|
| 55 |
wmo = cur.get("weathercode", 0)
|
| 56 |
|
| 57 |
-
# Map WMO weather codes to readable descriptions
|
| 58 |
descriptions = {
|
| 59 |
0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast",
|
| 60 |
45: "fog", 48: "depositing rime fog",
|
|
@@ -106,7 +103,7 @@ def convert_currency(amount: float, from_currency: str, to_currency: str) -> str
|
|
| 106 |
|
| 107 |
|
| 108 |
# ---------------------------------------------------------------------------
|
| 109 |
-
#
|
| 110 |
# ---------------------------------------------------------------------------
|
| 111 |
@tool
|
| 112 |
def get_current_time_in_timezone(timezone: str) -> str:
|
|
@@ -122,19 +119,78 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 122 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 123 |
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
final_answer = FinalAnswerTool()
|
| 126 |
|
| 127 |
-
# If the agent does not answer, the model is overloaded, please use another model
|
|
|
|
| 128 |
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
|
| 129 |
|
| 130 |
model = HfApiModel(
|
| 131 |
max_tokens=2096,
|
| 132 |
temperature=0.5,
|
| 133 |
-
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
|
| 134 |
custom_role_conversions=None,
|
| 135 |
)
|
| 136 |
|
| 137 |
-
|
| 138 |
# Import tool from Hub
|
| 139 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 140 |
|
|
@@ -144,13 +200,14 @@ with open("prompts.yaml", 'r') as stream:
|
|
| 144 |
agent = CodeAgent(
|
| 145 |
model=model,
|
| 146 |
tools=[
|
| 147 |
-
final_answer,
|
| 148 |
-
DuckDuckGoSearchTool(),
|
| 149 |
-
VisitWebpageTool(),
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
| 154 |
],
|
| 155 |
max_steps=6,
|
| 156 |
verbosity_level=1,
|
|
@@ -162,4 +219,4 @@ agent = CodeAgent(
|
|
| 162 |
)
|
| 163 |
|
| 164 |
|
| 165 |
-
GradioUI(agent).launch()
|
|
|
|
|
|
|
| 1 |
from smolagents import (
|
| 2 |
CodeAgent,
|
| 3 |
DuckDuckGoSearchTool,
|
|
|
|
| 10 |
import requests
|
| 11 |
import pytz
|
| 12 |
import yaml
|
| 13 |
+
from bs4 import BeautifulSoup
|
| 14 |
from tools.final_answer import FinalAnswerTool
|
| 15 |
|
| 16 |
from Gradio_UI import GradioUI
|
|
|
|
| 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 |
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 |
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",
|
|
|
|
| 103 |
|
| 104 |
|
| 105 |
# ---------------------------------------------------------------------------
|
| 106 |
+
# Custom tool 3: Current time in a timezone
|
| 107 |
# ---------------------------------------------------------------------------
|
| 108 |
@tool
|
| 109 |
def get_current_time_in_timezone(timezone: str) -> str:
|
|
|
|
| 119 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 120 |
|
| 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, max_chars: int = 4000) -> str:
|
| 128 |
+
"""Fetch a web page and return its main readable text content.
|
| 129 |
+
Use this after a web search to read the full content of a result.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
url: The full URL of the page to read (must start with http:// or https://).
|
| 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 |
+
if not url.startswith(("http://", "https://")):
|
| 145 |
+
url = "https://" + url
|
| 146 |
+
|
| 147 |
+
resp = requests.get(url, headers=headers, timeout=20)
|
| 148 |
+
resp.raise_for_status()
|
| 149 |
+
content_type = resp.headers.get("Content-Type", "")
|
| 150 |
+
|
| 151 |
+
if "application/json" in content_type:
|
| 152 |
+
return resp.text[:max_chars]
|
| 153 |
+
if "text/plain" in content_type:
|
| 154 |
+
return resp.text[:max_chars]
|
| 155 |
+
|
| 156 |
+
soup = BeautifulSoup(resp.text, "html.parser")
|
| 157 |
+
|
| 158 |
+
# Strip noise
|
| 159 |
+
for tag in soup(["script", "style", "noscript", "header",
|
| 160 |
+
"footer", "nav", "aside", "form", "iframe"]):
|
| 161 |
+
tag.decompose()
|
| 162 |
+
|
| 163 |
+
# Prefer <main> / <article> if present
|
| 164 |
+
main = soup.find("main") or soup.find("article") or soup.body or soup
|
| 165 |
+
|
| 166 |
+
text = main.get_text(separator="\n", strip=True)
|
| 167 |
+
|
| 168 |
+
# Collapse blank lines
|
| 169 |
+
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
|
| 170 |
+
cleaned = "\n".join(lines)
|
| 171 |
+
|
| 172 |
+
if len(cleaned) > max_chars:
|
| 173 |
+
cleaned = cleaned[:max_chars] + "\n\n[...truncated...]"
|
| 174 |
+
|
| 175 |
+
title = soup.title.string.strip() if soup.title and soup.title.string else url
|
| 176 |
+
return f"# {title}\nSource: {url}\n\n{cleaned}"
|
| 177 |
+
except Exception as e:
|
| 178 |
+
return f"Error browsing '{url}': {str(e)}"
|
| 179 |
+
|
| 180 |
+
|
| 181 |
final_answer = FinalAnswerTool()
|
| 182 |
|
| 183 |
+
# If the agent does not answer, the model is overloaded, please use another model
|
| 184 |
+
# or the following Hugging Face Endpoint that also contains qwen2.5 coder:
|
| 185 |
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
|
| 186 |
|
| 187 |
model = HfApiModel(
|
| 188 |
max_tokens=2096,
|
| 189 |
temperature=0.5,
|
| 190 |
+
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
|
| 191 |
custom_role_conversions=None,
|
| 192 |
)
|
| 193 |
|
|
|
|
| 194 |
# Import tool from Hub
|
| 195 |
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 196 |
|
|
|
|
| 200 |
agent = CodeAgent(
|
| 201 |
model=model,
|
| 202 |
tools=[
|
| 203 |
+
final_answer, # don't remove
|
| 204 |
+
DuckDuckGoSearchTool(), # 🔍 search the web
|
| 205 |
+
VisitWebpageTool(), # (kept as a fallback)
|
| 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=6,
|
| 213 |
verbosity_level=1,
|
|
|
|
| 219 |
)
|
| 220 |
|
| 221 |
|
| 222 |
+
GradioUI(agent).launch()
|