Spaces:
Paused
Paused
Create tools.py
Browse files
tools.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class VisitWebpageTool(Tool):
|
| 2 |
+
name = "visit_webpage"
|
| 3 |
+
description = (
|
| 4 |
+
"Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."
|
| 5 |
+
)
|
| 6 |
+
inputs = {
|
| 7 |
+
"url": {
|
| 8 |
+
"type": "string",
|
| 9 |
+
"description": "The url of the webpage to visit.",
|
| 10 |
+
}
|
| 11 |
+
}
|
| 12 |
+
output_type = "string"
|
| 13 |
+
|
| 14 |
+
def forward(self, url: str) -> str:
|
| 15 |
+
try:
|
| 16 |
+
import re
|
| 17 |
+
|
| 18 |
+
import requests
|
| 19 |
+
from markdownify import markdownify
|
| 20 |
+
from requests.exceptions import RequestException
|
| 21 |
+
|
| 22 |
+
from smolagents.utils import truncate_content
|
| 23 |
+
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 e
|
| 27 |
+
try:
|
| 28 |
+
response = requests.get(url, timeout=20)
|
| 29 |
+
response.raise_for_status() # Raise an exception for bad status codes
|
| 30 |
+
markdown_content = markdownify(response.text).strip()
|
| 31 |
+
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
|
| 32 |
+
return truncate_content(markdown_content, 40000)
|
| 33 |
+
|
| 34 |
+
except requests.exceptions.Timeout:
|
| 35 |
+
return "The request timed out. Please try again later or check the URL."
|
| 36 |
+
except RequestException as e:
|
| 37 |
+
return f"Error fetching the webpage: {str(e)}"
|
| 38 |
+
except Exception as e:
|
| 39 |
+
return f"An unexpected error occurred: {str(e)}"
|