Agent Engineering in the Recursive Self-Improvement Era: Memory, Steerability, Model Routing, Cost, and Evaluation
As general-purpose LLM releases accelerate, agent systems must absorb capability upgrades without quality or cost regressions. This article presents practical engineering patterns for recursive self-improvement in agent systems: structured experience memory with write validation and constrained recall; steerability and rollback for human takeover; tiered model routing by risk and complexity; token- and cache-aware cost estimation; and a task-specific evaluation suite. It also covers governance risks such as behavior drift, privacy, permission boundaries, and auditability, plus an implementation sequence.
I. Background: Engineering Pressure from Accelerating Model Releases
Over the past year or two, version updates for general-purpose large models have clearly accelerated. For engineering teams, a new version usually means improvements in reasoning, long-task execution, and instruction following. It also means that API behavior, billing structure, and performance boundaries may change. If a system treats the behavior of a particular model version as a fixed premise, version changes can easily lead to quality fluctuations, cost overruns, and similar problems.
Teams therefore need to answer three questions: how can the system automatically benefit when model capabilities improve; what model scale should different tasks use; and how can reproducible metrics determine whether an upgrade is worthwhile. The following sections are organized around these three questions, with a focus on practices that can be implemented in engineering.
II. What Is Recursive Self-Improvement?
Recursive self-improvement (RSI) means that a system uses feedback from its own execution results to optimize subsequent decision strategies and then applies those optimizations to the next round of execution, forming a loop. The concept has a long history in AI research. In current agent systems, its meaning is more concrete.
In engineering practice, self-improvement can occur at three layers:
- Prompt layer: Adjust system instructions, task templates, and checklists based on historical failure cases.
- Memory layer: Write successful and failed experiences into structured storage and recall them on demand in later tasks.
- Model layer: Update model parameters through fine-tuning or training.
Most teams can reliably implement the first two layers. The third layer requires large amounts of data, compute, and compliance review. It is costly, takes a long cycle, and its risks are difficult to fully predict in advance. This article focuses on the prompt and memory layers.
III. Experience Memory: Let the System Remember Why It Failed
Saving conversation history alone does not amount to an improvement capability. Effective experience memory needs to satisfy three conditions: structured experience, a write threshold, and relevant recall.
3.1 Structured Records
Each experience record should include at least the following fields: task type, input feature summary, execution path, failure reason, corrective action, and whether it has been validated. Structured fields make it easier to retrieve by task type and to perform statistical analysis later.
3.2 Write Threshold
Bad experience can pollute later decisions, so it must be validated before being written. Common approaches include using rules to check whether a corrective action passes regression tests, or having humans review high-risk categories of experience. Unverified content can only be stored in a temporary area and must not enter long-term memory.
3.3 Relevant Recall
The recall stage usually combines task-type filtering with semantic similarity ranking. The number of recalled items must be controlled. Too much historical experience consumes the context window and may interfere with the current task. In practice, recalling three to five experiences per task is common.
3.4 Example Implementation
from dataclasses import dataclass, fieldfrom datetime import datetime@dataclassclass Experience:task_type: strfeature_summary: strfailure_reason: strfix_action: strverified: bool = Falsecreated_at: datetime = field(default_factory=datetime.now)class ExperienceStore:def __init__(self) -> None:self._items: list[Experience] = []def add(self, item: Experience) -> None:if not item.verified:raise ValueError("Unverified experience cannot be written to long-term memory")self._items.append(item)def recall(self, task_type: str, limit: int = 3) -> list[Experience]:hits = [e for e in self._items if e.task_type == task_type]hits.sort(key=lambda e: e.created_at, reverse=True)return hits[:limit]
In production, _items should be replaced with a database or vector index, with expiration and eviction policies added. If an experience has not been hit for a long time, or conflicts with the behavior of the latest version, it should be downweighted or deleted.
IV. Steerability and Correction: Let Humans Take Over Execution
Self-improvement does not mean full autonomy. For multi-step tasks, the system should support human intervention during execution. This capability is often called steerability.
Implementation can focus on the following points:
- Checkpoint mechanism: Pause before key steps, show the plan and intermediate results, and wait for confirmation before continuing.
- Rollback-capable operations: Record the pre-change state of files, configurations, or database modifications so they can be undone.
- Immediate effect of corrective instructions: After a user gives a correction, the system should follow it in subsequent steps and convert the correction into an experience record.
- Fabrication rate monitoring: Track the proportion of factual statements in outputs that cannot be traced back to a source, and use it as a long-term quality metric.
The value of correction capability lies in shortening the error propagation chain. If a task deviates at step two but is only discovered at step three, the repair cost is usually much higher than if it had been intercepted at step two.
V. Tiered Model Routing: Allocate Resources by Task Difficulty
Different tasks have very different requirements for reasoning depth, response speed, and cost. Sending every request to the strongest model is expensive; sending every request to a lightweight model increases the failure rate on complex tasks. Tiered routing is a common compromise.
Tasks can be divided into three tiers:
- Deep tasks: Involve multi-file changes, complex reasoning, or high-risk operations. They are suitable for the model with the strongest reasoning capability and allow a larger number of execution steps.
- Standard tasks: Have a moderate number of steps and clear rules, such as code review, document generation, and data cleaning. A balanced model is sufficient.
- High-frequency lightweight tasks: Such as classification, format conversion, and simple question answering. Use a small model and prioritize low latency and low cost.
Routing policies can be rule-based or based on a lightweight classifier. A rule-based approach is simple and transparent, making it suitable for the early stage.
TIERS = {"deep": {"model_alias": "reasoning-large", "max_steps": 30},"standard": {"model_alias": "balanced-mid", "max_steps": 12},"light": {"model_alias": "fast-small", "max_steps": 4},}def route(task: dict) -> str:risk = task.get("risk", "low")steps = task.get("steps_estimate", 1)frequency = task.get("frequency", "low")if risk == "high" or steps > 15:return "deep"if frequency == "high" and steps <= 4:return "light"return "standard"
Note that model_alias should use an internal alias rather than hard-coding a specific version number. This way, when a model is upgraded, only the mapping needs to change, not the business code.
VI. Cost Accounting: Combined Calculation of Input, Output, and Cache
The cost of large models usually consists of input tokens and output tokens. Some platforms also offer cached billing for repeated prefixes, where input that hits the cache is charged at a lower unit price. Cost estimation therefore cannot rely only on total token count.
The following usage categories should be distinguished during estimation:
- Fresh input tokens (cache misses)
- Cached input tokens
- Output tokens
The convenience of long-context capabilities does not mean that historical information can be stacked without limit. The longer the context, the larger the input volume per request. If the cache hit rate is low, costs can grow quickly. Common controls include summarizing historical conversations, keeping only fragments relevant to the current task, and placing stable system instructions at the front of the request to improve prefix cache hit rates.
def estimate_cost(input_tokens: int,output_tokens: int,cached_tokens: int,price_per_million: dict,) -> float:"""price_per_million should be supplied by the caller from the provider's price list.It contains input, cached_input, and output fields in the same units as the price list."""if cached_tokens > input_tokens:raise ValueError("Cached tokens cannot exceed input tokens")fresh_input = input_tokens - cached_tokenstotal = (fresh_input * price_per_million["input"]+ cached_tokens * price_per_million["cached_input"]+ output_tokens * price_per_million["output"])return total / 1_000_000
This function does not embed any specific prices, avoiding estimates that become invalid when prices change. In actual use, unit prices should be synchronized regularly from the official pricing page, and the results should be recorded in a monitoring dashboard.
VII. Evaluation System: Replace a Single Leaderboard with Your Own Task Set
Public leaderboards can reflect the approximate capability range of a model, but there is often a gap between them and business scenarios. Small differences in leaderboard scores may have no effect on outcomes in a specific business context, or may even be masked by scenario noise. Teams should build their own evaluation sets.
Recommendations for building an evaluation set are as follows:
- Cover task types: Sample according to the actual task distribution in the business and retain enough samples for each task type.
- Define quantifiable metrics: Include task completion rate, average execution steps, fabrication rate, post-correction success rate, per-task cost, and end-to-end latency.
- Fix the evaluation environment: When running the same batch of tasks on different versions, keep prompt templates, tool configurations, and random parameters consistent; otherwise, results are not comparable.
- Report confidence intervals: When sample sizes are small, a single score difference may be only random fluctuation. Conclusions should include interval estimates.
Before upgrading a model, run both the old and new versions on the evaluation set, compare the metrics, and then decide whether to switch. If metrics decline for a certain task category, keep the old route only for that category and migrate the rest gradually.
VIII. Risks and Governance
Self-improvement mechanisms bring efficiency gains but also introduce new risks, mainly the following.
Behavior drift: As experience memory accumulates, system behavior may gradually deviate from the original design. Long-term memory content should be reviewed regularly, and regression tests should be set up to ensure that core workflows are not broken.
Privacy and data retention: Execution logs and experience records may contain personal information or business secrets. They should be redacted before storage, and retention periods should be defined.
Permission boundaries: If automated execution has write permissions, the impact of erroneous operations expands. Follow the principle of least privilege and set human confirmation points for operations such as deletion, publishing, and permission changes.
Auditability: The experience entries on which each decision is based, the model alias and version used, and the key actions executed should all be logged for later review.
IX. Implementation Recommendations
Teams can proceed in the following order:
- Inventory existing tasks, classify them into deep, standard, and light tiers by risk and frequency, and establish routing rules.
- Build a minimal evaluation set for each task type and record current baseline metrics.
- Build structured experience storage. First implement write validation and recall by task type, then consider semantic retrieval.
- Add checkpoints and rollback mechanisms at key steps to ensure that humans can intervene mid-execution.
- Build a cost dashboard that breaks down usage into input, cache, and output categories and tracks the cache hit rate.
- For every model or prompt template change, validate it on the evaluation set first, then ramp it up gradually after it passes.
Following this order allows teams to continuously absorb improvements in model capabilities without depending on a single model version, while keeping quality, efficiency, and cost within manageable bounds.
