Firebase 外掛程式

Firebase 外掛程式提供下列幾種 Firebase 服務整合的功能:

  • 使用 Cloud Firestore 向量儲存庫的索引和擷取器
  • 使用 Cloud Firestore 的 Trace 儲存空間
  • 使用 Cloud Functions 部署流程
  • Firebase 驗證使用者的授權政策

安裝項目

npm i --save @genkit-ai/firebase

先備知識

  • 所有 Firebase 產品都需要 Firebase 專案。您可以使用 Firebase 主控台建立新專案,或在現有 Google Cloud 專案中啟用 Firebase。
  • 此外,若要將流程部署至 Cloud Functions,必須將專案升級為 Blaze 即付即用方案。

設定

如要使用這個外掛程式,請在呼叫 configureGenkit() 時指定:

import {configureGenkit} from "@genkit-ai/core";
import {firebase} from "@genkit-ai/firebase";

configureGenkit({
  plugins: [firebase({projectId: "your-firebase-project"})],
});

外掛程式會要求您指定 Firebase 專案 ID。您可以透過下列任一方式指定 Firebase 專案 ID:

  • firebase() 設定物件中設定 projectId

  • 設定 GCLOUD_PROJECT 環境變數。如果您是從 Google Cloud 環境 (Cloud Functions、Cloud Run 等) 執行流程,系統會自動將 GCLOUD_PROJECT 設為環境的專案 ID。

    如果您設定了 GCLOUD_PROJECT,則可以省略設定參數:firebase()

如要提供 Firebase 憑證,您還需要設定 Google Cloud 應用程式預設憑證。指定憑證的方法如下:

  • 如果您是從 Google Cloud 環境 (Cloud Functions、Cloud Run 等) 執行流程,系統會自動完成這項設定。

  • 其他環境:

    1. 為您的 Firebase 專案產生服務帳戶憑證,並下載 JSON 金鑰檔案。您可以在 Firebase 控制台的「Service account」(服務帳戶) 頁面中執行這項操作。
    2. 將環境變數 GOOGLE_APPLICATION_CREDENTIALS 設為包含服務帳戶金鑰的 JSON 檔案路徑。

用量

這個外掛程式提供多種與 Firebase 服務整合的功能,您可以搭配使用,也可以單獨使用。

Cloud Firestore 向量儲存庫

Cloud Firestore 可做為 RAG 索引和擷取的向量儲存庫。

本節包含 firebase 外掛程式和 Cloud Firestore 向量搜尋功能的專屬資訊。如需使用 Genkit 實作 RAG 的詳細討論,請參閱擷取評估生成頁面。

firebase 外掛程式提供便利函式,可以定義 Firestore 擷取作業 defineFirestoreRetriever()

import {defineFirestoreRetriever} from "@genkit-ai/firebase";
import {retrieve} from "@genkit-ai/ai/retriever";

import {initializeApp} from "firebase-admin/app";
import {getFirestore} from "firebase-admin/firestore";

const app = initializeApp();
const firestore = getFirestore(app);

const yourRetrieverRef = defineFirestoreRetriever({
  name: "yourRetriever",
  firestore: getFirestore(app),
  collection: "yourCollection",
  contentField: "yourDataChunks",
  vectorField: "embedding",
  embedder: textEmbeddingGecko, // Import from '@genkit-ai/googleai' or '@genkit-ai/vertexai'
  distanceMeasure: "COSINE", // "EUCLIDEAN", "DOT_PRODUCT", or "COSINE" (default)
});

如要使用,請將其傳遞至 retrieve() 函式:

const docs = await retrieve({
  retriever: yourRetrieverRef,
  query: "look for something",
  options: {limit: 5},
});

可用的擷取選項包括:

  • limit:指定要傳回的相符結果數量。
  • where:除了向量搜尋以外,要比對的欄位/值組合 (例如 {category: 'food'})。
  • collection:覆寫預設集合以搜尋子集合搜尋等項目。

如要填入 Firestore 集合,請搭配使用嵌入產生器與 Admin SDK。例如,「擷取增強式產生」頁面中的選單擷取指令碼可針對 Firestore 進行以下調整:

import { configureGenkit } from "@genkit-ai/core";
import { embed } from "@genkit-ai/ai/embedder";
import { defineFlow, run } from "@genkit-ai/flow";
import { textEmbeddingGecko, vertexAI } from "@genkit-ai/vertexai";

import { applicationDefault, initializeApp } from "firebase-admin/app";
import { FieldValue, getFirestore } from "firebase-admin/firestore";

import { chunk } from "llm-chunk";
import pdf from "pdf-parse";
import * as z from "zod";

import { readFile } from "fs/promises";
import path from "path";

// Change these values to match your Firestore config/schema
const indexConfig = {
  collection: "menuInfo",
  contentField: "text",
  vectorField: "embedding",
  embedder: textEmbeddingGecko,
};

configureGenkit({
  plugins: [vertexAI({ location: "us-central1" })],
  enableTracingAndMetrics: false,
});

const app = initializeApp({ credential: applicationDefault() });
const firestore = getFirestore(app);

