CoolFace
Apppublic

flutterdev555/mymodel

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
visit_webpage.py49 linesDownload Raw Back to tools
1from typing import Any, Optional2import re3from smolagents.tools import Tool4import requests5import markdownify6import smolagents7 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 requests17            from markdownify import markdownify18            from requests.exceptions import RequestException19 20            from smolagents.utils import truncate_content21        except ImportError as e:22            raise ImportError(23                "You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."24            ) from e25        try:26            # Send a GET request to the URL with a 20-second timeout27            response = requests.get(url, timeout=20, headers={28                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"29            })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