發布日期:2024 年 11 月 11 日,上次更新日期:2025 年 5 月 20 日
說明 | 網頁 | 額外資訊 | Chrome 狀態 | Intent |
---|---|---|---|---|
GitHub | 查看 | 意圖進行實驗 |
您可以使用 Prompt API,在瀏覽器中向 Gemini Nano 傳送自然語言要求。
您可以透過多種方式在 Chrome 擴充功能中使用提示 API。例如:
- 即時日曆活動。開發 Chrome 擴充功能,自動從網頁中擷取活動詳細資料,讓使用者只需幾個步驟就能建立日曆項目。
- 順暢的聯絡人擷取功能:建立可從網站擷取聯絡資訊的擴充功能,方便使用者與商家聯絡,或在聯絡人名單中新增詳細資料。
- 動態內容篩選。建立 Chrome 擴充功能,以便分析新聞文章,並根據使用者定義的主題自動模糊處理或隱藏內容。
以上只是幾個可能的應用情境,我們很期待看到你的創作。
在擴充功能中使用 Prompt API
在 LanguageModel
命名空間中,您可以使用兩個擴充函式:
availability()
來查看模型的功能,以及是否可用。create()
開始語言模型工作階段。
下載模型
Prompt API 會使用 Chrome 中的 Gemini Nano 模型。雖然 API 已內建於 Chrome,但擴充功能首次使用 API 時,系統會另外下載模型。
如要判斷模型是否已準備好供使用,請呼叫非同步 LanguageModel.availability()
函式。這應該會傳回下列其中一個回應:
'no'
:瀏覽器支援 Prompt API,但目前無法使用。這可能是因為磁碟空間不足,無法下載模型。'readily'
:瀏覽器支援 Prompt API,可立即使用。'after-download'
:瀏覽器支援 Prompt API,但必須先下載模型。
如要觸發模型下載作業並建立語言模型工作階段,請呼叫非同步 LanguageModel.availability()
函式。如果對 availability()
的回應是 'after-download'
,建議您監聽下載進度。這樣一來,如果下載作業需要一段時間,您就能通知使用者。
const session = await LanguageModel.create({
monitor(m) {
m.addEventListener("downloadprogress", (e) => {
console.log(`Downloaded ${e.loaded} of ${e.total} bytes.`);
});
},
});
模型功能
availability()
函式也會告知您語言模型的功能。除了 available
之外,這個物件還有下列欄位:
defaultTopK
:預設的前 K 項值 (預設值:3
)。maxTopK
:最高前 K 項值 (8
)。defaultTemperature
:預設溫度 (1.0
)。溫度值必須介於0.0
和2.0
之間。
await LanguageModel.availability();
// {available: 'readily', defaultTopK: 3, maxTopK: 8, defaultTemperature: 1}
建立工作階段
當 Prompt API 可執行時,您可以使用 create()
函式建立工作階段。您可以使用 prompt()
或 promptStreaming()
函式提示模型。
自訂工作階段
您可以使用選用的選項物件,透過 topK
和 temperature
自訂每個工作階段。這些參數的預設值會從 LanguageModel.availability()
傳回。
const capabilities = await LanguageModel.availability();
// Initializing a new session must either specify both `topK` and
// `temperature` or neither of them.
const slightlyHighTemperatureSession = await LanguageModel.create({
temperature: Math.max(availability.defaultTemperature * 1.2, 2.0),
topK: capabilities.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.tokensSoFar}/${session.maxTokens}
(${session.tokensLeft} left)`);
工作階段持續性
每個工作階段都會追蹤對話情境。系統會將先前的互動納入未來互動考量,直到工作階段的上下文視窗已滿為止。
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 {available, defaultTemperature, defaultTopK, maxTopK } =
await LanguageModel.availability();
if (available !== 'no') {
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()
函式,這樣您就能在模型傳回結果時顯示部分結果。
const {available, defaultTemperature, defaultTopK, maxTopK } =
await LanguageModel.availability();
if (available !== 'no') {
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);
}
}
promptStreaming()
會傳回 ReadableStream
,其區塊會依序彼此建構。例如:"Hello,"
、"Hello world,"
、"Hello world I am,"
、"Hello world I am an AI."
。這不是預期的行為。我們打算與平台上的其他串流 API 保持一致,在該 API 中,區塊是單一長串流的連續片段。這表示輸出內容會是 "Hello"
、" world"
、" I am"
、" an AI"
等序列。
目前,您可以實作下列內容,以達到預期的行為。這項功能適用於標準和非標準行為。
let result = '';
let previousChunk = '';
for await (const chunk of stream) {
const newChunk = chunk.startsWith(previousChunk)
? chunk.slice(previousChunk.length) : chunk;
console.log(newChunk);
result += newChunk;
previousChunk = chunk;
}
console.log(result);
停止執行提示
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."
);
示範
如要測試 Chrome 擴充功能中的提示 API,請安裝示範擴充功能。擴充功能原始碼可在 GitHub 上取得。
參與並提供意見
您的意見回饋會直接影響我們建構及實作此 API 後續版本,以及所有內建 AI API 的方式。
- 如要提供 Chrome 實作方式的意見回饋,請提交錯誤報告或功能要求。
- 如要分享您對 API 形狀的意見回饋,請在現有問題中留言,或是在 Prompt API GitHub 存放區中開啟新問題。
- 在 GitHub 下載提示 API 範例擴充功能。
- 加入 Web Incubator 社群群組,參與標準制定工作。