How to Build Multi-Step Agent Tasks: Model Selection, Memory, and Self-Improvement

    Multi-step agent work goes beyond a single question and answer: the model plans, uses tools, checks intermediate results, and corrects course before delivery. This article explains the main failure modes—context growth, error propagation, mid-task user corrections, and hallucination—and covers layered model routing, input-cost control with stable prefixes, reviewed experience memory, evaluation metrics, and a practical launch checklist.

    1. From Single-Turn Answers to Multi-Step Tasks

    The typical use of a large language model used to be one question and one answer. The user sent text, the model returned text, and the task ended in a single turn. More applications now ask the model to complete a sequence of actions: understand the request, break it into subtasks, call tools such as retrieval or code execution, inspect intermediate results, go back and fix problems, and only then deliver an outcome. These workloads are usually called multi-step tasks, or agent tasks.

    Their value is that they can handle complex, time-consuming work—for example, fixing a defect that spans several files, organizing dozens of source documents into a report, or completing an approval flow in an enterprise system. The cost is also higher. Every step can introduce an error, every step consumes inference resources, and mistakes travel forward along the chain. Engineers therefore need more than a stronger model. They also need mechanisms that constrain behavior, control cost, and measure quality.

    This article follows engineering practice rather than any vendor-specific feature. The methods apply to most mainstream model services and self-hosted inference setups.

    2. Four Core Difficulties in Multi-Step Tasks

    2.1 Accumulated State and Growing Context

    Every tool result is appended to the context. By step twenty, that context may contain a large amount of logs and intermediate output that no longer matter to the current decision. Longer context spreads the model’s attention, raises the chance that key constraints are ignored, and increases inference cost.

    Three common responses help. First, summarize or structurally trim tool returns so only fields needed by later steps remain. Second, store task state externally and inject only the fragment relevant to the current turn. Third, set an explicit step budget; when it is exceeded, force the run to close and emit a staged conclusion.

    2.2 Error Propagation and Mid-Run Drift

    In a multi-step flow, an early wrong judgment becomes a premise for later steps. If the model misreads a file’s version number at step two, every later edit is built on the wrong version. The final output can look complete and still be unusable.

    The main way to limit this risk is checkpoints. After each stage, the system should verify the output with logic that is independent of the model—run unit tests, compare row counts, or check the format of critical fields. If verification fails, roll back to the previous checkpoint and rerun from there instead of letting the model continue on a false premise.

    2.3 Steerability: Adjusting After the User Corrects the Task

    In real use, people often add requirements or point out problems halfway through. A useful agent should fold those corrections into later decisions rather than mechanically follow the original instruction. In practice, the system must write every user feedback item into task state and explicitly remind the model of the latest constraints on each subsequent inference turn.

    2.4 Fabrication and Hallucination

    When evidence is missing, a model may produce content that looks plausible but does not exist: function names that are not real, invented citations, or unverified numbers. In a multi-step task, once that content is stored as fact or passed to a downstream tool, the error is amplified. Anything that can be checked by a program should be checked by a program, not left to the model’s self-confirmation.

    3. Choose Models by Task Difficulty

    Steps in a multi-step task do not all need the same capability. Sending every step to the strongest and most expensive model is too costly. Sending every step to the lightest model fails on critical decisions. A better approach is to layer models by task type.

    Tier Typical tasks Selection principle
    High-capability Long-horizon planning, complex code changes, reasoning across documents Prioritize accuracy; higher latency and cost are acceptable
    Balanced Routine coding, structured extraction, report writing Balance quality, speed, and cost
    Fast Classification, format conversion, simple Q&A, log summaries Prioritize low latency and low cost; quality is defined by passing checks

    Routing rules can stay simple after the tiers are defined. For example, the task entry point can look at description length, the number of files involved, and whether cross-module reasoning is required, then choose a tier. Those rules themselves need validation against historical data so hard tasks are not misrouted to a lightweight model.

    4. Cost Control: Pricing Structure and Context Design

    Most model services bill input tokens and output tokens separately. In multi-step tasks, input tokens often far exceed output tokens because each turn resubmits a large context. Reducing input cost is therefore the main optimization.

    Many services offer cache pricing for a repeated context prefix. Cached input is usually much cheaper than ordinary input. To use that, organize the context as a stable prefix plus a dynamic suffix: system instructions, tool definitions, and fixed background material go first; content that changes each turn goes last. If the prefix includes a timestamp or a random ID, the cache will not hit.

    The following code estimates the cost of a single call so different designs can be compared:

    1. def estimate_cost(
    2. input_tokens: int,
    3. output_tokens: int,
    4. cached_tokens: int,
    5. price_in: float, # unit price per million ordinary input tokens
    6. price_out: float, # unit price per million output tokens
    7. price_cache: float, # unit price per million cache-hit input tokens
    8. ) -> float:
    9. fresh_tokens = max(input_tokens - cached_tokens, 0)
    10. cost = (
    11. fresh_tokens * price_in
    12. + cached_tokens * price_cache
    13. + output_tokens * price_out
    14. )
    15. return cost / 1_000_000
    16. # Example: compare total cost of two context designs over a 20-turn task
    17. rounds = 20
    18. per_round_input = 60_000
    19. stable_prefix = 45_000 # stable prefix length, eligible for cache
    20. per_round_output = 800
    21. cost_with_cache = sum(
    22. estimate_cost(
    23. per_round_input, per_round_output,
    24. cached_tokens=stable_prefix if i > 0 else 0,
    25. price_in=3.0, price_out=15.0, price_cache=0.3,
    26. )
    27. for i in range(rounds)
    28. )
    29. print(f"Estimated cost for a 20-turn task: {cost_with_cache:.4f}")

    The unit prices in the example only demonstrate the calculation. Use the official pricing for the service you actually call.

    Another often overlooked cost source is useless retries and overly long output. Set an output-length limit for each step, use explicit format constraints for structured output, and detect repeated content in code so looping output can be stopped.

    5. Experience Memory: Learning from Past Tasks

    Continuous improvement is an important goal for multi-step agents. One workable approach is to store experience from successful and failed tasks, then retrieve and inject relevant experience into later tasks. This idea is discussed in both research and engineering practice. The core is to keep a structured record of what was done, what the result was, and why.

    A usable experience-memory system usually has four stages.

    First, record. After each task, store the task type, key decisions, verification results, failure reasons, and user feedback.

    Second, distill. Turn raw records into reusable rules, such as “after editing this class of configuration file, a syntax check is required.”

    Third, review. A distilled rule should pass an automated test or human confirmation before it is written into long-term memory. Unreviewed memory can lock in bad practice and pollute later runs.

    Fourth, retrieve and inject. When a new task starts, retrieve rules that match its features, place them in a designated part of the context, and label their source and scope.

    The simplified framework below shows the basic logic of write-time review and retrieval by tag:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class ExperienceRule:
    4. rule_id: str
    5. text: str
    6. tags: set[str]
    7. verified: bool = False # whether review has passed
    8. evidence_count: int = 0 # number of successful cases supporting the rule
    9. class ExperienceStore:
    10. def __init__(self) -> None:
    11. self._rules: dict[str, ExperienceRule] = {}
    12. def propose(self, rule: ExperienceRule) -> None:
    13. # New rules are stored unverified and are excluded from retrieval
    14. self._rules[rule.rule_id] = rule
    15. def verify(self, rule_id: str, passed: bool) -> None:
    16. rule = self._rules[rule_id]
    17. if passed:
    18. rule.verified = True
    19. rule.evidence_count += 1
    20. def retrieve(self, task_tags: set[str], limit: int = 5) -> list[ExperienceRule]:
    21. matched = [
    22. r for r in self._rules.values()
    23. if r.verified and r.tags & task_tags
    24. ]
    25. matched.sort(key=lambda r: r.evidence_count, reverse=True)
    26. return matched[:limit]

    Memory systems have two main risks. One is over-generalization: treating a convention that is special to one project as a universal rule. Label each rule with its scope, and promote it only after it holds across several independent cases. The other is staleness: the tool version or business rule the memory depends on has changed. Give rules an expiry and check their dependencies at retrieval time.

    6. Evaluation: Measuring Agent Quality with Metrics

    Without reliable evaluation, you cannot tell whether a change helped. Evaluation of multi-step tasks should cover outcome quality, process quality, and resource use.

    Outcome quality includes task success rate, the share of outputs that pass automatic checks, and satisfaction from human sampling. Process quality includes average step count, the share of repeated calls, recovery rate after user corrections, and the rate at which fabricated content is detected. Resource use includes average cost per task, end-to-end latency, and retry count.

    The evaluation set should come from real tasks and be updated regularly. Public benchmarks or historical samples alone can make a system look strong on the test set while remaining unstable in production.

    The following code computes core metrics from execution logs:

    1. from statistics import mean
    2. def summarize_runs(runs: list[dict]) -> dict[str, float]:
    3. """Each item in runs includes: success (bool), steps (int), cost (float),
    4. retries (int), corrected_ok (bool | None), hallucination (bool)."""
    5. total = len(runs)
    6. corrected = [r for r in runs if r.get("corrected_ok") is not None]
    7. return {
    8. "success_rate": sum(r["success"] for r in runs) / total,
    9. "avg_steps": mean(r["steps"] for r in runs),
    10. "avg_cost": mean(r["cost"] for r in runs),
    11. "avg_retries": mean(r["retries"] for r in runs),
    12. "correction_recovery_rate": (
    13. sum(r["corrected_ok"] for r in corrected) / len(corrected)
    14. if corrected else float("nan")
    15. ),
    16. "hallucination_rate": sum(r["hallucination"] for r in runs) / total,
    17. }

    When comparing two versions, use the same task set and watch the direction of each metric. A higher success rate with double the cost is not automatically a better version. Set trade-off rules from business priorities instead of watching a single number.

    7. Engineering Launch Checklist

    Before putting a multi-step agent into use, confirm the following items.

    1. Each stage has verification logic independent of the model, and a failed check can roll back to a checkpoint.
    2. Context uses a stable prefix plus a dynamic suffix, and tool returns are trimmed.
    3. Each step has a step budget and an output-length limit.
    4. Model-tier routing rules are backed by historical data and reviewed on a schedule.
    5. Experience memory is retrieved only after review, and each rule is labeled with scope and expiry.
    6. User corrections are written into task state and explicitly surfaced on later inference turns.
    7. Anything that can be machine-checked is confirmed by a program, not by the model alone.
    8. The evaluation set comes from real tasks, and metrics cover quality, process, and cost together.
    9. Logs record an input summary, tool calls, and verification results for every step so failures can be investigated later.
    10. Sensitive data is redacted before it enters the context, and secrets live in environment variables or a secrets manager—not in prompts or source code.

    8. Conclusion

    The hard part of a multi-step agent is not how clever a single answer is. It is whether the whole chain runs reliably. Model tiers match cost to capability. A stable prefix reduces repeated billing. Reviewed experience memory lets the system accumulate practices that hold up. A complete evaluation setup makes every change traceable.

    For an engineering team, a steadier path is to start with one task type that has clear boundaries, build an evaluation set and verification logic, and only then add tiered routing and memory. Each time a component is introduced, metrics should confirm that it actually improved the system.