-
Notifications
You must be signed in to change notification settings - Fork 4.1k
feat(firebaseai): add Google Maps Grounding support #18144
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
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
b8bb073
feat(ai): add Google Maps Grounding support
ryanwilson 8327599
Fixes
ryanwilson 4301b4b
Formatting and import fix
ryanwilson 9880afb
Update packages/firebase_ai/firebase_ai/example/lib/pages/grounding_p…
ryanwilson 8851d18
Gemini Code Review feedback
ryanwilson dad79a3
Remove unnecessary comment
ryanwilson 222a575
Add WebGroundingChunk, improved sorting
ryanwilson 34672af
update example to merge multimodel and add nano banana page
cynthiajoan ad06fab
fix the new file year header
cynthiajoan f3b2252
fix analyzer
cynthiajoan 211ec5e
fix the format
cynthiajoan fbe033d
Merge branch 'main' into rw-maps-grounding
cynthiajoan b419070
Merge branch 'firebaseai/nanobanana_sample' into rw-maps-grounding
cynthiajoan 7519fa9
Add maps grounding to server prompt template
cynthiajoan b2e199d
Merge branch 'main' into rw-maps-grounding
cynthiajoan cb11ce5
extra white space
cynthiajoan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
303 changes: 303 additions & 0 deletions
303
packages/firebase_ai/firebase_ai/example/lib/pages/grounding_page.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,303 @@ | ||
| // Copyright 2026 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| import 'package:firebase_auth/firebase_auth.dart'; | ||
| import 'package:flutter/material.dart'; | ||
| import 'package:firebase_ai/firebase_ai.dart'; | ||
| import '../widgets/message_widget.dart'; | ||
|
|
||
| class GroundingPage extends StatefulWidget { | ||
| const GroundingPage({ | ||
| super.key, | ||
| required this.title, | ||
| required this.useVertexBackend, | ||
| }); | ||
|
|
||
| final String title; | ||
| final bool useVertexBackend; | ||
|
|
||
| @override | ||
| State<GroundingPage> createState() => _GroundingPageState(); | ||
| } | ||
|
|
||
| class _GroundingPageState extends State<GroundingPage> { | ||
| GenerativeModel? _model; | ||
| final ScrollController _scrollController = ScrollController(); | ||
| final TextEditingController _textController = TextEditingController(); | ||
| final TextEditingController _latController = TextEditingController(); | ||
| final TextEditingController _lngController = TextEditingController(); | ||
| final FocusNode _textFieldFocus = FocusNode(); | ||
| final List<MessageData> _messages = <MessageData>[]; | ||
|
|
||
| bool _loading = false; | ||
| bool _enableSearchGrounding = false; | ||
| bool _enableMapsGrounding = false; | ||
|
|
||
| @override | ||
| void initState() { | ||
| super.initState(); | ||
| _latController.text = '37.422'; // Default Googleplex lat | ||
| _lngController.text = '-122.084'; // Default Googleplex lng | ||
| } | ||
|
|
||
| void _initializeModel() { | ||
| List<Tool> tools = []; | ||
| ToolConfig? toolConfig; | ||
|
|
||
| if (_enableSearchGrounding) { | ||
| tools.add(Tool.googleSearch()); | ||
| } | ||
|
|
||
| if (_enableMapsGrounding) { | ||
| tools.add(Tool.googleMaps()); | ||
|
|
||
| final lat = double.tryParse(_latController.text); | ||
| final lng = double.tryParse(_lngController.text); | ||
|
|
||
| if (lat != null && lng != null) { | ||
| toolConfig = ToolConfig( | ||
| retrievalConfig: RetrievalConfig( | ||
| latLng: LatLng(latitude: lat, longitude: lng), | ||
| ), | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| final aiProvider = widget.useVertexBackend | ||
| ? FirebaseAI.vertexAI(auth: FirebaseAuth.instance) | ||
| : FirebaseAI.googleAI(auth: FirebaseAuth.instance); | ||
|
|
||
| _model = aiProvider.generativeModel( | ||
| model: 'gemini-2.5-flash', | ||
| tools: tools.isNotEmpty ? tools : null, | ||
| toolConfig: toolConfig, | ||
| ); | ||
| } | ||
|
|
||
| void _scrollDown() { | ||
| WidgetsBinding.instance.addPostFrameCallback( | ||
| (_) => _scrollController.animateTo( | ||
| _scrollController.position.maxScrollExtent, | ||
| duration: const Duration(milliseconds: 750), | ||
| curve: Curves.easeOutCirc, | ||
| ), | ||
| ); | ||
| } | ||
|
|
||
| Future<void> _sendPrompt(String message) async { | ||
| if (message.isEmpty) return; | ||
|
|
||
| _initializeModel(); // Re-initialize before sending to capture current toggles | ||
|
|
||
| setState(() { | ||
| _loading = true; | ||
| }); | ||
|
|
||
| try { | ||
| _messages.add(MessageData(text: message, fromUser: true)); | ||
|
|
||
| final response = await _model?.generateContent([Content.text(message)]); | ||
|
|
||
| var text = response?.text; | ||
|
|
||
| // Extract grounding metadata to display | ||
| final groundingMetadata = | ||
| response?.candidates.firstOrNull?.groundingMetadata; | ||
| if (groundingMetadata != null) { | ||
| final chunks = groundingMetadata.groundingChunks.map((chunk) { | ||
| if (chunk.web != null) { | ||
| final title = chunk.web!.title ?? chunk.web!.uri; | ||
| return '- [$title](${chunk.web!.uri})'; | ||
| } | ||
| if (chunk.maps != null) { | ||
| final title = chunk.maps!.title ?? chunk.maps!.uri; | ||
| return '- [${title ?? 'Maps Result'}](${chunk.maps!.uri ?? ''})'; | ||
| } | ||
| return '- Unknown chunk'; | ||
| }).join('\n'); | ||
|
|
||
| if (chunks.isNotEmpty) { | ||
| text = '$text\n\n**Grounding Sources:**\n$chunks'; | ||
| } | ||
| } | ||
|
|
||
| _messages.add(MessageData(text: text, fromUser: false)); | ||
|
|
||
| if (text == null) { | ||
| _showError('No response from API.'); | ||
| return; | ||
| } | ||
| } catch (e) { | ||
| _showError(e.toString()); | ||
| } finally { | ||
| if (mounted) { | ||
| _textController.clear(); | ||
| setState(() { | ||
| _loading = false; | ||
| }); | ||
| _textFieldFocus.requestFocus(); | ||
| _scrollDown(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| void _showError(String message) { | ||
| showDialog<void>( | ||
| context: context, | ||
| builder: (context) { | ||
| return AlertDialog( | ||
| title: const Text('Something went wrong'), | ||
| content: SingleChildScrollView( | ||
| child: SelectableText(message), | ||
| ), | ||
| actions: [ | ||
| TextButton( | ||
| onPressed: () { | ||
| Navigator.of(context).pop(); | ||
| }, | ||
| child: const Text('OK'), | ||
| ), | ||
| ], | ||
| ); | ||
| }, | ||
| ); | ||
| } | ||
|
|
||
| @override | ||
| Widget build(BuildContext context) { | ||
| return Scaffold( | ||
| appBar: AppBar( | ||
| title: Text(widget.title), | ||
| ), | ||
| body: Padding( | ||
| padding: const EdgeInsets.all(8), | ||
| child: Column( | ||
| children: [ | ||
| Row( | ||
| children: [ | ||
| Expanded( | ||
| child: SwitchListTile( | ||
| title: const Text( | ||
| 'Search Grounding', | ||
| style: TextStyle(fontSize: 12), | ||
| ), | ||
| value: _enableSearchGrounding, | ||
| onChanged: (bool value) { | ||
| setState(() { | ||
| _enableSearchGrounding = value; | ||
| }); | ||
| }, | ||
| ), | ||
| ), | ||
| Expanded( | ||
| child: SwitchListTile( | ||
| title: const Text( | ||
| 'Maps Grounding', | ||
| style: TextStyle(fontSize: 12), | ||
| ), | ||
| value: _enableMapsGrounding, | ||
| onChanged: (bool value) { | ||
| setState(() { | ||
| _enableMapsGrounding = value; | ||
| }); | ||
| }, | ||
| ), | ||
| ), | ||
| ], | ||
| ), | ||
| if (_enableMapsGrounding) | ||
| Padding( | ||
| padding: const EdgeInsets.symmetric(horizontal: 16), | ||
| child: Row( | ||
| children: [ | ||
| Expanded( | ||
| child: TextField( | ||
| controller: _latController, | ||
| decoration: | ||
| const InputDecoration(labelText: 'Latitude'), | ||
| keyboardType: const TextInputType.numberWithOptions( | ||
| decimal: true, | ||
| signed: true, | ||
| ), | ||
| ), | ||
| ), | ||
| const SizedBox(width: 16), | ||
| Expanded( | ||
| child: TextField( | ||
| controller: _lngController, | ||
| decoration: | ||
| const InputDecoration(labelText: 'Longitude'), | ||
| keyboardType: const TextInputType.numberWithOptions( | ||
| decimal: true, | ||
| signed: true, | ||
| ), | ||
| ), | ||
| ), | ||
| ], | ||
| ), | ||
| ), | ||
| const Divider(), | ||
| Expanded( | ||
| child: ListView.builder( | ||
| controller: _scrollController, | ||
| itemBuilder: (context, idx) { | ||
| final message = _messages[idx]; | ||
| return MessageWidget( | ||
| text: message.text, | ||
| isFromUser: message.fromUser ?? false, | ||
| ); | ||
| }, | ||
| itemCount: _messages.length, | ||
| ), | ||
| ), | ||
| Padding( | ||
| padding: const EdgeInsets.symmetric( | ||
| vertical: 25, | ||
| horizontal: 15, | ||
| ), | ||
| child: Row( | ||
| children: [ | ||
| Expanded( | ||
| child: TextField( | ||
| autofocus: true, | ||
| focusNode: _textFieldFocus, | ||
| controller: _textController, | ||
| onSubmitted: _sendPrompt, | ||
| decoration: const InputDecoration( | ||
| hintText: 'Enter a prompt...', | ||
| ), | ||
| ), | ||
| ), | ||
| const SizedBox.square(dimension: 15), | ||
| if (!_loading) | ||
| IconButton( | ||
| onPressed: () { | ||
| _sendPrompt(_textController.text); | ||
| }, | ||
| icon: Icon( | ||
| Icons.send, | ||
| color: Theme.of(context).colorScheme.primary, | ||
| ), | ||
| ) | ||
| else | ||
| const CircularProgressIndicator(), | ||
| ], | ||
| ), | ||
| ), | ||
| ], | ||
| ), | ||
| ), | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.