Download web_search.py from agents-course/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 1.43 kB
-
https://huggingface.co/spaces/agents-course/Final_Assignment_Template/resolve/refs%2Fpr%2F586/web_search.py
- Command line
-
hf download hf://spaces/agents-course/Final_Assignment_Template@refs/pr/586/web_search.py
-
curl -L -o web_search.py https://huggingface.co/spaces/agents-course/Final_Assignment_Template/resolve/refs%2Fpr%2F586/web_search.py
1.43 kB
| from smolagents import Tool | |
| from ddgs import DDGS | |
| class WebSearchTool(Tool): | |
| name = "web_search" | |
| description = ( | |
| "Searches the web for relevant information. " | |
| "Use this to find sources, facts, dates, statistics, " | |
| "and other information needed to answer the question. " | |
| "Search results include titles, URLs, and snippets." | |
| ) | |
| inputs = { | |
| "query": { | |
| "type": "string", | |
| "description": "The search query to run.", | |
| } | |
| } | |
| output_type = "string" | |
| def __init__(self, max_results=8): | |
| super().__init__() | |
| self.max_results = max_results | |
| def forward(self, query: str) -> str: | |
| try: | |
| results = list( | |
| DDGS().text( | |
| query, | |
| max_results=self.max_results, | |
| ) | |
| ) | |
| if not results: | |
| return "No search results found." | |
| output = [] | |
| for result in results: | |
| title = result.get("title", "Untitled") | |
| url = result.get("href", "") | |
| body = result.get("body", "") | |
| output.append( | |
| f"TITLE: {title}\n" | |
| f"URL: {url}\n" | |
| f"SNIPPET: {body}" | |
| ) | |
| return "\n\n".join(output) | |
| except Exception as e: | |
| return f"Search failed: {e}" |