Communitygithub.com

SamuelChien/mega-skills-collection

메모리는 지능형 에이전트의 핵심입니다. 이것이 없으면 모든 상호작용은 매번 처음부터 시작됩니다. 이 스킬은 단기(컨텍스트 윈도우), 장기(벡터 스토어) 에이전트 메모리와 이를 구성하는 인지 아키텍처를 다룹니다.

mega-skills-collection란 무엇인가요?

이 스킬은 AI 에이전트의 메모리 시스템에 대한 포괄적인 가이드입니다. CoALA(인지 아키텍처 및 학습 아키텍처) 프레임워크를 기반으로 의미 기억(사실), 일화 기억(경험), 절차 기억(방법)의 세 가지 메모리 유형을 설명하며, 단순한 저장이 아닌 효과적인 검색의 중요성을 강조합니다. LangMem, MemGPT/Letta, Mem0과 같은 주요 메모리 프레임워크와 Pinecone, Qdrant, Weaviate, ChromaDB, pgvector를 포함한 벡터 스토어를 지원하며, 사용 사례에 따른 선택 기준을 제공합니다. 또한 청킹 전략(고정 크기, 의미론적, 구조 인식, 컨텍스트 기반, 코드별), 백그라운드 메모리 형성(비동기 처리), 메모리 감쇠(시간 기반, 사용량 기반, 중요도 기반)와 같은 고급 패턴을 다룹니다. 이 스킬의 목표는 개발자가 지능적이고 컨텍스트를 인식하는 에이전트를 구축할 수 있도록 실용적인 코드 예제, 의사 결정 매트릭스, 모범 사례를 제공하는 것입니다.

지원 대상✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/SamuelChien/mega-skills-collection/tree/HEAD/agent-memory-systems

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

에이전트 메모리 시스템

메모리는 지능형 에이전트의 핵심입니다. 이것이 없으면 모든 상호작용은 매번 처음부터 시작됩니다. 이 스킬은 단기(컨텍스트 윈도우), 장기(벡터 스토어) 에이전트 메모리와 이를 구성하는 인지 아키텍처를 다룹니다.

핵심 통찰: 메모리는 단순한 저장이 아닌 검색입니다. 올바른 정보를 찾을 수 없다면 백만 개의 저장된 사실도 의미가 없습니다. 청킹, 임베딩, 검색 전략이 에이전트의 기억과 망각을 결정합니다.

이 분야는 일관되지 않은 용어로 인해 파편화되어 있습니다. 우리는 CoALA 인지 아키텍처 프레임워크를 사용합니다: 의미 기억(사실), 일화 기억(경험), 절차 기억(방법 지식).

원칙

  • 메모리 품질 = 저장량이 아닌 검색 품질
  • 저장이 아닌 검색을 위해 청킹하세요
  • 컨텍스트 격리는 메모리의 적입니다
  • 올바른 정보에 올바른 메모리 유형을 사용하세요
  • 오래된 기억은 삭제하세요 - 모든 것을 영원히 보관할 필요는 없습니다
  • 프로덕션 전에 검색 정확도를 테스트하세요
  • 실시간 처리보다 백그라운드 메모리 형성이 좋습니다

기능

  • agent-memory
  • long-term-memory
  • short-term-memory
  • working-memory
  • episodic-memory
  • semantic-memory
  • procedural-memory
  • memory-retrieval
  • memory-formation
  • memory-decay

범위

  • vector-database-operations → data-engineer
  • rag-pipeline-architecture → llm-architect
  • embedding-model-selection → ml-engineer
  • knowledge-graph-design → knowledge-engineer

도구

Memory_frameworks

  • LangMem (LangChain) - 사용 시기: 지속적 메모리가 필요한 LangGraph 에이전트 참고: 의미, 일화, 절차 메모리 유형
  • MemGPT / Letta - 사용 시기: 가상 컨텍스트 관리, OS 스타일 메모리 참고: 계층적 메모리 계층, 자동 페이징
  • Mem0 - 사용 시기: 개인화를 위한 사용자 메모리 계층 참고: 사용자 선호도 및 기록을 위해 설계됨

