게시일: 2025년 1월 27일
설명 | 웹 | 확장 프로그램 | Chrome 상태 | 인텐트 |
---|---|---|---|---|
GitHub | View | 실험 의도 |
Prompt 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'
기본 세션 클론
세션이 종료된 후 새 세션을 시작하거나 여러 독립적인 대화를 동시에 진행하려면 기본 세션을 클론하면 됩니다.
클론은 temperature
또는 topK
과 같은 세션 매개변수와 세션 상호작용 기록을 상속합니다. 예를 들어 초기 프롬프트로 기본 세션을 초기화한 경우에 유용합니다. 이렇게 하면 앱에서 이 작업을 한 번만 수행하면 됩니다. 모든 클론이 기본 세션의 초기 프롬프트를 상속받기 때문입니다.
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.');
이전 세션 복원
초기 프롬프트를 사용하면 더 나은 결과를 생성할 수 있도록 일련의 예시 프롬프트와 대답으로 모델을 준비할 수 있습니다. 이는 n샷 프롬프트에서 기대치를 반영하는 대답을 생성하는 데 자주 사용됩니다.
모델과의 진행 중인 대화를 추적하는 경우 이 방법을 사용하여 세션을 복원할 수 있습니다. 예를 들어 브라우저가 다시 시작된 후 사용자가 중단한 위치에서 모델과 계속 상호작용할 수 있도록 지원할 수 있습니다. 한 가지 방법은 로컬 저장소에 세션 기록을 추적하는 것입니다.
// 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);
}
사용자가 모델을 중지하도록 허용하여 세션 할당량 유지
각 세션에는 세션의 관련 필드 inputQuota
및 inputUsage
에 액세스하여 확인할 수 있는 컨텍스트 창이 있습니다.
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 세션 관리 데모에서 AI 세션 관리의 실제 작동 방식을 확인하세요. 프롬프트 API로 여러 개의 병렬 대화를 만들고, 탭을 새로고침하거나 브라우저를 다시 시작한 후 중단한 부분부터 계속할 수 있습니다. GitHub의 소스 코드를 참고하세요.
프롬프트 API의 잠재력 최대한 활용하기
이러한 기술과 권장사항을 사용하여 AI 세션을 신중하게 관리하면 프롬프트 API의 잠재력을 최대한 활용하여 더 효율적이고 반응성이 뛰어나며 사용자 중심적인 애플리케이션을 제공할 수 있습니다. 예를 들어 사용자가 복원된 이전 세션을 클론하여 '가상' 시나리오를 실행할 수 있도록 하는 등 이러한 접근 방식을 결합할 수도 있습니다.