使用 Prompt API 管理工作階段的最佳做法

發布日期:2025 年 1 月 27 日

說明 網頁 擴充功能 Chrome 狀態 意圖
GitHub 來源試用 來源試用 Chrome 138 查看 實驗意圖

提示 API 的主要功能之一是工作階段。 您可以透過這些工作階段,與 AI 模型進行一或多個持續對話,而不會讓模型遺漏相關資訊。本指南將介紹使用語言模型管理工作階段的最佳做法。

如果您要建構傳統聊天機器人 (使用者與 AI 互動),可能需要管理一或多個平行工作階段。或者,如果您有客戶關係管理系統,其中一位支援服務專員會同時處理多位客戶的問題,並運用 AI 協助支援服務專員追蹤各種對話。

使用初始提示詞啟動工作階段

初始提示會在工作階段開始時設定情境。舉例來說,您可以使用初始提示,告訴模型應如何回應。

const languageModel = await LanguageModel.create({   initialPrompts: [{     role: 'system',     content: 'You are a helpful assistant and you speak like a pirate.'   }], }); console.log(await languageModel.prompt('Tell me a joke.')); // 'Avast ye, matey! What do you call a lazy pirate?\n\nA **sail-bum!**\n\nAhoy // there, me hearties!  Want to hear another one? \n' 

複製主要議程

如要在工作階段結束後開始新的工作階段,或要同時進行多個獨立對話,可以複製主要工作階段。

複製的對話會沿用工作階段參數,例如 temperaturetopK,以及任何工作階段互動記錄。舉例來說,如果您使用初始提示初始化主要工作階段,這項功能就很有用。這樣一來,應用程式只需要執行一次這項工作,所有複製的對話都會沿用主要對話的初始提示。

const languageModel = await LanguageModel.create({   initialPrompts: [{     role: 'system',     content: 'You are a helpful assistant and you speak like a pirate.'   }] });  // The original session `languageModel` remains unchanged, and // the two clones can be interacted with independently from each other. const firstClonedLanguageModel = await languageModel.clone(); const secondClonedLanguageModel = await languageModel.clone(); // Interact with the sessions independently. await firstClonedLanguageModel.prompt('Tell me a joke about parrots.'); await secondClonedLanguageModel.prompt('Tell me a joke about treasure troves.'); // Each session keeps its own context. // The first session's context is jokes about parrots. await firstClonedLanguageModel.prompt('Tell me another.'); // The second session's context is jokes about treasure troves. await secondClonedLanguageModel.prompt('Tell me another.'); 

還原先前的工作階段

使用初始提示,您可以提供一組提示和回覆範例,讓模型生成更優質的結果。這項功能通常用於單次提示,可生成符合預期的回覆。

如果您會追蹤與模型進行中的對話,可以運用這項做法還原工作階段。舉例來說,瀏覽器重新啟動後,您可以協助使用者從上次中斷的地方繼續與模型互動。其中一種做法是在本機儲存空間中追蹤工作階段記錄。

// Restore the session from localStorage, or initialize a new session. // The UUID is hardcoded here, but would come from a // session picker in your user interface. const uuid = '7e62c0e0-6518-4658-bc38-e7a43217df87';  function getSessionData(uuid) {   try {     const storedSession = localStorage.getItem(uuid);     return storedSession ? JSON.parse(storedSession) : false;   } catch {     return false;   } }  let sessionData = getSessionData(uuid);  // Initialize a new session. if (!sessionData) {   // Get the current default parameters so they can be restored as they were,   // even if the default values change in the future.   const { defaultTopK, defaultTemperature } =     await LanguageModel.params();   sessionData = {     initialPrompts: [],     topK: defaultTopK,     temperature: defaultTemperature,   }; }  // Initialize the session with the (previously stored or new) session data. const languageModel = await LanguageModel.create(sessionData);  // Keep track of the ongoing conversion and store it in localStorage. const prompt = 'Tell me a joke'; try {   const stream = languageModel.promptStreaming(prompt);   let result = '';   // You can already work with each `chunk`, but then store   // the final `result` in history.   for await (const chunk of stream) {     // In practice, you'd render the chunk.     console.log(chunk);     result = chunk;   }    sessionData.initialPrompts.push(     { role: 'user', content: prompt },     { role: 'assistant', content: result },   );    // To avoid growing localStorage infinitely, make sure to delete   // no longer used sessions from time to time.   localStorage.setItem(uuid, JSON.stringify(sessionData)); } catch (err) {   console.error(err.name, err.message); } 

讓使用者停止模型,保留工作階段配額

每個工作階段都有一個內容視窗,您可以存取工作階段的相關欄位 inputQuotainputUsage,查看該視窗。

const { inputQuota, inputUsage } = languageModel; const inputQuotaLeft = inputQuota - inputUsage; 

如果超過這個內容視窗,工作階段就會無法追蹤最舊的訊息。如果背景資訊很重要,這可能會導致結果不佳。 為保留配額,如果使用者認為模型回覆沒有幫助,請允許他們使用 AbortController 停止工作階段。

prompt()promptStreaming() 方法都會接受含有 signal 欄位的選用第二個參數,讓使用者停止工作階段。

const controller = new AbortController(); stopButton.onclick = () => controller.abort();  try {   const stream = languageModel.promptStreaming('Write me a poem!', {     signal: controller.signal,   });   for await (const chunk of stream) {     console.log(chunk);   } } catch (err) {   // Ignore `AbortError` errors.   if (err.name !== 'AbortError') {     console.error(err.name, err.message);   } } 

移除未使用的工作階段

每個工作階段都會消耗記憶體。如果啟動多個大型工作階段,可能會造成問題。終止未使用的工作階段,提高資源可用性。

示範

如要瞭解 AI 工作階段管理功能的實際運作方式,請觀看這部示範影片。使用 Prompt API 建立多個並行對話、重新載入分頁,甚至是重新啟動瀏覽器,然後從上次中斷的地方繼續。請參閱 GitHub 上的原始碼

充分發揮提示 API 的潛力

只要善用這些技巧和最佳做法管理 AI 工作階段,就能充分發揮 Prompt API 的潛力,打造更有效率、反應迅速且以使用者為中心的應用程式。您也可以結合這些方法,例如讓使用者複製還原的過去工作階段,以便執行假設情境。

特別銘謝

本指南由 Sebastian BenzAndre BandarraFrançois BeaufortAlexandra Klepper 審查。