Vector_stores

  • Pinecone - 사용 시기: 관리형, 엔터프라이즈 규모(수십억 벡터) 참고: 최고의 쿼리 성능, 가장 높은 비용
  • Qdrant - 사용 시기: 복잡한 메타데이터 필터링, 오픈 소스 참고: Rust 기반, 뛰어난 필터링
  • Weaviate - 사용 시기: 하이브리드 검색, 지식 그래프 기능 참고: GraphQL 인터페이스, 관계에 적합
  • ChromaDB - 사용 시기: 프로토타이핑, 소형/중형 앱 참고: 개발자 친화적, 100K 벡터에서 ~20ms p50
  • pgvector - 사용 시기: 이미 PostgreSQL을 사용 중인 경우, 더 간단한 설정 참고: <100만 벡터에 적합, 친숙한 도구

Embedding_models

  • OpenAI text-embedding-3-large - 사용 시기: 최고 품질, 3072 차원 참고: $0.13/100만 토큰
  • OpenAI text-embedding-3-small - 사용 시기: 좋은 균형, 1536 차원 참고: $0.02/100만 토큰, 5배 저렴
  • nomic-embed-text-v1.5 - 사용 시기: 오픈 소스, 로컬 배포 참고: 768 차원, 좋은 품질
  • all-MiniLM-L6-v2 - 사용 시기: 경량, 빠른 로컬 임베딩 참고: 384 차원, 가장 낮은 지연 시간

패턴

메모리 유형 아키텍처

다양한 정보에 적합한 메모리 유형 선택

사용 시기: 에이전트 메모리 시스템 설계

메모리 유형 아키텍처 (CoALA 프레임워크):

""" 세 가지 메모리 유형은 각각 다른 목적을 가집니다:

  1. 의미 기억: 사실과 지식

    • 세상에 대해 아는 것
    • 사용자 선호도, 도메인 지식
    • 프로필(구조화됨) 또는 컬렉션(비구조화됨)에 저장
  2. 일화 기억: 경험과 이벤트

    • 발생한 일(타임스탬프가 있는 이벤트)
    • 과거 대화, 작업 결과
    • 경험을 통한 학습에 사용
  3. 절차 기억: 작업 수행 방법

    • 규칙, 스킬, 워크플로우
    • 종종 몇 가지 샷 예제로 구현
    • "전에 이 문제를 어떻게 해결했지?" """

LangMem 구현

""" from langmem import MemoryStore from langgraph.graph import StateGraph

메모리 저장소 초기화

memory = MemoryStore( connection_string=os.environ["POSTGRES_URL"] )

의미 기억: 사용자 프로필

await memory.semantic.upsert( namespace="user_profile", key=user_id, content={ "name": "Alice", "preferences": ["dark mode", "concise responses"], "expertise_level": "developer", } )

일화 기억: 과거 상호작용

await memory.episodic.add( namespace="conversations", content={ "timestamp": datetime.now(), "summary": "인증 문제 디버깅 도움", "outcome": "해결됨", "key_insights": ["토큰 만료가 근본 원인이었음"], }, metadata={"user_id": user_id, "topic": "debugging"} )

절차 기억: 학습된 패턴

await memory.procedural.add( namespace="skills", content={ "task_type": "debug_auth", "steps": ["토큰 만료 확인", "갱신 흐름 확인"], "example_interaction": few_shot_example, } ) """

런타임 메모리 검색

""" async def prepare_context(user_id, query): # 사용자 프로필 가져오기 (의미 기억) profile = await memory.semantic.get( namespace="user_profile", key=user_id )

# 관련 과거 경험 찾기 (일화 기억)
similar_experiences = await memory.episodic.search(
    namespace="conversations",
    query=query,
    filter={"user_id": user_id},
    limit=3
)

# 관련 스킬 찾기 (절차 기억)
relevant_skills = await memory.procedural.search(
    namespace="skills",
    query=query,
    limit=2
)

return {
    "profile": profile,
    "past_experiences": similar_experiences,
    "relevant_skills": relevant_skills,
}

"""

벡터 스토어 선택 패턴

사용 사례에 맞는 벡터 데이터베이스 선택

