Firebase プラグイン

Firebase プラグインは、Firebase サービスといくつかの統合を提供します。

  • Cloud Firestore Vector Store を使用したインデクサとリトリーバー
  • Cloud Firestore を使用してストレージをトレースする
  • Cloud Functions を使用したフローのデプロイ
  • Firebase Authentication ユーザーの認可ポリシー

インストール

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 コンソールの [サービス アカウント] ページで行えます。
    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 はインデックスを作成するための正しいコマンドでエラーをスローします。

詳細

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 ベースのトレース ストレージを使用する場合は、トレース ドキュメントの TTL を有効にすることをおすすめします(https://firebase.google.com/docs/firestore/ttl)。

Cloud Functions

このプラグインには、Cloud Functions for Firebase HTTPS トリガー関数に基づくフローを作成する onFlow() コンストラクタがあります。これらの関数は、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 Functions の関数の構成に使用される HttpsOptions オブジェクト。 js export const exampleFlow = onFlow( { name: "exampleFlow", httpsOptions: { cors: true, }, // ... }, async (prompt) => { // ... } );

  • enforceAppCheck: true の場合、App Check トークンがないか、無効であるリクエストを拒否します。

  • consumeAppCheckToken: true の場合、App Check トークンを検証後に無効にします。

    リプレイからの保護をご覧ください。

Firebase Auth

このプラグインは、Firebase Auth に関する認可ポリシーを作成するヘルパー関数を提供します。

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) => {
    // ...
  }
);

認証ポリシーを定義するには、DecodedIdToken を唯一のパラメータとして受け取るコールバック関数を firebaseAuth() に指定します。この関数では、ユーザー トークンを調べ、必要な条件のいずれかをユーザーが満たさなかった場合にエラーをスローします。

このトピックの詳細については、認可と整合性をご覧ください。