0.9 から 1.0 に移行する

Genkit 1.0 では、全体的な機能を改善する多くの機能強化が導入されています。また、一部の破壊的変更もあります。Genkit 0.9 でアプリケーションを開発している場合は、最新バージョンの Genkit にアップグレードするときにアプリケーション コードを更新する必要があります。このガイドでは、最も重要な変更の概要と、既存のアプリケーションをスムーズに移行する方法について説明します。

ベータ版 API

不安定なベータ版 API チャンネルを導入し、セッション、チャット、Genkit クライアント API は引き続きベータ版として提供し、改良を続けていきます。具体的には、現在 beta 名前空間にある関数は次のとおりです。

  • ai.chat
  • ai.createSession
  • ai.loadSession
  • ai.currentSession
  • ai.defineFormat
  • ai.defineInterrupt

旧:

import { genkit } from 'genkit';
const ai = genkit({...})
const session = ai.createSession({ ... })

新規:

import { genkit } from 'genkit/beta';
const ai = genkit({...})
const session = ai.createSession({ ... })

旧:

import { runFlow, streamFlow } from 'genkit/client';

新規:

import { runFlow, streamFlow } from 'genkit/beta/client';

新しい @genkit-ai/express パッケージの導入

この新しいパッケージには、Genkit で Express.js サーバーを簡単に構築するためのユーティリティが含まれています。詳しくは、こちらのページをご覧ください。

startFlowServer は、genkit オブジェクトの一部からこの新しい @genkit-ai/express パッケージに移動しました。startFlowServer を使用するには、インポートを更新する必要があります。

旧:

const ai = genkit({ ... });
ai.startFlowServer({
  flows: [myFlow1, myFlow2],
});

新規:

import { startFlowServer } from '@genkit-ai/express';
startFlowServer({
  flows: [myFlow1, myFlow2],
});

フローへの変更

1.0 のフローにはいくつかの変更が加えられています。

  • ai.defineStreamingFlowai.defineFlow に統合されました。
  • onFlowonCallGenkit に置き換えました。
  • runai.run に移動しました。
  • 認証の処理が変更されました。

カスタム トレース ブロックの run 関数は genkit オブジェクトの一部に移動されました。代わりに ai.run を使用して呼び出してください。

旧:

ai.defineFlow({name: 'banana'}, async (input) => {
  const step = await run('myCode', async () => {
    return 'something'
  });
})

新規:

ai.defineFlow({name: 'banana'}, async (input) => {
  const step = await ai.run('myCode', async () => {
    return 'something'
  });
})

ai.defineStreamingFlow は削除されました。代わりに ai.defineFlow を使用してください。また、streamingCallback はフロー関数の 2 つ目の引数内のフィールドに移動し、sendChunk という名前になりました。

旧:

const flow = ai.defineStreamingFlow({name: 'banana'}, async (input, streamingCallback) => {
  streamingCallback({chunk: 1});
})

const {stream} = await flow()
for await (const chunk of stream) {
  // ...
}

新規:

const flow = ai.defineFlow({name: 'banana'}, async (input, {context, sendChunk}) => {
  sendChunk({chunk: 1});
})

const {stream, output} = flow.stream(input);
for await (const chunk of stream) {
  // ...
}

FlowAuth 認証の名前が context になりました。auth には、コンテキスト内のフィールドとしてアクセスできます。

旧:

ai.defineFlow({name: 'banana'}, async (input) => {
  const auth = getFlowAuth();
  // ...
})

新規:

ai.defineFlow({name: 'banana'}, async (input, { context }) => {
  const auth = context.auth;
})

onFlowfirebase-functions/https パッケージに移動し、名前を onCallGenkit に変更しました。次のスニペットは、その使用方法の例を示しています。

古い

import { onFlow } from "@genkit-ai/firebase/functions";

export const generatePoem = onFlow(
  ai,
  {
    name: "jokeTeller",
    inputSchema: z.string().nullable(),
    outputSchema: z.string(),
    streamSchema: z.string(),
  },
  async (type, streamingCallback) => {
    const { stream, response } = await ai.generateStream(
      `Tell me a longish ${type ?? "dad"} joke.`
    );
    for await (const chunk of stream) {
      streamingCallback(chunk.text);
    }
    return (await response).text;
  }
);

新規:

import { onCallGenkit } from "firebase-functions/https";
import { defineSecret } from "firebase-functions/params";
import { genkit, z } from "genkit";

const apiKey = defineSecret("GOOGLE_GENAI_API_KEY");

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

