Recursive Self-Improvement for Multi-Step AI Agents: Engineering Practices

    This article explains how multi-step LLM agents can improve through a closed loop of execution, evaluation, induction, and update. It covers experience memory design, retrieval and risk controls, evaluation dimensions for multi-step tasks, context and cost management including prefix caching, and practical rollout recommendations. Readers learn engineering patterns for building agents that record trajectories, extract reusable lessons, and apply them safely without retraining model weights.

    1. Background: From Single-Turn QA to Multi-Step Tasks

    Early language models mainly handled single-turn question answering. A user asked a question, the model returned an answer, and the task ended. As model capabilities improved, the industry began placing models inside longer workflows. Typical scenarios include reading a set of technical documents and then writing a proposal, calling multiple internal APIs to complete data reconciliation, and locating a defect in a code repository and submitting a fix suggestion. These tasks often contain five to twenty steps, and each step depends on the results of previous steps.

    Multi-step tasks introduce three new problems. First, errors accumulate across steps; a small deviation in an earlier step can be amplified later. Second, tasks often require human correction midway, so the system must be able to receive correction instructions and adjust subsequent actions. Third, experience from completed tasks is usually discarded, and similar tasks start from scratch every time.

    Around these three problems, the engineering community has gradually reached a consensus: an agent system should not only “do things” but also record how it does them, extract lessons from results, and use those lessons in the next execution. This approach is commonly called recursive self-improvement, where the system continuously optimizes subsequent behavior based on its own execution records.

    2. What Is Recursive Self-Improvement?

    Recursive self-improvement describes a closed-loop process with four stages.

    1. Execution: the agent calls tools and generates intermediate results according to the task goal.
    2. Evaluation: result quality is judged through rule checks, test cases, or human feedback.
    3. Induction: reusable conclusions are extracted from successful and failed trajectories, such as “a certain type of API requires pagination for batch requests.”
    4. Update: conclusions are written to some persistent store and retrieved for use in later tasks.

    This loop differs clearly from traditional model retraining. Retraining requires collecting data, adjusting weights, and redeploying, which takes a long cycle and high cost. Updates in this loop can happen on the inference side, such as modifying prompt templates, maintaining an experience library, or adjusting tool selection strategies, without necessarily changing model weights. Therefore, iteration is faster, but it depends more on the reliability of the evaluation stage. If evaluation criteria are biased, the system will steadily improve in the wrong direction.

    3. Designing Experience Memory

    Experience memory is the carrier for the “induction” and “update” stages in the loop. A usable experience memory usually needs to solve four problems: what to store, how to store it, how to retrieve it, and when to retire it.

    Storage Structure

    Each experience entry should include task type, trajectory summary, outcome status, reusable conclusion, and timestamp. The trajectory summary should not store the full conversation; otherwise retrieval cost and privacy risk both increase. Conclusions should be specific and verifiable, avoiding generalized statements such as “check more.”

    Below is an illustrative structure definition that only describes field design and does not depend on any specific framework:

    1. Experience:
    2. task_type # Task type, e.g., "API data reconciliation"
    3. trajectory # Key-step summary, capped at a few hundred words
    4. outcome # success / failure / partial
    5. lesson # Reusable conclusion; should be specific and verifiable
    6. created_at # Creation time, used for expiration checks
    7. reviewed_by # Human review flag; unreviewed entries do not enter production retrieval

    Retrieval and Injection

    Retrieval determines which experiences enter the context of the current task. The simplest approach is to filter by task type and then take the most recent few entries in reverse chronological order. This is cheap to implement, but it cannot identify semantically similar experiences with different type labels. Mature systems generally combine semantic vectors of the task description with label filtering and limit the number of injected entries to prevent the context from being filled with historical experience.

    The following illustrative code shows a basic retrieval flow based on task type:

    1. class ExperienceMemory:
    2. store = []
    3. def add(experience):
    4. store.append(experience)
    5. def retrieve(task_type, k=3):
    6. matched = [e for e in store if e.task_type == task_type and e.reviewed_by]
    7. sort matched by created_at, newest first
    8. return first k items of matched
    9. def build_context(task, memory, task_type):
    10. hints = memory.retrieve(task_type)
    11. lessons = join each hint.lesson as a bullet line, or "None" if empty
    12. return "Task: " + task + "\nHistorical experience:\n" + lessons

    Risk Control

    Experience memory has two typical risks. One is that incorrect experience becomes fixed. An accidental success may be mistakenly recorded as a general rule and interfere with every later task. Countermeasures include requiring experience to be validated across multiple independent tasks, setting an expiration period for each entry, and enforcing human review for experience in high-impact domains. The other risk is privacy and permission leakage. Experience may contain customer data or internal credentials, so it should be redacted before writing, and retrieval should be filtered by user permissions.

    4. Evaluation Dimensions for Multi-Step Tasks

    Evaluation determines the direction of the loop. Looking only at a single score easily hides problems. It is advisable to measure agent performance from at least the following five dimensions.

    1. Task completion rate: whether the final result meets acceptance criteria. This is the baseline metric.
    2. Step efficiency: the average number of steps and tool calls required to complete the task. More steps often mean detours or repeated probing.
    3. Correctability: after the user gives a correction midway, whether the agent can correctly adjust subsequent actions instead of repeating the original error.
    4. Fabrication rate: the proportion of output containing facts, numbers, or citations that cannot be traced back to the input or tool returns.
    5. Cost and latency: token consumption, tool call costs, and end-to-end time per task.

    Construction of the evaluation set is equally critical. It is advisable to sample from real tickets, cover normal paths, boundary conditions, and known failure cases, and update the set regularly. The evaluation set should be isolated from data used for training or prompt adjustments to avoid inflated metrics.

    Below is an illustrative evaluation framework showing how to count completion rate, fabrication rate, and step count together:

    1. function evaluate(agent, cases):
    2. report = {total: 0, passed: 0, fabricated: 0, step_counts: []}
    3. for case in cases:
    4. output, steps = agent.run(case.input)
    5. report.total += 1
    6. if check_result(output, case.expected): report.passed += 1
    7. if has_untraceable_claim(output, case.sources): report.fabricated += 1
    8. report.step_counts.append(steps)
    9. report.pass_rate = report.passed / report.total
    10. report.fabrication_rate = report.fabricated / report.total
    11. return report

    Here, check_result and has_untraceable_claim need to be implemented for the business scenario. The former can be structured field comparison or unit tests; the latter can require that every number in the output be traceable to a tool return.

    5. Context and Cost Control

    The context of a multi-step task grows with each step. If all history is placed into the input at every step, both cost and latency rise rapidly. Common control strategies include the following.

    Asymmetric Input and Output Pricing

    Most model services bill input and output tokens separately, and the output unit price is usually higher than the input unit price. This means that, without affecting quality, redundant model-generated content should be reduced as much as possible, for example by requiring structured output and limiting explanation length.

    Prefix Caching

    System instructions, tool definitions, and fixed specification documents are largely unchanged across calls. Placing these stable contents at the prompt prefix can improve cache hit rates. Cached input is usually billed significantly lower than ordinary input; the specific discount depends on the provider’s published rules. During design, note that any dynamic content, such as the current time or user identifier, should not be inserted into the stable prefix, because doing so breaks the cache.

    Assume the input unit price is a yuan per million tokens, the cached input unit price is b yuan, the stable prefix for a task is P tokens, the dynamic part is Q tokens, and each task makes N calls. The cost of the stable prefix portion can be approximated as:

    Cost ≈ N × P × b / 1,000,000 + N × Q × a / 1,000,000

    Long Context Is Not Infinite Memory

    As windows grow larger, many teams tend to put all history into the context. But the longer the context, the harder it is for the model to focus on key information, and the higher the cost. A safer approach is to generate a brief state summary at each step, keeping only the goal, completed items, open issues, and key data, while raw logs are persisted to disk and retrieved when needed.

    Storage and Observability Infrastructure

    Experience libraries, trajectory logs, and evaluation results all need persistence. You can use object storage to save full trajectories, a database to save structured experience, and a logging service to record tool calls and latency at each step. Monitoring and alerting can track trends in completion rate and fabrication rate. When metrics drop significantly, experience writes should be paused automatically and the owner notified for investigation.

    6. Practical Rollout Recommendations

    First, use small canary releases. Run a new experience injection strategy on a small number of tasks first, compare completion rate and cost against a control group, and then decide whether to roll it out fully.

    Second, retain rollback capability. Every change to prompt templates or the experience library version should have a version number, so that when metrics decline you can quickly restore the previous version.

    Third, limit write permissions. The agent can propose experience candidates, but writing to the production experience library requires a review process. The agent itself should not have permission to modify the evaluation set or review rules.

    Fourth, retain human intervention points. Steps involving funds, permission changes, or external content should have explicit confirmation points rather than relying on the model to judge on its own.

    Fifth, continuously review failure cases. Failure trajectories contain more information than successful ones. Organize high-frequency failure types weekly, determine whether the problem lies in retrieval, tool definitions, evaluation criteria, or model capability itself, and then decide the direction of improvement.

    Recursive self-improvement provides a path for continuous optimization of multi-step agents, but its benefits depend on whether evaluation is reliable, whether experience is validated, and whether permissions are controlled. Engineering teams should first establish trusted evaluation and monitoring, and then gradually open automated experience writes.