Download tools/web_search.py from Realistvik0/First_agent_template: direct link, hf CLI and curl.
- Browser
- Download file 1.5 kB
-
https://huggingface.co/spaces/Realistvik0/First_agent_template/resolve/main/tools/web_search.py
- Command line
-
hf download hf://spaces/Realistvik0/First_agent_template/tools/web_search.py
-
curl -L -o web_search.py https://huggingface.co/spaces/Realistvik0/First_agent_template/resolve/main/tools/web_search.py
1.5 kB
| from typing import Any, Optional | |
| from smolagents.tools import Tool | |
| from ddgs import DDGS | |
| class DuckDuckGoSearchTool(Tool): | |
| name = "web_search" | |
| description = ( | |
| "Searches the web for relevant sources. " | |
| "Returns titles, URLs, and snippets from search results." | |
| ) | |
| inputs = { | |
| "query": { | |
| "type": "string", | |
| "description": "The web search query.", | |
| } | |
| } | |
| output_type = "string" | |
| def __init__(self, max_results=10, **kwargs): | |
| super().__init__() | |
| self.max_results = max_results | |
| self.ddgs = DDGS(**kwargs) | |
| def forward(self, query: str) -> str: | |
| try: | |
| results = list( | |
| self.ddgs.text( | |
| query, | |
| max_results=self.max_results, | |
| ) | |
| ) | |
| if not results: | |
| return ( | |
| f"No search results were returned for: {query}. " | |
| "Try a broader or differently worded query." | |
| ) | |
| formatted = [] | |
| for result in results: | |
| title = result.get("title", "Untitled") | |
| url = result.get("href", "") | |
| body = result.get("body", "") | |
| formatted.append( | |
| f"[{title}]({url})\n{body}" | |
| ) | |
| return "## Search Results\n\n" + "\n\n".join(formatted) | |
| except Exception as e: | |
| return f"Search failed for '{query}': {e}" | |