Adding powerful AI features to your app can make it smarter and more engaging. This guide shows you a way to use Google's Gemini AI, but instead of adding it directly with a Flutter plugin, we use Firebase Functions. This method keeps your sensitive API key safe on your server, not directly in your app.
Why Use Firebase Functions?
Security is a big reason. By keeping your Gemini API key in Firebase Functions, you avoid putting it into your app's code, which is less secure.
Steps to Add Gemini with Firebase
Here's how you can set this up:
1. Set up Firebase and Dependencies
Start a new Firebase project or use an existing one. You'll need to initialize genkit
in your project using the firebase init genkit
command. Make sure you have Node.js version 18 or higher installed. You also need these packages:
@genkit-ai/ai
@genkit-ai/core
@genkit-ai/dotprompt
@genkit-ai/firebase
@genkit-ai/flow
@genkit-ai/googleai
zod
2. Install Genkit Globally
Open your terminal and run this command:
npm install -g genkit
3. Configure Genkit
In your Firebase project, set up Genkit. You'll need to configure it to use Firebase and Google AI. Importantly, you must add your GOOGLE_GENAI_API_KEY
to a .env
file in your Firebase functions directory. Make sure your .gitignore
file is set up so this .env
file is not accidentally uploaded.
How the Firebase Function Works
You create a function, like suggestionFlow
shown in the example, that runs on Firebase. This function:
- Handles requests securely (you can check if the user is allowed).
- Defines what kind of data it expects to receive (input) and what kind of data it will send back (output).
- Takes the user's request.
- Calls the Gemini model (like
gemini15Flash
) with a specific prompt. - Asks Gemini to respond in a specific format, like JSON.
- Returns Gemini's answer.
Calling the Function from Flutter
In your Flutter app, you use the Firebase Functions package to call your deployed function (suggestionFlow
). You pass the necessary info (like user ID, what they are asking for, and their language). When you get the response back, you can easily read the data, especially if you asked the AI to send it back in JSON format.
Deploy and Test
After creating your function, deploy it to Firebase using firebase deploy --only functions
. You can also test your function on your computer locally using the genkit start
command (remember to set up your API key locally for testing).
This method gives you a secure way to bring the power of Gemini AI into your Flutter app.