Firebase 外掛程式

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

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

安裝

npm i --save @genkit-ai/firebase

事前準備

  • 所有 Firebase 產品都需要 Firebase 專案。您可以建立新專案 或是使用 Firebase 控制台
  • 另外,若要將流程部署至 Cloud Functions,您必須 升級專案 升級至 Blaze 方案,即付即用的方案。

設定

專案 ID

如要使用這個外掛程式,請在呼叫 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 金鑰檔案您可以前往 服務帳戶 頁面。
    2. 將環境變數 GOOGLE_APPLICATION_CREDENTIALS 設為檔案 包含服務帳戶金鑰的 JSON 檔案路徑,或者您也可以將環境變數 GCLOUD_SERVICE_ACCOUNT_CREDS 設為 JSON 檔案的內容。

遙測

這個外掛程式直接依賴 Google Cloud 外掛程式,因此設有相關佈建功能,可讓遙測資料匯出至 Google 的 Cloud 作業套件。如要啟用遙測匯出功能,請將 enableTracingAndMetrics 設為 true,並將遙測部分新增至 Genkit 設定:

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

configureGenkit({
  plugins: [firebase()],
  enableTracingAndMetrics: true,
  telemetry: {
    instrumentation: 'firebase',
    logger: 'firebase',
  },
});

如要瞭解所有設定選項,以及需要為專案啟用的必要 API,請參閱 Google Cloud 外掛程式說明文件。

用量

這個外掛程式提供多種與 Firebase 服務整合的功能, 一起或單獨使用

Cloud Firestore 向量儲存庫

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

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

使用 GCLOUD_SERVICE_ACCOUNT_CREDS 和 Firestore

如果您使用服務帳戶憑證的方式是透過 GCLOUD_SERVICE_ACCOUNT_CREDS 直接傳遞憑證,同時也使用 Firestore 做為向量儲存庫,您必須在初始化期間將憑證直接傳遞至 Firestore 執行個體,或者根據外掛程式初始化順序,使用應用程式預設憑證來初始化單例模式。

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

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

if (process.env.GCLOUD_SERVICE_ACCOUNT_CREDS) {
  const serviceAccountCreds = JSON.parse(process.env.GCLOUD_SERVICE_ACCOUNT_CREDS);
  const authOptions = { credentials: serviceAccountCreds };
  firestore.settings(authOptions);
}

擷取

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 欄位必須編入索引,才能為 這些研究有助於我們找出 能引導後續作業的標準如何建立索引:

  • 執行 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 也會擲回錯誤: 正確的指令來建立索引

瞭解詳情

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() 中未提供的部分選項:

  • httpsOptionsHttpsOptions 物件,用於設定 Cloud 函式:

    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() 提供符合下列條件的回呼函式: CANNOT TRANSLATE DecodedIdToken 做為唯一的參數在這個函式中,檢查使用者憑證並擲回 則使用者不符合任何您需要的條件。

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