發布日期:2025 年 5 月 20 日,上次更新日期:2026 年 10 月 21 日
| 說明影片 | 網頁 | 擴充功能 | Chrome 狀態 | 意圖 |
|---|---|---|---|---|
| GitHub | 查看 | 出貨意願 | ||
| GitHub | 查看 | 實驗意願 |
您可以使用 Prompt API,向 Chrome 中的基礎模型傳送自然語言要求。
Prompt API 有多種用途。舉例來說,您可以建構:
- AI 輔助搜尋:根據網頁內容回答問題。
- 個人化新聞動態消息:建立動態消息,動態分類文章,並允許使用者篩選內容。
- 自訂內容篩選器。分析新聞報導,並根據使用者定義的主題,自動模糊處理或隱藏內容。
- 建立日曆活動。開發 Chrome 擴充功能,自動從網頁擷取活動詳細資料,讓使用者只需幾個步驟就能建立日曆項目。
- 輕鬆擷取聯絡人資料。建構可從網站擷取聯絡資訊的擴充功能,方便使用者與商家聯絡,或將詳細資料新增至聯絡人清單。
以上只是幾個例子,我們很期待看到你的創作。
查看硬體需求
開發人員和在 Chrome 中使用這些 API 操作功能的使用者,必須符合下列規定。其他瀏覽器可能有不同的操作需求。
Language Detector 和 Translator 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 以上版本)。使用基礎模型的 API 尚未支援 Android 版 Google Chrome、iOS 和非 Chromebook Plus 裝置上的 ChromeOS。
- 儲存空間:Chrome 設定檔所在磁碟區至少要有 22 GB 的可用空間。
- GPU 或 CPU:內建模型可透過 GPU 或 CPU 執行。
- GPU:VRAM 必須超過 4 GB。
- CPU:RAM 至少 16 GB,CPU 核心至少 4 個。
- 注意:Prompt API 搭配音訊輸入時需要 GPU。
- 網路:無限量數據或不計量的連線。
瀏覽器更新模型時,Gemini Nano 的確切大小可能會有所變動。如要查看目前的大小,請前往 chrome://on-device-internals。
使用 Prompt API
Prompt API 會使用 Chrome 中的 Gemini Nano 模型。雖然 API 內建於 Chrome,但模型會在來源首次使用 API 時另外下載。
如要判斷模型是否可供使用,請呼叫 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,請監聽下載進度並通知使用者,因為下載可能需要一些時間。
建立工作階段
Prompt API 可執行後,請使用 create() 函式建立工作階段。
const session = await LanguageModel.create();
create() 函式的選用選項物件會採用 signal 欄位,可讓您傳遞 AbortSignal 來刪除工作階段。
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
const session = await LanguageModel.create({
signal: controller.signal,
});
取樣參數
控制取樣可調整模型回覆的可預測性 (確定性) 或創意性 (多樣性)。取樣參數的可用性因網頁平台和 Chrome 擴充功能而異:
- 網頁:使用
samplingMode選項,該選項會使用描述性列舉值 (而非原始數字) 調整輸出可預測性。 - Chrome 擴充功能:支援舊版數值參數 (
topK、temperature) 和LanguageModel.params()方法。
網頁取樣模式
將 samplingMode 選項傳遞至 LanguageModel.create() (或 LanguageModel.availability())。
支援的 samplingMode 列舉值如下:
"most-predictable":確定性和可預測性最高。"predictable":輸出內容較可預測,變化極小。"slightly-predictable":輸出內容略可預測。"balanced":在可預測性和創意之間取得平衡 (一般預設行為)。"slightly-creative":輸出內容略有變化,且具創意。"creative":輸出內容富有創意且多樣化。"most-creative":變化性和創意程度最高。
// Available on the web with the Sampling Parameters Origin Trial enabled
const session = await LanguageModel.create({
samplingMode: 'creative',
});
// The configured sampling mode is exposed on the session instance
console.log(session.samplingMode);
// "creative"
Chrome 擴充功能的取樣參數
在 Chrome 擴充功能中使用 Prompt API 時,您仍可使用選項物件,透過 topK 和 temperature 自訂每個工作階段。
靜態 LanguageModel.params() 函式會告知語言模型的預設和最大參數限制:
// Only available in Chrome Extensions
const params = await LanguageModel.params();
// {defaultTopK: 3, maxTopK: 128, defaultTemperature: 1, maxTemperature: 2}
// Initializing a new session in extensions must either specify both `topK` and
// `temperature` or neither of them.
const slightlyHighTemperatureSession = await LanguageModel.create({
temperature: Math.min(params.defaultTemperature * 1.2, params.maxTemperature),
topK: params.defaultTopK,
});
console.log(slightlyHighTemperatureSession.temperature);
console.log(slightlyHighTemperatureSession.topK);
使用初始提示詞加入背景資訊
透過初始提示,您可以向語言模型提供先前互動的背景資訊,例如允許使用者在瀏覽器重新啟動後,繼續進行已儲存的工作階段。
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可以是text、image或audio。- 在
expectedOutputs中,Prompt API 僅允許text。
languages:用於設定預期語言的陣列。Prompt API 接受"en"、"ja"、"es"、"de"和"fr"。我們正在開發其他語言的支援功能。- 針對
expectedInputs,設定系統提示語言和一或多種預期的使用者提示語言。 - 設定一或多種
expectedOutputs語言。
- 針對
const session = await LanguageModel.create({
expectedInputs: [
{ type: "text", languages: ["en" /* system prompt */, "ja" /* user prompt */] }
],
expectedOutputs: [
{ type: "text", languages: ["ja"] }
]
});
如果模型遇到不支援的輸入或輸出內容,您可能會收到 "NotSupportedError" DOMException。
多模態功能
有了這些功能,您就能:
- 允許使用者轉錄即時通訊應用程式中傳送的語音訊息。
- 描述上傳到網站的圖片,用於說明文字或替代文字。
請參閱 Mediarecorder Audio Prompt 示範,瞭解如何搭配音訊輸入使用 Prompt API,以及 Canvas Image Prompt 示範,瞭解如何搭配圖片輸入使用 Prompt API。
Prompt API 支援下列輸入類型:
- 音訊:
- 視覺:
這段程式碼片段顯示多模態工作階段,首先處理兩個影像 (一個圖片 Blob 和一個 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 就會履行。如果無法附加提示,系統會拒絕承諾。
傳遞 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.measureContextUsage(),藉此評估會使用多少脈絡窗口。
您可以使用 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 欄位,可讓您停止執行提示。
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
const result = await session.prompt('Write me a poem!', {
signal: controller.signal,
});
工作階段管理
每個工作階段都會追蹤對話情境。系統會考量先前的互動,再進行後續互動,直到工作階段的內容視窗填滿為止。
每個工作階段可處理的詞元數量有上限。請透過下列方式查看這項限制的進度:
console.log(`${session.contextUsage}/${session.contextWindow}`);
傳送的提示可能會導致脈絡窗口溢位。在這種情況下,系統會移除與語言模型對話的初始部分,一次移除一組提示和回覆,直到有足夠的權杖可處理新提示為止。系統提示詞除外,這類提示詞一律不會移除。
如要偵測這類溢位,請監聽工作階段的 contextoverflow 事件:
session.addEventListener("contextoverflow", () => {
console.log("We've gone past the context window, and some inputs will be dropped!");
});
如果無法從對話記錄中移除足夠的權杖來處理新提示,prompt() 或 promptStreaming() 呼叫會失敗,並擲回 QuotaExceededError 例外狀況,且不會移除任何內容。QuotaExceededError 具有下列屬性:
requested:輸入內容包含多少詞元contextWindow:可用的權杖數量
進一步瞭解工作階段管理。
複製工作階段
如要保留資源,可以使用 clone() 函式複製現有工作階段。這會建立對話分支,保留上下文和初始提示。
clone() 函式會採用選用的選項物件,其中包含 signal 欄位,可讓您傳遞 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 和 Web Worker
根據預設,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 目前不適用於 Web Worker,因為要為每個 Worker 建立負責的文件,以檢查權限政策審查狀態,這項作業相當複雜。
參與並提供意見
您的意見會直接影響我們如何建構及實作這個 API 和所有內建 AI API 的未來版本。
- 如要針對 Chrome 的實作方式提供意見,請提交錯誤報告或功能要求。
- 如要對 API 形式提供意見,請在 Prompt API GitHub 存放區中,對現有問題留言或建立新問題。
- 加入搶先體驗計畫。