Prompt API

公開日: 2025 年 5 月 20 日、最終更新日: 2025 年 9 月 21 日

商品の解説 ウェブ 拡張機能 Chrome ステータス インテント
GitHub オリジン トライアル [Origin trial] Chrome 138 表示 テストの目的

Prompt API を使用すると、ブラウザで Gemini Nanoに自然言語リクエストを送信できます。

Prompt API の使用方法は多岐にわたります。たとえば、次のようなものを構築できます。

  • AI を活用した検索: ウェブページのコンテンツに基づいて質問に回答します。
  • パーソナライズされたニュースフィード: 記事をカテゴリで動的に分類し、ユーザーがそのコンテンツをフィルタできるフィードを作成します。
  • カスタム コンテンツ フィルタ。ニュース記事を分析し、ユーザー定義のトピックに基づいてコンテンツを自動的にぼかしたり 非表示にしたりします。
  • カレンダーの予定の作成。ウェブページから予定の詳細を自動的に 抽出する Chrome 拡張機能を開発することで、ユーザーは数ステップでカレンダーの予定を 作成できます。
  • シームレスな連絡先抽出。ウェブサイトから連絡先 情報を抽出する拡張機能を作成することで、ユーザーは企業に連絡したり 、連絡先リストに詳細を追加したりしやすくなります。

これらはほんの一例です。皆様がどのようなものを作成されるか、とても楽しみにしております。

ハードウェア要件を確認する

Chrome でこれらの API を使用して機能を操作するデベロッパーとユーザーには、次の要件があります。他のブラウザでは、動作要件が異なる場合があります。

Language Detector APITranslator API は、パソコン版 Chrome で動作します。これらの API はモバイル デバイスでは動作しません。

Prompt APISummarizer APIWriter APIRewriter APIProofreader API は、次の条件を満たす場合に Chrome で動作します。

  • オペレーティング システム: Windows 10 または 11、macOS 13 以降(Ventura 以降)、 Linux、またはChromebook Plus デバイスの ChromeOS(プラットフォーム 16389.0.0 以降)。 Gemini Nano を使用する API は、Android、iOS、Chromebook Plus 以外のデバイスの ChromeOS 用 Chrome ではまだサポートされていません 。
  • ストレージ: Chrome プロファイルを含むボリュームに 22 GB 以上の空き容量。
  • GPU または CPU: 組み込みモデルは GPU または CPU で実行できます。
    • GPU: 4 GB を超える VRAM。
    • CPU: 16 GB 以上の RAM と 4 個以上の CPU コア。
  • ネットワーク: 無制限のデータまたは従量制課金ではない接続。

Gemini Nano の正確なサイズは、ブラウザがモデルを更新するにつれて変わる可能性があります。現在のサイズを確認するには、chrome://on-device-internals にアクセスしてください。

Prompt API を使用する

Prompt API は、Chrome の Gemini Nano モデルを使用します。API は Chrome に組み込まれていますが、オリジンが API を初めて使用するときにモデルが個別にダウンロードされます。この API を使用する前に、 Google の生成 AI の使用禁止に関するポリシーに同意してください。

モデルを使用できる状態かどうかを確認するには、 LanguageModel.availability() を呼び出します。

const availability = await LanguageModel.availability({
  // The same options in `prompt()` or `promptStreaming()`
});

ダウンロードをトリガーして言語モデルをインスタンス化するには、 ユーザーのアクティベーションを確認します。次に、 create() 関数を呼び出します。

const session = await LanguageModel.create({
  monitor(m) {
    m.addEventListener('downloadprogress', (e) => {
      console.log(`Downloaded ${e.loaded * 100}%`);
    });
  },
});

availability() へのレスポンスが downloading の場合は、 ダウンロードに時間がかかる可能性があるため、ダウンロードの進行状況をリッスンしてユーザーに通知します

localhost で使用する

組み込みの AI API はすべて、Chrome の localhost で使用できます。次のフラグを [**有効**]に設定します。

  • chrome://flags/#optimization-guide-on-device-model
  • chrome://flags/#prompt-api-for-gemini-nano-multimodal-input

[**再起動**] をクリックするか、Chrome を再起動します。エラーが発生した場合は、 localhost のトラブルシューティングを行います

モデル パラメータ

params() 関数は、言語モデルのパラメータを通知します。オブジェクトには次のフィールドがあります。

