ปลั๊กอิน Firebase

ปลั๊กอิน Firebase ผสานรวมบริการ Firebase หลายอย่าง ดังนี้

  • ผู้จัดทำดัชนีและรีทรีฟเวอร์โดยใช้ที่เก็บเวกเตอร์ Cloud Firestore
  • ติดตามพื้นที่เก็บข้อมูลโดยใช้ Cloud Firestore
  • การทำให้โฟลว์ใช้งานได้โดยใช้ 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 ของคุณ คุณสามารถระบุ รหัสโปรเจ็กต์ Firebase ด้วยวิธีใดวิธีหนึ่งต่อไปนี้

  • ตั้งค่า projectId ในออบเจ็กต์การกำหนดค่า firebase()

  • ตั้งค่าตัวแปรสภาพแวดล้อม GCLOUD_PROJECT หากคุณเรียกใช้ขั้นตอน จากสภาพแวดล้อม Google Cloud (Cloud Functions, Cloud Run เป็นต้น) ระบบจะตั้งค่า GCLOUD_PROJECT เป็นรหัสโปรเจ็กต์ของสภาพแวดล้อมโดยอัตโนมัติ

    หากตั้งค่า GCLOUD_PROJECT คุณจะละพารามิเตอร์การกําหนดค่าได้ ดังนี้ วันที่ firebase()

หากต้องการระบุข้อมูลเข้าสู่ระบบ Firebase คุณจะต้องตั้งค่า Google Cloud ด้วย ข้อมูลเข้าสู่ระบบเริ่มต้นของแอปพลิเคชัน วิธีระบุข้อมูลเข้าสู่ระบบ

  • หากเรียกใช้โฟลว์จากสภาพแวดล้อม Google Cloud (Cloud Functions, Cloud Run เป็นต้น) โดยระบบจะตั้งค่านี้โดยอัตโนมัติ

  • สำหรับสภาพแวดล้อมอื่นๆ

    1. สร้างข้อมูลเข้าสู่ระบบของบัญชีบริการสำหรับโปรเจ็กต์ Firebase และ ดาวน์โหลดไฟล์คีย์ JSON คุณสามารถทำได้ใน บัญชีบริการ ของคอนโซล Firebase
    2. ตั้งค่าตัวแปรสภาพแวดล้อม GOOGLE_APPLICATION_CREDENTIALS ให้กับไฟล์ เส้นทางของไฟล์ JSON ที่มีคีย์บัญชีบริการ

การส่งข้อมูลทางไกล

ปลั๊กอินมีทรัพยากร Dependency โดยตรงในปลั๊กอิน Google Cloud จึงมีสิทธิ์เปิดใช้การส่งออกทางไกลไปยังชุดการดำเนินการในระบบคลาวด์ของ Google หากต้องการเปิดใช้การส่งออกการวัดและส่งข้อมูลทางไกล ให้ตั้งค่า 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',
  },
});

โปรดดูเอกสารประกอบของปลั๊กอิน Google Cloud สำหรับตัวเลือกการกำหนดค่าทั้งหมดและ API ที่จำเป็นซึ่งต้องเปิดใช้ในโปรเจ็กต์

การใช้งาน

ปลั๊กอินนี้มีการผสานรวมกับบริการ Firebase มากมาย ซึ่งคุณจะ ใช้ด้วยกันหรือทีละรายการ

ที่เก็บเวกเตอร์ใน Cloud Firestore

คุณใช้ Cloud Firestore เป็นที่เก็บเวกเตอร์สำหรับการจัดทำดัชนีและการดึงข้อมูล RAG ได้

ส่วนนี้ประกอบด้วยข้อมูลเฉพาะเกี่ยวกับปลั๊กอิน firebase และ Cloud ฟีเจอร์การค้นหาเวกเตอร์ของ Firestore ดูรายละเอียดเพิ่มเติมได้ในหน้าการสร้างแบบดึงข้อมูลเพิ่มเติม การพูดคุยเกี่ยวกับการใช้ RAG ด้วย Genkit

ปลั๊กอิน 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 ที่อธิบายไว้ใน สร้างดัชนีเวกเตอร์ฟิลด์เดียว ในเอกสาร Firestore

    คำสั่งมีลักษณะดังต่อไปนี้

    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 สำหรับฟังก์ชันที่ทริกเกอร์ HTTPS ของ Firebase ฟังก์ชันเหล่านี้สอดคล้องกับ ของ Firebase อินเทอร์เฟซฟังก์ชันที่เรียกใช้ได้ และคุณสามารถใช้ SDK ของไคลเอ็นต์ Cloud Functions เพื่อโทรหา

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 Function

    export const exampleFlow = onFlow(
      {
        name: "exampleFlow",
        httpsOptions: {
          cors: true,
        },
        // ...
      },
      async (prompt) => {
        // ...
      }
    );
    
  • enforceAppCheck: เมื่อtrue ให้ปฏิเสธคำขอที่ไม่มีการตรวจสอบแอปหรือไม่ถูกต้อง โทเค็น

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

หากต้องการกำหนดนโยบายการตรวจสอบสิทธิ์ ให้ระบุฟังก์ชัน Callback ที่ firebaseAuth() ใช้เวลา DecodedIdToken เป็นพารามิเตอร์เดียว ในฟังก์ชันนี้ ให้ตรวจสอบโทเค็นผู้ใช้และส่ง หากผู้ใช้มีคุณสมบัติไม่ตรงตามเกณฑ์ที่คุณต้องการ

โปรดดูที่การให้สิทธิ์และความซื่อสัตย์สำหรับการสนทนาเกี่ยวกับ หัวข้อนี้