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

發布日期:2025 年 1 月 27 日

說明 網頁 額外資訊 Chrome 狀態 Intent
GitHub 實驗功能EPP 標記後面 Origin 試用 不適用 不適用

Prompt API 的一項重要功能是工作階段。這類對話可讓您與 AI 模型進行一或多個持續對話,而模型不會遺失所說內容的背景。本指南將介紹使用語言模型管理工作階段的最佳做法。

如果您正在建構傳統聊天機器人,也就是使用者與 AI 互動的應用程式,建議您為一或多個並行工作階段進行工作階段管理。或者,如果您有客戶關係管理系統,其中一個支援專員可以同時處理多位客戶,並利用 AI 技術協助支援專員追蹤各種對話。

使用系統提示初始化工作階段

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

// Make this work in web apps and in extensions.
const aiNamespace = self.ai || chrome.aiOriginTrial || chrome.ai;
const languageModel = await aiNamespace.languageModel.create({
  systemPrompt: '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) 和任何工作階段互動記錄。舉例來說,如果您使用系統提示來初始化主工作階段,這項功能就很實用。這樣一來,應用程式只需執行這項工作一次,所有副本都會繼承主要工作階段的系統提示。

// Make this work in web apps and in extensions.
const aiNamespace = self.ai || chrome.aiOriginTrial || chrome.ai;
const languageModel = await aiNamespace.languageModel.create({
  systemPrompt: '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.');

還原過去的工作階段

透過初始提示,您可以使用一組提示和回覆範例來預先設定模型,以便產生更理想的結果。這項功能通常用於多鏡頭提示,以便產生符合預期的回覆。

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

// Make this work in web apps and in extensions.
const aiNamespace = self.ai || chrome.aiOriginTrial || chrome.ai;

// 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 aiNamespace.languageModel.capabilities();
  sessionData = {
    systemPrompt: '',
    initialPrompts: [],
    topK: defaultTopK,
    temperature: defaultTemperature,
  };
}

// Initialize the session with the (previously stored or new) session data.
const languageModel = await aiNamespace.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);
}

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

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

const { maxTokens, tokensLeft, tokensSoFar } = languageModel;

超過這個脈絡視窗後,工作階段就會遺失最舊訊息的追蹤記錄,這可能會造成不必要的情況,因為這個脈絡可能很重要。為保留配額,如果使用者在提交提示訊息後發現答案不實用,可以使用 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 工作階段管理示範,瞭解 AI 工作階段管理的實際應用。使用 Prompt API 建立多個並行對話,重新載入分頁或甚至重新啟動瀏覽器,並繼續上次中斷的地方。請參閱 GitHub 上的原始碼

結論

透過這些技巧和最佳做法,您可以妥善管理 AI 工作階段,充分發揮 Prompt API 的潛力,提供更有效率、更即時且以使用者為中心的應用程式。您也可以結合這些方法,例如讓使用者複製已還原的過去工作階段,以便執行「假設」情境。

特別銘謝

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