Firebase Genkit は、本番環境に対応した AI 搭載アプリの構築、デプロイ、モニタリングを支援するオープンソース フレームワークです。
Genkit はアプリ デベロッパー向けに設計されており、強力な AI 機能を既存のパターンやパラダイムで簡単にアプリに統合できます。Firebase と同じチームが構築し、世界中の何百万人ものデベロッパーが使用するツールを構築してきた Google の経験が活かされています。
Genkit を使用すると、カスタム コンテンツの生成、セマンティック検索の使用、非構造化入力の処理、ビジネスデータによる質問への回答、自律的な意思決定、ツール呼び出しのオーケストレーションなどを行うアプリを作成できます。
Genkit は現在、JavaScript/TypeScript(Node.js)でのサーバーサイド開発をサポートしており、Go もサポートしています。
GitHub リポジトリで、開発を追うことも、独自のコントリビューションを行うこともできます。
主な機能
Genkit は、プロトタイピングの始まりから本番環境でのモニタリングまで、AI 開発プロセスのあらゆる段階でお客様をサポートします。
まずは、お客様におすすめの Genkit の 10 の主要機能をご紹介します。
1. 多数のモデル、1 つのインターフェース
Genkit には、すぐに使用できる人気のモデルにアクセスできるプラグインと、モデル API を簡単に統合してコミュニティで維持されたモデルを使用できる柔軟なモデル抽象化機能が用意されています。新しいモデルを試すのは 1 つの引数を変更するだけで簡単ですが、各モデルでカスタム構成を指定できます。
import { gemini15Flash } 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(gemini15Flash, '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 { gemini15Flash } 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: gemini15Flash,
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, gemini15Flash } 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: gemini15Flash,
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 { gemini15Flash } 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: gemini15Flash,
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.5-flash
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 のオペレーション スイートへのデータのエクスポートや、Cloud Functions for Firebase、Firebase Authentication、App Check、Firestore などの Firebase サービスとの統合に役立つ、Google Cloud と Firebase の公式プラグインもあります。
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 テキスト エンベディング 評価者: Vertex AI 評価 |
ollama |
生成モデル: Gemma、Llama 3、Mistral などの多くのローカルモデル |
chroma |
ベクトル データベース: ChromaDB |
pinecone |
ベクトル データベース: Pinecone |
google-cloud |
モニタリング ツール: Google Cloud Trace、Google Cloud Logging |
firebase |
クラウドへのデプロイ: Cloud Functions、Firebase Authentication、App Check ベクトル データベース: Cloud Firestore ベクトルストア |
langchain |
Genkit フローで LangChain チェーンとユーティリティを使用する |
始める
スタートガイドを読み、Genkit をインストールして最初の AI フローを実行する方法を確認する。