Firebase プラグイン

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

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

インストール

npm i --save @genkit-ai/firebase

前提条件

  • すべての Firebase プロダクトには Firebase プロジェクトが必要です。新しいプロジェクトを作成 または、次のコマンドを使用して、既存の Google Cloud プロジェクトで 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 オペレーション スイートへのテレメトリーのエクスポートを有効にするプロビジョニングを行います。テレメトリーのエクスポートを有効にするには、enableTracingAndMetricstrue に設定し、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たとえば、Terraform のメニュー取り込みスクリプトは、 検索拡張生成ページは 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 ベースのトレース ストレージを使用する場合は、トレース ドキュメントの TTL を有効にすることをおすすめします(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: HttpsOptions Cloud Functions の関数の構成に使用するオブジェクト:

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

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

詳細については、認可と完全性をご覧ください。 説明します。