Spaces:
Sleeping
Sleeping
Update tools/WebSearchTool.py
Browse files- tools/WebSearchTool.py +26 -21
tools/WebSearchTool.py
CHANGED
|
@@ -1,30 +1,35 @@
|
|
| 1 |
from smolagents import Tool
|
| 2 |
-
from
|
|
|
|
| 3 |
|
| 4 |
-
class
|
| 5 |
name = "web_search"
|
| 6 |
-
description = "Use
|
| 7 |
-
|
| 8 |
inputs = {
|
| 9 |
-
"query": {"type": "string"
|
| 10 |
}
|
| 11 |
output_type = "string"
|
| 12 |
|
| 13 |
def forward(self, query: str) -> str:
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
return f"DuckDuckGo search error: {e}"
|
|
|
|
| 1 |
from smolagents import Tool
|
| 2 |
+
from serpapi import GoogleSearch
|
| 3 |
+
import os
|
| 4 |
|
| 5 |
+
class SerpApiSearchTool(Tool):
|
| 6 |
name = "web_search"
|
| 7 |
+
description = "Use SerpAPI (Google search) to get reliable snippets."
|
| 8 |
+
|
| 9 |
inputs = {
|
| 10 |
+
"query": {"type": "string"}
|
| 11 |
}
|
| 12 |
output_type = "string"
|
| 13 |
|
| 14 |
def forward(self, query: str) -> str:
|
| 15 |
+
params = {
|
| 16 |
+
"q": query,
|
| 17 |
+
"api_key": os.getenv("SERPAPI_KEY"),
|
| 18 |
+
"num": 3
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
search = GoogleSearch(params)
|
| 22 |
+
results = search.get_dict()
|
| 23 |
+
|
| 24 |
+
if "organic_results" not in results:
|
| 25 |
+
return "XX record info: No results."
|
| 26 |
+
|
| 27 |
+
formatted = []
|
| 28 |
+
for item in results.get("organic_results", []):
|
| 29 |
+
formatted.append(
|
| 30 |
+
f"Title: {item.get('title')}\n"
|
| 31 |
+
f"Snippet: {item.get('snippet')}\n"
|
| 32 |
+
f"URL: {item.get('link')}"
|
| 33 |
+
)
|
| 34 |
|
| 35 |
+
return "\n---\n".join(formatted) if formatted else "No record info: No results."
|
|
|