Firebase Genkit

Genkit は、AI を活用したアプリケーションや機能を構築するためのフレームワークです。Node.js と Go 用のオープンソース ライブラリに加え、テストとデバッグ用の開発ツールも提供されています。

このドキュメントでは、Node.js 用の Genkit について説明します。Go デベロッパーの方は、Genkit Go のドキュメントをご覧ください。

Genkit ライブラリは、Node.js がサポートされている任意の場所にデプロイして実行できます。多くの AI モデル プロバイダとベクトル データベースで動作するように設計されています。Firebase と Google Cloud との統合が提供されていますが、Google サービスから独立して Genkit を使用できます。

始めましょう

主な機能

AI 生成用の統合 API 1 つの API を使用して、さまざまな AI モデルからコンテンツを生成またはストリーミングします。マルチモーダル入出力とカスタムモデル設定で動作します。
構造化出力 組み込みの検証機能を使用して、構造化オブジェクト(JSON など)を生成またはストリーミングします。アプリとの統合を簡素化し、非構造化データを使用可能な形式に変換します。
ツールの呼び出し AI モデルがタスクを完了するためのツールとして関数と API を呼び出すようにします。モデルが、どのツールをいつ使用するかを決定します。
チャット Genkit には、AI モデルとのマルチターンの会話を容易にするチャット固有の API があります。この API はステートフルで永続的です。
エージェント ツール(他のエージェントを含む)を使用して複雑なタスクやワークフローを自動化するインテリジェント エージェントを作成します。
データの取得 データを統合することで、生成される出力の精度と関連性を高めることができます。シンプルな API を使用すると、さまざまなソースから情報を埋め込み、インデックスに登録し、取得できます。
プロンプト テンプレート リッチテキスト テンプレート、モデル設定、マルチモーダル サポート、ツール統合を含む効果的なプロンプトを、実行可能なコンパクトなプロンプト ファイル内に作成します。

これらの機能をコードで使用する方法については、次のコードサンプルをご覧ください。

基本的な生成

import { genkit } from 'genkit';
import { googleAI, gemini20Flash } from '@genkit-ai/googleai';

const ai = genkit({
  plugins: [googleAI()],
  model: gemini20Flash,  // Set default model
});

// Simple generation
const { text } = await ai.generate('Why is AI awesome?');
console.log(text);

// Streamed generation 
const { stream } = ai.generateStream('Tell me a story');
for await (const chunk of stream) {
  console.log(chunk.text);
}

構造化出力

import { genkit, z } from 'genkit';
import { googleAI, gemini20Flash } from '@genkit-ai/googleai';

const ai = genkit({
  plugins: [googleAI()],
  model: gemini20Flash,
});

const { output } = await ai.generate({
  prompt: 'Create a brief profile for a character in a fantasy video game.',
  // Specify output structure using Zod schema
  output: {
    format: 'json',  
    schema: z.object({
      name: z.string(),
      role: z.enum(['knight', 'mage', 'archer']),
      backstory: z.string(),
    }),
  },
});

console.log(output);

ツールの呼び出し

import { genkit, z } from 'genkit';
import { googleAI, gemini20Flash } from '@genkit-ai/googleai';

const ai = genkit({
  plugins: [googleAI()],
  model: gemini20Flash,
});

// Define tool to get current weather for a given location
const getWeather = ai.defineTool(
  {
    name: "getWeather",
    description: "Gets the current weather in a given location",
    inputSchema: z.object({ 
      location: z.string().describe('The location to get the current weather for')
    }),
    outputSchema: z.object({ 
      weatherReport: z.string().describe('Weather report of a particular location') 
    }),
  },
  async (input) => {
    // Here, we would typically make an API call or database query. For this
    // example, we just return a fixed value.
    return `The current weather in ${input.location} is 63°F and sunny.`;
  }
);

const { text } = await ai.generate({
    tools: [getWeather], // Give the model a list of tools it can call
    prompt: 'What is the weather like in New York? ',
});

console.log(text);

チャット

import { genkit, z } from 'genkit/beta';
import { googleAI, gemini20Flash } from '@genkit-ai/googleai';

const ai = genkit({
  plugins: [googleAI()],
  model: gemini20Flash,
});

const chat = ai.chat({ system: 'Talk like a pirate' });

let response = await chat.send('Hi, my name is Pavel');

response = await chat.send('What is my name?');
console.log(response.text);
// Ahoy there! Your name is Pavel, you scurvy dog

エージェント

import { genkit, z } from 'genkit/beta';
import { googleAI, gemini20Flash } from '@genkit-ai/googleai';

const ai = genkit({
  plugins: [googleAI()],
  model: gemini20Flash,
});

// Define tools for your agents to use
const reservationTool = ai.defineTool( ... );
const reservationCancelationTool = ai.defineTool( ... );
const reservationListTool = ai.defineTool( ... );

// Define prompts that represent specialist agents
const reservationAgent = ai.definePrompt({
  name: 'reservationAgent',
  description: 'Reservation Agent can help manage guest reservations',
  tools: [reservationTool, reservationCancelationTool, reservationListTool],
  system: `Help guests make and manage reservations`
});
const menuInfoAgent = ai.definePrompt( ... );
const complaintAgent = ai.definePrompt( ... );

// Define a triage agent that routes to the proper specialist agent
const triageAgent = ai.definePrompt({
  name: 'triageAgent',
  description: 'Triage Agent',
  tools: [reservationAgent, menuInfoAgent, complaintAgent],
  system: `You are an AI customer service agent for Pavel's Cafe.
    Greet the user and ask them how you can help. If appropriate, transfer to an
    agent that can better handle the request. If you cannot help the customer with
    the available tools, politely explain so.`
});

// Create a chat to enable conversational agent interactions
const chat = ai.chat(triageAgent);

chat.send('I want a reservation at Pavel\'s Cafe for noon on Tuesday.');

データの取得

import { genkit } from 'genkit';
import { googleAI, gemini20Flash, textEmbedding004 } from '@genkit-ai/googleai';
import { devLocalRetrieverRef } from '@genkit-ai/dev-local-vectorstore';

const ai = genkit({ 
  plugins: [
    googleAI()
    devLocalVectorstore([
      {
        indexName: 'BobFacts',
        embedder: textEmbedding004,
      },
    ]),
  ],
  model: gemini20Flash,
});

// Reference to a local vector database storing Genkit documentation
const retriever = devLocalRetrieverRef('BobFacts');

// Consistent API to retrieve most relevant documents based on semantic similarity to query
const docs = await ai.retrieve(
  retriever: retriever,
  query: 'How old is bob?',
);

const result = await ai.generate({
    prompt: `Use the provided context from the Genkit documentation to answer this query: ${query}`,
    docs // Pass retrieved documents to the model
});

プロンプト テンプレート

---
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 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}}.

開発ツール

Genkit には、AI アプリケーションの構築を容易にするためのコマンドライン インターフェース(CLI)とローカル デベロッパー UI が用意されています。これらのツールは、次のような場合に役立ちます。

  • テスト: AI 関数、プロンプト、クエリをテストして調整します。
  • デバッグ: 詳細な実行トレースを使用して問題を見つけて修正します。
  • 評価: 複数のテストケースで生成された結果を評価します。

ソーシャル メディアで

  • コミュニティに参加する: Discord サーバーで最新情報を入手したり、質問したり、作品を共有したりできます。
  • フィードバックを送信する: GitHub の Issue Tracker を使用して、問題の報告や新機能の提案を行う。

次のステップ

Genkit で最初の AI アプリケーションを作成する方法については、スタートガイドをご覧ください。