1. Introduction
In this codelab, you'll add a smart customer support chat widget to an outdoor gear ecommerce shop called Rugged Terrain Guide. You'll use Firebase AI Logic to build this agent, and you'll learn how to configure a server-side prompt template (product-agent) that handles the AI's persona, strict appeasement budget rules, and dynamically uses the product catalog as context.
What you'll do:
- Get the starter code for this codelab's web app.
- Set up a Firebase project.
- Set up and initialize Firebase services (like Firebase AI Logic) in a web app.
- Configure a server-side prompt template in the Firebase console.
- Access the template from a call to the generative AI service from a React-like TypeScript frontend.
What you'll need:
- A web browser such as Chrome.
- Basic familiarity with TypeScript and Node.js.
- An IDE or text editor of your choice. Antigravity is a good choice.
2. Get the starter code
- In your terminal, clone the starter repository:
git clone https://github.com/GoogleCloudPlatform/devrel-demos.git - Navigate to the code directory and install dependencies:
cd devrel-demos/codelabs/firebase-server-prompt-templates-codelab npm install
3. Set up a Firebase project
Create a Firebase project
- Sign into the Firebase console using your Google Account.
- Click the button to create a new project, and then enter a project name (for example,
rugged-terrain-ai).
- Click Continue.
- If prompted, review and accept the Firebase terms, and then click Continue.
- (Optional) Enable AI assistance in the Firebase console (called "Gemini in Firebase").
- For this codelab, you do not need Google Analytics, so toggle off the Google Analytics option.
- Click Create project, wait for your project to provision, and then click Continue.
Upgrade your Firebase pricing plan
To use the Firebase services in this codelab, your Firebase project needs to be on the pay-as-you go (Blaze) pricing plan, which means it's linked to a Cloud Billing account.
- A Cloud Billing account requires a payment method, like a credit card.
- During special promotions or if you're doing this codelab as part of an event, there may be Google Cloud credits available.
- If you're new to Firebase and Google Cloud, check if you're eligible for a $300 credit and a Free Trial Cloud Billing account.
To upgrade your project to the Blaze plan, follow these steps:
- In the Firebase console, select to upgrade your plan.
- Select the Blaze plan. Follow the on-screen instructions to link a Cloud Billing account to your project.
- If you're using Google Cloud credits for this codelab, the billing account is likely called
Google Cloud Platform Trial Billing AccountorMy Billing Account. - If you needed to create a Cloud Billing account as part of this upgrade, you might need to navigate back to the upgrade flow in the Firebase console to complete the upgrade.
- If you're using Google Cloud credits for this codelab, the billing account is likely called
4. Set up Firebase services and connect your app
For this codelab, you need to set up Cloud Storage for Firebase and Firebase AI Logic in your Firebase project. You also need to connect your app's source code to your Firebase project.
Set up Cloud Storage for Firebase
This codelab uses Cloud Storage for Firebase to store product descriptions.
- In the Firebase console, go to Databases & Storage > Storage.
- Click Get started.
- Select a location for your default Storage bucket.
Buckets inUS-WEST1,US-CENTRAL1, andUS-EAST1can take advantage of the "Always Free" tier for Google Cloud Storage. Buckets in all other locations follow Google Cloud Storage pricing and usage. - Click Production mode. In the steps just below, you'll update these Security Rules to be specific for this codelab.
- Click Create.
- Update your Security Rules:
- After the bucket is provisioned, go to the Rules tab.
- Copy and then paste in the following rules:
rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /products.txt { allow read; } } } - Click Publish.
- Upload the product descriptions from the starter code:
- Click the Files tab for your Storage bucket.
- Click Upload File, and then upload the
products.txtfile from the starter code. This file can be found at:src/data/products.txt.
Configure Firebase AI Logic
Firebase AI Logic is the main Firebase service that you'll use in this codelab.
- In the Firebase console, go to AI Services > AI Logic.
- Click Get started.
- On the Agent Platform Gemini API card, click Get started with this API and follow the on-screen instructions. This flow will enable the required APIs for you to use Firebase AI Logic with the Agent Platform Gemini API.
- (Optional) Select to Enable AI monitoring so that you can observe various app-level metrics and usage to gain comprehensive visibility into your requests via Firebase AI Logic.
Connect your code to your Firebase project
As part of setting up Firebase AI Logic, you'll be prompted to create a Firebase Web App and to add your configuration to your source code.
- When prompted in the Firebase AI Logic setup flow, click the Web (
>) icon to register a new web app. - Name the app (for example,
Rugged Web). - Copy the
firebaseConfigobject from the setup instructions.
Next, update the starter code:
- In your code editor, open
src/firebase.ts. - Replace the existing
firebaseConfigwith the one you copied from the Firebase console.
Your file should look like this:
import { getAI, getTemplateGenerativeModel, AgentPlatformBackend } from "firebase/ai";
import { initializeApp } from "firebase/app";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.firebasestorage.app",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
// Initialize Firebase
export const app = initializeApp(firebaseConfig);
const ai = getAI(app, { backend: new AgentPlatformBackend() });
5. Create the server-side prompt template
Instead of hardcoding complex AI prompts in the client app, you'll use Dotprompt syntax to manage instructions securely on the server.
This prevents end-users from seeing the secret "Appeasement Budget" rules.
- In the Firebase console, go to the AI Services > AI Logic > Prompt templates tab.
- Click Create template, and choose Blank template.
- Set the template name to
Product Agentand the ID toproduct-agent. - Set the model to
gemini-3.1-flash-lite(or the latest version available). - From the starter code provided for this codelab, copy the contents of
product-agent.prompt(find this file in the root directory). Then, paste this content into the Prompt and (optional) system instructions field of the server prompt template in the Firebase console. This content securely instructs the model how to behave as "Rugged Operator" and reference the product catalog. - In the Test input field define the input schema exactly as follows:
{ "type": "object", "required": [ "query" ], "properties": { "query": { "type": "string", "description": "the customers ask of the robot" }, "productId": { "type": "string", "description": "the product the customer is looking at right now" }, "history": { "type": "array", "description": "list of previous history between the user and system", "items": { "type": "object", "required": [ "role", "contents" ], "properties": { "role": { "type": "string" }, "contents": { "type": "string" } } } } } } - Click Save template to save and publish the
product-agenttemplate.
6. Call the AI model
Now that the template is defined securely on the server, you just need to call it from your app's frontend.
- In your code editor, return to
src/firebase.ts. - Below the initialization, use
getTemplateGenerativeModelto connect to the template:const model = getTemplateGenerativeModel(ai); export const callCustomerSupportModel = async (query: string, productId?: string, history?: { role: string, contents: string }[]) => { // Generate content using the published 'product-agent' template const result = await model.generateContent('product-agent', { query, productId, history, }); return result.response.text(); }
7. Secure the agent with Firebase App Check
AI models are powerful, but they can also be abused if public endpoints are left unprotected. You should always use Firebase App Check to ensure that only your actual web app can make successful requests to the Gemini API, blocking bots and unauthorized clients.
- In the Google Cloud console, go to Security > Fraud Defense
- Click Create Key and fill out the fields:
- Display name:
Codelab Key - Application Type: Web
- Domain list: Add
localhostand127.0.0.1so that your local Vite server is allowed to make requests.
- Display name:
- Click Create key to register the key.
- From the top of the Fraud Defense Key Details page, copy the site key ID to your clipboard.
- In the Firebase console, go to Security > App Check.
- Click the Apps tab, expand your web app (
Rugged Web), and click the reCAPTCHA Enterprise provider. - In the reCAPTCHA Enterprise site key field, paste the site key ID from the Fraud Defense Key Details page and click Save.
- In your code editor, open
src/firebase.tsagain. - Add the following imports at the top:
import { initializeAppCheck, ReCaptchaEnterpriseProvider } from "firebase/app-check"; - Add the App Check initialization right after your
initializeApp(firebaseConfig)call, and paste the site key ID you copied:// Initialize App Check const appCheck = initializeAppCheck(app, { provider: new ReCaptchaEnterpriseProvider('YOUR_RECAPTCHA_ENTERPRISE_SITE_KEY'), isTokenAutoRefreshEnabled: true }); - Update your
getAI()function call to use these tokens. Make the following change: By setting the value ofconst ai = getAI(app, { backend: new AgentPlatformBackend(), useLimitedUseAppCheckTokens: true });useLimitedUseAppCheckTokensto true, you're ensuring that short-lived tokens are applied to help limit the abuse your backend might receive.
8. Run the app
With your Firebase configuration in place and the support chat widget wired up, it's time to run the app.
- In your terminal, run the Vite development server:
npm run dev - Open the local URL provided (usually
http://localhost:5173/). - Click the Tactical Support Floating Action Button (FAB) in the bottom right corner.
- Try asking questions about the products, for example:
- "I'm looking for a weatherproof shell"
- "My sub-zero beanie is defective, what can I do?"
- Keep pushing back to trigger the AI's "Appeasement Budget" logic!
9. (Optional) Clean up resources from codelab
To avoid possible charges to your Google Cloud Billing account, you can delete the resources created during this codelab.
- In the Firebase console, go to the Settings > General tab.
- Make sure that the project you're viewing is the project you used for this codelab. If it's not your codelab's project, then you can use the project picker dropdown in the top-left corner to change projects.
- Go to the bottom of the page, and then click Delete project.
- Follow the on-screen instructions to confirm deletion.
10. Congratulations!
🎊 Mission Complete! You've successfully integrated a robust, template-driven AI customer support agent.
What you accomplished:
- Initialized Firebase and the Agent Platform backend on a client app.
- Configured a secure server-side prompt template using Handlebars and strict input schemas to define the agent's complex behavior.
- Dynamically called an LLM securely passing chat history and contextual product IDs without exposing internal prompt logic to the client.
What's next?
- Firebase App Check: Secure your AI endpoints against abuse.