Firebase 插件

Firebase 插件提供与 Firebase 服务的多种集成:

  • 使用 Cloud Firestore 矢量存储区的索引器和检索器
  • 使用 Cloud Firestore 跟踪存储
  • 使用 Cloud Functions 部署流
  • 适用于 Firebase Authentication 用户的授权政策

安装

npm i --save @genkit-ai/firebase

配置

如需使用此插件,请在调用 configureGenkit() 时指定该插件:

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 插件提供了一个用于定义 Firestore 检索器的便捷函数 defineFirestoreRetriever()

import {defineFirestoreRetriever} from "@genkit-ai/firebase";
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,
  distanceMeasure: "COSINE", // "EUCLIDEAN", "DOT_PRODUCT", or "COSINE" (default)
});

如需使用它,请将其传递给 retrieve() 函数:

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

如需编入索引,请将嵌入生成器与 Admin SDK 搭配使用:

import {initializeApp} from "firebase-admin";
import {getFirestore, FieldValue} from "firebase-admin/firestore";
import {textEmbeddingGecko} from "@genkit-ai/vertexai";
import {embed} from "@genkit-ai/ai/embedder";

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

const indexConfig = {
  collection: "yourCollection",
  contentField: "yourDataChunks",
  vectorField: "embedding",
  embedder: textEmbeddingGecko,
};

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

Firestore 依赖索引来提供对集合的快速高效的查询。前面的示例要求将 embedding 字段编入索引才能正常运行。为此,请调用该函数,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 的 Callable 函数接口,您可以使用 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 Authentication 创建授权政策:

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 作为其唯一参数。在此函数中,检查用户令牌,并在用户未满足您所需的任何条件时抛出错误。

如需详细了解此主题,请参阅授权和完整性