Prompt API를 사용한 세션 관리 권장사항

게시일: 2025년 1월 27일

설명 동영상 확장 프로그램 Chrome 상태 인텐트
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'

기본 세션 클론

세션이 종료된 후 새 세션을 시작하거나 여러 개의 독립적인 대화를 동시에 진행하려면 기본 세션을 클론하면 됩니다.

클론은 temperature 또는 topK와 같은 세션 매개변수와 모든 세션 상호작용 기록을 상속합니다. 예를 들어 시스템 프롬프트로 기본 세션을 초기화한 경우에 유용합니다. 이렇게 하면 앱에서 이 작업을 한 번만 하면 됩니다. 모든 클론은 기본 세션에서 시스템 프롬프트를 상속합니다.

// 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.');

이전 세션 복원

초기 프롬프트를 사용하면 일련의 프롬프트 및 응답 예시로 모델을 준비하여 더 나은 결과를 얻을 수 있습니다. 이는 n샷 프롬프트에서 사용자의 기대에 부합하는 대답을 생성하는 데 자주 사용됩니다.

모델과의 대화가 진행되는 동안 계속 추적하면 이 방법을 사용하여 세션을 복원할 수 있습니다. 예를 들어 브라우저가 다시 시작된 후 사용자가 중단한 지점부터 모델과 계속 상호작용할 수 있도록 지원할 수 있습니다. 한 가지 방법은 로컬 저장소에서 세션 기록을 추적하는 것입니다.

// 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);
}

사용자가 모델을 중지하도록 허용하여 세션 할당량 유지

각 세션에는 세션의 관련 필드인 maxTokens, tokensLeft, tokensSoFar에 액세스하여 볼 수 있는 컨텍스트 창이 있습니다.

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의 잠재력을 최대한 활용하여 더 효율적이고 반응이 빠르며 사용자 중심의 애플리케이션을 제공할 수 있습니다. 이러한 접근 방식을 결합할 수도 있습니다. 예를 들어 사용자가 복원된 이전 세션을 클론하여 '가정' 시나리오를 실행할 수 있도록 허용할 수 있습니다.

감사의 말씀

이 가이드는 세바스티안 벤츠, 안드레 반다라, 프랑소와 보포르, 알렉산드라 클레퍼가 검토했습니다.