Self-Evolving AI Agents: Prompt and Context Engineering Practices
This article explains how to build long-running, self-evolving AI agents through three engineering layers: prompt engineering, context engineering, and harness engineering. It covers a layered prompt structure, output contracts, prompt versioning, tiered memory, write and recall strategies, context compression, runtime loop control, state persistence, sandboxing, observability, cost control, and the five-step self-evolution loop. It also lists common anti-patterns and a practical implementation order for deploying such agents on cloud infrastructure.
Self-Evolving AI Agents: Prompt and Context Engineering Practices
1. Introduction: From Chat Assistants to Persistent Agents
A class of autonomous agents has recently drawn significant attention: agents deployed on the server side that stay online for long periods and continuously accumulate experience. Unlike coding assistants embedded in an integrated development environment, or chat wrappers that simply expose a single model API, these systems are built on two core claims: persistent operation (the process and its state exist over the long term, and tasks can be triggered on a schedule) and self-evolution (successful experience from execution is distilled into reusable assets, so capability grows with runtime).
Both traits are not exclusive selling points of any particular product; they are an inevitable direction in the evolution of agent engineering. Once model capabilities become largely homogeneous, real differentiation comes from the surrounding engineering: how prompts are organized, how context is governed, and the framework layer that runs both. This article does not cover the frontend or backend details of any specific implementation. Instead, it follows the widely used three-dimensional framework—Prompt Engineering, Context Engineering, and Harness Engineering—to discuss how to build an agent that stays online for the long term.
2. Capability Foundation: Tools, Models, and Scheduling
A long-running agent is typically supported by three types of infrastructure:
- Tool layer: atomic capabilities such as file read/write, command execution, web retrieval, and structured data queries. The number of tools is not what matters; semantic orthogonality and clear descriptions are.
- Model layer: compatibility with multiple mainstream large language models, with a unified abstraction that hides differences and routes requests by task type and cost budget.
- Scheduling layer: a built-in scheduled-task mechanism (with cron-like semantics) that shifts the agent from “passive response” to “proactive inspection.”
The scheduling layer is the qualitative leap. It gives the agent autonomy along the time dimension: it can run inspections, produce summaries, retry, and raise alerts without human intervention, generating execution traces that can be used for learning.
3. Prompt Engineering: Defining Roles, Boundaries, and Output Contracts
Long-running agents place far higher demands on prompts than one-off conversations. Three things matter most: a stable role, clear boundaries, and parseable output.
3.1 Layered Prompt Structure
Split the prompt into four layers, narrowing the scope at each level:
- Identity and responsibility layer: defines who the agent is and which goals it is accountable for, kept consistent across sessions.
- Rules and prohibited actions layer: specifies high-risk actions that must not be executed directly (such as irreversible deletion or external publishing) and requires confirmation first.
- Domain knowledge layer: terminology, conventions, and directory structure notes relevant to the task domain.
- Task instruction layer: the specific goal and constraints of the current request.
An illustrative structure:
[Identity] You are an autonomous agent responsible for operations inspection. Your goal is to keep services healthy and costs under control.[Prohibited] Do not delete data directly; before any change, output a plan and wait for confirmation.[Knowledge] Log directory conventions, alert severity levels, and change window times.[Task] Inspection scope = all production clusters; output = a structured report.
3.2 Output Contracts
Self-evolution depends on “parseable execution results.” If the model output is free-form prose, there is no way to extract experience or run regression evaluation. A structured output format (such as JSON or fixed subheadings) should be agreed upon, with fields for the conclusion, evidence, actions taken, failure reasons, and next-step suggestions.
{"conclusion": "Disk usage will hit the ceiling within 3 days","evidence": ["4.1% daily growth over the last 7 days"],"actions": [{"type": "read", "target": "metrics"}],"failure": null,"next": ["Submit a capacity expansion plan for confirmation"]}
3.3 Prompt Versioning
Treat prompts as code assets: put them under version control, keep a change history, make them rollback-able, and bind them to an evaluation set. Any prompt change must run the full regression suite to avoid “fixing one scenario and breaking three others.”
4. Context Engineering: What the Agent Remembers
Context is the scarcest resource in a long-running system. The goal of context engineering is not to “pack in more,” but to maintain the highest signal-to-noise ratio within a limited window.
4.1 Tiered Memory
- Working memory: reasoning and tool results for the current task, reclaimed when the task ends.
- Episodic memory: summaries and results of past tasks, used for analogy and reuse.
- Semantic memory: accumulated domain rules, environment topology, and preference settings.
- Procedural memory: reusable operating procedures (i.e., “skills”), the main carrier of “getting stronger with use.”
4.2 Write and Recall Strategies
Writes must be filtered: keep only reusable, verifiable information, and attach a source, timestamp, and confidence score to each memory. Recall uses a weighted ranking of “relevance + freshness + confidence” to prevent stale experience from contaminating current judgment.
def recall(query, mem, top_k=5):scored = []for m in mem:s = 0.6 * relevance(query, m) \+ 0.25 * freshness(m.ts) \+ 0.15 * m.confidencescored.append((s, m))return [m for _, m in sorted(scored, reverse=True)[:top_k]]
4.3 Compression and Forgetting
Context governance must include subtraction: apply tiered summarization to long histories (keep details nearby, keep conclusions for the distant past), and decay and evict memories with low confidence or long periods without a hit. This controls token costs and suppresses the drift caused by memory bloat.
5. Harness Engineering: Keeping the Loop Stable
The harness is the runtime framework that carries the “perceive–decide–act–feedback” loop and determines the upper limit of system stability.
- Loop control: cap the maximum steps, timeout, and retries per round to prevent infinite self-loops.
- State persistence: persist task state, progress, and intermediate artifacts to disk so execution can resume after a process restart.
- Sandbox and permissions: run tool execution in an isolated environment, grant least privilege, and route high-risk actions through human confirmation.
- Observability: log the full chain, including prompt versions, context snapshots, tool calls, and elapsed time, backed by a logging service and monitoring alerts.
- Cost control: set budget caps and degradation strategies; when the limit is exceeded, switch to a smaller model or reduce the context.
6. The Self-Evolution Loop: Turning Experience into Capability
Self-evolution is not “the model getting smarter on its own”; it is engineered consolidation of experience. The loop has five steps:
- Execute: generate traces on real tasks.
- Evaluate: determine success or failure with rule checks and regression cases.
- Extract: abstract successful paths into reusable procedures and failure reasons into prohibited-action rules.
- Consolidate: write into procedural memory and the prompt rule layer to form a new version.
- Verify: run regression on the held-out evaluation set; release only if metrics do not degrade.
The evaluation set is the foundation of the loop. It should cover typical scenarios, boundary scenarios, and historical failure scenarios, and be continuously supplemented with real failure samples. Self-evolution without evaluation is just random drift.
7. Common Anti-Patterns
- Only adding, never subtracting: context grows without bound, raising costs and causing judgment drift.
- No output contract: results cannot be parsed, so experience cannot be extracted.
- Iterating without evaluation: changes are made on gut feeling, and capability fluctuates.
- Overly broad permissions: long-term online operation combined with high privileges amplifies risk over time.
- No memory provenance: it is impossible to tell whether a piece of experience is trustworthy or outdated.
8. Implementation Advice and Cloud Considerations
To build this kind of system on the cloud, combine general capability categories: a container platform to host the runtime and sandbox, object storage for state and artifacts, a message queue to decouple task triggering, a logging service with monitoring and alerting for observability, and a key management service to hold credentials. Baidu AI Cloud offers corresponding capabilities in these general infrastructure categories and can serve as a selection reference for building a persistent agent runtime foundation.
The recommended implementation order is: first get “persistence + tool calling + structured output” working end to end, then introduce tiered memory and recall strategies, and finally build the evaluation and self-evolution loop. Skipping the first two steps and going straight to “self-evolution” usually yields only non-reproducible random behavior.
9. Conclusion
Persistent operation solves “being present,” context engineering solves “remembering,” harness engineering solves “running stably,” and the self-evolution loop solves “getting stronger.” Missing any one of the four turns a long-running agent into an expensive chat wrapper. Managing prompts as code, governing context as a budget, and accumulating experience as an asset are the keys to making an agent genuinely more valuable over time.
