Designing Persistent and Self-Evolving AI Agents: Prompts, Context, and Runtime Harness
This article explains how to move from session-based LLM tools to persistent, self-evolving AI agents. It covers the three feedback loops that let agents accumulate experience, reusable skills, and policies; layered and versioned prompt design; context governance with budgets, memory tiers, compression, and retrieval; and the runtime harness for scheduling, tool abstraction, permissions, and observability. It also outlines migration steps, evaluation practices, and common anti-patterns, giving teams a practical blueprint for building long-running agents on general-purpose infrastructure.
1. From Session-Based Tools to Persistent Agents
Traditional Q&A applications live inside a single request: receive input, assemble a prompt, call the model, return the result, and discard all state. A persistent agent stretches that lifecycle to weeks or months. It runs continuously on the server side, with a stable identity, reusable memory, and workflows that can be triggered on a schedule.
The difference is not just runtime duration but a shift in where state lives: from request memory to external persistent storage, and from an implicit context window to an explicit, retrievable store of knowledge and experience.
This shift has three direct consequences. First, capabilities accumulate, so solved problems do not need to be reasoned through again. Second, behavior becomes auditable, since every tool call and decision can be recorded and replayed. Third, tasks can be made asynchronous, with long-running work handed to a scheduler and queues instead of blocking a single interaction.
Persistence does not mean stuffing the entire conversation history back into the prompt. That only raises cost and dilutes attention. The right approach is to reassemble context from information that is necessary, retrieved by relevance, and compressed.
2. Three Feedback Loops for Self-Evolving Capabilities
“More runtime means more capability” is not magic; it can be broken down into three engineering feedback loops.
The first is the experience loop. After completing a task, the agent structures “problem features, chosen approach, execution result, failure cause” into an experience record and writes it to a retrievable experience store. When a similar task appears, it retrieves experience first and then decides whether to reuse it. Filtering and deduplication before writing are critical, otherwise the store gets polluted by low-value entries.
The second is the skill loop. When a class of operations is executed repeatedly with stable steps, it can be solidified into a reusable skill, essentially a parameterized script or tool orchestration. This downgrades “reasoning from scratch every time” to “one retrieval plus one parameter fill,” significantly reducing randomness.
The third is the policy loop. Based on statistics from historical execution data, the agent dynamically adjusts policy tendencies in the prompt, such as tool selection priority, retry limits after failure, and when to confirm with the user. Policy changes must be gated by canary rollout and rollback, so one wrong generalization does not contaminate long-term behavior.
All three loops share the same underlying data: structured execution traces. Without high-quality traces, self-evolution degrades into random drift.
3. Prompt Design: Layered, Versioned, and Evaluable
In a persistent agent, the prompt is not a string but a layered configuration. A recommended structure has four layers:
- Identity layer: stable role definition, capability boundaries, refusal and safety principles; rarely changes.
- Domain layer: business terminology, data definitions, output specifications; iterates in small steps as the business evolves.
- Policy layer: tool selection preferences, retry and confirmation rules, cost constraints.
- Task layer: temporary instructions for the current request and retrieved experience snippets.
The core benefit of layering is change isolation: adjusting policy does not break identity constraints, and updating domain knowledge does not touch safety clauses. Prompts should be placed under version control, with each change recording its reason and evaluation results, forming traceable prompt assets.
A schematic layered assembly logic (pseudocode, structure only):
def build_prompt(req, store):parts = [load("identity.md", version="stable"), # Identity layer, stableload("domain.md", version=req.domain_ver), # Domain layer, iterablerender_policy(store.policy()), # Policy layer, dynamic canaryretrieve_experience(req, store, top_k=3), # Task layer, retrieval-augmentedreq.user_input,]return "\n\n".join(p for p in parts if p)
For evaluation, maintain a fixed test set covering normal paths, boundary inputs, and adversarial inputs. Run it on every prompt change and record three metrics: success rate, average tool calls, and average latency. A change may ship only if the metrics do not regress.
4. Context Governance: Budget, Compression, and Retrieval
Context is a limited and expensive resource. The governance goal is to maximize effective information density within a fixed budget. Four areas matter.
Budget allocation. Set quotas for identity, domain, retrieved snippets, history summaries, and current input. When limits are exceeded, trim by priority so retrieved content does not crowd out safety constraints.
Layered memory. Split memory into working memory (intermediate state of the current task), episodic memory (specific event traces), and semantic memory (abstracted conclusions and preferences). Extract structure on write, recall by relevance on read, and archive rarely used entries to low-cost storage.
Compression and summarization. Use rolling summaries for long traces: compress after each stage, keep decisions and results, and discard redundant observations. The compression process should retain references to the original traces for traceback.
Retrieval quality. Retrieval is the key variable in context governance. Pay attention to chunk granularity, metadata tagging (task type, time, success or failure), and reranking. The experience store should prioritize entries that are “successful and reused multiple times”; failure entries are recalled only when risk avoidance is needed.
A practical rule: if removing a piece of context barely changes model behavior, it should not consume budget.
5. Harness Runtime: Scheduling, Tools, and Observability
The harness is the runtime skeleton wrapping the model, responsible for lifecycle, tool calls, concurrency, and fault tolerance. Key designs for persistent scenarios include:
- Decouple the resident process from the task queue: the interaction entry only receives requests and returns acknowledgments, while execution is handed to queues and schedulers; long tasks return via status queries or callbacks.
- Dual triggers for schedules and events: periodic tasks are driven by the scheduler, external events by the message entry; both share the same idempotency key to prevent duplicate execution.
- Unified tool abstraction: each tool declares its name, purpose, parameter schema, permission level, and timeout; the model only sees the subset of tools matching its current permissions.
- Permission and confirmation mechanisms: write, delete, and operations with external side effects require secondary confirmation or an approval flow.
- Observability: record request IDs, prompt versions, retrieval hits, tool call chains, tokens, and latency to form replayable execution traces.
A schematic tool declaration:
{"name": "query_metric","description": "Query business metrics by time range","parameters": {"range": "string", "metric": "string"},"permission": "read","timeout_ms": 5000}
For deployment, a common pattern is to run the stateless compute in a container platform with elastic scaling, keep memory and experience in object storage or a managed database, hand asynchronous tasks to a message queue, and cover error rate, timeout rate, and queue backlog with logging and monitoring alerts. This provides elasticity while ensuring state survives instance restarts.
6. Migration, Evaluation, and Common Anti-Patterns
When migrating from a legacy setup, first perform structured extraction on historical sessions and migrate only reusable conclusions rather than full raw text, then rebuild indexes according to the new framework’s metadata specification. After migration, run a parallel observation period comparing success rate and latency between old and new pipelines on similar tasks.
There are four common anti-patterns. First, replaying full history, which causes cost blowup and instruction conflicts. Second, writing experience without filtering, so the store gets dirtier over time. Third, automatic policy adjustment without canary and rollback, so one wrong generalization takes effect long-term. Fourth, focusing only on answer quality while ignoring tool call permissions and idempotency, which amplifies errors in side effects.
7. Conclusion
Persistence answers “where state lives,” and self-evolution answers “how capability accumulates.” Layered prompts, context budget governance, and the runtime harness are the three pillars that put both into practice. For teams building long-running agents in their own environments, a lower-risk and more verifiable path is to first build the state and trace foundation on general-purpose infrastructure with containers, storage, queues, and observability, such as Baidu AI Cloud, and then gradually introduce experience reuse and skill solidification.
