cpatino10 commited on
Commit
98c0192
·
verified ·
1 Parent(s): 115b402

Update tools.py

Browse files

updated search tool to use googleSearch.

Files changed (1) hide show
  1. tools.py +26 -17
tools.py CHANGED
@@ -1,5 +1,4 @@
1
  from smolagents import Tool, tool
2
- from duckduckgo_search import DDGS
3
  import requests
4
  from bs4 import BeautifulSoup
5
  import os
@@ -34,31 +33,41 @@ class TranscriptTool(Tool):
34
  transcription_tool = TranscriptTool()
35
 
36
 
37
- class SimpleSearchTool(Tool):
38
  name = "web_search"
39
- description = "Performs a google-like search for a query and returns the top results with snippets."
40
- inputs = {'query': {'type': 'string', 'description': 'The search query to perform.'}}
41
  output_type = "string"
42
 
43
  def forward(self, query: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
44
  try:
45
- results = []
46
- # Try the standard backend first
47
- with DDGS() as ddgs:
48
- for r in ddgs.text(query, max_results=5):
49
- if r.get('body'):
50
- results.append(f"Title: {r['title']}\nLink: {r['href']}\nSnippet: {r['body']}")
51
-
52
- if not results:
53
- return "No results found. Try a broader query."
54
 
55
- return "\n\n".join(results)
 
56
 
 
 
 
 
 
57
  except Exception as e:
58
- return f"Search failed: {str(e)}"
59
 
60
- # Instantiate web search tool
61
- search_tool = SimpleSearchTool()
62
 
63
  class VisitWebpageTool(Tool):
64
  name = "visit_webpage"
 
1
  from smolagents import Tool, tool
 
2
  import requests
3
  from bs4 import BeautifulSoup
4
  import os
 
33
  transcription_tool = TranscriptTool()
34
 
35
 
36
+ class GoogleSearchTool(Tool):
37
  name = "web_search"
38
+ description = "Searches the web using Google. Essential for finding specific articles and papers."
39
+ inputs = {'query': {'type': 'string', 'description': 'The search query.'}}
40
  output_type = "string"
41
 
42
  def forward(self, query: str) -> str:
43
+ api_key = os.getenv("SERPER_API_KEY")
44
+ if not api_key:
45
+ return "Error: SERPER_API_KEY not found in environment variables."
46
+
47
+ url = "https://google.serper.dev/search"
48
+ payload = {"q": query}
49
+ headers = {
50
+ 'X-API-KEY': api_key,
51
+ 'Content-Type': 'application/json'
52
+ }
53
+
54
  try:
55
+ response = requests.post(url, headers=headers, json=payload)
56
+ response.raise_for_status()
57
+ results = response.json()
 
 
 
 
 
 
58
 
59
+ if 'organic' not in results:
60
+ return "No results found."
61
 
62
+ output = []
63
+ for item in results['organic'][:5]: # Take top 5 results
64
+ output.append(f"Title: {item['title']}\nLink: {item['link']}\nSnippet: {item['snippet']}\n")
65
+
66
+ return "\n---\n".join(output)
67
  except Exception as e:
68
+ return f"Google Search failed: {str(e)}"
69
 
70
+ search_tool = GoogleSearchTool()
 
71
 
72
  class VisitWebpageTool(Tool):
73
  name = "visit_webpage"