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
# 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:
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
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:
// 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); });
timeoutSeconds: 540 in the function options.
Deploying
# 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.
AI & ML Courses - 30% Off
Live instructor-led AI, machine learning, data science, and cloud courses for working professionals. Use code Limited30 at checkout.
EdurekaDataCamp - AI & Data Science
Hands-on Python, machine learning, and AI courses with interactive exercises and real projects.
DataCampedX - Top AI Courses
University-level AI courses from MIT, Harvard, Stanford. Earn certificates that employers recognize.
edX