Create web_search.py
#586
by Realistvik0 - opened
- web_search.py +56 -0
web_search.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from smolagents import Tool
|
| 2 |
+
from ddgs import DDGS
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class WebSearchTool(Tool):
|
| 6 |
+
name = "web_search"
|
| 7 |
+
|
| 8 |
+
description = (
|
| 9 |
+
"Searches the web for relevant information. "
|
| 10 |
+
"Use this to find sources, facts, dates, statistics, "
|
| 11 |
+
"and other information needed to answer the question. "
|
| 12 |
+
"Search results include titles, URLs, and snippets."
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
inputs = {
|
| 16 |
+
"query": {
|
| 17 |
+
"type": "string",
|
| 18 |
+
"description": "The search query to run.",
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
output_type = "string"
|
| 23 |
+
|
| 24 |
+
def __init__(self, max_results=8):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.max_results = max_results
|
| 27 |
+
|
| 28 |
+
def forward(self, query: str) -> str:
|
| 29 |
+
try:
|
| 30 |
+
results = list(
|
| 31 |
+
DDGS().text(
|
| 32 |
+
query,
|
| 33 |
+
max_results=self.max_results,
|
| 34 |
+
)
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
if not results:
|
| 38 |
+
return "No search results found."
|
| 39 |
+
|
| 40 |
+
output = []
|
| 41 |
+
|
| 42 |
+
for result in results:
|
| 43 |
+
title = result.get("title", "Untitled")
|
| 44 |
+
url = result.get("href", "")
|
| 45 |
+
body = result.get("body", "")
|
| 46 |
+
|
| 47 |
+
output.append(
|
| 48 |
+
f"TITLE: {title}\n"
|
| 49 |
+
f"URL: {url}\n"
|
| 50 |
+
f"SNIPPET: {body}"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
return "\n\n".join(output)
|
| 54 |
+
|
| 55 |
+
except Exception as e:
|
| 56 |
+
return f"Search failed: {e}"
|