🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
Fix: Google Maps Toolkit Incompatible Parameters (#919)
Isaac Jin5037f6857724
diff --git a/camel/toolkits/google_maps_toolkit.py b/camel/toolkits/google_maps_toolkit.pyindex 7abbad4aa..b82b66b25 100644--- a/camel/toolkits/google_maps_toolkit.py+++ b/camel/toolkits/google_maps_toolkit.py@@ -13,10 +13,11 @@# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========import osfrom functools import wraps-from typing import Any, Callable, List, Optional, Tuple, Union+from typing import Any, Callable, List, Optional, Unionfrom camel.toolkits.base import BaseToolkitfrom camel.toolkits.openai_function import OpenAIFunction+from camel.utils import dependencies_requireddef handle_googlemaps_exceptions(@@ -74,57 +75,47 @@ def handle_googlemaps_exceptions(return wrapper+def _format_offset_to_natural_language(offset: int) -> str:+ r"""Converts a time offset in seconds to a more natural language+ description using hours as the unit, with decimal places to represent+ minutes and seconds.++ Args:+ offset (int): The time offset in seconds. Can be positive,+ negative, or zero.++ Returns:+ str: A string representing the offset in hours, such as+ "+2.50 hours" or "-3.75 hours".+ """+ # Convert the offset to hours as a float+ hours = offset / 3600.0+ hours_str = f"{hours:+.2f} hour{'s' if abs(hours) != 1 else ''}"+ return hours_str++class GoogleMapsToolkit(BaseToolkit):r"""A class representing a toolkit for interacting with GoogleMaps API.-This class provides methods for validating addresses, retrieving elevation,and fetching timezone information using the Google Maps API."""- def _import_googlemaps_or_raise(self) -> Any:- r"""Attempts to import the `googlemaps` library and returns it.+ @dependencies_required('googlemaps')+ def __init__(self) -> None:+ import googlemaps- Returns:- module: The `googlemaps` module if successfully imported.-- Raises:- ImportError: If the `googlemaps` library is not installed, this- error is raised with a message instructing how to install the- library using pip.- """- try:- import googlemaps-- return googlemaps- except ImportError:- raise ImportError(- "Please install `googlemaps` first. You can install "- "it by running `pip install googlemaps`."- )-- def _get_googlemaps_api_key(self) -> str:- r"""Retrieve the Google Maps API key from environment variables.-- Returns:- str: The Google Maps API key.-- Raises:- ValueError: If the API key is not found in the environment- variables.- """- # Get `GOOGLEMAPS_API_KEY` here:- # https://console.cloud.google.com/apis/credentials- GOOGLEMAPS_API_KEY = os.environ.get('GOOGLEMAPS_API_KEY')- if not GOOGLEMAPS_API_KEY:+ api_key = os.environ.get('GOOGLE_API_KEY')+ if not api_key:raise ValueError(- "`GOOGLEMAPS_API_KEY` not found in environment "- "variables. `GOOGLEMAPS_API_KEY` API keys are "- "generated in the `Credentials` page of the "- "`APIs & Services` tab of "+ "`GOOGLE_API_KEY` not found in environment variables. "+ "`GOOGLE_API_KEY` API keys are generated in the `Credentials` "+ "page of the `APIs & Services` tab of ""https://console.cloud.google.com/apis/credentials.")- return GOOGLEMAPS_API_KEY+ self.gmaps = googlemaps.Client(key=api_key)++ @handle_googlemaps_exceptionsdef get_address_description(self,address: Union[str, List[str]],@@ -132,18 +123,17 @@ class GoogleMapsToolkit(BaseToolkit):locality: Optional[str] = None,) -> str:r"""Validates an address via Google Maps API, returns a descriptive- summary.-- Validates an address using Google Maps API, returning a summary that- includes information on address completion, formatted address, location- coordinates, and metadata types that are true for the given address.+ summary. Validates an address using Google Maps API, returning a+ summary that includes information on address completion, formatted+ address, location coordinates, and metadata types that are true for+ the given address.Args:address (Union[str, List[str]]): The address or components tovalidate. Can be a single string or a list representingdifferent parts.region_code (str, optional): Country code for regional restriction,- helps narrowing down results. (default: :obj:`None`)+ helps narrow down results. (default: :obj:`None`)locality (str, optional): Restricts validation to a specificlocality, e.g., "Mountain View". (default: :obj:`None`)@@ -157,84 +147,69 @@ class GoogleMapsToolkit(BaseToolkit):ImportError: If the `googlemaps` library is not installed.Exception: For unexpected errors during the address validation."""- googlemaps = self._import_googlemaps_or_raise()- google_maps_api_key = self._get_googlemaps_api_key()- try:- gmaps = googlemaps.Client(key=google_maps_api_key)- except Exception as e:- return f"Error: {e!s}"-- try:- addressvalidation_result = gmaps.addressvalidation(- [address],- regionCode=region_code,- locality=locality,- enableUspsCass=False,- ) # Always False as per requirements-- # Check if the result contains an error- if 'error' in addressvalidation_result:- error_info = addressvalidation_result['error']- error_message = error_info.get(- 'message', 'An unknown error occurred'- )- error_status = error_info.get('status', 'UNKNOWN_STATUS')- error_code = error_info.get('code', 'UNKNOWN_CODE')- return (- f"Address validation failed with error: {error_message} "- f"Status: {error_status}, Code: {error_code}"- )-- # Assuming the successful response structure- # includes a 'result' key- result = addressvalidation_result['result']- verdict = result.get('verdict', {})- address_info = result.get('address', {})- geocode = result.get('geocode', {})- metadata = result.get('metadata', {})-- # Construct the descriptive string- address_complete = (- "Yes" if verdict.get('addressComplete', False) else "No"- )- formatted_address = address_info.get(- 'formattedAddress', 'Not available'+ addressvalidation_result = self.gmaps.addressvalidation(+ [address],+ regionCode=region_code,+ locality=locality,+ enableUspsCass=False,+ ) # Always False as per requirements++ # Check if the result contains an error+ if 'error' in addressvalidation_result:+ error_info = addressvalidation_result['error']+ error_message = error_info.get(+ 'message', 'An unknown error occurred')- location = geocode.get('location', {})- latitude = location.get('latitude', 'Not available')- longitude = location.get('longitude', 'Not available')- true_metadata_types = [- key for key, value in metadata.items() if value- ]- true_metadata_types_str = (- ', '.join(true_metadata_types)- if true_metadata_types- else 'None'+ error_status = error_info.get('status', 'UNKNOWN_STATUS')+ error_code = error_info.get('code', 'UNKNOWN_CODE')+ return (+ f"Address validation failed with error: {error_message} "+ f"Status: {error_status}, Code: {error_code}")- description = (- f"Address completion status: {address_complete}. "- f"Formatted address: {formatted_address}. "- f"Location (latitude, longitude): ({latitude}, {longitude}). "- f"Metadata indicating true types: {true_metadata_types_str}."- )+ # Assuming the successful response structure+ # includes a 'result' key+ result = addressvalidation_result['result']+ verdict = result.get('verdict', {})+ address_info = result.get('address', {})+ geocode = result.get('geocode', {})+ metadata = result.get('metadata', {})++ # Construct the descriptive string+ address_complete = (+ "Yes" if verdict.get('addressComplete', False) else "No"+ )+ formatted_address = address_info.get(+ 'formattedAddress', 'Not available'+ )+ location = geocode.get('location', {})+ latitude = location.get('latitude', 'Not available')+ longitude = location.get('longitude', 'Not available')+ true_metadata_types = [key for key, value in metadata.items() if value]+ true_metadata_types_str = (+ ', '.join(true_metadata_types) if true_metadata_types else 'None'+ )- return description- except Exception as e:- return f"An unexpected error occurred: {e!s}"+ description = (+ f"Address completion status: {address_complete}. "+ f"Formatted address: {formatted_address}. "+ f"Location (latitude, longitude): ({latitude}, {longitude}). "+ f"Metadata indicating true types: {true_metadata_types_str}."+ )++ return description@handle_googlemaps_exceptions- def get_elevation(self, lat_lng: Tuple) -> str:+ def get_elevation(self, lat: float, lng: float) -> str:r"""Retrieves elevation data for a given latitude and longitude.-Uses the Google Maps API to fetch elevation data for the specifiedlatitude and longitude. It handles exceptions gracefully and returns adescription of the elevation, including its value in meters and thedata resolution.Args:- lat_lng (Tuple[float, float]): The latitude and longitude for- which to retrieve elevation data.+ lat (float): The latitude of the location to query.+ lng (float): The longitude of the location to query.Returns:str: A description of the elevation at the specified location(s),@@ -242,15 +217,8 @@ class GoogleMapsToolkit(BaseToolkit):elevation data is not available, a message indicating this isreturned."""- googlemaps = self._import_googlemaps_or_raise()- google_maps_api_key = self._get_googlemaps_api_key()- try:- gmaps = googlemaps.Client(key=google_maps_api_key)- except Exception as e:- return f"Error: {e!s}"-# Assuming gmaps is a configured Google Maps client instance- elevation_result = gmaps.elevation(lat_lng)+ elevation_result = self.gmaps.elevation((lat, lng))# Extract the elevation data from the first# (and presumably only) result@@ -273,28 +241,9 @@ class GoogleMapsToolkit(BaseToolkit):return description- def _format_offset_to_natural_language(self, offset: int) -> str:- r"""Converts a time offset in seconds to a more natural language- description using hours as the unit, with decimal places to represent- minutes and seconds.-- Args:- offset (int): The time offset in seconds. Can be positive,- negative, or zero.-- Returns:- str: A string representing the offset in hours, such as- "+2.50 hours" or "-3.75 hours".- """- # Convert the offset to hours as a float- hours = offset / 3600.0- hours_str = f"{hours:+.2f} hour{'s' if abs(hours) != 1 else ''}"- return hours_str-@handle_googlemaps_exceptions- def get_timezone(self, lat_lng: Tuple) -> str:+ def get_timezone(self, lat: float, lng: float) -> str:r"""Retrieves timezone information for a given latitude and longitude.-This function uses the Google Maps Timezone API to fetch timezonedata for the specified latitude and longitude. It returns a naturallanguage description of the timezone, including the timezone ID, name,@@ -302,23 +251,16 @@ class GoogleMapsToolkit(BaseToolkit):offset from Coordinated Universal Time (UTC).Args:- lat_lng (Tuple[float, float]): The latitude and longitude for- which to retrieve elevation data.+ lat (float): The latitude of the location to query.+ lng (float): The longitude of the location to query.Returns:str: A descriptive string of the timezone information,- including the timezone ID and name, standard time offset,- daylight saving time offset, and total offset from UTC.+ including the timezone ID and name, standard time offset,+ daylight saving time offset, and total offset from UTC."""- googlemaps = self._import_googlemaps_or_raise()- google_maps_api_key = self._get_googlemaps_api_key()- try:- gmaps = googlemaps.Client(key=google_maps_api_key)- except Exception as e:- return f"Error: {e!s}"-# Get timezone information- timezone_dict = gmaps.timezone(lat_lng)+ timezone_dict = self.gmaps.timezone((lat, lng))# Extract necessary informationdst_offset = timezone_dict[@@ -330,10 +272,10 @@ class GoogleMapsToolkit(BaseToolkit):timezone_id = timezone_dict['timeZoneId']timezone_name = timezone_dict['timeZoneName']- raw_offset_str = self._format_offset_to_natural_language(raw_offset)- dst_offset_str = self._format_offset_to_natural_language(dst_offset)+ raw_offset_str = _format_offset_to_natural_language(raw_offset)+ dst_offset_str = _format_offset_to_natural_language(dst_offset)total_offset_seconds = dst_offset + raw_offset- total_offset_str = self._format_offset_to_natural_language(+ total_offset_str = _format_offset_to_natural_language(total_offset_seconds)@@ -343,9 +285,8 @@ class GoogleMapsToolkit(BaseToolkit):f"The standard time offset is {raw_offset_str}. "f"Daylight Saving Time offset is {dst_offset_str}. "f"The total offset from Coordinated Universal Time (UTC) is "- f"{total_offset_str}, including any "- "Daylight Saving Time adjustment "- f"if applicable. "+ f"{total_offset_str}, including any Daylight Saving Time "+ f"adjustment if applicable. ")return descriptiondiff --git a/poetry.lock b/poetry.lockindex 21168b34b..119de20dd 100644--- a/poetry.lock+++ b/poetry.lock@@ -1,4 +1,4 @@-# This file is automatically @generated by Poetry 1.8.2 and should not be changed by hand.+# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.[[package]]name = "accelerate"diff --git a/test/toolkits/test_google_maps_function.py b/test/toolkits/test_google_maps_function.pyindex 8611eec34..f6b002147 100644--- a/test/toolkits/test_google_maps_function.py+++ b/test/toolkits/test_google_maps_function.py@@ -11,7 +11,6 @@# See the License for the specific language governing permissions and# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========-from functools import wrapsfrom unittest.mock import MagicMock, patchimport pytest@@ -19,27 +18,11 @@ import pytestfrom camel.toolkits import GoogleMapsToolkit-def mock_googlemaps(test_func):- @wraps(test_func)- @patch('googlemaps.Client')- @patch('os.environ.get')- def wrapper(*args, **kwargs):- mock_get = args[0]- mock_get.return_value = 'fake_api_key'- return test_func(*args, **kwargs)-- return wrapper--@pytest.fixture-def google_maps_toolkit():- return GoogleMapsToolkit()---@mock_googlemaps-def test_get_address_description(mock_get, mock_client, google_maps_toolkit):- # Create a mock response for the addressvalidation method- mock_response = {+@patch('googlemaps.Client')+def google_maps_toolkit(mock_client):+ mock_instance = MagicMock()+ mock_validation_resp = {'result': {'verdict': {'addressComplete': True},'address': {@@ -58,12 +41,33 @@ def test_get_address_description(mock_get, mock_client, google_maps_toolkit):},}}+ mock_instance.addressvalidation.return_value = mock_validation_resp++ # Create a mock response for the elevation method+ mock_elevation_resp = [+ {+ 'elevation': 10.53015995025635,+ 'location': {'lat': 40.71473, 'lng': -73.99867},+ 'resolution': 76.35161590576172,+ }+ ]+ mock_instance.elevation.return_value = mock_elevation_resp++ # Create a mock response for the timezone method+ mock_timezone_resp = {+ 'dstOffset': 3600,+ 'rawOffset': -28800,+ 'status': 'OK',+ 'timeZoneId': 'America/Los_Angeles',+ 'timeZoneName': 'Pacific Daylight Time',+ }+ mock_instance.timezone.return_value = mock_timezone_resp- # Configure the mock client instance to return the mock response- mock_instance = MagicMock()- mock_instance.addressvalidation.return_value = mock_responsemock_client.return_value = mock_instance+ return GoogleMapsToolkit()++def test_get_address_description(google_maps_toolkit):# Call the function with a test addressresult = google_maps_toolkit.get_address_description('1600 Amphitheatre Pk', region_code='US', locality='Mountain View'@@ -79,24 +83,9 @@ def test_get_address_description(mock_get, mock_client, google_maps_toolkit):assert result == expected_result-@mock_googlemaps-def test_get_elevation(mock_get, mock_client, google_maps_toolkit):- # Create a mock response for the elevation method- mock_response = [- {- 'elevation': 10.53015995025635,- 'location': {'lat': 40.71473, 'lng': -73.99867},- 'resolution': 76.35161590576172,- }- ]-- # Configure the mock client instance to return the mock response- mock_instance = MagicMock()- mock_instance.elevation.return_value = mock_response- mock_client.return_value = mock_instance-+def test_get_elevation(google_maps_toolkit):# Call the function with a test latitude and longitude- result = google_maps_toolkit.get_elevation((40.71473, -73.99867))+ result = google_maps_toolkit.get_elevation(40.71473, -73.99867)# Verify the resultexpected_result = (@@ -107,26 +96,9 @@ def test_get_elevation(mock_get, mock_client, google_maps_toolkit):assert result == expected_result-@mock_googlemaps-def test_get_timezone(mock_get, mock_client, google_maps_toolkit):- # Create a mock response for the timezone method- mock_response = {- 'dstOffset': 3600,- 'rawOffset': -28800,- 'status': 'OK',- 'timeZoneId': 'America/Los_Angeles',- 'timeZoneName': 'Pacific Daylight Time',- }-- # Configure the mock client instance to return the mock response- mock_instance = MagicMock()- mock_instance.timezone.return_value = mock_response- mock_client.return_value = mock_instance-+def test_get_timezone(google_maps_toolkit):# Call the function with a test latitude and longitude- result = google_maps_toolkit.get_timezone(- (39.603481, -119.682251)- ) # Coordinates for Los Angeles+ result = google_maps_toolkit.get_timezone(39.603481, -119.682251)# Verify the resultexpected_result = (@@ -137,22 +109,3 @@ def test_get_timezone(mock_get, mock_client, google_maps_toolkit):"if applicable. ")assert result == expected_result---def test_wrong_api_key(monkeypatch, google_maps_toolkit):- monkeypatch.setenv('GOOGLEMAPS_API_KEY', 'invalid_api_key')- expected_output = "Error: Invalid API key provided."- assert (- google_maps_toolkit.get_address_description(- '1600 Amphitheatre Pk', region_code='US', locality='Mountain View'- )- == expected_output- )- assert (- google_maps_toolkit.get_elevation((40.714728, -73.998672))- == expected_output- )- assert (- google_maps_toolkit.get_timezone((40.714728, -73.998672))- == expected_output- )