Build an AI-powered customer support agent using Firebase AI Logic

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

  1. In your terminal, clone the starter repository:
    git clone https://github.com/GoogleCloudPlatform/devrel-demos.git
    
  2. 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

  1. Sign into the Firebase console using your Google Account.
  2. Click the button to create a new project, and then enter a project name (for example, rugged-terrain-ai).
  3. Click Continue.
  4. If prompted, review and accept the Firebase terms, and then click Continue.
  5. (Optional) Enable AI assistance in the Firebase console (called "Gemini in Firebase").
  6. For this codelab, you do not need Google Analytics, so toggle off the Google Analytics option.
  7. 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:

  1. In the Firebase console, select to upgrade your plan.
  2. 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 Account or My 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.

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.

  1. In the Firebase console, go to Databases & Storage > Storage.
  2. Click Get started.
  3. Select a location for your default Storage bucket.
    Buckets in US-WEST1, US-CENTRAL1, and US-EAST1 can take advantage of the "Always Free" tier for Google Cloud Storage. Buckets in all other locations follow Google Cloud Storage pricing and usage.
  4. Click Production mode. In the steps just below, you'll update these Security Rules to be specific for this codelab.
  5. Click Create.
  6. Update your Security Rules:
    1. After the bucket is provisioned, go to the Rules tab.
    2. Copy and then paste in the following rules:
      rules_version = '2';
      service firebase.storage {
        match /b/{bucket}/o {
          match /products.txt {
            allow read;
          }
        }
      }
      
    3. Click Publish.
  7. Upload the product descriptions from the starter code:
    1. Click the Files tab for your Storage bucket.
    2. Click Upload File, and then upload the products.txt file 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.

  1. In the Firebase console, go to AI Services > AI Logic.
  2. Click Get started.
  3. 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.
  4. (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.

  1. When prompted in the Firebase AI Logic setup flow, click the Web () icon to register a new web app.
  2. Name the app (for example, Rugged Web).
  3. Copy the firebaseConfig object from the setup instructions.

Next, update the starter code:

  1. In your code editor, open src/firebase.ts.
  2. Replace the existing firebaseConfig with 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.

  1. In the Firebase console, go to the AI Services > AI Logic > Prompt templates tab.
  2. Click Create template, and choose Blank template.
  3. Set the template name to Product Agent and the ID to product-agent.
  4. Set the model to gemini-3.1-flash-lite (or the latest version available).
  5. 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.
  6. 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"
              }
            }
          }
        }
      }
    }
    
  7. Click Save template to save and publish the product-agent template.

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.

  1. In your code editor, return to src/firebase.ts.
  2. Below the initialization, use getTemplateGenerativeModel to 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.

  1. In the Google Cloud console, go to Security > Fraud Defense
  2. Click Create Key and fill out the fields:
    • Display name: Codelab Key
    • Application Type: Web
    • Domain list: Add localhost and 127.0.0.1 so that your local Vite server is allowed to make requests.
  3. Click Create key to register the key.
  4. From the top of the Fraud Defense Key Details page, copy the site key ID to your clipboard.
  5. In the Firebase console, go to Security > App Check.
  6. Click the Apps tab, expand your web app (Rugged Web), and click the reCAPTCHA Enterprise provider.
  7. In the reCAPTCHA Enterprise site key field, paste the site key ID from the Fraud Defense Key Details page and click Save.
  8. In your code editor, open src/firebase.ts again.
  9. Add the following imports at the top:
    import { initializeAppCheck, ReCaptchaEnterpriseProvider } from "firebase/app-check";
    
  10. 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
    });
    
  11. Update your getAI() function call to use these tokens. Make the following change:
    const ai = getAI(app, { backend: new AgentPlatformBackend(), useLimitedUseAppCheckTokens: true });
    
    By setting the value of useLimitedUseAppCheckTokens to 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.

  1. In your terminal, run the Vite development server:
    npm run dev
    
  2. Open the local URL provided (usually http://localhost:5173/).
  3. Click the Tactical Support Floating Action Button (FAB) in the bottom right corner.
  4. 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.

  1. In the Firebase console, go to the Settings > General tab.
  2. 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.
  3. Go to the bottom of the page, and then click Delete project.
  4. 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?