發布日期:2025 年 5 月 20 日
說明 | 網頁 | 額外資訊 | Chrome 狀態 | Intent |
---|---|---|---|---|
GitHub | 查看 | 意圖進行實驗 |
您可以使用 Prompt API,在瀏覽器中向 Gemini Nano 傳送自然語言要求。
您可以透過多種方式使用 Prompt API。在網頁應用程式或網站中,您可以建立:
- AI 輔助搜尋:根據網頁內容回答問題。
- 個人化新聞動態饋給:建立動態分類文章的動態饋給,並允許使用者篩選該內容。
以上只是幾個可能的應用情境,我們很期待看到你的創作。
查看硬體需求
Language Detector API 和 Translator API 僅適用於 Chrome 桌面版。
在 Chrome 中,Prompt API、Summarizer API、Writer API 和 Rewriter API 會在下列條件下運作:
- 作業系統:Windows 10 或 11;macOS 13 以上版本 (Ventura 以上版本);或 Linux。由 Gemini Nano 支援的 API 尚未支援 Android、iOS 和 ChromeOS 版 Chrome。
- 儲存空間:至少 22 GB 的儲存空間 (包含 Chrome 設定檔的磁碟區)。
- GPU:VRAM 必須大於 4 GB。
- 網路:無限上網流量或無限上網連線。
這些規定適用於您在開發過程中,以及使用您建構的功能的使用者。
使用 Prompt API
使用這個 API 前,請先確認您已閱讀並同意 Google 的生成式 AI 使用限制政策。
LanguageModel
命名空間提供兩個函式:
availability()
來查看模型的功能,以及是否可用。create()
開始語言模型工作階段。
下載模型
Prompt API 會使用 Chrome 中的 Gemini Nano 模型。雖然 API 已內建於 Chrome,但來源第一次使用 API 時,系統會另外下載模型。
如要判斷模型是否已準備好供使用,請呼叫非同步 LanguageModel.availability()
函式。這應該會傳回下列其中一個回應:
"unavailable"
表示實作不支援所要求的選項,或完全不支援提示語言模型。"downloadable"
表示實作項目支援要求的選項,但必須先下載某些內容 (例如語言模型本身或精細調整),才能使用這些選項建立工作階段。"downloading"
表示實作項目支援要求的選項,但必須先完成目前的下載作業,才能使用這些選項建立工作階段。"available"
表示實作項目支援要求的選項,且不需要任何新下載項目。
如要觸發模型下載作業並建立語言模型工作階段,請呼叫非同步 LanguageModel.create()
函式。如果對 availability()
的回應是 'downloadable'
,建議您監聽下載進度。這樣一來,如果下載作業需要一段時間,您就能通知使用者。
const session = await LanguageModel.create({
monitor(m) {
m.addEventListener("downloadprogress", (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
},
});
模型功能
params()
函式會告知您語言模型的參數。這個物件包含下列欄位:
defaultTopK
:預設的前 K 項值 (預設值:3
)。maxTopK
:最高前 K 項值 (8
)。defaultTemperature
:預設溫度 (1.0
)。溫度值必須介於0.0
和2.0
之間。maxTemperature
:最高溫度。
await LanguageModel.params();
// {defaultTopK: 3, maxTopK: 8, defaultTemperature: 1, maxTemperature: 2}
建立工作階段
當 Prompt API 可執行時,您可以使用 create()
函式建立工作階段。您可以使用 prompt()
或 promptStreaming()
函式提示模型。
自訂工作階段
您可以使用選用的選項物件,透過 topK
和 temperature
自訂每個工作階段。這些參數的預設值會從 LanguageModel.params()
傳回。
const params = await LanguageModel.params();
// Initializing a new session must either specify both `topK` and
// `temperature` or neither of them.
const slightlyHighTemperatureSession = await LanguageModel.create({
temperature: Math.max(params.defaultTemperature * 1.2, 2.0),
topK: params.defaultTopK,
});
create()
函式的選用選項物件也會使用 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. [...]' }
]
});
工作階段相關限制
特定語言模型工作階段可處理的詞元數量有上限。您可以使用工作階段物件上的下列屬性,檢查用量和達到該限制的進度:
console.log(`${session.inputUsage}/${session.inputQuota}`);
工作階段持續性
每個工作階段都會追蹤對話情境。系統會將先前的互動納入考量,以便在會話的上下文視窗已滿之前,為日後的互動進行評估。
const session = await LanguageModel.create({
initialPrompts: [{
role: "system",
content: "You are a friendly, helpful assistant specialized in clothing choices."
}]
});
const result1 = await session.prompt(
"What should I wear today? It is sunny. I am unsure between a t-shirt and a polo."
);
console.log(result1);
const result2 = await session.prompt(
"That sounds great, but oh no, it is actually going to rain! New advice?"
);
console.log(result2);
複製工作階段
如要保留資源,您可以使用 clone()
函式複製現有工作階段。對話內容會重設,但初始提示會保持不變。clone()
函式會採用含有 signal
欄位的選用選項物件,讓您傳遞 AbortSignal
來銷毀複製的工作階段。
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
const clonedSession = await session.clone({
signal: controller.signal,
});
提示模型
您可以使用 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 {defaultTemperature, maxTemperature, defaultTopK, maxTopK } =
await LanguageModel.params();
const available = await LanguageModel.availability();
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 {defaultTemperature, maxTemperature, defaultTopK, maxTopK } =
await LanguageModel.params();
const available = await LanguageModel.availability();
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 }
);
終止工作階段
如果您不再需要工作階段,請呼叫 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 unsure between a
t-shirt and a polo."
);
多模態功能
Prompt API 支援 Chrome 138 Canary 的音訊和圖像輸入內容,可用於本機實驗。API 會傳回文字輸出內容。
有了這些功能,您可以:
- 允許使用者轉錄在即時通訊應用程式中傳送的音訊訊息。
- 說明上傳至網站的圖片,以便用於說明文字或替代文字。
const session = await LanguageModel.create({
// { type: "text" } is not necessary to include explicitly, unless
// you also want to include expected input languages for text.
expectedInputs: [
{ type: "audio" },
{ type: "image" }
]
});
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 audioBlob = await captureMicrophoneInput({ seconds: 10 });
const response2 = await session.prompt([{
role: "user",
content: [
{ type: "text", value: "My response to your critique:" },
{ type: "audio", value: audioBlob }
]
}]);
多模態示範
如要使用 Prompt API 搭配音訊輸入內容,請參閱 Mediarecorder Audio Prompt 示範;如要使用 Prompt API 搭配圖片輸入內容,請參閱 Canvas Image Prompt 示範。
成效策略
網頁版提示 API 仍在開發中。在我們建構此 API 的同時,請參考工作階段管理的最佳做法,以便取得最佳成效。
意見回饋
您的意見回饋有助於我們瞭解這個 API 的未來發展,並改善 Gemini Nano。甚至可能會產生專屬工作 API (例如音訊轉錄或圖片說明 API),以滿足您和使用者的需求。
參與並提供意見
您的意見會直接影響我們建構及實作此 API 和所有內建 AI API 的未來版本。
- 加入搶先體驗方案。
- 如要針對 Chrome 的實作方式提供意見,請提交錯誤報告或功能要求。
- 如要分享您對 API 形狀的意見回饋,請在現有問題中留言,或是在 Prompt API GitHub 存放區中開啟新問題。
- 加入 Web Incubator 社群群組,參與標準制定工作。