Understanding the Self-Evolution Loop in AI Agents: A Source Code Walkthrough
This article breaks down the architecture behind a self-evolving AI agent loop, using an open-source agent project as a reference. It explains how three subsystems—memory, skill, and a reflection trigger—form a feedback loop that lets agents retain context across sessions instead of forgetting everything when a conversation ends. You will see how tight character budgets force memory compression, why freezing a system prompt snapshot keeps single-session behavior predictable, how to distill one-off experience into reusable skills, and how low-interruption reflection keeps the loop running. The article closes with deployment notes for Baidu AI Cloud and the core takeaway: constrained memory, experience distillation, and scheduled reflection matter more than a smarter model.
Understanding the Self-Evolution Loop in AI Agents: A Source Code Walkthrough
1. Where the Problem Starts: Forgetting When the Session Ends
Most mainstream agent frameworks today share a structural flaw: the context window is volatile. When a session ends, the model knows nothing about the user’s preferences, project conventions, or pitfalls already encountered, so the next session starts probing from zero. A common industry workaround is a two-part setup of “skill files plus memory files,” but these are usually maintained by hand—the agent knows only what you write down, and nothing you leave out. The capability growth curve is therefore capped by the slope of manual effort.
The real dividing line is not a feature checklist but design philosophy: one approach is fed by humans, the other grows on its own. This article uses the implementation approach of an open-source agent project as a sample, abstracts it into a vendor-neutral reference architecture for a “self-evolution loop,” and explains how to build similar capabilities on top of Baidu AI Cloud’s container platform, object storage, and logging service.
2. Overall Architecture: Three Subsystems, One Loop
Self-evolution is not a single feature but a feedback loop formed by three interlocking subsystems:
- Memory subsystem: Retains facts across sessions, answering “who you are and what your environment looks like.”
- Skill subsystem: Turns one-off successful experience into reusable procedures, answering “how to handle this kind of problem next time.”
- Reflection trigger (Nudge Engine): Periodically prompts self-review with minimal interruption, answering “when it is time to summarize.”
Missing any one of them breaks the loop. Memory without skills means the agent “remembers you” but never gets stronger. Skills without a trigger means experience consolidation depends on the user starting it manually and is soon forgotten. A trigger without constrained memory means reflection output expands without bound and eventually degrades into a long document nobody reads.
3. Memory Subsystem: Using a Capacity Cap to Force Information Compression
3.1 Two-File Structure and Character Budget
One proven minimal approach uses only two plain text files, with entries separated by a consistent delimiter:
~/.agent/memories/├── MEMORY.md # Environment facts, project conventions, tool quirks└── USER.md # User preferences, communication style, collaboration habits
The key is a deliberately tight character limit: about 2200 characters for environment memory and about 1375 characters for the user profile. This is not laziness; it converts “memory governance” from a complex retrieval-and-ranking problem into a clear write-time iteration problem: a new entry must displace an old one to get in, and only higher-density information can displace an old entry.
Compare this with the common append-only mode: the file only grows, swells to tens of thousands of lines after a few months, and retrieval then requires reading the whole file or relying on vector recall, with the noise ratio steadily rising. The essence of the constrained-capacity approach is to make forgetting the default behavior and make retention a result that must compete.
3.2 Dual-State Design: Writable Entries Plus a Frozen Snapshot
In implementation, the memory storage layer typically maintains two parallel states: a list of entries that can be written in real time, and a system prompt snapshot frozen at session start.
class MemoryStore:def __init__(self, memory_char_limit=2200, user_char_limit=1375):self.memory_entries: list[str] = []self.user_entries: list[str] = []self.memory_char_limit = memory_char_limitself.user_char_limit = user_char_limitself._system_prompt_snapshot: dict[str, str] = {}def snapshot(self) -> dict[str, str]:self._system_prompt_snapshot = {"memory": "\n".join(self.memory_entries),"user": "\n".join(self.user_entries),}return self._system_prompt_snapshot
Why freeze it? Because rewriting the system prompt mid-session causes instruction drift: the model applies inconsistent criteria to the same task, and output quality fluctuates. The frozen snapshot guarantees predictable behavior within a single session, and writes only affect the next session. This is a classic technique for decoupling “learning” from “execution” in time.
3.3 Write Path and Conflict Resolution
Entry updates should follow three steps: candidate generation, conflict detection, and budget trimming. Conflict detection can start with normalized string comparison, then hand off to the model to judge semantic equivalence; budget trimming removes the entry with the lowest information gain. All changes should be appended to a structured log so you can trace “why the agent remembered this.”
4. Skill Subsystem: Distilling Pitfall Experience into Reusable Procedures
Skill files are also carried as plain text but with a stricter structure, generally containing four parts: trigger conditions, pre-checks, a step sequence, and failure fallback. The generation flow is: after a task completes, the model reviews the trajectory, extracts “the minimal decision fragment reusable next time,” and writes it as a candidate skill; later tasks trigger it via semantic similarity matching.
Three practical points. First, keep skills short: one skill solves one class of problem, and long documents have low hit rates. Second, include pre-checks, for example “confirm the image has been pushed before deploying,” turning pitfalls already hit into assertions. Third, make them eliminable: skills not hit for a long time should be down-weighted or archived so the skill library does not swell into a new noise source.
5. Reflection Trigger: Low-Interruption Scheduled Self-Review
The trigger does not have to be a resident process; it can be a combination of conditions such as a session count, a time window, or task-completion events. Once triggered, it does only one thing: have the model do a short review with a single criterion—whether new facts worth writing to memory or skills have appeared—and exit silently if there is no output. Frequency control and silence policy are key; otherwise reflection itself becomes a source of cost and noise.
6. Deployment Notes on Baidu AI Cloud
- Store memory and skill files in object storage with versioning, and mount them on stateless instances on the container platform so they can be shared;
- Use a message queue to decouple reflection task triggering from execution and to smooth out peaks and valleys;
- Deliver full-chain write and hit records to the logging service, and use monitoring and alerting to observe skill hit rate and memory eviction rate;
- Mask sensitive fields before writing, and restrict permissions to the minimum set.
7. Conclusion
The core of self-evolution is not a smarter model but the constraint design of constrained memory + experience distillation + scheduled reflection. The capacity cap creates scarcity, scarcity drives compression, compression settles into skills, and skills are repeatedly validated during reflection—once the loop starts turning, capability growth no longer depends on manual feeding.
