|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright 2025 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +from absl.testing import absltest |
| 17 | + |
| 18 | +MODEL_ID = "gemini-2.5-flash" |
| 19 | + |
| 20 | + |
| 21 | +class GroundingUnitTests(absltest.TestCase): |
| 22 | + |
| 23 | + def test_grounding_maps(self): |
| 24 | + # [START grounding_maps] |
| 25 | + """Generates text using Google Maps as a grounding tool.""" |
| 26 | + from google import genai |
| 27 | + from google.genai.types import GenerateContentConfig, GoogleMaps, LatLng, RetrievalConfig, Tool, ToolConfig |
| 28 | + |
| 29 | + client = genai.Client() |
| 30 | + |
| 31 | + maps_tool = Tool( |
| 32 | + google_maps=GoogleMaps() |
| 33 | + ) |
| 34 | + |
| 35 | + location_context = RetrievalConfig( |
| 36 | + lat_lng=LatLng(latitude=34.050481, longitude=-118.248526) |
| 37 | + ) |
| 38 | + |
| 39 | + prompt = "What are the best Italian restaurants within a 15-minute walk from here?" |
| 40 | + |
| 41 | + response = client.models.generate_content( |
| 42 | + model=MODEL_ID, |
| 43 | + contents=prompt, |
| 44 | + config=GenerateContentConfig( |
| 45 | + tools=[maps_tool], |
| 46 | + tool_config=ToolConfig(retrieval_config=location_context), |
| 47 | + ) |
| 48 | + ) |
| 49 | + |
| 50 | + # Display the text output. |
| 51 | + print(response.text) |
| 52 | + |
| 53 | + # Display the grounding sources. |
| 54 | + if grounding := response.candidates[0].grounding_metadata: |
| 55 | + if grounding.grounding_chunks: |
| 56 | + print('-' * 40) |
| 57 | + print("Sources:") |
| 58 | + for chunk in grounding.grounding_chunks: |
| 59 | + print(f'- [{chunk.maps.title}]({chunk.maps.uri})') |
| 60 | + |
| 61 | + if widget_token := grounding.google_maps_widget_context_token: |
| 62 | + print('-' * 40) |
| 63 | + print(f'Maps token: {widget_token[:14]}...') |
| 64 | + # [END grounding_maps] |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + absltest.main() |
| 68 | + |
0 commit comments