Update app.py
Browse filesadded custom web search has a tool
12346 unmodified lines1112131415169 unmodified lines262728293031324 unmodified lines3738394041424310 unmodified lines5455565758596045 unmodified lines1061071081091101111129 unmodified lines1221231241251261271281291301311321331341351361371381391403 unmodified lines1441451461471481491501511521531541551565 unmodified lines162163164165from smolagents import (CodeAgent,DuckDuckGoSearchTool,6 unmodified linesimport requestsimport pytzimport yamlfrom tools.final_answer import FinalAnswerToolfrom Gradio_UI import GradioUI9 unmodified linescity: the name of the city (e.g. 'Paris', 'New York')."""try:# 1) Geocode the city name into lat/longeo = requests.get("https://geocoding-api.open-meteo.com/v1/search",params={"name": city, "count": 1, "language": "en", "format": "json"},4 unmodified linesloc = geo["results"][0]lat, lon = loc["latitude"], loc["longitude"]# 2) Fetch current weather at that locationweather = requests.get("https://api.open-meteo.com/v1/forecast",params={10 unmodified lineswindspeed = cur.get("windspeed")wmo = cur.get("weathercode", 0)# Map WMO weather codes to readable descriptionsdescriptions = {0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast",45: "fog", 48: "depositing rime fog",45 unmodified lines# ---------------------------------------------------------------------------# Existing tools# ---------------------------------------------------------------------------@tooldef get_current_time_in_timezone(timezone: str) -> str:9 unmodified linesreturn f"Error fetching time for timezone '{timezone}': {str(e)}"final_answer = FinalAnswerTool()# 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 overloadedcustom_role_conversions=None,)# Import tool from Hubimage_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)3 unmodified linesagent = CodeAgent(model=model,tools=[final_answer, # don't removeDuckDuckGoSearchTool(), # web search (was imported but never added!)VisitWebpageTool(), # read the pages the search findsimage_generation_tool, # text-to-image (was loaded but never added!)get_current_time_in_timezone, # current local time in any timezoneget_weather, # real-time weather by cityconvert_currency, # currency conversion],max_steps=6,verbosity_level=1,5 unmodified lines)GradioUI(agent).launch()1236 unmodified lines101112131415169 unmodified lines2627282930314 unmodified lines36373839404110 unmodified lines52535455565745 unmodified lines1031041051061071081099 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951963 unmodified lines2002012022032042052062072082092102112122135 unmodified lines219220221222from smolagents import (CodeAgent,DuckDuckGoSearchTool,6 unmodified linesimport requestsimport pytzimport yamlfrom bs4 import BeautifulSoupfrom tools.final_answer import FinalAnswerToolfrom Gradio_UI import GradioUI9 unmodified linescity: the name of the city (e.g. 'Paris', 'New York')."""try:geo = requests.get("https://geocoding-api.open-meteo.com/v1/search",params={"name": city, "count": 1, "language": "en", "format": "json"},4 unmodified linesloc = geo["results"][0]lat, lon = loc["latitude"], loc["longitude"]weather = requests.get("https://api.open-meteo.com/v1/forecast",params={10 unmodified lineswindspeed = cur.get("windspeed")wmo = cur.get("weathercode", 0)descriptions = {0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast",45: "fog", 48: "depositing rime fog",45 unmodified lines# ---------------------------------------------------------------------------# Custom tool 3: Current time in a timezone# ---------------------------------------------------------------------------@tooldef get_current_time_in_timezone(timezone: str) -> str:9 unmodified linesreturn f"Error fetching time for timezone '{timezone}': {str(e)}"# ---------------------------------------------------------------------------# Custom tool 4: Browse a webpage and return readable text# (A robust replacement / companion for VisitWebpageTool)# ---------------------------------------------------------------------------@tooldef browse_webpage(url: str, max_chars: int = 4000) -> str:"""Fetch a web page and return its main readable text content.Use this after a web search to read the full content of a result.Args:url: The full URL of the page to read (must start with http:// or https://).max_chars: Maximum number of characters to return (default 4000)."""headers = {"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) ""Chrome/122.0.0.0 Safari/537.36"),"Accept-Language": "en-US,en;q=0.9",}try:if not url.startswith(("http://", "https://")):url = "https://" + urlresp = requests.get(url, headers=headers, timeout=20)resp.raise_for_status()content_type = resp.headers.get("Content-Type", "")if "application/json" in content_type:return resp.text[:max_chars]if "text/plain" in content_type:return resp.text[:max_chars]soup = BeautifulSoup(resp.text, "html.parser")# Strip noisefor tag in soup(["script", "style", "noscript", "header","footer", "nav", "aside", "form", "iframe"]):tag.decompose()# Prefer <main> / <article> if presentmain = soup.find("main") or soup.find("article") or soup.body or souptext = main.get_text(separator="\n", strip=True)# Collapse blank lineslines = [ln.strip() for ln in text.splitlines() if ln.strip()]cleaned = "\n".join(lines)if len(cleaned) > max_chars:cleaned = cleaned[:max_chars] + "\n\n[...truncated...]"title = soup.title.string.strip() if soup.title and soup.title.string else urlreturn f"# {title}\nSource: {url}\n\n{cleaned}"except Exception as e:return f"Error browsing '{url}': {str(e)}"final_answer = FinalAnswerTool()# 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',custom_role_conversions=None,)# Import tool from Hubimage_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)3 unmodified linesagent = CodeAgent(model=model,tools=[final_answer, # don't removeDuckDuckGoSearchTool(), # 🔍 search the webVisitWebpageTool(), # (kept as a fallback)browse_webpage, # 🌐 custom: read any page cleanlyimage_generation_tool, # 🎨 text-to-imageget_current_time_in_timezone, # 🕒 current time in any timezoneget_weather, # 🌤️ real-time weatherconvert_currency, # 💱 currency conversion],max_steps=6,verbosity_level=1,5 unmodified lines)GradioUI(agent).launch()
app.py+73-16