Building Persistent Agent Architectures with Self-Evolution Capabilities
This article breaks down why stateless large language models lose context between sessions and how to fix it with persistent agent architectures. It covers closed-loop learning that turns successful task traces into reusable, parameterized skills, automated prompt optimization with measurable and reviewable iteration, layered memory design for stable preferences and large histories, and architectural decoupling of inference, capabilities, and state. It also outlines the key risks of self-evolving systems and the guardrails needed to keep them safe.
1. The Root Cause: Stateless Models Meet Stateful Tasks
A single LLM inference call is essentially a stateless function: it takes context as input, returns a sampled result from a probability distribution, and releases all internal activations when the call ends. The deployment workflow you just finished debugging, the naming conventions you just aligned on, and the rollback strategy you just confirmed are all gone in the next session. What users perceive as “amnesia” is not a loss of model capability; it is that the runtime has no place to store experience outside the call.
The problem breaks down into three gaps:
- Context gap: a single context window has limited capacity, so long-running tasks cannot be replayed in full.
- Experience gap: process data from successful and failed tasks is never captured in a structured form.
- Identity gap: sessions share no stable baseline of preferences, environment, and constraints.
The traditional response is to keep extending the context window and repeatedly pasting background notes. That only pushes the gap further out. The direction that can actually be engineered is to turn the agent from a “one-shot calculator” into a runtime with persistent state and a learning loop.
2. Closed-Loop Learning: Turning One Success into a Reusable Asset
A conventional agent runs a linear pipeline: receive an instruction, plan steps, call tools, return a result, and reset experience to zero at the end. The key to self-evolution is a return channel at the end of that pipeline, so successful traces become knowledge assets that are searchable, reusable, and verifiable.
A practical loop usually has five stages:
- Trace collection: record the task goal, the tool call sequence, retry points, and the final verification method.
- Key decision extraction: separate “general steps” from “one-off actions specific to this environment,” so an accidental path is not hardened into a standard.
- Skill solidification: write the extracted result into a structured skill document that states preconditions, dependencies, execution steps, verification method, and rollback plan.
- Parameterization: abstract the variable parts into placeholder variables so the same skill can be reused across projects.
- Matching and reuse: when a new task arrives, run similarity and precondition matching first; on a hit, skip the lengthy reasoning, and on a miss, fall back to normal planning.
Skill documents are best kept in a readability-first plain text format, for example:
---name: container_service_deploytrigger: keyword match on deploy/release/go-live AND a build artifact existspreconditions: [image pushed, config injected]vars: {image_name, tag, namespace, replicas}steps:- verify the image is pullable- apply config and secret references- roll out and watch readiness probesverify: ready replica count meets target and error rate is below thresholdrollback: revert to the previous image tag---
Two engineering details are easy to overlook. First, a skill must carry preconditions and a verification method; without them, reuse amplifies errors. Second, skills need versioning and invalidation flags, so once the environment evolves, outdated skills are automatically downgraded instead of continuing to be matched.
3. Automated Prompt and Skill Optimization: Measurable and Reviewable Iteration
Once the skill library grows, the marginal return of manually tuning prompts drops quickly. Mature approaches to automatic prompt optimization already exist: use a set of scored task samples as a training set, then iterate with evolutionary search or prompt-revision methods inspired by backpropagation, improving task pass rate while keeping prompts concise. Compared with pure reinforcement learning, these methods usually require no model weight updates and no compute cluster; they run through inference APIs alone, at a significantly lower iteration cost.
For production use, design the optimization loop to be measurable, rollback-capable, and review-gated:
- Evaluation set: cover typical scenarios, edge cases, and historical failures, with metrics for success rate, step count, and tool call cost.
- Search strategy: keep better-performing candidate prompts, discard regressions, and cap the number of iterations to control cost.
- Submission: optimization output enters the code repository as a change request and takes effect only after human review and merge.
- Safety boundary: treat changes to the system prompt with the same control as business code, and never allow automatic merges into production branches.
This keeps the efficiency of automatic iteration while preventing the agent from drifting from its original intent without supervision.
4. Layered Memory: Persistent Memory, Session Retrieval, and External Storage
No single memory structure can satisfy both “stable preferences” and “massive history,” so a layered design is common in practice:
- Long-term memory: stable user preferences, environment constraints, naming and compliance conventions; small in size, slow to change, and highest priority.
- Session memory: current task state stored as a summary plus key information slots, carrying goals and completed items across turns.
- Retrieval memory: historical sessions and documents chunked into a vector index and recalled by semantic similarity, which resolves the capacity bottleneck.
- External memory: relational databases, object storage, logging services, and monitoring alerts connected through plugins or standard interfaces for cross-device consistency.
Memory writes need governance, or the system will “remember its way into more errors”:
Before write: extract -> deduplicate -> detect sensitive data -> score confidenceAfter write: tag the source -> set expiry -> detect conflicts -> archive periodicallyOn read: filter by permission -> weight by time decay -> on conflict, prefer higher confidence and higher recency
Credentials, keys, and personal sensitive data should never enter long-term memory; they should be retrieved at runtime through a key management service or environment injection.
5. Architectural Decoupling: Separate Capability, Memory, and Execution
If self-evolution is coupled inside a monolith, upgrades and troubleshooting both spiral out of control. A more robust approach separates three layers:
- Inference layer: responsible only for planning and decisions, kept stateless for horizontal scaling.
- Capability layer: tools and skills registered as independent services or through standard interfaces, with timeouts, retries, idempotency, and rate limiting.
- State layer: memory and the skill library stored independently, with versioning, backup, and migration support.
For deployment, container platforms host the inference and capability services, object storage holds skill packages and historical archives, a message queue smooths spikes and chains long-running tasks, and the logging and monitoring stack handles trace tracking and cost observation. If you use Baidu AI Cloud, this can be assembled as a “container platform + object storage + logging and monitoring” combination, keeping each layer replaceable and avoiding tight coupling to a single implementation.
6. Boundaries and Risks: Self-Evolution Is Not Unlimited Delegation
The risks of a self-evolving system concentrate in three places: wrong experience being solidified, prompts being poisoned by malicious samples, and permissions expanding along with automation. The corresponding constraints: skill matches require precondition checks and human spot checks; all external content is treated as untrusted input and is forbidden from triggering system prompt changes; tool calls follow least privilege, and write and delete operations require explicit confirmation; all automatically optimized artifacts keep an audit trail and can be rolled back with one action.
7. Summary
The fix for “amnesia on restart” is not to wait for a stronger model, but to fill in the state and learning mechanisms: use the closed loop to distill successful tasks into parameterized skills, use automated optimization to keep refining prompts under human review, use layered memory to balance stable preferences against massive history, and use architectural decoupling to stay operable and replaceable. Together, these four turn an agent from a one-off question-answering tool into a long-term collaborator that grows with use.
