Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Google Maps toolkit. #1689

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions cookbook/tools/google_maps_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
Business Contact Search Agent for finding and extracting business contact information.
"""
from dotenv import load_dotenv
load_dotenv()

from phi.agent import Agent
from phi.tools.crawl4ai_tools import Crawl4aiTools
from phi.tools.google_map_tools import GoogleMapTools

agent = Agent(
name="Business contact info agent",
tools=[
GoogleMapTools(), # For searching businesses on Google Maps
Crawl4aiTools(max_length=5000), # For scraping business websites
],
description="You are a business contact information researcher specializing in finding accurate contact details for businesses.",
instructions=[
"When given a search query to find business contact information:",
"Use the Google Maps Search tool to find relevant businesses in the specified location.",
"For each business found by Google Maps Search tool, if they have a website, use web crawler tool to extract other business information.",
"Whatever information you dont get from google maps, try to get it from website.",
],
markdown=True,
show_tool_calls=True,
debug_mode=True,
)

agent.print_response(
"get me the business details of indian restaurants in phoenix AZ",
markdown=True,
stream=True
)
63 changes: 63 additions & 0 deletions phi/tools/google_map_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""
Tool for searching business information using Google Maps API.
This required API key to be set in the environment variable `GOOGLE_MAPS_API_KEY`

You can get the API key here: https://console.cloud.google.com/projectselector2/google/maps-apis/credentials
"""
from os import getenv
from phi.tools import Toolkit
import googlemaps
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move this into a try and catch block. Take inspiration from here https://github.com/phidatahq/phidata/blob/main/phi/tools/slack.py#L8


_google_map_client = googlemaps.Client(key=getenv('GOOGLE_MAPS_API_KEY'))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move this inside the class in __init__ function and also a check if the key is set or not else raise an error


class GoogleMapTools(Toolkit):
def __init__(self):
super().__init__(name="google_map")
self.register(self.search_google_maps)

def search_google_maps(self, query: str) -> str:
"""
Search for businesses using Google Maps Places API.
This tool takes a search query and returns detailed business information.

Args:
query (str): The query string to search for using Google Maps Search API. (e.g., "dental clinics in Noida")

Returns:
Stringified list of dictionaries containing business information like name, address, phone, website, rating, and reviews etc.
"""
try:
# Perform places search
places_result = _google_map_client.places(query)

if not places_result or 'results' not in places_result:
return []

businesses = []
for place in places_result['results']:
business = {
'name': place.get('name', ''),
'address': place.get('formatted_address', ''),
'rating': place.get('rating', 0.0),
'reviews': place.get('user_ratings_total', 0),
'place_id': place.get('place_id', ''),
}

# Get place details for additional information
if place.get('place_id'):
details = _google_map_client.place(place['place_id'])
if details and 'result' in details:
result = details['result']
business.update({
'phone': result.get('formatted_phone_number', ''),
'website': result.get('website', ''),
'hours': result.get('opening_hours', {}).get('weekday_text', [])
})

businesses.append(business)

return str(businesses)
Comment on lines +18 to +59
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this function only for search businesses? If yes then we should either make it generalised to find any place on the map else rename the function to search_businesses_google_maps. What do you think?


except Exception as e:
print(f"Error searching Google Maps: {str(e)}")
return str([])