C.W.K.
Stream
Lesson 03 of 06 · published

멀티턴 대화와 메모리

~14 min · multi-turn, memory, history

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

API는 메모리 없어; 너가 가져

messages.create() 호출은 stateless. 대화 이어가려면 매 요청에 전체 히스토리(이전 user/assistant 턴 전부)를 다시 보내. 모델은 호출 사이 기억 없어 — 너의 애플리케이션이 메모리 레이어야.

커지는 히스토리 관리 세 가지

짧은 채팅이면 verbatim 다 보내. 중간이면 옛 턴을 응축된 assistant note로 요약하고 최근 턴은 verbatim 유지. 오래 도는 에이전트면 턴을 외부 저장(DB, JSONL)에 두고 매 호출에 관련 슬라이스 재구성. cwkPippa는 옵션 셋 — 모든 턴이 conversation_id로 키된 JSONL에 살고, Agent SDK가 일관성 위한 만큼만 내부적으로 replay.

Append-only가 친구

대화 히스토리를 append-only로 다뤄. 모델 응답 'fix'한다고 과거 턴을 편집하면 Claude 헷갈림(append된 텍스트가 이미 말했다고 가정한 것과 모순). 턴을 다시 하고 싶으면 새 브랜치 시작, in-place로 rewrite 안 해.

원칙: 애플리케이션이 메모리 소유. 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

두 모드를 지원하는 chat helper 구현해 — 'verbatim'(full history 재전송), 'summarized'(옛 턴이 한 요약으로 접힘). 20턴 대화를 둘 다 통과시키고 사용된 총 입력 토큰 비교.
Hint
Token counting endpoint 써서 테스트 동안 completion 비용 안 내고 비교해.

Progress

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

댓글 0

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

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