AI-Powered Cloud Functions Advanced

Cloud Functions for Firebase let you run server-side AI operations that trigger on database events, HTTP requests, or schedules. Combined with Vertex AI, they enable powerful AI pipelines that process data automatically.

Setup Cloud Functions with Vertex AI

Bash
# Initialize Cloud Functions
firebase init functions

# Install dependencies
cd functions
npm install @google-cloud/vertexai firebase-admin

Firestore Trigger: Auto-Generate Embeddings

Automatically generate embeddings when a new document is created:

TypeScript - functions/src/index.ts
import { onDocumentCreated } from 'firebase-functions/v2/firestore';
import { VertexAI } from '@google-cloud/vertexai';
import * as admin from 'firebase-admin';

admin.initializeApp();
const db = admin.firestore();

const vertexAI = new VertexAI({
  project: process.env.GCLOUD_PROJECT!,
  location: 'us-central1',
});

export const generateEmbedding = onDocumentCreated(
  'articles/{articleId}',
  async (event) => {
    const data = event.data?.data();
    if (!data) return;

    // Generate embedding using Vertex AI
    const model = vertexAI.getGenerativeModel({ model: 'text-embedding-004' });
    const result = await model.embedContent(data.content);
    const embedding = result.embedding.values;

    // Store embedding back in the document
    await event.data?.ref.update({
      embedding: admin.firestore.FieldValue.vector(embedding),
      embeddedAt: admin.firestore.FieldValue.serverTimestamp(),
    });
  }
);

HTTP Function: AI Chat Endpoint

TypeScript
import { onRequest } from 'firebase-functions/v2/https';

export const chat = onRequest(
  { cors: true, maxInstances: 10 },
  async (req, res) => {
    const { message } = req.body;

    const model = vertexAI.getGenerativeModel({ model: 'gemini-2.0-flash' });
    const result = await model.generateContent(message);

    res.json({
      response: result.response.candidates()[0].content.parts[0].text,
    });
  }
);

Firestore Vector Search

Firestore now supports native vector search on documents:

TypeScript
// Query Firestore with vector similarity
import { FieldValue } from 'firebase-admin/firestore';

const queryEmbedding = /* generate from user query */;

const results = await db
  .collection('articles')
  .findNearest({
    vectorField: 'embedding',
    queryVector: FieldValue.vector(queryEmbedding),
    limit: 5,
    distanceMeasure: 'COSINE',
  })
  .get();

results.docs.forEach(doc => {
  console.log(doc.data().title, doc.data().content);
});
Function Timeouts: Cloud Functions have a default timeout of 60 seconds (configurable up to 9 minutes on Gen 2). For long AI operations, increase the timeout with timeoutSeconds: 540 in the function options.

Deploying

Bash
# Deploy all functions
firebase deploy --only functions

# Deploy a specific function
firebase deploy --only functions:generateEmbedding

Cloud Functions Running!

Your server-side AI pipeline is deployed. In the final lesson, learn production best practices for Firebase AI.

Next: Best Practices →

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.