사용 시기: 지속적인 메모리 저장소 설정

벡터 스토어 선택:

""" 결정 매트릭스:

PineconeQdrantWeaviateChromaDBpgvector
규모수십억1억+1억+100만100만
관리형예둘 다둘 다자체자체
필터링기본최고좋음기본SQL
하이브리드아니오예최고아니오예
비용높음중간중간무료무료
지연 시간5ms7ms10ms20ms15ms
"""

Pinecone (엔터프라이즈 규모)

""" from pinecone import Pinecone

pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"]) index = pc.Index("agent-memory")

메타데이터와 함께 Upsert

index.upsert( vectors=[ { "id": f"memory-{uuid4()}", "values": embedding, "metadata": { "user_id": user_id, "timestamp": datetime.now().isoformat(), "type": "episodic", "content": memory_text, } } ], namespace=namespace )

필터로 쿼리

results = index.query( vector=query_embedding, filter={"user_id": user_id, "type": "episodic"}, top_k=5, include_metadata=True ) """

Qdrant (복잡한 필터링)

""" from qdrant_client import QdrantClient from qdrant_client.models import PointStruct, Filter, FieldCondition

client = QdrantClient(url="http://localhost:6333")

Qdrant로 복잡한 필터링

results = client.search( collection_name="agent_memory", query_vector=query_embedding, query_filter=Filter( must=[ FieldCondition(key="user_id", match={"value": user_id}), FieldCondition(key="type", match={"value": "semantic"}), ], should=[ FieldCondition(key="topic", match={"any": ["auth", "security"]}), ] ), limit=5 ) """

ChromaDB (프로토타이핑)

""" import chromadb

client = chromadb.PersistentClient(path="./memory_db") collection = client.get_or_create_collection("agent_memory")

프로토타입에 간단하고 빠름

collection.add( ids=[str(uuid4())], embeddings=[embedding], documents=[memory_text], metadatas=[{"user_id": user_id, "type": "episodic"}] )

results = collection.query( query_embeddings=[query_embedding], n_results=5, where={"user_id": user_id} ) """

청킹 전략 패턴

문서를 검색 가능한 청크로 분할

사용 시기: 메모리 저장을 위한 문서 처리

청킹 전략:

""" 청킹 딜레마:

  • 너무 크면: 벡터가 특수성을 잃음
  • 너무 작으면: 컨텍스트를 잃음

최적 청크 크기는 다음에 따라 달라짐:

  • 문서 유형 (코드 vs 산문 vs 데이터)
  • 쿼리 패턴 (사실적 vs 탐색적)
  • 임베딩 모델 (각각 최적 지점이 있음)

일반 지침: 대부분의 사용 사례에 대해 256-512 토큰 """

고정 크기 청킹 (기준)

""" from langchain.text_splitter import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter( chunk_size=500, # 문자 chunk_overlap=50, # 중복은 문장 절단 방지 separators=["\n\n", "\n", ". ", " ", ""] # 우선 순위 )

chunks = splitter.split_text(document) """

의미론적 청킹 (더 나은 품질)

""" from langchain_experimental.text_splitter import SemanticChunker from langchain_openai import OpenAIEmbeddings

의미론적 유사성에 따라 분할

splitter = SemanticChunker( embeddings=OpenAIEmbeddings(), breakpoint_threshold_type="percentile", breakpoint_threshold_amount=95 )

chunks = splitter.split_text(document) """

구조 인식 청킹 (계층 구조가 있는 문서)

""" from langchain.text_splitter import MarkdownHeaderTextSplitter

문서 구조 존중

splitter = MarkdownHeaderTextSplitter( headers_to_split_on=[ ("#", "Header 1"), ("##", "Header 2"), ("###", "Header 3"), ] )

chunks = splitter.split_text(markdown_doc)

각 청크에는 컨텍스트를 위한 헤더 메타데이터가 있음

"""

컨텍스트 기반 청킹 (Anthropic의 접근 방식)

