Designing Persistent Memory and Self-Improvement Mechanisms for AI Agents

    This article examines why stateless LLM interactions cause agents to forget context and experience, then presents a three-layer engineering approach: persistent memory for user and project context, a skill library distilled from complex tool-use trajectories, and full-text retrieval over historical conversations. It also covers loading and update strategies, a closed-loop self-improvement workflow, and practical pitfalls around memory quality, skill validation, retrieval granularity, privacy, and observability.

    1. Why Do Most Agents Forget After One Use?

    Most mainstream large language model applications operate in a stateless interaction mode: a user starts a session, the model answers with the available context, and everything resets when the session ends. The next time the user asks a question, the agent must relearn preferences, agreed tool workflows, and past mistakes—even if they were discussed the day before.

    This mode has three significant problems:

    1. High repeat communication cost: Users must repeatedly provide background information such as the project technology stack, coding conventions, and common deployment methods, which creates a fragmented experience.
    2. Experience cannot be reused: A problem-solving approach that took dozens of tool calls to discover must be explored again when a similar task appears.
    3. Limited context window: Even if all historical conversations are inserted into the context, the agent is constrained by window length and retrieval accuracy, so it cannot “recall on demand.”

    A mature engineering direction is therefore to separate the “smart” part from model parameters and externalize it into a manageable, searchable, and evolvable storage system, turning agent capability growth into a practical engineering problem.

    2. Core Mechanism One: Persistent Memory

    2.1 Design Philosophy

    The essence of persistent memory is to actively distill high-value information from conversations into structured long-term knowledge instead of passively relying on session context. In practice, memory is usually divided into two categories:

    • User profile memory: Records user preferences, habits, and background. For example, a user may prefer concise responses, habitually use a certain language, or own a certain business module. This type of information answers the question: “Who are you?”
    • Project/work memory: Records project background, technology choices, agreed conventions, and important conclusions. This type of information answers the question: “What are you working on?”

    2.2 Implementation Points

    A simple and effective implementation is to use Markdown files as memory carriers:

    1. memory/
    2. ├── MEMORY.md # Project and work preferences
    3. └── USER.md # User understanding model

    The write logic can be abstracted into three trigger conditions:

    1. The user explicitly expresses a preference (“Use TypeScript from now on”).
    2. A long-lived conclusion emerges during the session (“The release process for this project includes a canary phase”).
    3. The agent finds that existing memory conflicts with current facts and needs to update rather than append.

    A key engineering detail is that memory writes should be actively judged by the agent rather than storing everything. A post-processing step can be designed: after answering, the model evaluates “which information in this conversation is worth retaining long-term” and then performs the write. Example code:

    1. def after_response(dialog, agent):
    2. candidates = agent.evaluate_memory_worthiness(dialog)
    3. for item in candidates:
    4. agent.memory.append(
    5. file=item.target_file, # MEMORY.md or USER.md
    6. entry=item.compact_fact # A single distilled fact
    7. )

    In addition, memory must have an eviction and correction mechanism: periodically check for conflicting entries and overwrite older versions with the “last written and user-confirmed” version. This prevents memory from bloating, contradicting itself, and polluting later reasoning.

    2.3 Loading Strategy

    At the start of a new session, memory files should be injected into the system prompt. Because the agent should keep these memory files concise (within one to two thousand characters), this does not significantly consume the effective context, but it can greatly reduce repeated communication costs.

    3. Core Mechanism Two: Skill Accumulation System

    3.1 From “Tool Calls” to “Methodology”

    If one type of past experience is most worth reusing, the answer is not the result of a single tool call but the complete problem-solving path. A complex task often involves multiple tool calls: search first, then read code, locate the problem, modify, and verify. This chain itself—what to do first, what to do next, and where mistakes are easy to make—is the most valuable knowledge.

    An operational criterion is: when a task execution involves more than a certain number of tool calls (for example, more than five), it has reached a certain level of complexity, and the agent should trigger a “skill distillation” process after completion.

    3.2 Structure Design of Skill Files

    A skill file should not be a running log but a structured methodology document:

    1. # SKILL: Database slow query troubleshooting
    2. ## Applicable scenarios
    3. Use when the task involves XX and the symptom is YY
    4. ## Execution steps
    5. 1. First confirm the current load with the XX command
    6. 2. Locate the slow log and filter with the condition ...
    7. 3. ...
    8. ## Common pitfalls
    9. - Do not directly do B under condition A, because ...
    10. ## Verification
    11. After the change, run XX to confirm the effect

    3.3 Invocation and Evolution of Skills

    During task routing, the agent can perform semantic matching between the task description and skill files. If a match is found, it reads the skill before execution, effectively carrying “a senior engineer’s notes.” Skills should also support version evolution: when the agent finds in practice that a skill description does not match reality, it should write back corrections so that the skill library forms a positive feedback loop.

    With cloud object storage or knowledge base capabilities, the skill library can also enable team sharing at this stage—turning individual experience into organizational assets.

    4. Core Mechanism Three: Full-Text Retrieval of Historical Conversations

    4.1 Why Retrieval Is Needed

    Memory and skills solve the problem of “high-frequency, structured” knowledge, but a large amount of valuable context is scattered across historical conversations—for example, the complete reasoning process used to debug an unusual issue three months ago. This type of information is difficult to structure in advance, and the most economical approach is full persistence plus full-text retrieval.

    4.2 Implementation Based on an Embedded Database

    A lightweight embedded relational database with full-text search extensions—such as a common embedded SQL engine with FTS5 support—is an ideal choice: zero operations, offline availability, and inverted index support. Example approach:

    1. -- Create table
    2. CREATE TABLE conversations (
    3. id INTEGER PRIMARY KEY,
    4. session_ts INTEGER,
    5. role TEXT,
    6. content TEXT
    7. );
    8. -- Enable full-text index (using a generic FTS extension as an example)
    9. CREATE VIRTUAL TABLE conv_fts
    10. USING fts5(content, tokenize='unicode61');
    11. -- Agent retrieves relevant discussions from three months ago
    12. SELECT c.session_ts, c.content
    13. FROM conv_fts f
    14. JOIN conversations c ON c.id = f.rowid
    15. WHERE conv_fts MATCH 'memory leak AND service restart'
    16. AND c.session_ts > strftime('%s','now') - 90*86400
    17. ORDER BY c.session_ts DESC;

    4.3 Integration with Context

    Retrieval results should not directly fill the context. Instead, follow three principles: relevance ranking, summary compression, and snippet trimming. Only take the most relevant entries and their corresponding reasoning summaries and let the model process them again. If retrieval hit quality is insufficient, cloud vector retrieval services and full-text retrieval capabilities can be added for hybrid recall, balancing semantic similarity and exact keyword matching.

    5. How the Three Work Together: A Self-Improvement Loop

    These three mechanisms are not parallel; they collaborate in layers:

    • Persistent memory handles “low-cost, high-frequency loading”—read in every session.
    • Skill library handles “routing acceleration for complex tasks”—matched by scenario.
    • Historical retrieval handles “fallback recall for long-tail knowledge”—mined when needed.

    This forms a closed loop: conversations produce information → after value judgment, write to memory or persist the original text → distill skills from complex tasks → subsequent tasks receive context through memory injection, skill matching, and historical retrieval → performance improves → higher-quality new information is produced. The agent’s growth curve changes from “a flat line” to “increasing with usage time.”

    6. Practical Recommendations and Pitfalls

    1. Prefer less memory over poor memory: Low-quality memory is worse than no memory. Value must be judged before writing, and a conflict correction mechanism must be established.
    2. Skills need a verification step: Distilled methodologies should be validated in the next similar task to avoid固化 accidental success into “wrong experience.” (Note: replace “固化” with “solidifying”—see revised text below.)
    3. Control retrieval granularity: Index at the message level rather than the session level, and use time filters to achieve precise recall.
    4. Privacy and compliance first: Memory and historical conversations contain sensitive information. They should be encrypted at rest, with a one-click deletion capability. If cloud logging services and object storage are used, fine-grained access control should be configured.
    5. Observability is essential: Track metrics such as memory hit rate, skill reuse rate, and retrieval relevance, integrate them with common monitoring and alerting systems, and continuously evaluate the real benefits of this mechanism.

    7. Conclusion

    “Getting smarter with use” is not a mysterious claim but a problem that can be broken down through engineering: use persistent memory to remember “who you are,” a skill library to remember “how to do it,” and historical retrieval to remember “how you once thought about it.” When these three layers work together, an agent evolves from a one-off tool into a system that can continuously accumulate knowledge and grow with its user. For teams building agent applications, this approach is worth incorporating into architecture design early, because it determines long-term product competitiveness—not merely how strong the model itself is, but whether it retains the experience of every interaction with the user.