Логотип Ai Agent Memory Systems

Ai Agent Memory Systems

Сообщество
j4flmao
ai-agent-memory-systems

Use this skill when the user says 'agent memory', 'long-term memory', 'conversation memory', 'remember user preferences', 'context window full', 'summarize history', 'episodic memory', 'semantic memory'. Designs what an agent keeps in its context window, what it stores externally, how it writes and retrieves memories, and how memories expire. Do NOT use for: document RAG pipelines (ai/llm-engineering/rag-architecture), vector DB operations (data or ai vector-database skills), or the agent loop itself (ai/ai-agents/core-architectures).

Обзор

Издательj4flmao
Репозиторийagent-skills
Название навыкаai-agent-memory-systems
Звёзды
41
Форки
6
Файлы в комплекте
Только инструкции
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Издатель навыка на GitHub — j4flmao. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Ai Agent Memory Systems в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/ai-agents/memory-systems
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/ai/ai-agents/memory-systems .claude/skills/ai-agent-memory-systems
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Ai Agent Memory Systems в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Ai Agent Memory Systems, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Ai Agent Memory Systems не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Agent Memory Systems

Purpose

An LLM is stateless between calls; anything the agent "remembers" is either placed in the context window or retrieved into it. Memory design is therefore a set of policies: what stays verbatim in context, what gets compressed, what is persisted to external stores, how it is retrieved, and when it is updated or deleted. Bad memory design shows up as forgotten constraints, contradictory facts, and leaked data between users.

Agent Protocol

Trigger

"agent memory", "long-term memory", "remember across sessions", "context window full", "conversation summarization", "user profile memory", "episodic memory", "memory leaks between users".

Input Context

  • Session length and turn count; model context size.
  • What must persist across sessions (preferences, facts, past task outcomes).
  • Privacy/tenancy constraints and retention requirements.
  • Existing storage (Postgres, Redis, vector DB).

Output Artifact

Memory design: tiers, schemas, write/read/eviction policies, isolation and retention rules.

Response Format

Working memory: pinned={...} window={n turns} compression={summary|drop}
Semantic store: {schema} retrieval={hybrid+rerank} k={n}
Episodic store: {schema} written on={event}
Profile/facts: {key-value schema} update={upsert w/ provenance}
Isolation: {tenant/user key}  Retention: {ttl}  Deletion: {API}

Completion Criteria

  • Pinned context (instructions, goal, constraints) never evicted.
  • Every stored memory carries owner id, source, timestamp.
  • Retrieval is scoped by owner before similarity search.
  • Conflicting facts resolved by recency/provenance, not duplicated.
  • User-facing delete path exists.

Memory Tiers

TierLives inContentRetrievalTypical store
WorkingContext windowSystem prompt, goal, plan, recent turns, tool resultsAlways presentIn-process
SemanticExternalFacts, documents, user profileSimilarity + filtersPostgres/pgvector, vector DB, KV
EpisodicExternalPast tasks: what was tried, outcome, lessonBy task similarity or recencyTable + embeddings
ProceduralPrompt/codeLearned instructions, tool usage rulesLoaded at startVersioned prompt files

Semantic memory answers "what is true"; episodic memory answers "what happened when I tried". Raw transcripts are not episodic memory: distill them into short records (task, actions, outcome, lesson).

Working Memory Management

Context is finite and long contexts degrade attention to the middle, so budget it explicitly:

[pinned]     system prompt, tool definitions, goal, constraints     ~fixed
[state]      current plan, key facts extracted so far              small, rewritten each step
[retrieved]  top-k memories for this step                          capped tokens
[window]     last N turns verbatim                                 sliding
[summary]    rolling summary of older turns                        rewritten when window overflows
python
from __future__ import annotations

from dataclasses import dataclass, field


@dataclass
class WorkingMemory:
    pinned: str
    max_window_tokens: int
    window: list[dict] = field(default_factory=list)
    summary: str = ""

    def add(self, message: dict, count_tokens, summarize) -> None:
        self.window.append(message)
        while sum(count_tokens(m["content"]) for m in self.window) > self.max_window_tokens:
            # Evict oldest turns into the rolling summary; never touch pinned content.
            oldest = self.window[:4]
            self.window = self.window[4:]
            self.summary = summarize(self.summary, oldest)

    def render(self, retrieved: list[str]) -> list[dict]:
        preamble = self.pinned
        if self.summary:
            preamble += f"\n\n<conversation_summary>\n{self.summary}\n</conversation_summary>"
        if retrieved:
            preamble += "\n\n<memories>\n" + "\n".join(retrieved) + "\n</memories>"
        return [{"role": "system", "content": preamble}, *self.window]