// Only available when using the Prompt API for Chrome Extensions.
await LanguageModel.params();
// {defaultTopK: 3, maxTopK: 128, defaultTemperature: 1, maxTemperature: 2}

セッションを作成する

Prompt API を実行できるようになったら、create() 関数を使用してセッションを作成します。

const session = await LanguageModel.create();

Chrome 拡張機能の Prompt API でセッションを作成する

Chrome 拡張機能の Prompt API を使用する場合、各セッションは topKtemperature でカスタマイズできます。これらのパラメータの デフォルト値は、LanguageModel.params() から返されます。

// Only available when using the Prompt API for Chrome Extensions.
const params = await LanguageModel.params();
// Initializing a new session must either specify both `topK` and
// `temperature` or neither of them.
// Only available when using the Prompt API for Chrome Extensions.
const slightlyHighTemperatureSession = await LanguageModel.create({
  temperature: Math.max(params.defaultTemperature * 1.2, 2.0),
  topK: params.defaultTopK,
});

create() 関数のオプションの options オブジェクトは signal フィールドも受け取ります。 これにより、AbortSignal を渡してセッションを破棄できます。

const controller = new AbortController();
stopButton.onclick = () => controller.abort();

const session = await LanguageModel.create({
  signal: controller.signal,
});

最初のプロンプトでコンテキストを追加する

最初のプロンプトを使用すると、以前のインタラクションに関するコンテキストを言語モデルに提供できます。たとえば、ブラウザの再起動後にユーザーが保存したセッションを再開できるようにします。

const session = await LanguageModel.create({
  initialPrompts: [
    { role: 'system', content: 'You are a helpful and friendly assistant.' },
    { role: 'user', content: 'What is the capital of Italy?' },
    { role: 'assistant', content: 'The capital of Italy is Rome.' },
    { role: 'user', content: 'What language is spoken there?' },
    {
      role: 'assistant',
      content: 'The official language of Italy is Italian. [...]',
    },
  ],
});

プレフィックスを使用してレスポンスを制約する

以前のロールに加えて、"assistant" ロールを追加して、モデルの以前のレスポンスを詳しく説明 できます。次に例を示します。

const followup = await session.prompt([
  {
    role: "user",
    content: "I'm nervous about my presentation tomorrow"
  },
  {
    role: "assistant",
    content: "Presentations are tough!"
  }
]);

新しいレスポンスをリクエストするのではなく、 "assistant" ロールのレスポンス メッセージの一部を事前入力したい場合があります。これは、特定のレスポンス形式を使用するように言語モデルを 誘導するのに役立ちます。これを行うには、末尾の "assistant" ロール メッセージに prefix: true を追加します。次に例を示します。

const characterSheet = await session.prompt([
  {
    role: 'user',
    content: 'Create a TOML character sheet for a gnome barbarian',
  },
  {
    role: 'assistant',
    content: '```toml\n',
    prefix: true,
  },
]);

想定される入力と出力を追加する

Prompt API にはマルチモーダル機能があり、 複数の言語をサポートしています。セッションの作成時に、expectedInputs および expectedOutputs モダリティと言語を設定します。

  • type: 想定されるモダリティ。
    • expectedInputs の場合、textimageaudio を指定できます。
    • expectedOutputs の場合、Prompt API では text のみを使用できます。
  • languages: 想定される言語を設定する配列。Prompt API は、"en""ja""es" を受け入れます。他の言語のサポートは 開発中です。
    • expectedInputs の場合は、システム プロンプト言語と、想定されるユーザー プロンプト言語を 1 つ以上設定します。
    • expectedOutputs の言語を 1 つ以上設定します。
const session = await LanguageModel.create({
  expectedInputs: [
    { type: "text", languages: ["en" /* system prompt */, "ja" /* user prompt */] }
  ],
  expectedOutputs: [
    { type: "text", languages: ["ja"] }
  ]
});

モデルがサポートされていない入力または出力を検出すると、"NotSupportedError" DOMException が返されることがあります。

マルチモーダル機能

このような機能によって、次のことができます。

  • ユーザーがチャット アプリケーションで送信された音声メッセージを文字起こしできるようにします。
  • キャプションや代替テキストで使用するために、ウェブサイトにアップロードされた画像を説明します。

音声入力で Prompt API を使用する Mediarecorder Audio Prompt デモと、画像入力で Prompt API を使用する Canvas Image Promptデモ をご覧ください。

