Sborole commited on
Commit
b18df76
·
verified ·
1 Parent(s): b81fcdf

Update tools/WebSearchTool.py

Browse files
Files changed (1) hide show
  1. tools/WebSearchTool.py +26 -21
tools/WebSearchTool.py CHANGED
@@ -1,30 +1,35 @@
1
  from smolagents import Tool
2
- from duckduckgo_search import DDGS
 
3
 
4
- class DuckDuckGoSearchTool(Tool):
5
  name = "web_search"
6
- description = "Use DuckDuckGo to search the web. Returns short snippets and URLs."
7
-
8
  inputs = {
9
- "query": {"type": "string", "description": "Search term"}
10
  }
11
  output_type = "string"
12
 
13
  def forward(self, query: str) -> str:
14
- try:
15
- results = []
16
- with DDGS() as ddgs:
17
- for r in ddgs.text(query, max_results=3):
18
- results.append(
19
- f"Title: {r.get('title')}\n"
20
- f"Snippet: {r.get('body')}\n"
21
- f"URL: {r.get('href')}"
22
- )
23
-
24
- if not results:
25
- return "No search results found."
26
-
27
- return "\n---\n".join(results)
 
 
 
 
 
28
 
29
- except Exception as e:
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."