# Prompt API

- 来源：Hacker News 热门（buzzing.cc 中文翻译）
- 作者：gslin
- 发布时间：2026-04-27 16:55
- AIHOT 分数：68
- AIHOT 链接：https://aihot.virxact.com/items/cmogzqrh401ozslwpybra9bkc
- 原文链接：https://developer.chrome.com/docs/ai/prompt-api

## AI 摘要

Chrome 开发者文档推出了 Prompt API，这是一个用于 AI 提示管理的应用程序编程接口，帮助开发者以编程方式处理提示词，提升开发效率。该 API 的发布信息在 Hacker News 上获得102点积分，反映出技术社区对此工具的关注和积极评价。开发者可通过官方文档进一步了解其功能和应用场景。

## 正文

Prompt API コレクションでコンテンツを整理 必要に応じて、コンテンツの保存と分類を行います。

公開日: 2025 年 5 月 20 日、最終更新日: 2026 年 5 月 19 日

商品の解説 ウェブ 拡張機能 Chrome ステータス インテント GitHub Chrome 148 Chrome 138 表示 リリースするインテント GitHub サンプリング パラメータのオリジン トライアル Chrome 148 表示 テストの目的

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

Prompt API の使用方法はたくさんあります。たとえば、次のようなものを構築できます。

AI を活用した検索: ウェブページの内容に基づいて質問に回答します。

カスタム版ニュース フィード: 記事をカテゴリで動的に分類し、ユーザーがそのコンテンツをフィルタできるフィードを作成します。

カスタム コンテンツ フィルタ 。ニュース記事を分析し、ユーザー定義のトピックに基づいてコンテンツを自動的にぼかしたり非表示にしたりします。

カレンダーの予定の作成 。ウェブページから予定の詳細を自動的に抽出する Chrome 拡張機能を開発することで、ユーザーは数ステップでカレンダーの予定を作成できます。

シームレスな連絡先の抽出 。ウェブサイトから連絡先情報を抽出する拡張機能を作成することで、ユーザーは企業に連絡したり、連絡先リストに詳細を追加したりしやすくなります。

これらはほんの一例です。どのようなものが作成されるか楽しみです。

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

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

言語検出 API と翻訳 API は、パソコン版 Chrome で動作します。これらの API はモバイル デバイスでは動作しません。

Prompt API、Summarizer API、Writer API、Rewriter API、Proofreader 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 コア。 注: 音声入力を使用する Prompt API には GPU が必要です。

GPU: 4 GB を超える VRAM。

CPU: 16 GB 以上の RAM と 4 個以上の CPU コア。

注: 音声入力を使用する Prompt API には GPU が必要です。

ネットワーク: 無制限のデータまたは従量制課金ではない接続。

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

chrome://on-device-internals

Prompt API を使用する

Prompt API は、Chrome の Gemini Nano モデルを使用します。API は Chrome に組み込まれていますが、オリジンが API を初めて使用するときにモデルが個別にダウンロードされます。

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

LanguageModel.availability()

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

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

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

create()

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

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

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

availability()

downloading

モデル パラメータ

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

params()

defaultTopK: デフォルト top-K 値。

defaultTopK

maxTopK: top-K の 最大値 。

maxTopK

defaultTemperature: デフォルト 温度。

defaultTemperature

maxTemperature: 最大温度。

maxTemperature

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

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

セッションを作成する

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

create()

const session = await LanguageModel.create();

const session = await LanguageModel.create();

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

topK

temperature

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, });

// 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 を渡してセッションを破棄できます。

create()

signal

AbortSignal

const controller = new AbortController(); stopButton.onclick = () => controller.abort(); const session = await LanguageModel.create({ signal: controller.signal, });

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. [...]', }, ], });

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" ロールを追加して、モデルの以前のレスポンスを詳しく説明 できます。次に例を示します。

"assistant"

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

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を追加します。次に例を示します。

"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, }, ]);

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 のモダリティと言語を設定します。

expectedInputs

expectedOutputs

type: 想定されるモダリティ。 expectedInputs の場合、text、image、audio を指定できます。 expectedOutputs の場合、Prompt API では text のみが許可されます。

type

expectedInputs の場合、text、image、audio を指定できます。

expectedInputs

text

image

audio

expectedOutputs の場合、Prompt API では text のみが許可されます。

expectedOutputs

text

languages: 想定される言語を設定する配列。Prompt API は、"en"、"ja"、"es" を受け入れます。他の言語のサポートは開発中です。 expectedInputs の場合は、システム プロンプト言語と、想定されるユーザー プロンプト言語を 1 つ以上設定します。 expectedOutputs の言語を 1 つ以上設定します。

languages

"en"

"ja"

"es"

expectedInputs の場合は、システム プロンプト言語と、想定されるユーザー プロンプト言語を 1 つ以上設定します。

expectedInputs

expectedOutputs の言語を 1 つ以上設定します。

expectedOutputs

const session = await LanguageModel.create({ expectedInputs: [ { type: "text", languages: ["en" /* system prompt */, "ja" /* user prompt */] } ], expectedOutputs: [ { type: "text", languages: ["ja"] } ] });

const session = await LanguageModel.create({ expectedInputs: [ { type: "text", languages: ["en" /* system prompt */, "ja" /* user prompt */] } ], expectedOutputs: [ { type: "text", languages: ["ja"] } ] });

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

"NotSupportedError"

マルチモーダル機能

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

ユーザーがチャット アプリケーションで送信された音声メッセージを文字起こしできるようにします。

ウェブサイトにアップロードされた画像を説明して、キャプションや代替テキストで使用できるようにします。

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

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

音声: AudioBuffer ArrayBufferView ArrayBuffer Blob

AudioBuffer

AudioBuffer

ArrayBufferView

ArrayBufferView

ArrayBuffer

ArrayBuffer

Blob

Blob

ビジュアル: HTMLImageElement SVGImageElement HTMLVideoElement （現在の動画位置の動画フレームを使用） HTMLCanvasElement ImageBitmap OffscreenCanvas VideoFrame Blob ImageData

HTMLImageElement

HTMLImageElement

SVGImageElement

SVGImageElement

HTMLVideoElement （現在の動画位置の動画フレームを使用）

HTMLVideoElement

HTMLCanvasElement

HTMLCanvasElement

ImageBitmap

ImageBitmap

OffscreenCanvas

OffscreenCanvas

VideoFrame

VideoFrame

Blob

Blob

ImageData

ImageData

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

Blob

HTMLCanvasElement

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);

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() メソッドを使用できます。

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); };

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 は拒否されます。

append()

JSON スキーマを渡す

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

responseConstraint

prompt()

promptStreaming()

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

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

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.measureContextUsage() に渡します。

responseConstraint

session.measureContextUsage()

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

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 });

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()

promptStreaming()

リクエスト ベースの出力

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

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); }

// 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 を返します。

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); } }
