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 (for example, the banner at the top of this page).
- 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 claimed 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 claimed 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 Vertex AI 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 Vertex AI 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, VertexAIBackend } 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 VertexAIBackend() });
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, navigate to the Vertex AI or Prompt Management section.
- Create a new prompt template, and name it
product-agent. - Set the model to
gemini-2.5-flash. - Define the input schema exactly as follows:
input: schema: 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 - Copy the contents of
agent-product.promptfrom the root directory into the Prompt and optional system instructions field. This securely instructs the model how to behave as "Rugged Operator" and injecting the product catalog. - In the Firebase console, 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 call the Vertex AI generative model, blocking bots and unauthorized clients.
- In the Firebase console, navigate to Build > App Check.
- Click the Apps tab, expand your web app (
Rugged Web), and click the reCAPTCHA Enterprise provider. - Select Create new reCAPTCHA Enterprise key and fill out the prompt:
- Name:
Codelab Key - Domains: Add
localhostand127.0.0.1so that your local Vite server is allowed to make requests.
- Name:
- Click Save to register the app.
- Once registered, the Firebase console will display your Site Key. Copy this string.
- 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 you copied:// Initialize App Check const appCheck = initializeAppCheck(app, { provider: new ReCaptchaEnterpriseProvider('YOUR_RECAPTCHA_ENTERPRISE_SITE_KEY'), useLimitedUseAppCheckTokens: true }); - Update your
getAI()function call to use these tokens. Make the following change: By setting the value ofconst ai = getAI(app, { backend: new VertexAIBackend(), 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.
- Go to the Firebase console.
- Select the
rugged-terrain-aiproject. - Go to Project settings (the gear icon).
- Scroll to the bottom and 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 Vertex AI 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.