본문 바로가기
C.W.K.
Stream
Lesson 03 of 06 · published

멀티턴의 기억은 API가 아니라 애플리케이션이 맡아

~14 min · multi-turn, memory, history

Level 0Observer
0 XP0/64 lessons0/13 achievements
0/150 XP to next level150 XP to go0% complete

호출 하나가 끝나면 모델의 기억도 끝나

messages.create()는 상태를 보관하지 않아. 대화를 이어 가려면 이전 userassistant 턴을 다음 요청에 다시 보내야 해. 모델이 저절로 앞 대화를 기억한다고 가정하는 순간, 누락과 재현 불가능성이 시작돼.

이력이 커질수록 보관과 전송을 나눠

짧은 대화는 원문을 모두 보내도 돼. 중간 길이에서는 오래된 턴을 요약하고 최근 턴은 원문으로 남겨. 오래 도는 에이전트는 전체 턴을 DB나 JSONL에 보관한 뒤, 매 호출에 필요한 구간만 재구성해. cwkPippa는 대화별 JSONL을 전체 기록으로 두고 Agent SDK가 일관성에 필요한 부분을 다시 불러와.

과거를 고치지 말고 새 갈래를 만들어

대화 이력은 덧붙이기 전용으로 다루는 편이 안전해. 이미 모델이 읽은 과거 응답을 제자리에서 고치면 뒤의 턴이 전제한 사실과 충돌하지. 다시 시도하려면 원본을 보존한 채 새 분기를 시작해.

원칙: 기억은 애플리케이션의 자산이야. API에는 그 순간 추론에 필요한 구간을 골라 보내.

Code

Stateless 멀티턴 루프·python
history = []  # list of {role, content}

def chat(user_text: str) -> str:
    history.append({"role": "user", "content": user_text})
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        system="You are a helpful assistant.",
        messages=history,  # 매 호출마다 full history
    )
    text = response.content[0].text
    history.append({"role": "assistant", "content": text})
    return text

chat("My favorite color is forest green.")
chat("What was my favorite color?")  # history 재전송으로 동작
옛 턴 요약 패턴·python
MAX_VERBATIM = 10

def trimmed_history(full_history: list[dict]) -> list[dict]:
    if len(full_history) <= MAX_VERBATIM:
        return full_history
    old, recent = full_history[:-MAX_VERBATIM], full_history[-MAX_VERBATIM:]
    summary = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=512,
        system="Summarize the following conversation in one paragraph, preserving facts the assistant might need.",
        messages=[{"role": "user", "content": str(old)}],
    ).content[0].text
    return [{"role": "user", "content": f"<earlier_summary>{summary}</earlier_summary>"}] + recent

External links

Exercise

원문 이력을 모두 보내는 모드와 오래된 턴을 요약하는 모드를 가진 채팅 도우미를 만들어. 20턴 대화를 각각 통과시켜 총 입력 토큰을 비교해.
Hint
완성 호출 대신 토큰 계수 엔드포인트를 쓰면 생성 비용 없이 비교할 수 있어.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.