상태 저장 다중 턴 Gemini 대화 (@google/genai)
이 스킬이 해결하는 핵심 문제
많은 AI 어시스턴트는 모든 프롬프트를 상태 비저장 단일 턴 요청으로 처리하여, 후속 질문이나 순차적 편집 시마다 전체 문서, 코드베이스 또는 워크스페이스 상태를 다시 업로드하거나 이전 턴을 단일 텍스트 블록으로 평탄화합니다. 이는 토큰을 낭비하고, 지연 시간을 증가시키며, 추론 품질을 저하시킵니다.
대신 상태 저장 다중 턴 대화를 유지하세요:
- 초기 컨텍스트(코드, 문서 또는 프로젝트 상태)는 1턴에 설정됩니다.
- 후속 턴은 변경되지 않은 상태를 다시 보내지 않고 동일한 대화를 계속합니다(
previous_interaction_id또는contents의 구조화된user/model턴 사용). - 전체 코드나 문서 상태는 사용자가 AI 흐름 외부에서 워크스페이스를 수동으로 편집한 경우에만 다시 전송됩니다(SHA-256 해시 비교를 통해 감지).
패턴 1: 서버 관리형 다중 턴 상태 (Interactions API)
Google의 Interactions API(@google/genai >= 2.3.0)를 사용할 때, Gemini는 Google 서버에서 대화 컨텍스트를 유지합니다(기본값 store: true). previous_interaction_id: interaction.id를 전달하여 턴을 연결하세요:
TypeScript (@google/genai)
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
// Turn 1: 대화 및 초기 워크스페이스/문서 상태 설정
const turn1 = await client.interactions.create({
model: "gemini-3.7-flash",
system_instruction: "You are an expert coding assistant. Remember the active code across turns.",
input: `Here is my current file:\n\`\`\`ts\n${initialCode}\n\`\`\`\nAdd input validation.`,
});
console.log(turn1.output_text);
// Turn 2: 후속 질문 또는 순차적 편집 — 파일이 변경되지 않았다면 다시 보내지 마세요!
// Google 서버는 previous_interaction_id를 통해 1턴의 입력과 모델 출력을 이미 유지하고 있습니다.
const turn2 = await client.interactions.create({
model: "gemini-3.7-flash",
system_instruction: "You are an expert coding assistant. Remember the active code across turns.",
previous_interaction_id: turn1.id,
input: "Why did you choose that validation pattern, and can we also log rejected inputs?",
});
console.log(turn2.output_text);
Python (google-genai)
from google import genai
client = genai.Client()
# Turn 1: 초기 컨텍스트 설정
turn1 = client.interactions.create(
model="gemini-3.7-flash",
system_instruction="You are an expert coding assistant. Remember the active code across turns.",
input=f"Here is my current file:\n```py\n{initial_code}\n```\nRefactor this into a class.",
)
# Turn 2: 파일을 다시 업로드하지 않고 previous_interaction_id로 연결
turn2 = client.interactions.create(
model="gemini-3.7-flash",
system_instruction="You are an expert coding assistant. Remember the active code across turns.",
previous_interaction_id=turn1.id,
input="Now add a unit test method for edge cases.",
)
interactions.create의 중요 규칙:
system_instruction,tools,generation_config는 상호작용 범위로 지정되며, 각 턴마다 다시 지정해야 합니다.store: true를 유지하세요(기본값).store: false로 설정하면previous_interaction_id가 비활성화됩니다.
패턴 2: 애플리케이션 관리형 다중 턴 contents와 해시 동기화 워크스페이스 상태
백엔드가 자체 데이터베이스에 대화 턴을 저장하거나(ai.models.generateContent / ai.chats.create와 구조화된 JSON 스키마 및 diff/apply 워크플로우 사용) 다음 다섯 가지 규칙을 따르면 변경되지 않은 파일이나 워크스페이스 섹션을 중복해서 다시 보내지 않습니다:
1. 네이티브 role: 'user' | 'model' 턴 배열 사용
이전 턴을 단일 사용자 메시지 내의 단일 문자열로 평탄화하지 마세요. 항상 적절한 다중 턴 contents 배열을 구성하세요:
type ContentTurn = {
role: "user" | "model";
parts: Array<{ text: string }>;
};
2. SHA-256 해시로 워크스페이스 동기화 추적
클라이언트에서 대화별 동기화 레코드를 유지하세요:
interface SyncedConversationState {
activeDocumentSha256: string | null;
secondaryContextHash: string | null; // 예: 다른 열린 탭, 장면 또는 프로젝트 트리 요약
}
ask(Q&A) 턴이 완료될 때:activeDocumentSha256은 전송된 문서의 SHA-256으로 유지됩니다.edit턴이 제안과 함께 완료될 때:activeDocumentSha256은proposal.sha256으로 업데이트됩니다(대화 기록의model턴에 제안된 코드가 포함되므로).- 사용자가 적용(Apply)을 클릭할 때:
activeDocumentSha256이 적용된proposal.sha256과 일치합니다. - 사용자가 폐기(Discard) 또는 실행 취소(Undo)를 클릭할 때:
activeDocumentSha256이 제안 전base.sha256으로 되돌아갑니다.
3. 후속 턴에서 변경되지 않은 워크스페이스 코드 생략 (sourceSynchronized: true)
새로운 턴을 보내기 전에 sha256(currentEditorCode)를 syncedState.activeDocumentSha256과 비교하세요:
sha256(currentEditorCode) === syncedState.activeDocumentSha256인 경우 (sourceSynchronized: true):Ask(Q&A) 모드에서: 파일을 전혀 업로드하지 마세요(source: null). 모델은 이미 대화 기록에 정확한 활성 코드를 가지고 있습니다.Edit모드에서: Gemini로 보내는 새로운user턴 내에currentSource를 중복하지 마세요({ mode: "edit", prompt, sourceSynchronized: true }). 로컬 기본 스냅샷은 클라이언트 측 diff/Undo 및 백엔드 검증용으로만 유지하세요.
sha256(currentEditorCode) !== syncedState.activeDocumentSha256인 경우 (sourceSynchronized: false):- 사용자가 파일을 수동으로 편집했거나 파일을 전환했습니다. 대화를 재동기화하기 위해 이 턴에 업데이트된
currentSource를 첨부하고activeDocumentSha256을 업데이트하세요.
- 사용자가 파일을 수동으로 편집했거나 파일을 전환했습니다. 대화를 재동기화하기 위해 이 턴에 업데이트된
4. 기록에 전체 소스를 한 번만 유지 (압축된 대체 턴)
10턴 편집 세션에서 모든 10개 역사적 턴에 파일의 전체 복사본 10개를 유지하지 마십시오.
- 활성 코드를 도입하거나 수정한 가장 최근 턴(최신 활성 편집을 제안한
model턴 또는 수동으로 편집된 코드를 마지막으로 첨부한user턴)에만 전체 코드를 유지하세요. - 코드가 대체된 모든 이전 턴의 경우, 인라인 코드 문자열을 압축 메타데이터(
{ supersededSourceSha256: "..." })로 바꾸세요. 이렇게 하면 전체 대화 추론 스레드를 보존하면서 장기 세션에서 토큰 사용량을 일정하게 유지할 수 있습니다.
5. 읽기 전용 보조 컨텍스트 중복 제거 (다른 파일 / 탭 / 섹션)
앱이 비활성 파일이나 섹션의 읽기 전용 요약을 포함하는 경우:
- 해당 요약을 대화의 1턴에 보내세요.
- 턴 2 이상에서는 해시가 변경된 경우에만 요약을 다시 보내세요(
secondaryContextHash !== currentSecondaryContextHash).
참조 구현: 다중 턴 요청 빌더 (TypeScript)
interface HistoryTurn {
prompt: string;
response: string;
mode: "ask" | "edit";
baseSource?: string | null;
baseSha256?: string | null;
proposalSource?: string | null;
proposalSha256?: string | null;
outcomeStatus?: "none" | "proposed" | "applied" | "discarded" | "undone";
}
export function buildMultiTurnContents(params: {
history: HistoryTurn[];
mode: "ask" | "edit";
prompt: string;
currentSource: string | null;
sourceSynchronized: boolean;
}) {
const { history, mode, prompt, currentSource, sourceSynchronized } = params;
// 현재 활성 소스를 보유한 역사적 턴 식별
let latestActiveSourceIndex = -1;
if (sourceSynchronized || currentSource === null) {
for (let i = history.length - 1; i >= 0; i--) {
const item = history[i];
const hasValidProposal =
item.mode === "edit" &&
item.proposalSource &&
item.outcomeStatus !== "discarded" &&
item.outcomeStatus !== "undone";
if (hasValidProposal || item.baseSource) {
latestActiveSourceIndex = i;
break;
}
}
}
const contents: Array<{ role: "user" | "model"; parts: Array<{ text: string }> }> = [];
for (let i = 0; i < history.length; i++) {
const item = history[i];
const isLatestSourceTurn = i === latestActiveSourceIndex;
const hasActiveProposal =
item.mode === "edit" &&
Boolean(item.proposalSource) &&
item.outcomeStatus !== "discarded" &&
item.outcomeStatus !== "undone";
// 기록의 사용자 턴
const userPayload: Record<string, unknown> = {
mode: item.mode ?? "ask",
prompt: item.prompt,
};
if (isLatestSourceTurn && !hasActiveProposal && item.baseSource) {
userPayload.currentSource = item.baseSource;
} else if (item.baseSha256) {
userPayload.supersededSourceSha256 = item.baseSha256;
}
contents.push({ role: "user", parts: [{ text: JSON.stringify(userPayload) }] });
// 기록의 모델 턴
const modelPayload: Record<string, unknown> = {
kind: item.mode === "edit" ? "code_proposal" : "answer",
explanation: item.response,
};
if (isLatestSourceTurn && hasActiveProposal && item.proposalSource) {
modelPayload.proposedSource = item.proposalSource;
} else if (item.proposalSha256) {
modelPayload.supersededProposalSha256 = item.proposalSha256;
}
contents.push({ role: "model", parts: [{ text: JSON.stringify(modelPayload) }] });
}
// 최종 (현재) 사용자 턴
const omitDuplicateSource = sourceSynchronized && latestActiveSourceIndex !== -1;
const currentTurnPayload: Record<string, unknown> = { mode, prompt };
if (omitDuplicateSource) {
currentTurnPayload.sourceSynchronized = true;
} else {
currentTurnPayload.currentSource = currentSource;
}
contents.push({ role: "user", parts: [{ text: JSON.stringify(currentTurnPayload) }] });
return contents;
}
다중 턴 AI를 검토하거나 구현할 때 확인 목록
-
@google/genai(GoogleGenAI)를 사용하고 있으며, 더 이상 사용되지 않는@google/generative-ai는 사용하지 않고 있습니까? - 2턴 이상에서 다중 턴
user/model역할(또는previous_interaction_id)을 유지하며, 히스토리를 단일 프롬프트 문자열로 평탄화하지 않습니까? - 편집기 코드가 변경되지 않은 후속 질문(
Ask모드)에서, 클라이언트에서 코드를 다시 업로드하지 않습니까? - 편집기 코드가 마지막 턴과 일치하는 순차적 AI 편집(
Edit모드)에서,contents의 새 사용자 프롬프트에 중복된currentSource를 생략합니까? - 대체된 이전 코드 버전이 히스토리에서 압축되어 활성 코드 버전만 전체로 전송됩니까?
- 사용자가 문서를 수동으로 편집하거나 변경을 실행 취소하는 경우, SHA-256 불일치가 다음 턴에서 자동으로 재동기화를 트리거합니까?