export const indexMenu = defineFlow(
  {
    name: "indexMenu",
    inputSchema: z.string().describe("PDF file path"),
    outputSchema: z.void(),
  },
  async (filePath: string) => {
    filePath = path.resolve(filePath);

    // Read the PDF.
    const pdfTxt = await run("extract-text", () =>
      extractTextFromPdf(filePath)
    );

    // Divide the PDF text into segments.
    const chunks = await run("chunk-it", async () => chunk(pdfTxt));

    // Add chunks to the index.
    await run("index-chunks", async () => indexToFirestore(chunks));
  }
);

async function indexToFirestore(data: string[]) {
  for (const text of data) {
    const embedding = await embed({
      embedder: indexConfig.embedder,
      content: text,
    });
    await firestore.collection(indexConfig.collection).add({
      [indexConfig.vectorField]: FieldValue.vector(embedding),
      [indexConfig.contentField]: text,
    });
  }
}

async function extractTextFromPdf(filePath: string) {
  const pdfFile = path.resolve(filePath);
  const dataBuffer = await readFile(pdfFile);
  const data = await pdf(dataBuffer);
  return data.text;
}

Firestore 仰賴索引,以針對集合提供快速且有效率的查詢功能。(請注意,這裡的「索引」是指資料庫索引,而非 Genkit 的索引器和擷取器抽象層)。

在上述範例中,embedding 欄位必須編入索引才能運作。如何建立索引:

  • 執行 Firestore 說明文件的建立單一欄位向量索引一節所述的 gcloud 指令。

    這個指令如下所示:

    gcloud alpha firestore indexes composite create --project=your-project-id \
      --collection-group=yourCollectionName --query-scope=COLLECTION \
      --field-config=vector-config='{"dimension":"768","flat": "{}"}',field-path=yourEmbeddingField
    

    不過,正確的索引設定取決於您建立的查詢,以及使用的嵌入模型。

  • 或者,呼叫 retrieve(),Firestore 就會擲回錯誤,其中包含建立索引的正確指令。

瞭解詳情

  • 有關 Genkit 索引器和擷取器的一般討論,請參閱擷取評估生成頁面。
  • 如要進一步瞭解向量搜尋功能,請參閱 Cloud Firestore 文件中的「使用向量嵌入搜尋」一節。

Cloud Firestore 追蹤記錄儲存空間

您可以使用 Cloud Firestore 儲存追蹤記錄:

import {firebase} from "@genkit-ai/firebase";

configureGenkit({
  plugins: [firebase()],
  traceStore: "firebase",
  enableTracingAndMetrics: true,
});

根據預設,外掛程式會將追蹤記錄儲存在專案預設資料庫中,名為 genkit-traces 的集合。如要更改這兩項設定,請按照下列步驟操作:

firebase({
  traceStore: {
    collection: "your-collection";
    databaseId: "your-db";
  }
})

如果您使用以 Firestore 為基礎的追蹤記錄儲存空間,需為追蹤記錄文件啟用存留時間:https://firebase.google.com/docs/firestore/ttl

Cloud Functions

此外掛程式提供 onFlow() 建構函式,會建立由 Cloud Functions for Firebase HTTPS 觸發函式支援的資料流。這些函式符合 Firebase 的可呼叫函式介面,您可以使用 Cloud Functions 用戶端 SDK 呼叫這些函式。

import {firebase} from "@genkit-ai/firebase";
import {onFlow, noAuth} from "@genkit-ai/firebase/functions";

configureGenkit({
  plugins: [firebase()],
});

export const exampleFlow = onFlow(
  {
    name: "exampleFlow",
    authPolicy: noAuth(), // WARNING: noAuth() creates an open endpoint!
  },
  async (prompt) => {
    // Flow logic goes here.

    return response;
  }
);

使用 Firebase CLI 部署流程:

firebase deploy --only functions

onFlow() 函式含有 defineFlow() 中未提供的部分選項:

  • httpsOptions:用於設定 Cloud 函式的 HttpsOptions 物件: js export const exampleFlow = onFlow( { name: "exampleFlow", httpsOptions: { cors: true, }, // ... }, async (prompt) => { // ... } );

  • enforceAppCheck:當 true 時,拒絕 App Check 權杖遺失或無效的要求。

  • consumeAppCheckToken:當 true 時,驗證 App Check 權杖後會失效。

    請參閱重播防護措施

Firebase Auth

這個外掛程式提供實用的輔助函式,可用來建立與 Firebase 驗證相關的授權政策:

import {firebaseAuth} from "@genkit-ai/firebase/auth";

export const exampleFlow = onFlow(
  {
    name: "exampleFlow",
    authPolicy: firebaseAuth((user) => {
      if (!user.email_verified) throw new Error("Requires verification!");
    }),
  },
  async (prompt) => {
    // ...
  }
);

如要定義驗證政策,請向 firebaseAuth() 提供回呼函式,該函式使用 DecodedIdToken 做為唯一的參數。在這個函式中,在使用者無法滿足任何您想要求的條件時,檢查使用者憑證並擲回錯誤。

如要進一步瞭解這個主題,請參閱授權與完整性