Prompt API は、次の入力タイプをサポートしています。

このスニペットは、最初に 2 つのビジュアル(1 つの 画像 Blob と 1 つの HTMLCanvasElement) を処理して AI に比較させ、次に ユーザーが音声録音(AudioBuffer として)で応答できるようにするマルチモーダル セッションを示しています。

const session = await LanguageModel.create({
  expectedInputs: [
    { type: "text", languages: ["en"] },
    { type: "audio" },
    { type: "image" },
  ],
  expectedOutputs: [{ type: "text", languages: ["en"] }],
});

const referenceImage = await (await fetch("reference-image.jpeg")).blob();
const userDrawnImage = document.querySelector("canvas");

const response1 = await session.prompt([
  {
    role: "user",
    content: [
      {
        type: "text",
        value:
          "Give a helpful artistic critique of how well the second image matches the first:",
      },
      { type: "image", value: referenceImage },
      { type: "image", value: userDrawnImage },
    ],
  },
]);
console.log(response1);

const audioBuffer = await captureMicrophoneInput({ seconds: 10 });

const response2 = await session.prompt([
  {
    role: "user",
    content: [
      { type: "text", value: "My response to your critique:" },
      { type: "audio", value: audioBuffer },
    ],
  },
]);
console.log(response2);

メッセージを追加する

推論には時間がかかることがあります。特に、マルチモーダル入力でプロンプトを表示する場合は時間がかかります。 事前にプロンプトを送信してセッションにデータを入力しておくと、 モデルが処理を早めに開始できるため便利です。

initialPrompts はセッションの作成時に便利ですが、セッションの作成後にコンテキスト プロンプトを追加するには、prompt() メソッドまたは promptStreaming() メソッドに加えて append() メソッドを使用できます。

次に例を示します。

const session = await LanguageModel.create({
  initialPrompts: [
    {
      role: 'system',
      content:
        'You are a skilled analyst who correlates patterns across multiple images.',
    },
  ],
  expectedInputs: [{ type: 'image' }],
});

fileUpload.onchange = async () => {
  await session.append([
    {
      role: 'user',
      content: [
        {
          type: 'text',
          value: `Here's one image. Notes: ${fileNotesInput.value}`,
        },
        { type: 'image', value: fileUpload.files[0] },
      ],
    },
  ]);
};

analyzeButton.onclick = async (e) => {
  analysisResult.textContent = await session.prompt(userQuestionInput.value);
};

append() によって返される Promise は、プロンプトが検証、 処理され、セッションに追加されると解決されます。プロンプト を追加できない場合、Promise は拒否されます。

JSON スキーマを渡す

responseConstraint フィールドを prompt() メソッドまたは promptStreaming() メソッド に追加して、JSON スキーマを値として渡します。これにより、 構造化出力を Prompt API で使用できます。

次の例では、JSON スキーマにより、特定のメッセージが陶器に関するものかどうかを分類するために、モデルが true または false で応答します。

const session = await LanguageModel.create();

const schema = {
  "type": "boolean"
};

const post = "Mugs and ramen bowls, both a bit smaller than intended, but that
happens with reclaim. Glaze crawled the first time around, but pretty happy
with it after refiring.";

const result = await session.prompt(
  `Is this post about pottery?\n\n${post}`,
  {
    responseConstraint: schema,
  }
);
console.log(JSON.parse(result));
// true

実装では、モデルに送信されるメッセージの一部として JSON スキーマまたは正規表現を含めることができます。これにより、 入力割り当ての一部が使用されます。使用する入力割り当ての量を測定するには、responseConstraint オプションを session.measureInputUsage() に渡します。

この動作は、omitResponseConstraintInput オプションで回避できます。その場合は、プロンプトにガイダンスを含めることをおすすめします。

const result = await session.prompt(`
  Summarize this feedback into a rating between 0-5. Only output a JSON
  object { rating }, with a single property whose value is a number:
  The food was delicious, service was excellent, will recommend.
`, { responseConstraint: schema, omitResponseConstraintInput: true });

モデルにプロンプトを表示する

モデルにプロンプトを表示するには、prompt() 関数または promptStreaming() 関数を使用します。

リクエスト ベースの出力

短い結果が予想される場合は、レスポンスが利用可能になるとレスポンスを返す prompt() 関数を使用できます。

