nikhmr1235 commited on
Commit
d0481ad
·
verified ·
1 Parent(s): 54240cb

serpapi_Google_Search_tool

Browse files
Files changed (1) hide show
  1. helper.py +113 -0
helper.py CHANGED
@@ -326,3 +326,116 @@ wikipedia_full_content_tool = Tool(
326
  """,
327
  func=wikipedia_full_content,
328
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
  """,
327
  func=wikipedia_full_content,
328
  )
329
+
330
+ import os
331
+ from serpapi import GoogleSearch # Or use SerpApiClient for other engines
332
+ from typing import Dict, Any
333
+ from langchain.tools import Tool # Import the Tool class
334
+
335
+ class SerpApiSearchTool:
336
+ """
337
+ A tool to perform searches using SerpApi.
338
+ Supports various search engines and extracts structured data.
339
+ """
340
+ def __init__(self):
341
+ # Retrieve API key from environment variables for security
342
+ self.api_key = os.getenv("SERPAPI_API_KEY")
343
+
344
+ if not self.api_key:
345
+ raise ValueError(
346
+ "SERPAPI_API_KEY must be set as an environment variable. "
347
+ "Get your API key from https://serpapi.com/dashboard"
348
+ )
349
+
350
+ def search_google(self, query: str, num_results: int = 5) -> str:
351
+ """
352
+ Performs a Google search via SerpApi and returns a formatted string of organic results.
353
+
354
+ Args:
355
+ query (str): The search query string.
356
+ num_results (int): The number of organic search results to return (max 100).
357
+
358
+ Returns:
359
+ str: A formatted string containing the title, link, and snippet of each result.
360
+ Also includes any featured snippet or knowledge graph if available.
361
+ Returns an error message if the search fails or no results are found.
362
+ """
363
+ if not query:
364
+ return "Error: Search query cannot be empty."
365
+
366
+ params = {
367
+ "api_key": self.api_key,
368
+ "engine": "google",
369
+ "q": query,
370
+ "num": num_results, # Number of organic results
371
+ "gl": "in", # Geo-location for the search (India in this case)
372
+ "hl": "en" # Host language for the search
373
+ }
374
+
375
+ try:
376
+ print(f"[TOOL: SerpApiSearch] Searching Google for: '{query}'")
377
+ search = GoogleSearch(params)
378
+ results = search.get_dict() # Execute the search and get results as a dictionary
379
+
380
+ formatted_output = []
381
+
382
+ # Check for common structured results first
383
+ if 'answer_box' in results and results['answer_box'].get('answer'):
384
+ formatted_output.append(f"Answer Box: {results['answer_box']['answer']}")
385
+ if 'knowledge_graph' in results and results['knowledge_graph'].get('description'):
386
+ formatted_output.append(f"Knowledge Graph: {results['knowledge_graph']['description']}")
387
+ if results['knowledge_graph'].get('title'):
388
+ formatted_output.append(f" Title: {results['knowledge_graph']['title']}")
389
+ if results['knowledge_graph'].get('link'):
390
+ formatted_output.append(f" Link: {results['knowledge_graph']['link']}")
391
+
392
+ # Then process organic results
393
+ organic_results = results.get('organic_results', [])
394
+ if organic_results:
395
+ if formatted_output: # Add a separator if other sections were added
396
+ formatted_output.append("\n--- Organic Results ---")
397
+ else:
398
+ formatted_output.append("Organic Results:")
399
+ for i, item in enumerate(organic_results):
400
+ title = item.get('title', 'No Title')
401
+ link = item.get('link', '#')
402
+ snippet = item.get('snippet', 'No Snippet')
403
+ formatted_output.append(
404
+ f"Result {i+1}:\n"
405
+ f" Title: {title}\n"
406
+ f" Link: {link}\n"
407
+ f" Snippet: {snippet}\n"
408
+ )
409
+
410
+ if not formatted_output: # If no structured data or organic results
411
+ return "No relevant search results found."
412
+
413
+ return "\n".join(formatted_output)
414
+
415
+ except Exception as e:
416
+ return f"Error performing SerpApi search: {e}"
417
+
418
+ # Instantiate the SerpApiSearchTool class
419
+ serpapi_search_instance = SerpApiSearchTool()
420
+
421
+ # Create the LangChain Tool object
422
+ serpapi_Google_Search_tool = Tool(
423
+ name="serpapi_Google Search",
424
+ description="""
425
+ Performs a Google search using SerpApi to get current and detailed information from the web.
426
+ Use this for factual queries, general knowledge, recent events, or when TavilySearch might not be sufficient.
427
+ It can return rich results including answer boxes, knowledge graphs, and multiple organic search results.
428
+ Input should be a clear, concise search query string.
429
+ """,
430
+ func=serpapi_search_instance.search_google,
431
+ )
432
+
433
+ # Remember to set your SERPAPI_API_KEY environment variable before running!
434
+ # Example: os.environ["SERPAPI_API_KEY"] = "YOUR_API_KEY_HERE"
435
+
436
+ # To use this tool, you would add `serpapi_Google Search_tool` to your `tools` list
437
+ # in your `BasicAgent` initialization, like this:
438
+ # tools = [travily_api_search_tool, python_repl, ..., serpapi_Google Search_tool]
439
+ #
440
+ # And you would need to update your prompt's "Available Tools" section
441
+ # to describe `serpapi_Google Search` to the LLM.