Agent Memory and Self-Evolution: A Practical Engineering Guide

    This guide explains how to build AI agents that retain state across sessions and improve over time. It covers a three-layer memory architecture (short-term, long-term, and skill memory), the real bottleneck of low-quality tool calls, rules for writing and forgetting memory, and the observability metrics and cost controls needed to operate these systems reliably.

    1. The Starting Problem: Why Agents Keep “Rediscovering the World”

    A topic that has drawn heavy discussion in technical communities is agent systems with persistent memory and self-iteration capabilities. The core of the discussion is not any specific implementation, but a common engineering problem: most agents lack stable state continuity across sessions and tasks, behaving as if they “start from zero every time.”

    This gap leads to three direct consequences.

    The first is duplicated work. Preconditions, constraints, and prior decisions for complex tasks must be restated repeatedly, which significantly increases interaction costs. The second is uncontrolled resource consumption. The context window fills up with repeated instructions and corrections, reasoning and trial-and-error cycles multiply, and the bill grows accordingly. The third is unpredictable stability. The same task produces inconsistent results at different times, failure causes are hard to isolate, and operations and debugging costs are high.

    It is worth stressing that “having memory and evolving” is not a product slogan, but a set of engineering capabilities that can be decomposed, measured, and optimized. The sections below break these capabilities down by layer.

    2. A Three-Layer Memory Architecture: From Context to Skills

    1. Short-Term Memory: In-Session State Management

    Short-term memory addresses state retention during a single task execution. Typical contents include the current goal, completed steps, key intermediate results obtained so far, and hypotheses awaiting validation. In engineering terms, this is usually represented as a structured task state object rather than a pile of natural language.

    1. {
    2. "task_id": "t-20260812-001",
    3. "goal": "Generate monthly metrics summary",
    4. "constraints": ["no high-privilege operations", "read-only access to data sources"],
    5. "done": ["data source located", "field definitions confirmed"],
    6. "artifacts": ["schema_snapshot.json"],
    7. "next": ["run aggregation", "validate total consistency"]
    8. }

    The key point is that state must be serializable and versionable so it can be restored after an interruption, instead of relying on the model to “remember.”

    2. Long-Term Memory: Cross-Session Knowledge Retention

    Long-term memory targets information that will be needed again later, such as user preferences, environment constraints, data dictionaries, and conclusions from past incident handling. It should not be a full archive of conversations, but filtered, structured entries. Each entry should contain at least its scope of applicability, confidence, source, and timestamp.

    For retrieval, the industry commonly uses a hybrid strategy combining vector search and keyword search. Vector search excels at recalling semantically similar content, while keyword search guarantees exact matches for proper nouns, field names, and error codes. With semantic recall alone, misuse tends to occur where “the meaning is close but the target object is wrong.”

    3. Skill Memory: Turning Successful Paths into Reusable Capabilities

    A skill is the highest form of memory: abstracting a successful operation sequence into a callable unit with parameters, precondition checks, and failure rollback. Compared with “remembering a prompt,” the value of a skill lies in determinism—the same input produces the same execution path.

    A simplified skill description example:

    1. skill: aggregate_metrics
    2. preconditions:
    3. - read_only_credential_available
    4. - schema_version_confirmed
    5. steps:
    6. - validate_schema
    7. - run_aggregation
    8. - reconcile_total
    9. rollback: drop_temp_view

    3. The Real Bottleneck: Low-Quality Tool Calls

    Many systems appear “smart” on the surface, but in practice spend a great deal of time in a loop of “observe the interface—guess the state—attempt an operation—discover a failure—replan.” Browser automation is a typical example: page structure changes, element state jitter, and popup repositioning can all push a workflow into repeated trial and error.

    Such trial and error is not free. It causes two consequences at once: first, token and compute consumption rises; second, long-running processes are more prone to interruption, disconnection, and crashes. In other words, the widely criticized “high cost” and “poor stability” often share the same root cause—using low-determinism tools to accomplish tasks that should be handled by deterministic interfaces.

    The alternative is to define clear tool layers:

    • Deterministic layer: data queries, aggregation, file reads and writes, and task scheduling, completed through stable interfaces with verifiable results;
    • Semi-deterministic layer: parsing of structured pages and interactions over fixed protocols;
    • Probabilistic layer: visual recognition, natural language understanding, and fuzzy matching, used only where necessary, with confidence thresholds and human fallback.

    Only when the probabilistic layer’s output falls below the threshold should escalation to multi-step exploration be allowed. This constraint can significantly compress ineffective loops.

    4. Writing and Forgetting Memory: Quality Sets the Ceiling

    More memory is not necessarily better. Incorrect memories get reused repeatedly and form systematic bias. Viable engineering constraints include:

    1. Write threshold: a path may be solidified into a skill only when the task succeeds and the result passes validation;
    2. Conflict handling: when a new entry conflicts with an old one, the retention policy is decided by source reliability and time decay;
    3. Scope isolation: global memory, project memory, and session memory are layered to avoid cross-project contamination;
    4. Periodic forgetting: entries that go unmatched for a long time or have low confidence are archived or deleted to control retrieval noise.

    Illustrative logic:

    1. def should_store(entry, memory):
    2. if not entry.verified:
    3. return False
    4. conflict = memory.find_conflict(entry)
    5. if conflict and conflict.confidence > entry.confidence:
    6. return False
    7. return entry.scope in memory.scopes

    5. Observability and Cost Control

    Making memory and evolution operable requires a supporting metrics system. At minimum, collect per-task token consumption, number of tool calls, number of failed retries, skill reuse rate, memory hit rate, and task interruption rate. Among these, “skill reuse rate” and “memory hit rate” are the two core indicators for judging whether evolution is actually happening; if both stay low over time, the retention mechanism is effectively useless.

    For cost control, common practices include context compression and summarization, injecting retrieval results on demand rather than in full, pushing deterministic computation down to query and compute engines, and setting segmented checkpoints for long tasks. In the cloud, object storage can typically hold state snapshots, message queues can decouple tasks, container platforms can host execution sandboxes, and logging and monitoring services can handle tracing and threshold alerts. Baidu AI Cloud offers corresponding product categories for these general capabilities that can be combined as needed, but the specific selection should still be based on your own workload characteristics.

    6. Conclusion

    Whether an agent can escape having “a fish’s memory” depends on three things: whether state is structured and recoverable, whether knowledge is filtered and retrievable, and whether successful paths are solidified into deterministic skills. At the same time, compressing unstable probabilistic operations into the smallest possible scope is the fundamental way to improve cost and stability together. Memory and self-evolution do not replace engineering discipline; they are incremental capabilities built on top of tool layering, validation loops, and an observability system.