Firebase Genkit is an open source framework that helps you build, deploy, and monitor production-ready AI-powered apps.
Genkit is designed for app developers. It helps you to easily integrate powerful AI capabilities into your apps with familiar patterns and paradigms.
Use Genkit to create apps that generate custom content, use semantic search, handle unstructured inputs, answer questions with your business data, autonomously make decisions, orchestrate tool calls, and much more.
Objective
This lab provides an introductory, hands-on experience with Firebase Genkit and the Gemini foundation model. You leverage the default flow and deploy it to both Google Cloud and Firebase.
You learn how to:
Create a new Firebase Genkit project.
Create flows with Genkit and Gemini.
Deploy a Genkit flow to Cloud Run.
Deploy a Genkit flow to Firebase.
Setup and requirements
Before you click the Start Lab button
Note: Read these instructions.
Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.
This Qwiklabs hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.
What you need
To complete this lab, you need:
Access to a standard internet browser (Chrome browser recommended).
Time to complete the lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab.Note: If you are using a Pixelbook, open an Incognito window to run this lab.
How to start your lab and sign in to the Console
Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method.
On the left is a panel populated with the temporary credentials that you must use for this lab.
Copy the username, and then click Open Google Console.
The lab spins up resources, and then opens another tab that shows the Choose an account page.
Note: Open the tabs in separate windows, side-by-side.
On the Choose an account page, click Use Another Account. The Sign in page opens.
Paste the username that you copied from the Connection Details panel. Then copy and paste the password.
Note: You must use the credentials from the Connection Details panel. Do not use your Google Cloud Skills Boost credentials. If you have your own Google Cloud account, do not use it for this lab (avoids incurring charges).
Click through the subsequent pages:
Accept the terms and conditions.
Do not add recovery options or two-factor authentication (because this is a temporary account).
Do not sign up for free trials.
After a few moments, the Cloud console opens in this tab.
Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left.
Activate Google Cloud Shell
Google Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud.
Google Cloud Shell provides command-line access to your Google Cloud resources.
In Cloud console, on the top right toolbar, click the Open Cloud Shell button.
Click Continue.
It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:
gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
You can list the active account name with this command:
Go to the src folder and open the index.ts file. Add the following import library references to the index.ts file:
import { z, genkit } from 'genkit';
import { vertexAI } from '@genkit-ai/vertexai';
import { gemini20Flash001 } from '@genkit-ai/vertexai';
import { logger } from 'genkit/logging';
import { enableGoogleCloudTelemetry } from '@genkit-ai/google-cloud';
import { startFlowServer } from '@genkit-ai/express';
After the import statements, add code to initialize and configure the genkit instance, and configure logging and telemetry:
const ai = genkit({
plugins: [
// Load the Vertex AI plugin. You can optionally specify your project ID
// by passing in a config object; if you don't, the Vertex AI plugin uses
// the value from the GCLOUD_PROJECT environment variable.
vertexAI({ location: '{{{project_0.default_region| Lab Region}}}' }),
],
});
logger.setLogLevel('debug');
enableGoogleCloudTelemetry();
Add code to define a flow named menuSuggestionFlow which prompts the model to suggest an item for a menu of a themed restaurant, with the theme provided as input:
export const menuSuggestionFlow = ai.defineFlow(
{
name: 'menuSuggestionFlow',
inputSchema: z.string(),
outputSchema: z.string(),
},
async (subject) => {
const llmResponse = await ai.generate({
prompt: `Suggest an item for the menu of a ${subject} themed restaurant`,
model: gemini20Flash001,
config: {
temperature: 1,
},
});
return llmResponse.text;
}
);
Add code to start the flow server and expose your flows as HTTP endpoints on the specified port:
startFlowServer({
flows: [menuSuggestionFlow],
port: 8080,
cors: {
origin: '*',
},
});
Note: The CORS setting allows any origin, which is designed to simplify the development of this lab. You will want a more restrictive CORS policy for production apps.
Test the application
To test the application, click Open Terminal, and, in Cloud Shell, run the following commands:
cd ~/genkit-intro
npx genkit start --noui -- npx tsx src/index.ts
This command starts Genkit without the Genkit Developer UI, and provides the npx tsx src/index.ts command to Genkit.
When prompted, press Enter to continue.
Wait till the Genkit flow server starts. When ready, you should see output similar to:
Flow server running on http://localhost:8080
Reflection server (1769) running on http://localhost:3100
Open a new terminal in Cloud Shell, and run:
cd ~/genkit-intro
npx genkit flow:run menuSuggestionFlow '"French"' | tee response.txt
Click Check my progress to verify the objectives.
Setup your Genkit Project
Note: Copying the files to the Google Cloud Storage location is used in the assessment process. If you've made file updates after copying the files, please upload the modified files again by running the same commands.
Task 2. Deploy the flow to Cloud Run
In this task, you deploy your Genkit application to Cloud Run, so that anyone can access it over the internet.
In Cloud Shell, to update package.json, run the following commands:
npm pkg set main="lib/index.js" scripts.build="tsc"
In the Cloud Shell editor, open the file ~/genkit-intro/package.json.
The exact versions of some libraries might be different from what is shown.
To create a default Typescript configuration file to build your application, in Cloud Shell, run the following command:
cat <<EOF >~/genkit-intro/tsconfig.json
{
"compileOnSave": true,
"include": [
"src"
],
"compilerOptions": {
"module": "NodeNext",
"noImplicitReturns": true,
"outDir": "lib",
"sourceMap": true,
"strict": true,
"target": "es2017",
"skipLibCheck": true,
"esModuleInterop": true,
"moduleResolution": "nodenext",
"noUnusedLocals": true
}
}
EOF
A tsconfig.json file is a configuration file for TypeScript projects that specifies compiler options and settings that are needed to compile your project.
To run the build, in the Cloud Shell, run the following commands:
cd ~/genkit-intro
npm run build
To deploy the application to Cloud Run, run the following command:
gcloud run deploy {{{project_0.startup_script.cloud_run_service_name| Cloud Run Service Name}}} --region {{{project_0.default_region| Lab Region}}} --allow-unauthenticated --source .
When prompted to continue, type Y, and press Enter.
It may take a few minutes to deploy the service.
Once the service is deployed, to test the service, run the following commands:
export SERVICE_URL=$(gcloud run services describe {{{project_0.startup_script.cloud_run_service_name| Cloud Run Service Name}}} --platform managed --region {{{project_0.default_region| Lab Region}}} --format 'value(status.url)')
curl -X POST "$SERVICE_URL/menuSuggestionFlow" -H "Authorization: Bearer $(gcloud auth print-identity-token)" -H "Content-Type: application/json" -d '{"data": "banana"}'
The first command retrieves the URL for the Cloud Run service, and the second command calls the flow hosted on the service.
In the Google Cloud Console, in the Navigation menu (), click Cloud Run, and click the service.
View the metrics for the call that you just performed.
To see the logs for your service, select the Logs tab.
Click Check my progress to verify the objectives.
Deploy the flow to Cloud Run
Task 3. Deploy a Genkit flow to Firebase
Firebase Genkit includes a plugin that helps you deploy your flows to Cloud Functions for Firebase. This task walks you through the process of deploying a default sample flow to Firebase.
Set up Firebase
To install Firebase tools, run:
npm install -g firebase-tools@14.0.1
The npm install command installs the Firebase Command Line Interface (CLI) tools to test, manage, and deploy your Firebase project from the command line.
Note: This version of the Firebase CLI is required to initialize the latest version of genkit in the later steps of this task.
Update the path, and verify the version of Firebase installed:
echo 'export PATH="$(npm config get prefix)/bin:$PATH"' >> ~/.bashrc
export PATH="$(npm config get prefix)/bin:$PATH"
echo "firebase version $(firebase --version)"
The path is updated to ensure that you run the firebase commands from the packages you just installed, instead of running them from preexisting installs that may exist in Cloud Shell.
In Cloud Shell Terminal, to create a directory for the new app and set the project and location variables, run the following commands:
To change the default region for Vertex AI, run the following command:
sed -i 's/us-central1/{{{project_0.default_region | Region}}}/g' ~/genkit-fire/functions/src/index.ts
Update the Gemini model used in the sample application:
sed -i 's/gemini15Flash/gemini20Flash/g' ~/genkit-fire/functions/src/index.ts
The latest genkit library used by the genkit-fire app supports the latest Gemini 2.0 Flash model gemini20Flash. Note that the genkit-intro app that you developed in the earlier lab tasks uses a previous genkit library version that only supports the stable model version gemini20Flash001. For more information, refer to the documentation on model versions and lifecycle.
Click Open Editor, navigate to the ~/genkit-fire/functions/src folder, and open the index.ts file.
To define an authorization policy for the flow, in the onCallGenkit() method, uncomment the authPolicy parameter:
authPolicy: hasClaim('email_verified'),
To deploy your flow to Firebase Cloud Functions, you must wrap the flow in the onCallGenkit() method that enables you to quickly create a callable function in Firebase.
Add the cors, and region parameters to the onCallGenkit() function:
cors: true,
region: '{{{project_0.default_region| Lab Region}}}',
Note: This CORS setting allows any origin, which is designed to simplify the development of this lab. You will want a more restrictive CORS policy for production apps.
Comment out the secrets parameter as the flow does not use the Gemini model in Google AI which reqires an API key to be provided. Instead, the flow uses Gemini in Vertex AI.
Also, comment out these lines above the genkit initialization code:
//import { defineSecret } from "firebase-functions/params";
//const apiKey = defineSecret("GOOGLE_GENAI_API_KEY");
const ai = genkit({
plugins: [
...
],
});
After the updates are made, the onCallGenkit() method invocation should look like this:
(Comments have been removed from the snippet below)
Click Open Terminal, navigate to the ~/genkit-fire/functions folder, and try the flow in the developer UI.
cd ~/genkit-fire/functions
npx genkit start -- npx tsx src/index.ts | tee -a flow_response.txt
Wait for the command to return the Genkit Developer UI URL in the output before continuing to the next step.
Click the Web Preview button, and click Change port.
Change the port to 4000, and click Change and Preview.
The Genkit Developer UI opens in your browser.
The Developer UI might indicate a warning that it is waiting to connect to the Genkit flow server. Wait until the connection is established before proceeding.
On the left side panel, click Flows. For the flow to run, click menuSuggestionFlow.
On the Input JSON tab, use the following subject for the model:
"seafood"
Click the Context JSON tab, and use the following as a simulated auth object:
{"auth": {"email_verified": true}}
To test the flow, click Run.
The output from the flow is displayed.
Note: You might have to go back to the Google Cloud Console tab and accept the popup asking for authorization.
Close the Genkit Developer UI tab, and return to Cloud Shell Terminal. Press CTRL+C to exit.
For lab assessment purposes, run the following commands to move the file to the Cloud Storage Bucket named .
Now, deploy the function to Firebase using the following command:
cd ~/genkit-fire
firebase deploy --only functions
Note: Re-run the command if you get the following error: User code failed to load, Cannot determine backend specification.
Ignore any warning messages that might be displayed.
If prompted to enter the number of days to keep container images, use the default and press Enter.
You've now deployed the flow as a Cloud Run function, but you won't be able to access your deployed endpoint with curl or a similar tool, because of the flow's authorization policy. Continue to the next section to learn how to securely access the flow.
The default sample flow uses the authorization policy:
authPolicy: hasClaim("email_verified")
The onCallGenkit() wrapper provided by the Firebase Functions library uses Firebase Auth to protect your flows. It has built-in support for the Cloud Functions for Firebase client SDKs.
Test the deployed flow
To test your flow endpoint, you can deploy a simple web app.
To use Genkit with the Firebase Emulator Suite, start the Firebase emulators by running the following commands.
To use Genkit with the Firebase Emulator Suite, in Cloud Shell, run the following commands:
cd ~/genkit-fire
GENKIT_ENV=dev firebase emulators:start --inspect-functions | tee -a response.txt
This will run your code in the emulator and run the Genkit framework in development mode, which launches and exposes the Genkit reflection API (but not the Dev UI).
The emulators' UI is hosted on localhost port 4000.
Click the Web Preview button, and click Change port.
Change the port to 4000, and click Change and Preview.
The emulators UI is presented.
Keep the emulators running in this terminal tab, and open a new tab using the + button in Cloud Shell.
To launch the Genkit Developer UI and run it against the emulated code, run the following commands:
cd ~/genkit-fire/functions
npx genkit start -- npx tsx src/index.ts --attach http://localhost:3100 --port 4001 | tee -a response.txt
The Genkit Developer UI will be hosted on port 4001. Instead of calling a Cloud Run function, the developer UI uses the emulator.
Click the Web Preview button, and click Change port.
Change the port to 4001, and click Change and Preview.
The Genkit developer UI opens in a new tab, and you can make calls against the emulator.
Return to the Cloud Shell terminal and press CTRL+C to exit.
Run the following commands to move the file to the Cloud Storage Bucket named .
Click Check my progress to verify the objectives.
Develop web app using Firebase Local Emulator
Congratulations!
You have successfully created a Genkit project and deployed it both to Google Cloud Run and Firebase. Additionally, you tested the application through the Genkit development UI and the CLI interface.
Manual Last Updated July 03, 2025
Lab Last Tested July 03, 2025
Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.
Moduły tworzą projekt Google Cloud i zasoby na określony czas.
Moduły mają ograniczenie czasowe i nie mają funkcji wstrzymywania. Jeśli zakończysz moduł, musisz go zacząć od początku.
Aby rozpocząć, w lewym górnym rogu ekranu kliknij Rozpocznij moduł.
Użyj przeglądania prywatnego
Skopiuj podaną nazwę użytkownika i hasło do modułu.
Kliknij Otwórz konsolę w trybie prywatnym.
Zaloguj się w konsoli
Zaloguj się z użyciem danych logowania do modułu. Użycie innych danych logowania może spowodować błędy lub naliczanie opłat.
Zaakceptuj warunki i pomiń stronę zasobów przywracania.
Nie klikaj Zakończ moduł, chyba że właśnie został przez Ciebie zakończony lub chcesz go uruchomić ponownie, ponieważ spowoduje to usunięcie wyników i projektu.
Ta treść jest obecnie niedostępna
Kiedy dostępność się zmieni, wyślemy Ci e-maila z powiadomieniem
Świetnie
Kiedy dostępność się zmieni, skontaktujemy się z Tobą e-mailem
Jeden moduł, a potem drugi
Potwierdź, aby zakończyć wszystkie istniejące moduły i rozpocząć ten
Aby uruchomić moduł, użyj przeglądania prywatnego
Uruchom ten moduł w oknie incognito lub przeglądania prywatnego. Dzięki temu unikniesz konfliktu między swoim kontem osobistym a kontem do nauki, co mogłoby spowodować naliczanie dodatkowych opłat na koncie osobistym.
This lab guides users through a hands-on experience with Firebase Genkit. Participants will learn to deploy a default flow to Cloud Run and Firebase.
Czas trwania:
Konfiguracja: 1 min
·
Dostęp na 90 min
·
Ukończono w 90 min