Firebase Genkit

Firebase Genkit は、本番環境に対応した AI 搭載アプリの構築、デプロイ、モニタリングに役立つオープンソース フレームワークです。

Genkit のロゴ

Genkit はアプリ デベロッパー向けに設計されており、使い慣れたパターンとパラダイムで強力な AI 機能をアプリに簡単に統合できます。世界中で何百万人ものデベロッパーが使用しているツールを構築してきた Google の経験を活かし、Firebase の背後にいるのと同じチームが構築しています。

Genkit を使用して、カスタム コンテンツの生成、セマンティック検索の使用、非構造化入力の処理、ビジネスデータによる質問への回答、自律的な意思決定、ツール呼び出しのオーケストレートなどを行うアプリを作成します。

Genkit は現在、JavaScript/TypeScript(Node.js)でのサーバー側開発をサポートし、Go もサポートしています。

GitHub リポジトリで、開発をフォローしたり、独自の投稿を作成したりできます。

主な機能

Genkit は、プロトタイピングの開始から本番環境でのモニタリングまで、AI 開発のあらゆる段階でお客様をサポートします。話すべきことがたくさんあります。

まずは、おすすめの Genkit の機能を 10 点ご紹介します。

1. 多数のモデル、1 つのインターフェース

Genkit は、人気のあるモデルにすぐにアクセスできるプラグインと、任意のモデル API の統合とコミュニティで維持されたモデルの使用を容易にする柔軟なモデル抽象化を提供します。1 つの引数を変更するだけで新しいモデルを試すことができますが、モデルごとにカスタム構成を指定できます。

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. 構造化出力

Genkit で Zod スキーマを使用して厳密に型指定されたデータを生成する。これにより、非構造化テキストの分析、クリエイティブ コンテンツの生成、タスクの選択を行い、その結果をタイプセーフの構造化オブジェクトとしてアプリに送信できます。

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 は、テキスト、データ、任意のメディアの組み合わせをサポートするコンテンツの一般的な形式を提供します。これにより、LLM だけでなく、生成タスク(画像生成など)を実行するモデルに Genkit を使用できます。

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 を提供しています。これはプロンプト ファイル形式で、すべてを 1 つのファイルにまとめ、テストと整理を容易にします。

---
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 Developer UI では、モデルや取得ツールなどの重要な AI コンポーネントを操作できるほか、記述したすべてのカスタムコードを含むエンドツーエンドのフローを手動でテストできます。

7. トレースを検証する

AI を使用して複雑なマルチステップのワークフローをデバッグするのは、ランダム性と隠れたプロセスのために困難な場合があります。Genkit のデベロッパー UI にトレース インスペクタが用意されており、フロー内のモデル呼び出しとステップごとにトレースを検査できます。本番環境のトレースを表示できるだけでなく、画像をレンダリングすることもできます。

8. オープンかつ拡張可能

AI エコシステムは、どのチームよりも速いスピードで成長しています。Genkit には、新しいモデルやリトリーブなどとの事前構築済みの統合を提供するオープン プラグイン モデルがあります。Genkit チームは少数の公式プラグインを管理していますが、誰でも独自の Genkit プラグインを NPM に公開できます。

必要な統合用のプラグインが見つからない場合は、心配は要りません。Genkit の抽象化は柔軟性が高く、次のカスタム Firestore Retriever のように、フレームワークに統合するカスタム コンポーネントを簡単に構築できます。

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 のオペレーション スイートにデータをエクスポートし、Cloud Functions for Firebase、Firebase Authentication、App Check、Firestore などの Firebase サービスと統合できます。

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 Pro、Gemini Pro Vision
エンベディング モデル: Gecko テキスト エンベディング
vertexai 生成モデル: Gemini Pro、Gemini Pro Vision、Gemini 1.5 Flash、Gemini 1.5 Pro、Imagen2、Anthropic Claude 3
エンベディング モデル: Gecko テキスト エンベディング
評価者: Vertex AI 評価
ollama 生成モデル: Gemma、Llama 3、Mistral など、多くのローカルモデル
chroma ベクター データベース: ChromaDB
pinecone ベクトル データベース: Pinecone
google-cloud モニタリング ツール: Google Cloud Trace、Google Cloud Logging
firebase Cloud Deployment: Cloud Functions、Firebase Authentication、App Check
ベクター データベース: Cloud Firestore Vector Store
langchain Genkit フローで LangChain チェーンとユーティリティを使用する

始める

Genkit をインストールして最初の AI フローを実行する方法については、スタートガイドをご覧ください。