"""

임베딩 전에 각 청크에 컨텍스트 추가

검색 실패율을 35% 줄임

def add_context_to_chunk(chunk, document_summary): context_prompt = f''' 문서 요약: {document_summary}

다음은 이 문서의 청크입니다:
{chunk}
'''
return context_prompt

원시 청크가 아닌 컨텍스트화된 청크를 임베딩

for chunk in chunks: contextualized = add_context_to_chunk(chunk, summary) embedding = embed(contextualized) store(chunk, embedding) # 원본 저장, 컨텍스트화된 버전 임베딩 """

코드별 청킹

""" from langchain.text_splitter import Language, RecursiveCharacterTextSplitter

언어 인식 분할

python_splitter = RecursiveCharacterTextSplitter.from_language( language=Language.PYTHON, chunk_size=1000, chunk_overlap=200 )

함수/클래스 경계 존중

chunks = python_splitter.split_text(python_code) """

백그라운드 메모리 형성

더 나은 품질을 위해 비동기적으로 메모리 처리

사용 시기: 상호작용 속도를 늦추지 않으면서 더 높은 재현율을 원할 때

백그라운드 메모리 형성:

""" 실시간 메모리 추출은 대화 속도를 늦추고 에이전트 도구 호출에 복잡성을 추가합니다. 대화 후 백그라운드 처리는 더 높은 품질의 메모리를 생성합니다.

패턴: 잠재의식 메모리 형성 """

LangGraph 백그라운드 처리

""" from langgraph.graph import StateGraph from langgraph.checkpoint.postgres import PostgresSaver

async def background_memory_processor(thread_id: str): # 대화가 끝나거나 유휴 상태가 되면 실행 conversation = await load_conversation(thread_id)

# 시간 제약 없이 인사이트 추출
insights = await llm.invoke('''
    다음 대화를 분석하고 추출하세요:
    1. 사용자에 대해 알게 된 주요 사실
    2. 드러난 사용자 선호도
    3. 완료되었거나 대기 중인 작업
    4. 사용자 행동 패턴

    이 작업은 백그라운드에서 실행되므로 철저히 수행하세요.

    대화:
    {conversation}
''')

# 장기 기억에 저장
for insight in insights:
    await memory.semantic.upsert(
        namespace="user_insights",
        key=generate_key(insight),
        content=insight,
        metadata={"source_thread": thread_id}
    )

대화 종료 또는 유휴 시간 초과 시 트리거

@on_conversation_idle(timeout_minutes=5) async def process_conversation(thread_id): await background_memory_processor(thread_id) """

메모리 통합 (수면과 유사)

"""

주기적으로 메모리 통합 및 중복 제거

async def consolidate_memories(user_id: str): # 사용자의 모든 메모리 가져오기 memories = await memory.semantic.list( namespace="user_insights", filter={"user_id": user_id} )

# 유사한 메모리 찾기 (잠재적 중복)
clusters = cluster_by_similarity(memories, threshold=0.9)

# 유사한 메모리 병합
for cluster in clusters:
    if len(cluster) > 1:
        merged = await llm.invoke(f'''
            다음 관련 메모리를 하나로 통합하세요:
            {cluster}

            모든 중요한 정보를 보존하세요.
        ''')
        await memory.semantic.upsert(
            namespace="user_insights",
            key=generate_key(merged),
            content=merged
        )
        # 원본 삭제
        for old in cluster:
            await memory.semantic.delete(old.id)

"""

메모리 감쇠 패턴

오래되고 관련 없는 기억 잊기

사용 시기: 메모리가 커지고 검색 속도가 느려질 때

메모리 감쇠:

""" 모든 기억이 영원히 지속되어야 하는 것은 아닙니다:

  • 오래된 선호도는 구식일 수 있음
  • 작업 세부 정보는 관련성을 잃음
  • 상충되는 기억은 검색을 혼란스럽게 함

다음을 기반으로 지능적인 감쇠 구현:

  • 최근성 (언제 생성/접근되었는가?)
  • 빈도 (얼마나 자주 검색되는가?)
  • 중요성 (핵심 사실인가 세부 정보인가?) """

시간 기반 감쇠