Keep tool-call/tool-result pairs together when evicting; most APIs reject a tool result whose call was removed.

Long-Term Memory Store

sql
CREATE TABLE agent_memory (
    id            BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tenant_id     TEXT NOT NULL,
    user_id       TEXT NOT NULL,
    kind          TEXT NOT NULL CHECK (kind IN ('fact', 'preference', 'episode')),
    subject_key   TEXT,                       -- e.g. 'preferred_language' for upserts
    content       TEXT NOT NULL,
    embedding     vector(1024),               -- pgvector; dimension = your embedding model
    source        TEXT NOT NULL,              -- message id / tool / user-stated
    confidence    REAL NOT NULL DEFAULT 1.0,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    expires_at    TIMESTAMPTZ,
    deleted_at    TIMESTAMPTZ,
    UNIQUE (tenant_id, user_id, kind, subject_key)
);
CREATE INDEX ON agent_memory USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON agent_memory USING gin (to_tsvector('english', content));

Retrieval: filter by tenant_id, user_id, deleted_at IS NULL, expires_at first; then hybrid search (vector + full-text, fused with reciprocal rank fusion) and rerank; inject only the top few with their timestamps so the model can judge freshness.

Write Policies

PolicyWhenRisk
Explicit ("remember that...")User asksLow
Extraction after each sessionBackground job extracts facts/preferencesHallucinated or sensitive facts stored
Episode on task completionStore task, outcome, lessonStoring failed approaches as advice
Agent-initiated tool (save_memory)Model decidesNoise, prompt-injected writes

Rules: upsert by subject_key so a new preference replaces the old one; store provenance; never persist secrets or content from untrusted documents as "facts" without review; treat retrieved memories as data, not instructions.

Anti-Patterns

  • Stuffing the entire history until the context limit; cost and latency balloon and quality drops.
  • Similarity search without owner filters: cross-user leakage.
  • Append-only facts with no conflict resolution ("likes tea", "likes coffee", both returned).
  • Summaries that drop constraints ("budget under $500"); pin constraints in state instead.
  • Memories with no expiry or deletion path (privacy and GDPR issues).

Checklist

  • Token budget per working-memory section.
  • Rolling summary keeps decisions, constraints, open questions.
  • Store schema with owner, kind, provenance, timestamps, expiry, soft delete.
  • Scoped hybrid retrieval with reranking; k and token cap set.
  • Upsert semantics for facts/preferences.
  • Deletion and export endpoints; retention job.
  • Eval: questions that require recalling facts from earlier sessions.

References

  • Packer et al., "MemGPT: Towards LLMs as Operating Systems" (2023) — tiered memory paging.
  • Park et al., "Generative Agents" (UIST 2023) — recency/importance/relevance retrieval scoring.
  • Liu et al., "Lost in the Middle" (TACL 2024) — position effects in long contexts.

Shared References

Additional reference material for this skill, stored outside its own references/ folder.

  • ../../../harness-engineering/context-engineering/references/context-drift-mitigation.md — Context Drift Mitigation
  • ../../../harness-engineering/context-engineering/references/dynamic-injection-patterns.md — Dynamic Injection Patterns
  • ../../../harness-engineering/context-engineering/references/memory-retrieval-architectures.md — Memory Retrieval Architectures
  • ../../../harness-engineering/context-engineering/references/priority-scoring-algorithms.md — Priority Scoring Algorithms
  • ../../../harness-engineering/context-engineering/references/prompt-token-optimization.md — Prompt Token Optimization

Часто задаваемые вопросы

Что делает навык ИИ Ai Agent Memory Systems?

Use this skill when the user says 'agent memory', 'long-term memory', 'conversation memory', 'remember user preferences', 'context window full', 'summarize history', 'episodic memory', 'semantic memory'. Designs what an agent keeps in its context window, what it stores externally, how it writes and retrieves memories, and how memories expire. Do NOT use for: document RAG pipelines (ai/llm-engineering/rag-architecture), vector DB operations (data or ai vector-database skills), or the agent loop itself (ai/ai-agents/core-architectures).

Зачем использовать Ai Agent Memory Systems в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Ai Agent Memory Systems — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Ai Agent Memory Systems в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/j4flmao/agent-skills/tree/main/skills/ai/ai-agents/memory-systems. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Ai Agent Memory Systems?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Ai Agent Memory Systems?

С любым количеством. В TypingMind вы можете использовать Ai Agent Memory Systems с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Ai Agent Memory Systems?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — j4flmao. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