// Start by checking if it's possible to create a session based on the
// availability of the model, and the characteristics of the device.
const available = await LanguageModel.availability({
  expectedInputs: [{type: 'text', languages: ['en']}],
  expectedOutputs: [{type: 'text', languages: ['en']}],
});

if (available !== 'unavailable') {
  const session = await LanguageModel.create();

  // Prompt the model and wait for the whole result to come back.
  const result = await session.prompt('Write me a poem!');
  console.log(result);
}

ストリーミング出力

長いレスポンスが予想される場合は、モデルから部分的な結果が届くたびに表示できる promptStreaming() 関数 を使用する必要があります。 promptStreaming() 関数は ReadableStream を返します。

const available = await LanguageModel.availability({
  expectedInputs: [{type: 'text', languages: ['en']}],
  expectedOutputs: [{type: 'text', languages: ['en']}],
});
if (available !== 'unavailable') {
  const session = await LanguageModel.create();

  // Prompt the model and stream the result:
  const stream = session.promptStreaming('Write me an extra-long poem!');
  for await (const chunk of stream) {
    console.log(chunk);
  }
}

プロンプトを停止する

prompt()promptStreaming() はどちらも、プロンプトの実行を停止できる signal フィールドを含む 2 番目のパラメータ(省略可)を受け取ります。

const controller = new AbortController();
stopButton.onclick = () => controller.abort();

const result = await session.prompt('Write me a poem!', {
  signal: controller.signal,
});

セッション管理

各セッションは、会話のコンテキストを追跡します。セッションの コンテキスト ウィンドウがいっぱいになるまで、以前の インタラクションが今後のインタラクションで考慮されます。

各セッションには、処理できるトークンの最大数があります。この上限までの 進行状況は、次の方法で確認できます。

console.log(`${session.inputUsage}/${session.inputQuota}`);

セッション管理の詳細をご確認ください。

セッションのクローンを作成する

リソースを保持するには、clone() 関数を使用して既存のセッションをコピーします。これにより、会話のフォークが作成され、コンテキストと 最初のプロンプトが保持されます。

clone() 関数は、signal フィールドを含むオプションの options オブジェクトを受け取ります。これにより、AbortSignal を渡してクローンされたセッションを破棄できます。

const controller = new AbortController();
stopButton.onclick = () => controller.abort();

const clonedSession = await session.clone({
  signal: controller.signal,
});

セッションを終了する

セッションが不要になった場合は、destroy() を呼び出してリソースを解放します。セッションが破棄されると、使用できなくなり、実行中の処理はすべて中止されます。セッションの作成には時間がかかる場合があるため、モデルに頻繁にプロンプトを表示する場合は、セッションを維持することをおすすめします。

await session.prompt(
  "You are a friendly, helpful assistant specialized in clothing choices."
);

session.destroy();

// The promise is rejected with an error explaining that
// the session is destroyed.
await session.prompt(
  "What should I wear today? It is sunny, and I am choosing between a t-shirt
  and a polo."
);

デモ

Prompt API のさまざまなユースケースを試すために、複数のデモを作成しました。 次のデモはウェブ アプリケーションです。

Chrome 拡張機能で Prompt API をテストするには、デモ拡張機能をインストールします。拡張機能のソースコードは GitHub で入手できます。

パフォーマンス戦略

ウェブ用の Prompt API はまだ開発中です。この API を構築する際は、 最適なパフォーマンスを実現するためのセッション管理 に関するベスト プラクティスをご覧ください。

権限ポリシー、iframe、ウェブワーカー

デフォルトでは、Prompt API はトップレベル ウィンドウとその 同一オリジンの iframe でのみ使用できます。権限ポリシーの allow="" 属性を使用すると、API へのアクセスをクロスオリジン iframe に委任できます。

<!--
  The hosting site at https://main.example.com can grant a cross-origin iframe
  at https://cross-origin.example.com/ access to the Prompt API by
  setting the `allow="language-model"` attribute.
-->
<iframe src="https://cross-origin.example.com/" allow="language-model"></iframe>

権限ポリシーのステータスを確認するために、各ワーカーの責任あるドキュメントを確立することが 複雑なため、現時点では Prompt API はウェブワーカーでは使用できません。

参加してフィードバックを共有する

お送りいただいた回答は、この API とすべての組み込み AI API の今後のバージョンの構築と実装に直接影響します。