""" from datetime import datetime, timedelta

async def decay_old_memories(namespace: str, max_age_days: int): cutoff = datetime.now() - timedelta(days=max_age_days)

old_memories = await memory.episodic.list(
    namespace=namespace,
    filter={"last_accessed": {"$lt": cutoff.isoformat()}}
)

for mem in old_memories:
    # 소프트 삭제 (보관됨으로 표시)
    await memory.episodic.update(
        id=mem.id,
        metadata={"archived": True, "archived_at": datetime

...

[번역을 위해 잘렸음]

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

SamuelChien/mega-skills-collection

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

SamuelChien/mega-skills-collection

Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español.

SamuelChien/mega-skills-collection

Ingeniero de Sistemas de Andru.ia. Diseña, redacta y despliega nuevas habilidades (skills) dentro del repositorio siguiendo el Estándar de Diamante.

SamuelChien/mega-skills-collection

Estratega de Inteligencia de Dominio de Andru.ia. Analiza el nicho específico de un proyecto para inyectar conocimientos, regulaciones y estándares únicos del sector. Actívalo tras definir el nicho.

SamuelChien/mega-skills-collection

2D game development principles. Sprites, tilemaps, physics, camera.

SamuelChien/mega-skills-collection

3D game development principles. Rendering, shaders, physics, cameras.

SamuelChien/mega-skills-collection

Expert in building 3D experiences for the web - Three.js, React Three Fiber, Spline, WebGL, and interactive 3D scenes. Covers product configurators, 3D portfolios, immersive websites, and bringing depth to web experiences.

SamuelChien/mega-skills-collection

Accessibility audit skill for scanning, fixing, and verifying WCAG 2.2 Level A and AA compliance across React, Next.js, Vue, Angular, Svelte, and plain HTML codebases. Use when auditing accessibility, fixing a11y violations, checking color contrast, generating compliance reports, or integrating accessibility checks into CI/CD pipelines.

SamuelChien/mega-skills-collection

Ab Test Analyzer - Auto-activating skill for Data Analytics. Triggers on: ab test analyzer, ab test analyzer Part of the Data Analytics skill category.

SamuelChien/mega-skills-collection

A B Test Config Creator - Auto-activating skill for ML Deployment. Triggers on: a b test config creator, a b test config creator Part of the ML Deployment skill category.

SamuelChien/mega-skills-collection

When the user wants to plan, design, or implement an A/B test or experiment. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "conversion experiment," "statistical significance," or "test this." For tracking implementation, see analytics-tracking.

SamuelChien/mega-skills-collection

Acceptance Criteria Creator - Auto-activating skill for Enterprise Workflows. Triggers on: acceptance criteria creator, acceptance criteria creator Part of the Enterprise Workflows skill category.

SamuelChien/mega-skills-collection

Use when a coding task should be driven end-to-end from issue intake through implementation, review, deployment, and acceptance verification with minimal human re-intervention.

SamuelChien/mega-skills-collection

Accessibility Audit Runner - Auto-activating skill for Frontend Development. Triggers on: accessibility audit runner, accessibility audit runner Part of the Frontend Development skill category.

SamuelChien/mega-skills-collection

You are an accessibility expert specializing in WCAG compliance, inclusive design, and assistive technology compatibility. Conduct audits, identify barriers, and provide remediation guidance.

SamuelChien/mega-skills-collection

Web accessibility patterns for WCAG 2.2 compliance including ARIA, keyboard navigation, screen readers, and testing

SamuelChien/mega-skills-collection

Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed, or change policy for the Discord channel.

SamuelChien/mega-skills-collection

Create unified specification packages across Business, Development, and Design teams. Staged elaboration (L0 Vision → L1 Requirements → L2 Team Detail → L3 Acceptance Criteria) to build shared understanding. Does not write code.

SamuelChien/mega-skills-collection

Research a company or person and get actionable sales intel. Works standalone with web search, supercharged when you connect enrichment tools or your CRM. Trigger with "research [company]", "look up [person]", "intel on [prospect]", "who is [name] at [company]", or "tell me about [company]".

SamuelChien/mega-skills-collection

Validate messaging consistency across website, GitHub repos, and local documentation generating read-only discrepancy reports. Use when checking content alignment or finding mixed messaging. Trigger with phrases like "check consistency", "validate documentation", or "audit messaging".

관련 스킬