export const jokeTeller = ai.defineFlow(
  {
    name: "jokeTeller",
    inputSchema: z.string().nullable(),
    outputSchema: z.string(),
    streamSchema: z.string(),
  },
  async (type, { sendChunk }) => {
    const { stream, response } = ai.generateStream(
      `Tell me a longish ${type ?? "dad"} joke.`
    );
    for await (const chunk of stream) {
      sendChunk(chunk.text);
    }
    return (await response).text;
  }
);

export const tellJoke = onCallGenkit({ secrets: [apiKey] }, jokeTeller);

defineFlow から認証ポリシーが削除されました。認証ポリシーの処理がサーバー依存になりました。

旧:

export const simpleFlow = ai.defineFlow(
  {
    name: 'simpleFlow',
    authPolicy: (auth, input) => {
      // auth policy
    },
  },
  async (input) => {
    // Flow logic here...
  }
);

次のスニペットは、Express で認証を処理する例を示しています。

新規:

import { UserFacingError } from 'genkit';
import { ContextProvider, RequestData } from 'genkit/context';
import { expressHandler, startFlowServer } from '@genkit-ai/express';

const context: ContextProvider<Context> = (req: RequestData) => {
  return {
    auth: parseAuthToken(req.headers['authorization']),
  };
};

export const simpleFlow = ai.defineFlow(
  {
    name: 'simpleFlow',
  },
  async (input, { context }) => {
    if (!context.auth) {
      throw new UserFacingError("UNAUTHORIZED", "Authorization required.");
    }
    if (input.uid !== context.auth.uid) {
      throw new UserFacingError("UNAUTHORIZED", "You may only summarize your own profile data.");
    }
    // Flow logic here...
  }
);

const app = express();
app.use(express.json());
app.post(
  '/simpleFlow',
  expressHandler(simpleFlow, { context })
);
app.listen(8080);

// or

startFlowServer(
  flows: [withContextProvider(simpleFlow, context)],
  port: 8080
);

詳細については、認証のドキュメントをご覧ください。

次のスニペットは、Cloud Functions for Firebase で認証を処理する例を示しています。

import { genkit } from 'genkit';
import { onCallGenkit } from 'firebase-functions/https';

const ai = genkit({ ... });;

const simpleFlow = ai.defineFlow({
  name: 'simpleFlow',
}, async (input) => {
  // Flow logic here...
});

export const selfSummary = onCallGenkit({
  authPolicy: (auth, data) => auth?.token?.['email_verified'] && auth?.token?.['admin'],
}, simpleFlow);

プロンプト

プロンプトにいくつかの変更と改善を加えました。

プロンプトとシステム メッセージに個別のテンプレートを定義できます。

const hello = ai.definePrompt({
  name: 'hello',
  system: 'talk like a pirate.',
  prompt: 'hello {{ name }}',
  input: {
    schema: z.object({
      name: z.string()
    })
  }
});
const { text } = await hello({name: 'Genkit'});

また、messages フィールドで複数のメッセージ プロンプトを定義することもできます。

const hello = ai.definePrompt({
  name: 'hello',
  messages: '{{ role "system" }} talk like a pirate. {{ role "user" }} hello {{ name }}',
  input: {
    schema: z.object({
      name: z.string()
    })
  }
});

プロンプト テンプレートの代わりに、関数を使用できます。

ai.definePrompt({
  name: 'hello',
  prompt: async (input, { context }) => {
    return `hello ${input.name}`
  },
  input: {
    schema: z.object({
      name: z.string()
    })
  }
});

プロンプト内からコンテキスト(認証情報を含む)にアクセスできます。

const hello = ai.definePrompt({
  name: 'hello',
  messages: 'hello {{ @auth.email }}',
});

ストリーミング関数には await は不要

旧:

const { stream, response } = await ai.generateStream(`hi`);
const { stream, output } = await myflow.stream(`hi`);

新規:

const { stream, response } = ai.generateStream(`hi`);
const { stream, output } = myflow.stream(`hi`);

Embed の戻り値の型が新しくなりました

マルチモーダル エンベディングのサポートを追加しました。Embed は、単一のエンベディング ベクトルを返すのではなく、エンベディング ベクトルとメタデータを含むエンベディング オブジェクトの配列を返します。

旧:

const response = await ai.embed({embedder, content, options});  // returns number[]

新規:

const response = await ai.embed({embedder, content, options}); // returns Embedding[]
const firstEmbeddingVector = response[0].embedding;  // is number[]