Firebase Genkit

Firebase Genkit 是一種開放原始碼架構,可協助您建構、部署 並監控可用於實際工作環境 AI 技術輔助應用程式

Genkit 標誌

Genkit 專為應用程式開發人員打造,可協助您輕鬆整合 強大的 AI 功能,以熟悉的模式和模式導入您的應用程式。 這個架構是由 Firebase 中相同的團隊打造,運用我們在 打造全球數百萬名開發人員使用的工具。

您可以運用 Genkit 建立應用程式,以便產生自訂內容、使用語意搜尋 處理非結構化的輸入內容、透過業務資料回答問題, 以自主執行決策、協調工具呼叫,還有更多其他功能!

Genkit 目前支援使用 JavaScript/TypeScript 進行伺服器端開發 支援 Go 的 Go 工具 (Node.js)。

跟著作品一起發展,或是自行做出貢獻 GitHub 存放區

主要功能與特色

Genkit 會協助您完成 AI 開發流程的每個步驟。 從原型設計到正式環境中進行監控 還有很多需要討論的事項

為幫助你踏出第一步,以下我們推薦你可能會喜歡的 10 項 Genkit 主要功能:

1. 眾多模型和單一介面

Genkit 提供外掛程式,讓你直接存取熱門模型 以及靈活的模型抽象化 可讓您輕鬆整合任何模型 API 以及使用社群維護的模型 試用新模型就像變更單一引數一樣簡單,但每個模型 您可以指定自訂設定

import { geminiPro } from '@genkit-ai/vertexai';
import { ollama } from 'genkitx-ollama';
import { generate } from '@genkit-ai/ai';

function flipACoin(a, b) {
  return Math.random() > 0.5 ? a : b;
}

const result = await generate({
  model: flipACoin(geminiPro, 'ollama/gemma'),
  config: { temperature: 0.3, maxOutputTokens: 200 },
  prompt: 'What makes you the best LLM out there?',
});

console.log(result.text());

2. 結構化輸出內容

使用 Zod 結構定義,透過 Genkit 產生強類型資料。這麼做能幫助 分析非結構化文字、生成創意內容、選擇工作,以及傳送 會以結構化的類型安全物件傳回應用程式。

import { generate } from "@genkit-ai/ai";
import { geminiPro } from "@genkit-ai/vertexai";
import { z } from "zod";

const CreatureSchema = z.object({
  name: z.string().describe('the name of the creature'),
  hitPoints: z.number().describe('hit points, between 5 and 100'),
  attacks: z.array(z.object({
    name: z.string(),
    damage: z.number().describe('amount of damage, between 2 and 25'),
  })).describe('3 attacks the creature can use')
});

const createCreature = defineFlow({
    name: "createCreature",
    inputSchema: z.string(),
    outputSchema: CreatureSchema,
  },
  (habitat) => {
    const result = await generate({
      model: geminiPro,
      prompt: `You are a brilliant RPG designer. Generate a creature that lives in ${habitat}.`,
      output: {schema: CreatureSchema}
    });
    // strongly typed and ready to go
    return result.output();
  }
)

console.log(await createCreature("a developer conference"));

3. 多模態、多媒體

Genkit 為支援混合文字的內容提供通用格式 資料及任意媒體這樣您就能將 Genkit 用於 生成式工作 (例如生成圖像),不只有 LLM。

import { imagen2, geminiProVision } from '@genkit-ai/vertexai';
import { generate } from '@genkit-ai/ai';

const imageResult = await generate({
  model: imagen2,
  prompt: 'Generate an image of a very specific historical time and place.',
});
const generatedImage = imageResult.media();

const descriptionResult = await generate({
  model: geminiProVision,
  prompt: [
    {
      text: 'What is the historical time and place represented in this picture?',
    },
    { media: generatedImage },
  ],
});
console.log(descriptionResult.text());

4. 提供 LLM 工具

Genkit 提供各種工具,讓你可以透過 LLM 輕鬆執行函式呼叫。工具 讓 AI 擷取資料、顯示 UI、寫入資料庫,或 任何可編寫程式碼的動作

import { generate, defineTool } from '@genkit-ai/ai';
import { geminiPro } from '@genkit-ai/vertexai';
import { z } from 'zod';

const createReminder = defineTool(
  {
    name: 'createReminder',
    description: 'Use this to create reminders for things in the future',
    inputSchema: z.object({
      time: z
        .string()
        .describe('ISO timestamp string, e.g. 2024-04-03T12:23:00Z'),
      reminder: z.string().describe('the content of the reminder'),
    }),
    outputSchema: z.number().describe('the ID of the created reminder'),
  },
  (reminder) => db.reminders.create(reminder)
);

const searchNotes = defineTool(
  {
    name: 'searchNotes',
    description: "Use this to search the user's notes for people or phrases",
    inputSchema: z.string().describe('the search query'),
    outputSchema: z.object({ notes: z.array(NoteSchema) }),
  },
  (query) => db.notes.search(query)
);

const result = await generate({
  model: geminiPro,
  tools: [createReminder, searchNotes],
  prompt: `
  You are a note-taking assistant. Using the tools available, try to answer the provided query.
  If you create a reminder, describe in text the reminder you created as a response.

  Query: I took a note about a meeting with Anna - can you set a reminder for the time?
  `,
});
console.log(result.text());

5. 使用 Dotprompt 管理提示

提示工程不只是調整文字而已。您使用的模型 以及您請求的所有格式,都會影響廣告品質 輸出內容Genkit 提供 Dotprompt 提示檔案格式 整合到單一檔案中,方便測試及整理。

