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

Class GooglePlacesAPIWrapper

bmtools/tools/google_places/api.py:10–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8import googlemaps
9
10class GooglePlacesAPIWrapper:
11 def __init__(self, subscription_key) -> None:
12 self.gplaces_api_key: str = subscription_key
13 self.google_map_client = googlemaps.Client(self.gplaces_api_key)
14 self.top_k_results: Optional[int] = None
15
16 def run(self, query: str) -> str:
17 """Run Places search and get k number of places that exists that match."""
18 search_results = self.google_map_client.places(query)["results"]
19 num_to_return = len(search_results)
20
21 places = []
22
23 if num_to_return == 0:
24 return "Google Places did not find any places that match the description"
25
26 num_to_return = (
27 num_to_return
28 if self.top_k_results is None
29 else min(num_to_return, self.top_k_results)
30 )
31
32 for i in range(num_to_return):
33 result = search_results[i]
34 details = self.fetch_place_details(result["place_id"])
35
36 if details is not None:
37 places.append(details)
38
39 return "\n".join([f"{i+1}. {item}" for i, item in enumerate(places)])
40
41 def fetch_place_details(self, place_id: str) -> Optional[str]:
42 try:
43 place_details = self.google_map_client.place(place_id)
44 formatted_details = self.format_place_details(place_details)
45 return formatted_details
46 except Exception as e:
47 logging.error(f"An Error occurred while fetching place details: {e}")
48 return None
49
50 def format_place_details(self, place_details: Dict[str, Any]) -> Optional[str]:
51 try:
52 name = place_details.get("result", {}).get("name", "Unkown")
53 address = place_details.get("result", {}).get(
54 "formatted_address", "Unknown"
55 )
56 phone_number = place_details.get("result", {}).get(
57 "formatted_phone_number", "Unknown"
58 )
59 website = place_details.get("result", {}).get("website", "Unknown")
60
61 formatted_details = (
62 f"{name}\nAddress: {address}\n"
63 f"Phone: {phone_number}\nWebsite: {website}\n\n"
64 )
65 return formatted_details
66 except Exception as e:
67 logging.error(f"An error occurred while formatting place details: {e}")

Callers 1

build_toolFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected