절대 반복하지 마세요: LLM 앱에 지속 메모리를 제공하는 ContextMD
Source: Dev.to
TL;DR: ContextMD는 OpenAI, Anthropic 및 LiteLLM API 호출에 영구 메모리를 추가하는 파이썬 미들웨어입니다. 대화를 사람이 읽을 수 있는 Markdown 파일에 저장하고, 사실을 자동으로 추출하여 향후 요청에 다시 적용합니다.
Source: …
문제: LLM은 기억이 없습니다
LLM API로 무언가를 구축해 본 적이 있다면, 다음과 같은 벽에 부딪혔을 것입니다:
# Conversation 1
response = openai.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": "I prefer TypeScript over JavaScript"}]
)
# Conversation 2 (hours later)
response = openai.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": "Help me build a React component"}]
)
# Assistant suggests JavaScript... again! 😤
LLM은 상태가 없습니다. 각 요청은 새롭게 시작됩니다. 대화 기록을 수동으로 전달해야 하며, 그마저도 일시적일 뿐입니다. 만약 AI가 다음을 기억하도록 하고 싶다면 어떨까요?
- 세션 간 사용자 선호도?
- 몇 주 전의 결정?
- 몇 달 전 설정한 프로젝트 컨텍스트?
ContextMD 소개: LLM을 위한 지속 메모리
ContextMD는 여러분의 코드와 LLM 제공자 사이에 위치하는 가벼운 Python 미들웨어입니다. 다음과 같은 기능을 제공합니다:
- 저장된 메모리를 자동으로 삽입하여 모든 API 요청에 적용
- 응답에서 기억에 남는 사실을 추출하고 저장
- 인간이 읽을 수 있는 Markdown 파일에 모두 저장 (데이터베이스가 필요 없음!)
빠른 시작: 메모리를 추가하는 3줄
from openai import OpenAI
from contextmd import ContextMD
# Wrap your existing client
client = ContextMD(OpenAI(), memory_dir=".contextmd/")
# Use exactly like normal – memory is automatic!
response = client.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": "I prefer TypeScript over JavaScript"}]
)
# The fact is now saved and will be injected into future requests
이게 전부입니다! 이제 OpenAI 클라이언트에 지속적인 메모리가 있습니다. 데이터베이스 설정도, 추가 API 키도 필요 없습니다—그냥 로컬 Markdown 파일만 사용합니다.
내부 작동 방식
ContextMD는 프로젝트에 .contextmd/ 디렉터리를 생성합니다:
.contextmd/
├── MEMORY.md # Semantic facts (200‑line cap)
├── config.md # Configuration
├── memory/
│ ├── 2024-03-01.md # Daily episodic logs
│ └── 2024-03-02.md
└── sessions/
└── 2024-03-01-auth.md # Session snapshots
세 가지 기억 유형
의미 기억 – 사용자/프로젝트에 대한 영구적인 사실
사용자 선호도
- JavaScript보다 TypeScript를 선호
- 다크 모드 테마 사용
- 원자적 git 커밋을 따름
연속 메모 – 타임스탬프가 있는 이벤트
2024-03-01 14:30
- 프런트엔드에 Next.js 사용을 결정함
- 인증 기능 완료
### 절차적 기억 – 학습된 워크플로
```markdown
워크플로우
- 커밋하기 전에 항상 테스트를 실행하세요
- 패키지 관리를 위해 pnpm을 사용하세요
실제 예시: AI 코딩 어시스턴트
from openai import OpenAI
from contextmd import ContextMD
client = ContextMD(OpenAI())
# First conversation – establish context
response = client.chat.completions.create(
model="gpt-4.1",
messages=[{
"role": "user",
"content": "I'm building a React app with TypeScript, Tailwind CSS, and Next.js. I prefer functional components with hooks."
}]
)
# ContextMD automatically saves these facts
# Week later – new conversation
response = client.chat.completions.create(
model="gpt-4.1",
messages=[{
"role": "user",
"content": "Help me create a user profile component"
}]
)
# Response automatically uses TypeScript, Tailwind, functional components!
기술 스택을 다시 언급할 필요가 없습니다. 선호도를 지정할 필요도 없습니다. ContextMD가 모든 것을 기억합니다.
Manual Memory Control
Sometimes you want to explicitly remember something:
# Remember a decision
client.remember(
"Chose PostgreSQL over MongoDB for better ACID compliance",
memory_type="semantic"
)
# Remember a completed task
client.remember(
"Implemented OAuth2 authentication with refresh tokens",
memory_type="episodic"
)
# Remember a workflow rule
client.remember(
"Always write tests before refactoring",
memory_type="procedural"
)
메모리 관리용 CLI 도구
# Initialize in your project
contextmd init
# View what the AI remembers about you
contextmd show
# See recent activity
contextmd history --hours 24
# List all sessions
contextmd sessions
# Manually add a fact
contextmd add "User loves Vim keybindings" --memory_type semantic
# Get statistics
contextmd stats
모든 주요 제공업체와 호환
ContextMD는 제공업체에 구애받지 않습니다:
# OpenAI
client = ContextMD(OpenAI())
# Anthropic
client = ContextMD(Anthropic())
# LiteLLM (100+ providers)
import litellm
client = ContextMD(litellm)
고급 기능
세션 관리
관련 대화를 그룹화:
with client.session("project‑setup"):
response = client.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": "Set up the initial repo structure"}]
)
(추가 세션 관련 API는 공식 README에 문서화되어 있습니다.)
t.new_session("feature-auth") as session:
# All conversations here are grouped
response = client.chat.completions.create(...)
# Session snapshot saved automatically
사용자 정의 구성
ContextMD 작동 방식을 미세 조정:
from contextmd import ContextMD, ContextMDConfig
config = ContextMDConfig(
memory_line_cap=200, # Max lines in MEMORY.md
bootstrap_window_hours=48, # Hours of episodic memory to load
compaction_threshold=0.8, # Token threshold for extraction
extraction_frequency="session_end", # When to extract facts
)
client = ContextMD(openai_client, config=config)
마크다운 파일을 사용하는 이유
- 인간 친화적 – 실제로 메모리를 읽고 편집할 수 있습니다.
- Git 친화적 – AI 메모리를 버전 관리합니다.
- 벤더 종속 없음 – 데이터가 로컬에 유지됩니다.
- 디버깅 가능 – AI가 정확히 무엇을 기억하는지 확인할 수 있습니다.
다음은?
ContextMD는 활발히 개발 중이며, 흥미로운 기능들이 곧 추가됩니다:
- 메모리 검색 및 RAG
- 다중 사용자/프로젝트 네임스페이스
- 메모리 감소 및 중요도 점수화
- Git 통합 및 동기화
- 메모리 시각화를 위한 웹 UI
- 그리고 더 많은 기능!
시작하기
pip install contextmd
전체 문서와 예제를 보려면 GitHub 저장소를 확인하세요.
놀라운 것을 만들어 보세요
ContextMD와 함께 다음을 만들 수 있습니다:
- 사용자 선호도를 기억하는 AI 어시스턴트
- 프로젝트 패턴을 아는 코드 생성기
- 며칠 동안 컨텍스트를 유지하는 챗봇
- 시간에 따라 진행 상황을 추적하는 학습 도구
LLM에 기억력이 생기면 가능성은 무한합니다.
지속적인 메모리로 무엇을 만들고 싶나요? 아래 댓글에 공유해 주세요!
P.S. GitHub에서 저장소에 별표를 달아 주세요 – 더 많은 사람들이 ContextMD를 발견하는 데 도움이 됩니다!
