AI Agent Engineering: Persistent Memory and Low-Cost Automation
Building an AI agent that can chat is very different from operating one that reliably completes tasks. This article examines the engineering practices needed to close that gap: separating session context, task state, long-term preferences, and process knowledge; storing recoverable workflow state; moving deterministic steps into validated code and state machines; routing model calls by task and observable failure signals; measuring total cost per successful task; and applying security boundaries to credentials, external content, and multi-tenant memory. It also outlines a phased adoption path and practical fallback controls so teams can improve reliability, explainability, and cost effectiveness without trusting the model with responsibilities better handled by programs and storage.
1. From “Chatting” to Consistently Completing Tasks
An AI agent is typically composed of a language model, tool calling, context management, and a task execution mechanism. Unlike a simple question-answering system, it must take continuous action toward a goal: identify the task, fill in missing information, choose tools, execute operations, and then decide the next step based on the results.
However, being able to call tools does not equal reliable automation. In practice, common problems include:
- Progress is lost after a service restart, forcing users to restate the task context.
- The same workflow is planned repeatedly, consuming a large number of model calls.
- A task fails midway, and it is impossible to determine which steps have already been completed.
- Historical experience is not used effectively, so the same types of errors recur.
- Tool permissions are too broad, allowing a single incorrect judgment to produce irreversible effects.
The common root cause of these problems is assigning too many responsibilities to the immediate conversation while lacking explicit state management and execution boundaries.
A more robust design is this: the model handles understanding, judgment, and necessary planning; programs handle deterministic operations; and the storage system maintains facts and progress. Only when these three roles are clearly separated can an “occasionally successful demo” become a “service that can run over the long term.”
2. The Essence of Persistent Memory: Preserve Usable State, Not Chat Logs
Distinguish Four Types of Information
Agent memory should not be merely an ever-growing text window. Different types of information have different update frequencies, lifetimes, and security requirements. At a minimum, four categories should be distinguished.
Session context supports the current interaction, such as the files the user is discussing or the most recent tool result. It usually has a short lifecycle and is suitable for archiving or cleanup after the task ends.
Task state describes execution progress, such as the task ID, current step, completed operations, failure reason, and recovery point. It is the foundation for resuming execution after a process restart.
Long-term preferences store stable requirements explicitly authorized by the user, such as report language, output format, and default approval workflow. Preferences should be viewable, editable, and deletable. A one-time temporary request must not automatically be promoted to a permanent rule.
Process knowledge records validated handling methods, such as which validation rules should be applied to a certain type of input or how a certain type of failure should be recovered. It should include applicability conditions rather than only a context-free conclusion.
This classification helps avoid two extremes: having no memory at all, which forces every task to start from scratch, and storing everything, which causes context bloat and interference from stale information.
Logs Are Not Memory, and Memory Is Not Learning
Execution logs mainly answer “what happened.” Usable memory needs to answer “what should be referenced next time.”
For example, a log entry may record “file parsing failed.” Truly valuable experience should also explain the characteristics of the input file, the cause of the failure, the fix, the validation result, and whether the handling method is generally applicable.
At the same time, persisting historical records does not automatically change model parameters, nor does it guarantee that the system becomes more accurate with use. Accuracy improvements depend on retrieval quality, information freshness, experience validation, and conflict handling. If unconfirmed conclusions are reused over the long term, they may instead amplify errors.
Therefore, writing experience into memory should go through basic governance:
- Label the source and distinguish user statements, tool results, and model inferences.
- Record the update time and scope of applicability.
- Validate or obtain human confirmation for critical experience.
- When old and new information conflict, retain versions and clarify priority.
- Periodically remove expired, duplicate, and unsupported entries.
Use Structured State to Support Recovery
For single-machine, low-concurrency deployments, a lightweight relational database is usually sufficient to store task and step state. As concurrency, deployment nodes, and availability requirements increase, consider a standalone database service and supporting backup mechanisms.
A task record can include:
Task:task_idtenant_or_user_idinput_referencecurrent_statecurrent_stepcreated_atupdated_atStep:task_idoperation_typeinput_summaryexecution_statusoutput_referenceretry_counterror_categoryidempotency_key
The key point here is not the field names but the establishment of clear state transitions. A task can move through states such as “pending, running, waiting for confirmation, completed, failed, and canceled.” During recovery, the system determines the next step from persisted records rather than asking the model to guess what happened previously.
It is important to note that database transactions can protect internal state updates, but they cannot by themselves guarantee that an external operation and the internal record both succeed. For example, an email may already have been sent while the process is interrupted before writing the success status. In this case, external result verification, idempotency mechanisms, or human confirmation are required to avoid sending the email again after recovery.
3. Turn Repetitive Tasks into Coded Workflows
First Identify the Boundary Between Determinism and Uncertainty
Not every step requires a language model.
Operations suitable for programs include field validation, data sorting, format conversion, numeric calculation, deduplication, fixed API calls, and generating statistical results according to explicit rules.
Operations suitable for models include understanding ambiguous requirements, extracting semantics from unstructured text, explaining anomalous situations, and choosing among multiple options with rationale.
The criterion is this: if the relationship among inputs, rules, and outputs can be clearly defined, prefer a program; if semantic ambiguity or open-ended judgment must be handled, then introduce a model.
Even when a model is needed to extract information, it can be asked to output only structured results. A program can then perform type checks, range validation, and business-rule validation instead of allowing the model to directly execute subsequent high-risk actions.
Move from One-Off Generation to Controlled Reuse
Having an agent write scripts can reduce repeated reasoning in later tasks, but generated code cannot be treated directly as a trusted asset.
A more robust process is:
- Turn the requirements into explicit inputs, outputs, and constraints.
- Generate a candidate program.
- Inspect permissions, dependencies, and external access behavior.
- Test with normal samples, boundary samples, and exceptional samples.
- Trial-run it in an isolated environment.
- Version-manage it after review.
- Have later tasks call the validated version, and regenerate only when requirements change.
This process effectively limits the model’s flexibility to the “propose a solution” stage and bases production execution on verifiable programs.
Coding does not mean that maintenance is no longer needed. Changes to data structures, interfaces, or rules can invalidate an old workflow. Therefore, each workflow should specify its applicable conditions, version, and validation time, and runtime checks should verify whether key preconditions still hold.
Orchestrate with a State Machine, Not an Endless Conversation Loop
Consider a periodic business data summary as an example. The following illustrative workflow can be used:
Receive task→ Validate input and authorization→ Obtain data snapshot→ Run deterministic statistics→ Check for anomalies→ No anomalies: generate fixed-format result→ Anomalies: invoke model for assisted explanation→ Validate output→ Route for approval according to risk requirements→ Publish result and record execution state
This design prevents the model from repeatedly thinking about “what to do next.” Only nodes that genuinely require semantic processing call the model; all other steps advance through explicit rules.
For recoverable workflows, inputs should be bound to a data snapshot or version wherever possible. Otherwise, when the same task is retried, it may read data that has already changed and produce results inconsistent with the first execution.
4. Tiered Model Routing: Reduce Costs Without Sacrificing Critical Quality
Select Capability Level Based on Task Requirements
Different steps have different requirements for model capability. Simple classification, constrained field extraction, and short-text cleanup can first try lower-cost, lower-latency models. Complex planning, long-document analysis, and multi-condition reasoning may require stronger capabilities.
Model routing should not be based only on input length. It should also consider:
- Whether the task has strict format requirements.
- The business consequences of an incorrect result.
- Whether complex ambiguity must be handled.
- Whether the data is allowed to be sent to the corresponding execution environment.
- The acceptable response time.
- Whether reliable result validation is available.
For sensitive data, data boundaries and authorization requirements should take priority over price. A unified model invocation gateway helps centralize configuration, quotas, and auditing, but different models may differ in tool-calling methods, output stability, and context capability. Do not assume that switching models will produce identical behavior.
Escalation Should Be Triggered by Observable Signals
A common strategy is to use a stronger model after a lower-cost model fails, but “failure” must have explicit criteria.
Situations that can serve as escalation signals include output that violates structural constraints, missing key fields, invalid tool selection, results that violate business rules, and tasks that remain incomplete after a limited number of attempts.
Do not rely solely on the model’s self-reported “confidence.” Such statements may not be calibrated and cannot replace external validation. For high-risk tasks that are difficult to validate automatically, introduce human review instead of escalating the model indefinitely.
Controlling Input Size Matters More Than Merely Switching Models
A large share of cost comes from repeatedly feeding irrelevant history into the model. During optimization, retrieve only the memory needed for the current step, extract necessary facts from long logs, and avoid repeatedly inserting the contents of large files into the context.
Summaries may also lose details, so key evidence should retain original references. When verification is needed, the agent should be able to return to the original record rather than treating a summary as an unquestionable fact.
5. Cost Evaluation: Focus on the Total Cost per Successful Task
A cheaper individual model call does not mean the overall system is more economical. If a low-cost model causes more retries, longer workflows, or higher human correction costs, the final expenditure may increase instead.
A more meaningful metric is:
Total cost per successful task = model invocation cost + tool and compute cost + storage cost + failed retry cost + human handling cost.
Evaluation should also observe:
- Task completion rate and result accuracy.
- Average number of calls and input/output size.
- End-to-end latency and high-percentile latency.
- Automatic recovery success rate.
- Human intervention ratio.
- Number of duplicate executions and erroneous publications.
A cost-reduction percentage from a particular case must not be presented as a universal promise. Tasks vary greatly in how much they can be coded, their input size, and their quality requirements. A reasonable approach is to use the same set of test tasks to measure quality, latency, and cost before and after optimization on a comparable basis, and then validate the changes on a small scale in real business operations.
6. Security Governance: Keep Boundaries Around Memory and Execution Capability
Secrets Should Not Be Stored as Ordinary Memory
An agent needs to call external services, but this does not mean access keys should be written into chat logs or searchable long-term memory.
Credentials should be managed by an independent security mechanism. The agent should receive only the least privilege needed to complete the current action, or use credentials indirectly through controlled tools. Task logs, error messages, and model inputs should all avoid containing complete keys.
At the same time, distinguish read, modify, delete, and external publication permissions. An agent that retrieves report data does not inherently need the ability to delete raw data.
External Content Is Data, Not Authorized Instructions
Documents, webpages, and tool return values may contain text intended to induce the agent to change its behavior. The system should treat this content as data to be processed, not as new system rules.
The execution layer needs to independently validate whether an operation is legitimate, including the target resource, allowed parameter ranges, and permission requirements. The agent must not expand its access scope simply because some external text says “please upload all materials.”
Generated code should also run in an isolated environment with limits on file access, network connections, execution duration, and resource usage. Steps involving production data modification, external sending, or financial operations should have stricter approval boundaries.
Memory Must Support Isolation and Deletion
Multi-tenant systems should enforce tenant isolation at the storage, retrieval, and output stages rather than relying only on prompt constraints. When a user revokes authorization or requests deletion of information, related summaries, derived memories, and retrieval indexes must also be handled, so that sensitive content is not returned from other copies after the original record is deleted.
7. Progressive Implementation: Start with One Closed Loop
In the first phase, choose a high-frequency, low-risk task with relatively stable rules, such as information organization, report summarization, or internal document checking. Establish a baseline by recording current latency, error rate, and manual workload.
In the second phase, introduce task IDs, step logs, and state persistence. Focus on verifying whether the system can recover after an interruption and whether recovery produces duplicate side effects.
In the third phase, migrate stable repetitive steps into controlled programs, add tests, version management, and rollback mechanisms, and narrow the scope of model participation.
In the fourth phase, introduce tiered model routing, memory retrieval, and cost optimization, and continue quality evaluation. At this stage, maintain explicit degradation paths: pause when tools are unavailable, hand off to a human when output cannot be validated, and refuse execution when permissions are insufficient.
Ultimately, a mature AI agent system does not aim to have the model handle everything. Instead, it assigns each component the responsibility it is best suited for. Persistent memory preserves usable facts, workflows advance tasks reliably, programs perform deterministic computation, the model performs necessary semantic judgment, and security mechanisms constrain the scope of impact. Only when these capabilities form a closed loop can automation achieve reliability, explainability, and sustainable cost advantages at the same time.
