MCPcopy Create free account
hub / github.com/OpenBMB/BMTools / GoogleSerperAPIWrapper

Class GoogleSerperAPIWrapper

bmtools/tools/google_serper/api.py:11–99  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

9from pydantic.class_validators import root_validator
10
11class GoogleSerperAPIWrapper:
12 def __init__(self, subscription_key) -> None:
13 self.k: int = 10
14 self.gl: str = "us"
15 self.hl: str = "en"
16 self.type: str = "search" # type: search, images, places, news
17 self.tbs: Optional[str] = None
18 self.serper_api_key: str = subscription_key
19 self.aiosession: Optional[aiohttp.ClientSession] = None
20
21 def results(self, query: str, **kwargs: Any) -> Dict:
22 """Run query through GoogleSearch."""
23 return self._google_serper_search_results(
24 query,
25 gl=self.gl,
26 hl=self.hl,
27 num=self.k,
28 tbs=self.tbs,
29 search_type=self.type,
30 **kwargs,
31 )
32
33 def run(self, query: str, **kwargs: Any) -> str:
34 """Run query through GoogleSearch and parse result."""
35 results = self._google_serper_search_results(
36 query,
37 gl=self.gl,
38 hl=self.hl,
39 num=self.k,
40 tbs=self.tbs,
41 search_type=self.type,
42 **kwargs,
43 )
44 return self._parse_results(results)
45
46 def _parse_snippets(self, results: dict) -> List[str]:
47 snippets = []
48
49 if results.get("answerBox"):
50 answer_box = results.get("answerBox", {})
51 if answer_box.get("answer"):
52 return [answer_box.get("answer")]
53 elif answer_box.get("snippet"):
54 return [answer_box.get("snippet").replace("\n", " ")]
55 elif answer_box.get("snippetHighlighted"):
56 return answer_box.get("snippetHighlighted")
57
58 if results.get("knowledgeGraph"):
59 kg = results.get("knowledgeGraph", {})
60 title = kg.get("title")
61 entity_type = kg.get("type")
62 if entity_type:
63 snippets.append(f"{title}: {entity_type}.")
64 description = kg.get("description")
65 if description:
66 snippets.append(description)
67 for attribute, value in kg.get("attributes", {}).items():
68 snippets.append(f"{title} {attribute}: {value}.")

Callers 1

build_toolFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected