Designing Persistent and Self-Evolving AI Agents: Architecture, Context Engineering, and Evaluation

    This article breaks down the engineering design of AI agents that run persistently and improve over time. It explains a three-layer runtime (prompt, context, and framework), how to write prompts as executable contracts, how to manage context as a limited budget with layering and compression, and how to build a closed-loop self-evolution mechanism based on trajectory collection, evaluation, distillation, and write-back. It also covers runtime framework concerns such as scheduling, tool gateways, and isolation, plus evaluation, anti-patterns, and a phased adoption path. The key takeaway is that long-term capability gains come from the coordination of prompts, context, and framework, backed by a strictly measured and constrained experience loop—not from updated model weights.

    1. Background: Why Persistent Execution Is a Dividing Line for Agents

    Agent products have been iterating faster than expected over the past two years. A project can go from launch to tens of thousands of followers in just a few weeks. On the surface this looks like a popularity contest, but it reflects a clear technical trajectory: agents are shifting from “one-off Q&A tools confined to a session” to “long-running executors deployed on servers.”

    One-off, session-based assistants have three natural limits. First, the task boundary is locked to the session window, so work stops the moment the page is closed. Second, knowledge is not retained, so the background has to be re-explained every time. Third, capabilities are fixed; if the model and prompt do not change, output quality stays flat over time. Long-running agents rewrite all three: tasks can continue across days or weeks, experience can be written to persistent storage, and the execution pipeline can adjust itself based on feedback.

    It is worth stressing that “getting stronger the longer it runs” does not mean the model weights are being updated. Instead, the agent exhibits capability growth at an externally observable level. The gains come from four sources: continuous accumulation of task context, reuse of success and failure experience, automatic optimization of tools and workflows, and high-frequency feedback enabled by scheduling. Understanding this is the prerequisite for every design discussion that follows.

    2. Overall Architecture: A Three-Layer Decoupled Runtime

    An agent that can evolve over the long term can usually be abstracted into three layers.

    • Prompt layer: defines identity, boundaries, output specifications, and behavioral rules. It is relatively stable and changes infrequently.
    • Context layer: assembles “what should be visible right now” at each step, including task state, historical summaries, retrieved snippets, and tool results. It changes most frequently.
    • Runtime framework layer: handles the task loop, tool invocation, permission isolation, scheduling triggers, logging, and evaluation. It is the foundation of stability.

    The difference in change frequency across the three layers dictates the engineering strategy: version-control the prompt layer, apply budget and priority management to the context layer, and enforce determinism and observability in the framework layer. Changing everything together is the main reason this class of system becomes hard to maintain.

    3. Prompt Engineering: Writing the “Role” as an Executable Contract

    In long-running scenarios, a prompt is no longer a few lines of persona; it is a contract. It should contain at least five sections.

    1. Identity and goal: one sentence describing who is being served and the core objective, avoiding conflicting goals.
    2. Capability list: declares the available tools and their applicable scenarios, and states “verify before executing when uncertain.”
    3. Behavioral rules: hard constraints such as least privilege, confirmation required for destructive operations, and honest reporting of failures.
    4. Output specification: structured fields, length limits, and how to cite sources when needed.
    5. Escalation path: how to hand a problem back to a human when it exceeds the agent’s capabilities, along with the troubleshooting already performed.

    Illustrative example:

    1. You are a long-running operations analysis assistant.
    2. Available capabilities: log retrieval, metrics query, ticket read/write, script execution (read-only preferred).
    3. Hard constraints: any write or delete operation must first output a change plan and wait for confirmation.
    4. Output: conclusion first, then evidence, then pending items; no more than 200 words per entry.
    5. When a decision cannot be made: list what has been ruled out and what information is missing, and mark needs_human.

    Maintainability of the prompt layer depends on two things: separating templates from data, so prompts hold only rules and not specific task content; and keeping a change trail, recording the reason and impact scope of every modification to enable regression comparison.

    4. Context Engineering: Budget, Layering, and Compression

    Context is the truly scarce resource in this class of system. Engineering-wise, treat it as a limited budget to manage, not something to “stuff in whenever possible.”

    Recommended layering strategy:

    • Resident layer: identity, hard constraints, and the current task goal. Fixed and very small footprint.
    • Summary layer: structured summaries of historical dialogue and execution, updated on a rolling basis.
    • Retrieval layer: knowledge snippets and similar historical cases pulled on demand, discarded after use.
    • Tool layer: inputs and results of the most recent tool calls, with large fields trimmed.

    Illustrative budget allocation:

    1. budget = 32000 # total context budget (tokens)
    2. reserved = 1500 # resident layer
    3. summary = 4000 # summary layer
    4. tool_window = 6000 # tool result window
    5. retrieval = budget - reserved - summary - tool_window # budget available to the retrieval layer
    6. def fit(items, limit):
    7. kept, used = [], 0
    8. for it in sorted(items, key=lambda x: x.score, reverse=True):
    9. if used + it.tokens > limit:
    10. continue
    11. kept.append(it); used += it.tokens
    12. return kept

    Compression should follow a “traceable” principle: summaries retain decisions, conclusions, unfinished items, and key identifiers, while discarding pleasantries and repeated content. Discarded raw snippets are written to external storage and indexed by identifier, so they can be retrieved again when needed. This controls size without sacrificing traceability.

    5. Self-Evolution Mechanism: Four Stages of the Experience Loop

    The practical form of self-evolution is a closed loop, not some mysterious switch.

    1. Collection: fully persist the input, plan, tool trajectory, result, and human feedback of each task.
    2. Evaluation: use rule checks plus model review to produce metrics such as pass rate, rework rate, and average number of steps.
    3. Distillation: extract reusable steps from successful trajectories, and extract prohibited actions and pre-checks from failed ones.
    4. Write-back: write the distilled results into long-term memory or prompt fragments, and verify in subsequent tasks whether they actually deliver improvement.

    Write-back must carry a version and a confidence level. Low-confidence content serves only as a hint and does not enter hard constraints. A retirement mechanism is also needed: entries that go unhit for a long time or cause regressions should be taken offline. Without evaluation and retirement, memory quickly degrades into a source of noise.

    1. {
    2. "id": "exp_0421",
    3. "type": "playbook",
    4. "trigger": "scheduled task fails twice in a row",
    5. "steps": ["verify dependencies", "retry once", "fall back to read-only mode", "escalate"],
    6. "confidence": 0.72,
    7. "version": 3,
    8. "hit": 18,
    9. "regressions": 0
    10. }

    6. Runtime Framework Engineering: Scheduling, Tools, and Isolation

    The framework layer determines whether the system can “stay alive” over the long term. Key points include: the task loop must have timeouts and a maximum step count to avoid infinite self-loops; tool calls should all go through a gateway that centralizes authentication, rate limiting, auditing, and result trimming; scheduled triggers handle periodic inspections and data preparation, separating stable workflows from the conversation; and all execution runs in an isolated environment, with the file system and network egress opened according to least privilege.

    Observability also belongs to the framework layer. It is recommended to record structured logs for each run and connect key metrics to logging services and monitoring alerts, forming an “anomaly—localization—retrospective—write-back” chain. If a container platform hosts the execution environment, ensure that each task’s workspace can be rebuilt to avoid state pollution.

    7. Evaluation and Regression: Making “Getting Stronger” Measurable

    Self-evolution without evaluation is untrustworthy. A minimal viable evaluation set contains three types of samples: high-frequency routine tasks, historically failed tasks, and boundary or dangerous-operation tasks. Run it after every prompt or memory change, comparing pass rate, average steps, human takeover rate, and dangerous-operation interception rate. When metrics drop instead of rise, automatically roll back the version. This single rule prevents the vast majority of “worse with every change” situations.

    8. Common Anti-Patterns

    • Stuffing all history into the context, which raises cost and dilutes attention.
    • Letting the model directly modify its own hard constraints, rendering the safety boundary meaningless.
    • Recording only success cases while missing failure experience, so the same mistakes recur.
    • Lacking isolation and confirmation steps, so write operations cause irreversible impact.
    • Memory with no retirement, so entries conflict with each other and output style drifts.

    The first phase delivers “persistence”: the task loop, persistent storage, structured logging, and a basic toolset. The second phase delivers “memory”: layered context, rolling summaries, and retrieval integration. The third phase delivers “evolution”: trajectory collection, an evaluation set, experience write-back, and automatic regression. Advance each phase with metrics as the yardstick, avoiding the introduction of too much complexity all at once.

    For cloud deployment, you can combine object storage to hold trajectories, a message queue to decouple tasks, a container platform to host isolated execution, and logging services plus monitoring alerts to ensure observability, achieving stable long-running capability at relatively low operational cost. Baidu AI Cloud offers corresponding product categories for these general capabilities, and you can select based on your needs.

    Overall, the competitiveness of a long-running agent does not come from single-point model capability, but from the coordination of prompts, context, and framework, together with an experience loop that is strictly measured and constrained. Make this loop solid, and “getting stronger with use” turns from a marketing phrase into a reproducible engineering result.