---
model: vertexai/gemini-1.0-pro
config:
  temperature: 0.9
input:
  schema:
    properties:
      location: {type: string}
      style: {type: string}
      name: {type: string}
    required: [location]
  default:
    location: a restaurant
---

You are the world's most welcoming AI assistant and are currently working at {{location}}.

Greet a guest{{#if name}} named {{name}}{{/if}}{{#if style}} in the style of {{style}}{{/if}}.

6. 在本機執行資料流

生成式 AI 的結果有很多種,因此實驗是超凡 非常重要本機 Genkit 開發人員 UI 可讓您與重要的 AI 互動 以及手動測試 包括您編寫的所有自訂程式碼

7. 檢查追蹤記錄

要利用 AI 對複雜的多步驟工作流程偵錯並不容易,原因如下: 隨機性和隱藏程序Genkit 提供追蹤檢查器 開發人員 UI,可讓您檢查每個模型呼叫的追蹤記錄,並 流程它可以查看實際工作環境的追蹤記錄,甚至算繪圖片!

8. 開啟 &可延伸

AI 生態系統的成長速度比任何團隊能跟上的速度還要快。Genkit 具備開放式外掛程式模型,提供預建的新模型整合。 擷取等多種功能Genkit 團隊負責維護 外掛程式,任何人都能將自己的 Genkit 外掛程式發布至 NPM。

找不到所需的特定整合外掛程式嗎?別擔心!Genkit 抽象化機制可靈活運用 而且能輕鬆建構自訂元件 整合至架構中,就像以下自訂 Firestore 擷取工具:

import { embed } from '@genkit-ai/ai/embedder';
import { Document, defineRetriever } from '@genkit-ai/ai/retriever';
import { textEmbeddingGecko } from '@genkit-ai/vertexai';
import {
  FieldValue,
  VectorQuery,
  VectorQuerySnapshot,
} from '@google-cloud/firestore';
import { Firestore } from 'firebase-admin/firestore';
import * as z from 'zod';
import { augmentedPrompt } from './prompt';

const QueryOptions = z.object({
  k: z.number().optional(),
});

const firestoreArtifactsRetriever = defineRetriever(
  {
    name: 'firestore/artifacts',
    configSchema: QueryOptions,
  },
  async (input, options) => {
    const embedding = await embed({
      embedder: textEmbeddingGecko,
      content: input,
    });

    const db = new Firestore();
    const coll = db.collection('vectors' /* your collection name */);

    const vectorQuery: VectorQuery = coll.findNearest(
      'embedding' /* the name of the field that contains the vector */,
      FieldValue.vector(embedding),
      {
        limit: options.k ?? 3,
        distanceMeasure: 'COSINE',
      }
    );

    const vectorQuerySnapshot: VectorQuerySnapshot = await vectorQuery.get();
    return {
      documents: vectorQuerySnapshot.docs.map((doc) =>
        // doc.data() represents the Firestore document. You may process
        // it as needed to generate a Genkit document object, depending on your
        // storage format.
        Document.fromText(doc.data().content.text)
      ),
    };
  }
);

9. 專為實際工作環境打造

輕鬆將流程部署到任何可提供 Express.js 應用程式的平台。 Genkit 已完全使用 OpenTelemetry 及自訂中繼資料 企業級的正式環境監控功能

您也可以使用 Google Cloud 和 Firebase 的官方外掛程式 將資料匯出至 Google Cloud 作業套件,並與 Firebase 整合 例如 Cloud Functions for Firebase、Firebase 驗證、App Check 以及 Firestore

Cloud Trace 螢幕截圖

10. 授權與安全處理

建構公開的應用程式時,保護資料很重要 儲存於系統中的檔案以 LLM 為例 確保模型只存取應有的資料,工具呼叫可正常執行 限定為叫用 LLM 的使用者 經過驗證的用戶端應用程式。

Genkit 提供用於管理授權政策和背景資訊的機制。

import { defineFlow, runFlow } from '@genkit-ai/flow';

export const selfSummaryFlow = defineFlow(
  {
    name: 'selfSummaryFlow',
    inputSchema: z.object({uid: z.string()}),
    outputSchema: z.string(),
    authPolicy: (auth, input) => {
      if (!auth) {
        throw new Error('Authorization required.');
      }
      if (input.uid !== auth.uid) {
        throw new Error('You may only summarize your own profile data.');
      }
    }
  },
  async (input) => { ... });

整合

Genkit 整合了 AI 模型、向量資料庫、遙測資料 以及執行更多業務以下是 是由 Genkit 團隊負責維護

官方外掛程式
googleai 生成式模型:Gemini Pro、Gemini 1.5 Pro、Gemini Pro Vision
嵌入模型:Gecko 文字嵌入
vertexai 生成式模型:Gemini Pro、Gemini Pro Vision、Gemini 1.5 Flash、Gemini 1.5 Pro、Imagen2、Anthropic Claude 3
嵌入模型:Gecko 文字嵌入
Evaluators:Vertex AI 評估
ollama 生成式模型:許多本機模型,包括 Gemma、Llama 3、Mistral 等
chroma 向量資料庫:ChromaDB
pinecone 向量資料庫:Pinecone
google-cloud 監控工具:Google Cloud Trace、Google Cloud Logging
firebase 雲端部署:Cloud Functions、Firebase 驗證、App Check
向量資料庫:Cloud Firestore 向量儲存庫
langchain 在 Genkit 流程中使用 LangChain 鏈結和公用程式

開始使用

參閱入門指南,瞭解如何安裝 Genkit 並執行第一個 AI 流程