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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

gauravdhiman
Copy link
Contributor

Description

Please include:

  • Summary of changes: Added set of tools to work with Google Maps.
  • Related issues: NA
  • Motivation and context: Currently there are no toolset for google maps in phidata as, so adding the same.
  • Environment or dependencies: NA
  • Impact on AI/ML components: NA

Fixes # (issue)

Type of change

Please check the options that are relevant:

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Model update
  • Infrastructure change

Checklist

  • My code follows Phidata's style guidelines and best practices
  • I have performed a self-review of my code
  • I have added docstrings and comments for complex logic
  • My changes generate no new warnings or errors
  • I have added cookbook examples for my new addition (if needed)
  • I have updated requirements.txt/pyproject.toml (if needed)
  • I have verified my changes in a clean environment

Additional Notes

Tested with below test script:

"""
Busines info agent that can search google maps for business listings and then search their respective websites to get more info before presenting to user.
"""
"""
Business Contact Search Agent for finding and extracting business contact information.
"""
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from phi.agent import Agent
from dotenv import load_dotenv
load_dotenv()

from phi.model.openrouter import OpenRouter
from phi.tools.crawl4ai_tools import Crawl4aiTools
from phi.tools.google_map_tools import GoogleMapTools

def create_agent():
    """Create and return the Business Contact Search Agent"""
    return Agent(
        name="business_contact_search",
        model=OpenRouter(id="deepseek/deepseek-chat"),
        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,
    )

# Test the agent if run directly
if __name__ == "__main__":
    agent = create_agent()
    agent.print_response(
        "get me the business name, website, email and phone numbers of 2 indian restaurants in phoenix AZ",
        markdown=True,
        stream=True
    )

Here is the output:
Screenshot 2025-01-02 at 1 24 52 PM

"""
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

from phi.tools import Toolkit
import googlemaps

_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

Comment on lines +18 to +59
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)
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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants