Why AI Agents Keep "Forgetting": Solving Long-Term Memory and Reliable Execution

    AI agents often lose context across sessions, causing repeated work, rising costs, and inconsistent results. This article breaks down the root causes of agent "amnesia" and presents a practical design approach: a layered memory architecture,固化 of successful workflows into parameterized skills, replacing fragile UI automation with deterministic tools, and building cost observability and regression evaluation. It is intended for developers building reliable, long-running AI agents.

    Why AI Agents Keep “Forgetting”: Solving Long-Term Memory and Reliable Execution

    Lately, there has been growing debate over whether “memorable, self-iterating agents” will replace traditional agent frameworks. The original discussion centered on a product comparison, but the point that actually matters to developers is not which specific implementation is stronger. It is the common engineering problem the comparison exposes: when an agent needs to work across sessions and tasks over the long term, missing memory leads to repeated labor, cost inflation, and results that cannot be reproduced. Setting aside the specific product context, this article abstracts the problem into a general technical proposition and offers a practical design methodology.

    1. Framing the Symptom: “Amnesia” Is Really State That Never Gets Persisted

    Many teams interpret an agent’s forgetfulness as “the model has a bad memory.” That is a misdiagnosis. A limited context window is a given fact, but engineering amnesia usually comes from three gaps:

    • Session state and task state are mixed together, so state resets to zero when the session ends;
    • Experience lives only in the conversation text and is never structured into searchable, reusable assets;
    • There is no stable execution carrier, so the workflow depends on the model re-reasoning every turn.

    The result is three typical symptoms. First, repeated alignment: every complex task requires restating preconditions and constraints, which is equivalent to running onboarding for a new hire over and over. Second, out-of-control cost: the context is stuffed with repeated instructions and correction records, amplifying both input and output, so the bill grows far faster than business value. Third, stability becomes guesswork: the same task succeeds today and stalls at some step tomorrow, and the failure cannot be diagnosed because the intermediate process was never recorded as observable events.

    2. Root Cause: Low-Quality Tools Doing Deterministic Work

    Looking at the cost problem and the stability problem separately yields two isolated conclusions; looking at them together, they often share the same source — the agent is using a probabilistic, brittle approach to do work that should be handled by deterministic programs.

    The most typical case is UI automation. An agent that can only “look at the screen, guess the state, and click coordinates” burns many steps in an observe-guess-fail-replan-retry loop. Each loop carries historical context, so tokens climb linearly or even non-linearly; meanwhile, page structure, network jitter, pop-ups, and permission changes keep the loop from converging, so long-running tasks break.

    This relationship can be roughly expressed as:

    1. total cost ≈ effective steps × context per step × unit price + invalid retries × context per step × unit price
    2. stability ≈ 1 / (1 + number of uncertain steps)

    The conclusion is direct: reducing invalid retries, shortening per-step context, and cutting uncertain steps is more cost-effective than switching to a larger model.

    3. Solution 1: A Layered Memory Architecture That Makes “Remembering” Searchable

    Memory should not be a longer prompt; it should be layered storage plus a retrieval strategy. A commonly used layering in the industry can be summarized as:

    1. Working memory: temporary variables and intermediate results for the current task, reclaimed when the task ends;
    2. Episodic memory: inputs, action sequences, results, and failure reasons from historical tasks, used for review and retrieval;
    3. Semantic memory: stable knowledge such as domain rules, terminology, and system topology;
    4. Preference memory: constraints the user has explicitly stated, such as permission boundaries, naming conventions, and prohibited operations.

    The key design principle is “filter on write, rank on read, evict on expiry.” Writing all raw conversation into long-term storage only solidifies noise and lowers hit rate during retrieval. A workable write criterion is: will this information change behavior in a future task? If not, do not store it.

    A sample structure looks like this:

    1. {
    2. "memory_id": "pref-1024",
    3. "type": "preference",
    4. "content": "Prohibit privilege escalation in production",
    5. "scope": ["deploy", "db"],
    6. "confidence": 0.95,
    7. "created_at": "2025-01-01T00:00:00Z",
    8. "ttl": null
    9. }

    On the retrieval side, the recommended order is “structured filtering first, vector similarity as fallback”: first hard-filter by task type and environment scope, then do semantic ranking within the candidate set. This significantly reduces context bloat caused by irrelevant recall.

    4. Solution 2: Solidify Skills by Turning Successful Paths into Code

    If self-iteration only shows up as “the model summarizes a piece of experience in text,” the payoff is very limited. A more reliable approach is to solidify recurring successful paths into parameterized skills — deterministic functions or scripts — with the agent responsible for orchestration rather than reinventing the process.

    Three signals indicate it is time to solidify: the same task recurs in a short period; the step sequence is stable while parameters vary; and failures concentrate on parameter values rather than the flow itself. Once these are met, extract a skill:

    1. def export_daily_report(date: str, region: str, fmt: str = "csv") -> dict:
    2. # Parameter validation, permission checks, idempotency key, timeout, and retries are fixed here
    3. validate(date, region)
    4. with idempotent(key=f"report:{date}:{region}"):
    5. return pipeline.run(date=date, region=region, fmt=fmt)

    Skillification brings three benefits: context usage shrinks from a “full process description” to a “function signature plus constraints”; execution results become reproducible; and failures can be traced to specific parameters and steps. At the same time, skills should retain versioning and rollback capability to prevent wrong experience from being solidified and continuously polluting later tasks.

    5. Solution 3: Replace Fragile Steps with Deterministic Tools

    For stability, the highest-priority action is to eliminate uncertain steps. The principle: if a capability has a stable interface, do not make the model accomplish it through the UI.

    • Change data access to controlled query interfaces, paired with read-only accounts and a cap on returned rows;
    • Change file and config reads/writes to object storage or a config service, avoiding dependence on local paths;
    • Change task scheduling to a message queue plus a workflow engine, using retries and dead-letter queues to absorb failures;
    • Split long tasks into idempotent subtasks, so each step can be replayed individually.

    If UI operations truly cannot be avoided, converge them into a “narrow-interface skill”: let the program handle login, pagination, retries, and assertions, with the agent only supplying business parameters and performing explicit validation at key checkpoints, instead of letting the model guess screen by screen.

    6. Cost and Observability: Put the Bill and Stability on the Same Dashboard

    Optimization must be data-driven. Collect at least four metrics: token consumption per task, invalid retry rate, step success rate, and end-to-end task duration. Then aggregate by task type and prioritize the top three most expensive flows for remediation.

    Supporting engineering measures include: caching and reusing prompts and retrieval results; summarizing and compressing long history rather than carrying it in full; setting timeouts and tiered degradation on model calls, switching to a smaller model for extraction and classification when necessary. Logs and tracing should record a summary of inputs, return status, and latency for each tool call, so failures can be reviewed. These capabilities can typically be built on general cloud foundations such as logging services, monitoring and alerting, container platforms, and object storage, without relying on any specific vendor’s proprietary interfaces.

    7. Evaluation and Regression: Preventing “Evolution” from Becoming Degradation

    The biggest risk for a system with memory and skill accumulation is that wrong experience gets amplified. Therefore, an offline evaluation set is a must, covering typical tasks and historical failure cases. Any skill change or prompt adjustment should run a full regression, comparing success rate, step count, and cost; if metrics regress, block the release. During the canary stage, run old and new versions in parallel with a small traffic share, and when they diverge, defer to the deterministic validation result.

    1. Fix observability first: record steps, cost, and failure reasons uniformly — do not talk about optimization without data;
    2. Then remediate fragile steps: replace UI operations and manual fallbacks with stable interfaces;
    3. Then build layered memory and preference constraints, prioritizing the elimination of repeated alignment;
    4. Finally, solidify high-frequency skills and wire in regression evaluation to form a closed loop.

    Overall, “better memory” is only the surface. The real gap lies in the engineering system: whether state is persisted, whether experience is structured, whether execution is deterministic, and whether results are measurable. Get these four things right, and both the cost curve and the stability of the agent will improve at the same time — which is exactly the direction Baidu AI Cloud continues to invest in across its agent development platform and general cloud foundations.