Self-Evolving AI Agents: Practices in Memory, Skills, and Retrieval

    Traditional AI agents often suffer from cross-session amnesia, leading to fragmented user experiences and wasted computational resources. This article explores how to build self-evolving agents by establishing a self-improvement loop consisting of persistent memory, a skill system, and cross-session retrieval. It covers the design motivations, engineering implementation details, risk boundaries, and best practices for these three complementary mechanisms.

    Traditional AI agents share a widely criticized flaw: they start from scratch in every session as if they have amnesia. Technical stack preferences communicated last week or troubleshooting approaches handled last month are completely reset in this week’s new conversation. This not only wastes tokens and computational power but also severely fragments the user experience. The industry is gradually reaching a consensus: truly usable agents must possess the ability to “grow with use.” The core idea is to treat “experience precipitation” as a first-class citizen in architectural design, rather than hastily piecing together context during each inference.

    A typical self-evolving agent system usually forms a closed loop through three complementary mechanisms: persistent memory, a skill system, and cross-session retrieval. Let’s break down their design motivations, implementation methods, and engineering details.

    1. Persistent Memory: Making Context Span Sessions

    Persistent memory addresses the issue of “long-term facts about users and projects.” It is generally divided into two categories:

    • User Profile: Records the user’s working preferences, such as preferred language versions, code styles, desired level of detail in responses, and common terminology habits. This type of information changes slowly but holds high value, directly impacting the relevance of each interaction.
    • Project Background: Includes codebase structure, technology choices, team conventions, and ongoing task objectives. These are indispensable backdrops for understanding the current task.

    In engineering, a common practice is to maintain a structured profile file for each user and a background file for each project. These are automatically injected into the system context when a session starts. During the session, the agent proactively determines which new information is worth writing down. The key lies in the write strategy: you cannot record everything, or the memory will be overwhelmed by noise; nor can you miss key preferences, or it loses its meaning. The following decision rules can be designed:

    1. Write to the user profile when the user explicitly expresses a preference or corrects behavior.
    2. Write to the project background when stable, reusable project facts (directory structure, build method, deployment target) appear.
    3. Do not write temporary, one-off information (such as intermediate variable values during this debugging session); keep it only in the current session.

    At the same time, the update and eviction of memory must be considered: preferences may change, and projects will evolve. It is recommended to attach context and timestamps to each memory entry and periodically have the agent itself organize them, merging conflicting entries and removing outdated content to prevent memories from accumulating into a mess.

    2. Skill System: Solidifying Problem-Solving Processes into Reusable Assets

    If memory precipitates “facts,” the skill system precipitates “methods.” When an agent completes a complex task (e.g., calling more than five external tools, going through multiple rounds of reasoning to converge), this process itself contains a transferable problem-solving pattern. The responsibilities of the skill system are:

    • Extract: Abstract the goals, steps, tool calling sequences, key judgment basis, and common pitfalls from the completion trajectory.
    • Store: Turn the extracted results into structured skill descriptions, including applicable conditions and execution steps.
    • Reuse: When encountering similar problems later, first retrieve existing skills. If hit, execute along the established path, significantly reducing exploration costs.
    • Validate and Evolve: After a skill is executed, revise its content based on result feedback, forming a positive loop of becoming more accurate with use.

    A simplified skill description structure is as follows:

    1. {
    2. "name": "Service Startup Failure Troubleshooting",
    3. "trigger": "Application fails to start and logs contain port occupation errors",
    4. "steps": [
    5. "Read error logs to locate the failing component",
    6. "Check the process occupying the target port",
    7. "Verify port and address binding in the configuration file",
    8. "Provide repair suggestions and verify restart"
    9. ],
    10. "pitfalls": ["In container environments, localhost and host machine addresses cannot be mixed up"],
    11. "last_validated": "2025-06-01"
    12. }

    It is important to note that skills are not universal scripts. Task contexts vary widely, so skills should describe “strategies and checkpoints,” leaving room for reasoning rather than acting as rigid instruction sequences, otherwise they will fail in edge scenarios.

    3. Cross-Session Retrieval: Turning Historical Conversations into a Knowledge Base

    Memory and skills cover filtered information, but a large amount of valuable historical details remain scattered across past conversations. The approach of cross-session retrieval is to persist all historical conversations to a local database and build a full-text search index, enabling the agent to “review the past” when needed.

    Typical implementation points:

    • Localized Storage: Historical data is saved in a user-controllable local database. A common choice is an embedded relational database paired with a full-text search extension (like SQLite’s FTS5), requiring no additional service processes.
    • Index Design: Build inverted indexes based on session ID, time, role, and body text to support keyword and phrase queries.
    • Retrieval Trigger: When there is an obvious correlation between the current task and a historical problem (similar error messages, involving the same module), proactively retrieve and cite historical conclusions.
    • Timeliness Validation: Historical solutions may become invalid due to environmental changes; when cited, they must be cross-verified with current information, and old answers should not be blindly trusted.

    A typical retrieval process:

    1. SELECT session_id, snippet(history_fts, 4, '[', ']', '…', 12) AS context
    2. FROM history_fts
    3. WHERE history_fts MATCH 'port occupation AND startup failure'
    4. ORDER BY rank
    5. LIMIT 5;

    4. The Closed-Loop Relationship of the Three

    These three mechanisms are not merely stacked in parallel; they form a self-improvement closed loop:

    1. Retrieve historical conversations and reuse skills to reduce repetitive exploration.
    2. After completing a new task, write key facts into memory and extract reusable methods into skills.
    3. Richer memories and skills, in turn, improve the hit rate of the next round of retrieval and execution.

    The data flow can be summarized as: Conversation -> Precipitation (Memory/Skill) -> Retrieval -> Better Conversation.

    5. Engineering Considerations and Risk Boundaries

    • Privacy and Security: Long-term memory and historical conversations contain sensitive information. Users should be supported to view, edit, and delete memory entries, adhering to the principle of minimized collection.
    • Context Budget: Injecting memory and retrieval results consumes the context window. Priority sorting and truncation strategies are needed, prioritizing content highly relevant to the current task.
    • Memory Pollution: Once an error is written into memory, it will be continuously amplified. Therefore, the threshold for writing should be high, with periodic audits and conflict detection.
    • Explainability: When the agent cites historical experience, it is best to explain the basis (which session, which skill) to facilitate user verification.
    • Rollback Capability: Changes to skills and memory should be traceable, allowing rollback to the previous stable version if quality degradation occurs.

    Conclusion

    “Growing smarter with use” is not a slogan, but an actionable architectural decision: use persistent memory to save long-term facts about users and projects, use a skill system to solidify problem-solving methods, and use full-text retrieval to activate the value of historical conversations. With these three working in synergy, agents can evolve from “stateless tools” that reset every time into long-term collaborative partners that continuously accumulate and improve. For developers, the real focus is not on piling up flashy capabilities, but on designing a sound closed loop for experience precipitation, retrieval, and evolution.