Firebase AI Logic plugin
The genkit_firebase_ai package calls Gemini models directly from Flutter apps through Firebase AI Logic, built on the firebase_ai SDK. Instead of shipping a model API key inside your client binary, requests authenticate through your Firebase project and Firebase App Check.
Use this plugin when your generation, tool calling, or Live audio logic runs on the client inside a Flutter app. When your AI workflows run on a server that your Flutter app calls over HTTP, use the Google Generative AI or Gemini Enterprise plugin on the backend instead (see the Flutter tutorial).
Before you start
Section titled “Before you start”- Set up Firebase AI Logic in your Firebase project, and configure Firebase in your Flutter app with
flutterfire configure. - Set up Firebase App Check.
Install packages
Section titled “Install packages”Add genkit, genkit_firebase_ai, and the Firebase packages to your Flutter app:
flutter pub add genkit genkit_firebase_ai firebase_core firebase_ai firebase_app_checkInitialize Firebase and App Check
Section titled “Initialize Firebase and App Check”Activate App Check before your first model call. The plugin reads App Check and Firebase Auth from the FirebaseApp instance. Use the debug providers during local development and the platform attestation providers in release builds:
import 'package:firebase_app_check/firebase_app_check.dart';import 'package:firebase_core/firebase_core.dart';import 'package:flutter/foundation.dart';import 'package:flutter/widgets.dart';
import 'firebase_options.dart';
Future<void> initFirebase() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); await FirebaseAppCheck.instance.activate( providerAndroid: kDebugMode ? const AndroidDebugProvider() : const AndroidPlayIntegrityProvider(), providerApple: kDebugMode ? const AppleDebugProvider() : const AppleAppAttestWithDeviceCheckFallbackProvider(), providerWeb: kDebugMode ? WebDebugProvider() : ReCaptchaEnterpriseProvider('your-recaptcha-site-key'), );}Never ship debug providers in a release build: anyone with a registered debug token passes App Check. On first run, each debug provider logs a debug token (in the browser console on web). Register that token in the Firebase console under App Check > Apps > Manage debug tokens. For release builds, configure each platform’s attestation provider in the Firebase console; see Get started with App Check in Flutter.
Basic usage
Section titled “Basic usage”Initialize Genkit with firebaseAI(), then pass firebaseAI.gemini('<model-id>') to ai.generate():
import 'package:genkit/genkit.dart';import 'package:genkit_firebase_ai/genkit_firebase_ai.dart';
Future<void> generateJoke() async { final ai = Genkit(plugins: [firebaseAI()]);
final response = await ai.generate( model: firebaseAI.gemini('gemini-flash-latest'), prompt: 'Tell me a joke about a developer.', );
print(response.text);}Available models
Section titled “Available models”firebaseAI.gemini('<model-id>') resolves model names dynamically, so any Gemini model that Firebase AI Logic serves works, including models released after this version of the plugin. See Firebase AI Logic supported models for model availability and shutdown dates.
The plugin also pre-registers current models so they appear in the Genkit Developer UI with their capability metadata:
- Text and multimodal:
gemini-4-argon,gemini-3.8-flash,gemini-3.5-flash,gemini-3.5-flash-lite,gemini-3.1-flash-lite, andgemini-3.1-pro-preview. On the Gemini Developer API (FirebaseAiProvider.googleAI()),gemini-flash-latest,gemini-3.7-flash, andgemini-3.6-flashare also registered (the-latestalias is not available on Agent Platform, and3.7/3.6are deprecated there). - Image generation:
gemini-nano-banana-2.1,gemini-3.1-flash-image,gemini-3.1-flash-lite-image, andgemini-3-pro-image. - Text-to-speech:
gemini-3.8-flash-ttsandgemini-3.8-flash-lite-tts. - Live (bidirectional):
gemini-3.8-liveon both providers, andgemini-live-2.5-flash-native-audioon Agent Platform only.
Update model names remotely
Section titled “Update model names remotely”Gemini models retire on regular schedules, and a model ID compiled into a mobile or desktop app stops working once that model shuts down. Firebase recommends reading the model name from Firebase Remote Config so you can roll forward to a newer model without shipping an app update. Add the package with flutter pub add firebase_remote_config, then:
import 'package:firebase_remote_config/firebase_remote_config.dart';
final remoteConfig = FirebaseRemoteConfig.instance;await remoteConfig.setDefaults({'model_name': 'gemini-3.8-flash'});await remoteConfig.fetchAndActivate();
final response = await ai.generate( model: firebaseAI.gemini(remoteConfig.getString('model_name')), prompt: 'Tell me a joke about a developer.',);Configuration
Section titled “Configuration”firebaseAI() accepts an optional FirebaseApp, backend provider, useLimitedUseAppCheckTokens flag, and custom httpClient:
final firebasePlugin = firebaseAI( app: Firebase.app('my-app'), provider: const FirebaseAiProvider.agentPlatform(), useLimitedUseAppCheckTokens: true,);
final ai = Genkit(plugins: [firebasePlugin]);provider:FirebaseAiProvider.googleAI()(default) routes requests through the Gemini Developer API.FirebaseAiProvider.agentPlatform({String? location})routes requests through the Gemini Enterprise (Agent Platform, formerly Vertex AI) Gemini API. Whenlocationis omitted, it defaults to'global'.
useLimitedUseAppCheckTokens: Sends a single-use App Check token with each request. Enable this when you turn on App Check replay protection, which rejects reusable session tokens.
Regional locations and Live models
Section titled “Regional locations and Live models”On FirebaseAiProvider.agentPlatform(), standard text and multimodal Gemini models are served from the default 'global' endpoint and can fail with NOT_FOUND on regional endpoints. Agent Platform Live models (and workloads with regional data residency requirements) require a regional location such as 'us-central1'.
Because each plugin instance targets a single location, an app that uses both text models and Live models on Agent Platform should create two Genkit instances:
final ai = Genkit( plugins: [firebaseAI(provider: const FirebaseAiProvider.agentPlatform())],);final liveAi = Genkit( plugins: [ firebaseAI( provider: const FirebaseAiProvider.agentPlatform(location: 'us-central1'), ), ],);Custom HTTP client
Section titled “Custom HTTP client”Pass httpClient to route generateContent and streamGenerateContent requests through your own http.Client (for proxies, custom logging, or mock transports in tests). Live models connect over a WebSocket and do not use httpClient. The plugin never closes a caller-supplied client, so close it yourself when done:
import 'package:http/http.dart' as http;
final httpClient = http.Client();final ai = Genkit(plugins: [firebaseAI(httpClient: httpClient)]);// ...httpClient.close();Model options
Section titled “Model options”Pass GeminiOptions via config:
final response = await ai.generate( model: firebaseAI.gemini('gemini-3.8-flash'), prompt: 'Plan a three-day trip to Lisbon.', config: GeminiOptions( maxOutputTokens: 2048, thinkingConfig: ThinkingConfig(thinkingLevel: 'LOW'), ),);Thinking
Section titled “Thinking”Gemini 3 and newer models accept an uppercase thinkingLevel ('MINIMAL', 'LOW', 'MEDIUM', or 'HIGH'; supported levels vary by model, and gemini-3.8-flash rejects 'MINIMAL'). Older models use thinkingBudget (token count) instead. Setting both fails with INVALID_ARGUMENT before sending a request. Set includeThoughts: true to return thought summaries as reasoning parts:
final response = await ai.generate( model: firebaseAI.gemini('gemini-3.8-flash'), prompt: 'Compare two approaches to offline sync in mobile apps.', config: GeminiOptions( thinkingConfig: ThinkingConfig( thinkingLevel: 'HIGH', includeThoughts: true, ), ),);
print( response.message?.content.map((part) => part.reasoning).nonNulls.join('\n'),);For multi-turn tool calling on Gemini 3+, the plugin preserves thought signatures in each part’s metadata['thoughtSignature'] and sends them back automatically when you pass the response messages into subsequent turns.
Safety settings
Section titled “Safety settings”Configure per-category blocking thresholds with safetySettings. The HARM_CATEGORY_IMAGE_* categories and method ('SEVERITY' or 'PROBABILITY') are supported on Agent Platform only; the plugin rejects them with INVALID_ARGUMENT when configured with FirebaseAiProvider.googleAI().
config: GeminiOptions( safetySettings: [ GeminiSafetySettings( category: 'HARM_CATEGORY_HARASSMENT', threshold: 'BLOCK_ONLY_HIGH', ), ],)Grounding
Section titled “Grounding”GeminiOptions supports three grounding tools:
googleSearch: Grounds answers in live Google Search results.urlContext: Lets the model fetch and read URLs included in the prompt.googleMaps: Grounds answers in Google Maps data. Pass user coordinates inretrievalConfig(latLngrequires bothlatitudeandlongitude).
final response = await ai.generate( model: firebaseAI.gemini('gemini-3.8-flash'), prompt: 'Who won the most recent Formula 1 race?', config: GeminiOptions(googleSearch: GeminiGoogleSearch()),);
final grounding = response.custom?['groundingMetadata'] as Map?;print(grounding?['webSearchQueries']);for (final chunk in grounding?['groundingChunks'] as List? ?? []) { print(chunk['web']?['uri']);}For Google Maps grounding:
config: GeminiOptions( googleMaps: GeminiGoogleMaps(), retrievalConfig: GeminiRetrievalConfig( latLng: GeminiLatLng(latitude: 38.72, longitude: -9.14), ),)response.custom contains groundingMetadata (webSearchQueries, groundingChunks, groundingSupports, and searchEntryPoint) and, when URL context is enabled, urlContextMetadata. Use firebase_ai 5.1.0 or later so webSearchQueries is populated. When you use Google Search grounding, you must display the search suggestions and the sources: render the HTML in searchEntryPoint.renderedContent, and show the sources from groundingChunks (groundingSupports links them to the response text).
Images and speech
Section titled “Images and speech”Image generation models return generated images as media parts with data: URLs. Set responseModalities and optional imageConfig:
final response = await ai.generate( model: firebaseAI.gemini('gemini-3.1-flash-image'), prompt: 'A watercolor of a lighthouse at dawn.', config: GeminiOptions( responseModalities: ['TEXT', 'IMAGE'], imageConfig: GeminiImageConfig(aspectRatio: '16:9', imageSize: '2K'), ),);final image = response.media; // Media(url: 'data:image/png;base64,...')Text-to-speech models return audio media parts the same way. SpeechConfig accepts either a single voiceConfig or a multiSpeakerVoiceConfig with two speakers. For two-speaker synthesis, pass promptParts and attach metadata: {'speechMetadata': {'speaker': '<name>'}} (with optional 'style') to every TextPart, matching the speaker names in speakerVoiceConfigs:
final response = await ai.generate( model: firebaseAI.gemini('gemini-3.8-flash-tts'), promptParts: [ TextPart( text: 'Did we ship it?', metadata: {'speechMetadata': {'speaker': 'Joe', 'style': 'nervous'}}, ), TextPart( text: 'We shipped it.', metadata: {'speechMetadata': {'speaker': 'Jane'}}, ), ], config: GeminiOptions( responseModalities: ['AUDIO'], speechConfig: SpeechConfig( multiSpeakerVoiceConfig: MultiSpeakerVoiceConfig( speakerVoiceConfigs: [ SpeakerVoiceConfig( speaker: 'Joe', voiceConfig: VoiceConfig( prebuiltVoiceConfig: PrebuiltVoiceConfig(voiceName: 'Kore'), ), ), SpeakerVoiceConfig( speaker: 'Jane', voiceConfig: VoiceConfig( prebuiltVoiceConfig: PrebuiltVoiceConfig(voiceName: 'Puck'), ), ), ], ), languageCode: 'en-US', ), ),);final audio = response.media; // Media(url: 'data:audio/...;base64,...')Media resolution
Section titled “Media resolution”Set mediaResolution on GeminiOptions ('MEDIA_RESOLUTION_LOW', 'MEDIA_RESOLUTION_MEDIUM', or 'MEDIA_RESOLUTION_HIGH') to control how much detail the model extracts from image and video inputs. Individual MediaPart items can override this in metadata and also accept 'MEDIA_RESOLUTION_ULTRA_HIGH':
MediaPart( media: Media(url: 'gs://my-bucket/scan.png', contentType: 'image/png'), metadata: {'mediaResolution': 'MEDIA_RESOLUTION_ULTRA_HIGH'},)Code execution
Section titled “Code execution”Set codeExecution: true on GeminiOptions to let the model write and execute Python. Generated code and execution output come back as custom parts under executableCode and codeExecutionResult (use firebase_ai 5.0.0 or later so generated file parts return as media parts).
Structured output
Section titled “Structured output”When you pass outputSchema, the plugin forwards your JSON Schema unchanged to Gemini as responseJsonSchema, preserving keywords such as enum, anyOf, $ref, minimum/maximum, additionalProperties, and required:
final response = await ai.generate( model: firebaseAI.gemini('gemini-flash-latest'), prompt: 'List three primary colors.', outputSchema: .list(.string()),);print(response.output); // List<String>For complex object schemas, define a @Schema() type with schemantic; see Generating content.
Tool calling
Section titled “Tool calling”Define tools with ai.defineTool() and reference them in ai.generate(). Tool input schemas are sent unchanged as parametersJsonSchema:
import 'package:schemantic/schemantic.dart';
part 'main.g.dart'; // generated by build_runner
@Schema()abstract class $WeatherToolInput { String get city;}
// ... inside an async function:ai.defineTool( name: 'getWeather', description: 'Get the weather for a location', inputSchema: WeatherToolInput.$schema, fn: (input, context) async { return .response('The weather in ${input.city} is 75F and sunny.'); },);
final response = await ai.generate( model: firebaseAI.gemini('gemini-flash-latest'), prompt: 'What is the weather in Boston?', toolNames: ['getWeather'],);See Tool calling for multi-step tool loops and interrupts.
Errors and cancellation
Section titled “Errors and cancellation”Errors from Firebase AI Logic, the network, or the SDK map to GenkitException with an appropriate StatusCode (for example, RESOURCE_EXHAUSTED for quota limits, UNAVAILABLE for transient backend failures, and FAILED_PRECONDITION when a prompt is blocked for safety).
ai.generate() reports model errors in the response rather than throwing: check response.finishReason == FinishReason.failed, inspect response.error for the status and message, or read response.cause for the thrown GenkitException (for a firebase_ai or network error, the original exception is its cause). Pair requests with the built-in retry() middleware to retry transient statuses such as UNAVAILABLE and RESOURCE_EXHAUSTED without retrying safety blocks:
final response = await ai.generate( model: firebaseAI.gemini('gemini-flash-latest'), prompt: 'Hello', use: [retry(maxRetries: 2)],);if (response.finishReason == FinishReason.failed) { print('${response.error?.status}: ${response.error?.message}');}To abort an in-flight HTTP request or stream (for example, when the user taps a Stop button), pass a CancellationToken. Cancelled requests finish with FinishReason.aborted:
final controller = CancellationController();final future = ai.generate( model: firebaseAI.gemini('gemini-flash-latest'), prompt: 'Write a long story.', cancel: controller.token,);
// Later, when the user cancels:controller.cancel('user pressed stop');Live API
Section titled “Live API”Live models stream over a WebSocket via ai.generateBidi(): you send text, audio, or video, and the model replies with audio (note that generateBidi takes a 'firebaseai/<model-id>' string identifier):
import 'package:genkit/experimental.dart';
final session = await ai.generateBidi( model: 'firebaseai/gemini-3.8-live', config: LiveGenerationConfig( responseModalities: ['AUDIO'], speechConfig: SpeechConfig( voiceConfig: VoiceConfig( prebuiltVoiceConfig: PrebuiltVoiceConfig(voiceName: 'Algenib'), ), ), ), system: 'You are a friendly assistant.',);
session.send('Hello');session.stream.listen((chunk) { // Audio media parts arrive as data: URLs.});Keep these platform and backend constraints in mind when using Live models:
- Agent Platform location: On
FirebaseAiProvider.agentPlatform(), Live models require a regional location such as'us-central1'(the'global'endpoint closes the session because the model is not served there). - Flutter web and App Check: On web, Live sessions fail while App Check is enforced because
firebase_aicannot attach the App Check header to browser WebSocket connections (flutterfire#18938). Android, iOS, and macOS attach the token header as expected. - System instructions: Pass system instructions only when opening the session (
system:ongenerateBidi); sending a system message mid-session fails withINVALID_ARGUMENT.
Local observability with the Developer UI
Section titled “Local observability with the Developer UI”Use genkit start:flutter to launch your Flutter app alongside the Genkit Developer UI. It starts the telemetry server and WebSocket reflection server, serves the Developer UI (at http://localhost:4000 by default; add -o to open it in your browser), and passes the required --dart-define flags to flutter run automatically so both live traces and registered models, flows, and tools appear in the UI:
genkit start:flutter
# Pass any flutter run flags after --genkit start:flutter -- -d chromeIf you launch Flutter separately (for example, from your IDE debugger or a second terminal), write the dev environment to a file and pass it with --dart-define-from-file (add genkit.env to .gitignore):
genkit start --write-env-file=genkit.env --experimental-reflection-v2flutter run --dart-define-from-file=genkit.env -d chromeFor a complete runnable Flutter sample covering chat, structured streaming, grounding, tool calling, and Live audio, see testapps/firebase_ai in the genkit-dart repository.
Migrate from pre-1.0
Section titled “Migrate from pre-1.0”If you’re upgrading from an earlier 0.x release of genkit_firebase_ai, update your code for these changes (the first two shipped in 0.4.0, the rest in 1.0.0):
FirebaseAiProvider.vertexAIis nowFirebaseAiProvider.agentPlatform: The default location changed from'us-central1'to'global'. Passlocation: 'us-central1'if you need the previous regional endpoint.appCheckandauthplugin parameters removed:firebase_aireads App Check and Auth from theFirebaseAppwhen it first constructs and caches itsFirebaseAIinstance. ActivateFirebaseAppCheckandFirebaseAuthfor yourFirebaseAppbefore the first model call, and usefirebase_ai5.1.0 or later souseLimitedUseAppCheckTokensis part of the SDK’s instance cache key.GeminiOptions.responseSchemareplaced byresponseJsonSchema: Prefer passingoutputSchemaonai.generate(), or pass raw JSON Schema inGeminiOptions(responseMimeType: 'application/json', responseJsonSchema: ...).- Internal converters and Live helpers unexported: Helper functions such as
toGemini*,fromGemini*,extractUsage, andrunLiveSessionare now private; call models throughfirebaseAIwithai.generate()orai.generateBidi(). firebaseAiModelInforemoved: Each registered model now carries its own label, stage, and capabilities in itsmetadata['model'].GeminiOptions.responseLogprobsandlogprobsremoved: Firebase AI Logic doesn’t support them; remove them from your config.- Output and tool input schemas sent unchanged:
outputSchemagoes to Gemini asresponseJsonSchema, and tool input schemas asparametersJsonSchema. They used to be converted to OpenAPI-style schemas, which dropped keywords such asenum,oneOf,additionalProperties, anddefault, so the same definitions can now produce different output or tool calls. - Errors and finish reasons use Genkit’s vocabulary: Firebase AI Logic and HTTP errors are reported as a
GenkitExceptionwith aStatusCode(the original exception is itscause), and finish reasons map toFinishReason.stop,length,blocked,other, orunknowninstead offirebase_ai’s enum names. The raw Gemini value is inresponse.custom?['finishReason']. - Live sessions the server closes end with an error: For example, a session with a bad setup now ends with the server’s error instead of a normal stop.