Memory란 무엇인가
메모리
- 사람 : 이전 대화를 기억하면서 현재 대화를 진행
- 챗봇 : 이전 대화를 기억, 이전 질문 답변을 Memory에 저장하고 이를 Prompt에 포함
- 메모리를 사용하기 위해서는 Chain으로 엮어야 함
- LLM과 메모리 엮기
Memory 종류
메모리 특징 언제 적합한가
| ConversationBufferMemory | 모든 대화를 순차적으로 저장 | 대화 길이가 짧고, 단순한 맥락 유지에 적합 |
| ConversationSummarytMemory | 대화를 요약해서 저장 | 긴 대화, 리소스 절약 필요할 때 |
| ConversationBufferWindowMemory | 최근 N턴만 기억 | 최신 문맥만 중요할 때(예 : 챗봇) |
ConversationBufferMemory
- 모든 대화 내용을 그대로 저장
- 텍스트 누적 방식으로 LLM에 절달됨
- 가장 기본적인 메모리로 대화 맥락이 적은 상황에 적합
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
# 메모리 포함 체인 생성
memory = ConversationBufferMemory()
llm = ChatOpenAI(model_name = 'gpt-4.1-mini',temperature = 0.5)
chain = ConversationChain(llm=llm, memory=memory)
# 대화 시작
print(chain.run("안녕? 나는 기영이야."))
print(chain.run("내 이름이 뭐라고?"))
ConversationSummaryMemory
- 대화 내용을 요약해 저장
- 긴 대화를 다룰 때 적합(프롬프트에 전체 내용을 붙이지 않아 토큰 절약 가능)
- 내부적으로 요약용 LLM이 호출됨
- 요약은 두 번째 대화부터 진행
- 요약 범위 : 이전 요약 + 새 메시지들만 요약해서 업데이트
from langchain.memory import ConversationSummaryMemory
# 요약 메모리 생성 (요약용 LLM 필요)
memory = ConversationSummaryMemory(llm = llm)
# 체인 구성
chain = ConversationChain(llm = llm, memory = memory)
# 대화
print(chain.run("오늘은 운동하고, 친구랑 밥도 먹고, 강의도 들었어."))
메모리 확인하기
- memory.chat_memory.messages : 지금까지 주고 받은 모든 메시지 확인
# 담긴 메모리 확인하기
memory.chat_memory.messages
- memory.buffer : 요약된 내용
# 내용 요약
memory.buffer
# 프롬프트에 포함되는 내용
memory.load_memory_variables({})
ConversationBufferWindowMemory
- 최근 N턴의 대화만 기억
- 메모리 용량 조절 가능(k=숫자)
- 과거 내용은 자동 삭제됨(메모리에는 k턴의 대화 내용만 저장됨)
- 챗봇처럼 최신 대화만 중요한 경우 적합
from langchain.memory import ConversationBufferWindowMemory
# 최근 2턴만 기억하는 메모리(테스트 해보면 실제로는 k+1턴까지 기억)
memory = ConversationBufferWindowMemory(k=2)
chain = ConversationChain(llm=llm, memory=memory)
# 대화
print(chain.run("나는 기영이야."))
memory.load_memory_variables({})
print(chain.run("나는 영화보는 것을 좋아해"))
memory.load_memory_variables({})
print(chain.run("지금 배고픈데 뭘 먹을까?"))
memory.load_memory_variables({})
AI_Agent/AI_Agent_Basic/05.LangChain기초4 - Memory.ipynb at main · 427paul/AI_Agent
Contribute to 427paul/AI_Agent development by creating an account on GitHub.
github.com
'AI Agent > AI Agent의 이해' 카테고리의 다른 글
| 6. LangGraph 기초1 기본 그래프2 (0) | 2026.05.30 |
|---|---|
| 5. LangGraph 기초1 기본 그래프 (0) | 2026.05.29 |
| 3. RAG 개념 이해 (0) | 2026.05.27 |
| 2. 메모리, RAG 개념 이해 (0) | 2026.05.26 |
| 1. LangChain 기초 (0) | 2026.05.24 |