acb-code/AlfredAgent
0
1from typing import Any, Optional2from smolagents.tools import Tool3import requests4import smolagents5import markdownify6import re7 8class VisitWebpageTool(Tool):9 name = "visit_webpage"10 description = "Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."11 inputs = {'url': {'type': 'string', 'description': 'The url of the webpage to visit.'}}12 output_type = "string"13 14 def forward(self, url: str) -> str:15 try:16 import re17 18 import requests19 from markdownify import markdownify20 from requests.exceptions import RequestException21 22 from smolagents.utils import truncate_content23 except ImportError as e:24 raise ImportError(25 "You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."26 ) from e27 try:28 # Send a GET request to the URL with a 20-second timeout29 response = requests.get(url, timeout=20)30 response.raise_for_status() # Raise an exception for bad status codes31 32 # Convert the HTML content to Markdown33 markdown_content = markdownify(response.text).strip()34 35 # Remove multiple line breaks36 markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)37 38 return truncate_content(markdown_content, 10000)39 40 except requests.exceptions.Timeout:41 return "The request timed out. Please try again later or check the URL."42 except RequestException as e:43 return f"Error fetching the webpage: {str(e)}"44 except Exception as e:45 return f"An unexpected error occurred: {str(e)}"46 47 def __init__(self, *args, **kwargs):48 self.is_initialized = False49 