BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
← All field notes

AI

Agent Planning Loops: When to Continue, Retry, Replan, or Stop

A practical control model for agent loops: define progress, distinguish retries from replanning, verify outcomes, and enforce clear stopping rules.

A green agent-planning loop routes through a validation gate to continue, retry, replan, or stop.

Agent Planning Loops: When to Continue, Retry, Replan, or Stop

Estimated reading time: 9 minutes

اقرأ النسخة العربية: دورات تخطيط الوكيل: متى يتابع أو يعيد المحاولة أو يعيد التخطيط أو يتوقف؟

An AI agent is more than a model that writes a plan. It is a system that repeatedly chooses an action, observes what the environment actually did, and decides what should happen next. The difficult engineering question is not simply “What is the next tool call?” It is “Does the latest evidence justify continuing the same plan, retrying one operation, changing the plan, asking a person, or stopping?”

Agent work is stateful: a write may commit even if its response is lost, search evidence may be weak, and some actions require approval. The loop therefore needs observable success evidence, bounded recovery, and enforceable stop conditions.

This article develops a practical control model. It is an engineering pattern, not a claim that a visible explanation or a particular model guarantees correctness.

The loop is a controller, not an endless conversation

A useful loop has four stages:

  1. Plan: choose a small next step tied to the goal.
  2. Act: call a tool or update a controlled environment.
  3. Observe: inspect the returned result and, where necessary, read the resulting state independently.
  4. Decide: continue, retry, replan, ask for help, or stop.

The key word is evidence. A generated sentence is not proof that an external action occurred; a tool result, fresh record read, or domain test is stronger. Anthropic recommends grounding agent decisions in environmental feedback and using limits such as maximum iterations. OpenAI’s agent guide describes explicit run exit conditions. ReAct interleaves reasoning and action so observations can update a plan, but a reasoning trace is not a correctness certificate.

A compact state model helps make the control decision reviewable:

flowchart TD
  A["Goal and constraints"] --> B["Choose bounded action"]
  B --> C["Execute tool"]
  C --> D["Inspect result and state"]
  D --> E{"Decision"}
  E -->|"evidence of progress"| B
  E -->|"transient and safe"| F["Retry within budget"]
  F --> C
  E -->|"assumption changed"| G["Replan from observed state"]
  G --> B
  E -->|"blocked or unsafe"| H["Ask, hand off, or stop"]
  E -->|"acceptance criteria met"| I["Return verified result"]

The diagram separates a retry from a replan. A retry repeats one operation because a temporary failure is plausible and repeating it is safe. A replan changes the sequence because an assumption, dependency, or available action has changed. Neither is the default response to every error.

Define progress before starting

Before an agent begins, express the goal as observable acceptance criteria. “Finish the deployment” is vague. “The target release is active, health checks pass, and the rollback pointer remains available” is testable. Criteria should name both the desired outcome and any conditions that must remain true.

Then define the task boundary:

  • Which tools and resources may the agent use?
  • Which actions have irreversible or external effects?
  • What evidence proves completion?
  • Which choices require human approval?
  • What are the maximum tool calls, elapsed time, and cost?
  • Which failures are recoverable, and which are stop conditions?

This contract keeps the agent from silently redefining success and gives the application a stable basis for grading. For multi-step work, keep a structured state record of the goal, constraints, completed steps, last observation, remaining budget, and next decision. Store tool facts separately from model interpretations.

Continue only when the last step changed the state usefully

Continuing is justified when the previous observation confirms progress and there is a clear next action. “The file was read successfully; now inspect the configuration section” is progress. “The search returned the same empty result again” is not progress unless the next query or hypothesis changes.

A practical progress check asks:

  1. What new observation did the last action produce?
  2. Which acceptance criterion is closer to being satisfied?
  3. Does the next step depend on an assumption that has now been disproved?
  4. Is the remaining budget enough to finish and verify?

If the answer to the first two questions is “nothing,” repeating the same plan is likely a loop. Track a compact progress signature such as the set of completed checklist items, relevant resource version, or normalized outcome. If the signature does not change across several steps, stop or replan. Structured actions, tool results, and state transitions are enough; private chain-of-thought is not required.

Retry only failures that are plausibly transient and safe to repeat

A timeout means no response arrived, not that the server did nothing. Before retrying a side effect, classify the failure:

  • Transient transport or capacity failure: a bounded retry with backoff may help.
  • Validation or authorization failure: repeating the same request will not fix the cause.
  • Conflict or stale version: reread state, then decide whether to merge or stop.
  • Unknown outcome after a write: reconcile using an operation key, transaction ID, or a fresh read before replay.
  • Policy or safety refusal: stop or ask for an authorized path; do not route around the control.

For a side effect, idempotency is part of the protocol. Give the operation a stable key derived from the intended logical action. Repeating the exact request with the same key should return the prior result rather than create a second effect. If the payload changes, use a new revision and a new key after reading the current resource version. Never turn an idempotency conflict into permission to improvise a different key.

Worked example 1: an uncertain invoice request

Suppose an agent submits a request to create invoice INV-204 and the network times out. The input is the invoice payload plus idempotency key “invoice:INV-204:create:v1”. The decision should not be “send another create.” First query the billing system for that key or invoice identifier:

  • If the operation is complete, reuse its invoice ID and continue to verification.
  • If the operation is pending, wait or reconcile; pending does not prove that no effect occurred.
  • If the operation is not found, retry the identical payload with the same key, subject to the retry budget.
  • If the same key is associated with a different payload, stop and raise a conflict.

The output is either the single known invoice ID or a clear unresolved state. The example is illustrative; a production integration must use the billing provider’s actual idempotency and lookup guarantees.

Replan when observations invalidate the current approach

Replanning is appropriate when the world differs from the model’s assumptions. An endpoint may return a newer schema. A file may be absent. A search may show that the target already exists. A dependency may be blocked by a permission boundary. The agent should incorporate the new fact and select a different legal route, rather than repeat the failed step.

A replan preserves completed work and resource identities. Record valid steps, changed assumptions, and unsafe actions, then choose the smallest alternative that meets the original criteria. Do not recreate resources with uncertain status; read before writing when a prior operation may have committed.

Worked example 2: a release check with a failed dependency

Consider an agent preparing a service release. Its planned sequence is: run tests, publish an artifact, shift a small amount of traffic, and check health. The test stage reveals that a required package source is unavailable. The agent should not keep rerunning the publish step because it has not reached it. It should inspect the dependency’s current status, distinguish a temporary registry outage from a missing or disallowed package, and apply the release policy:

  • If the registry is temporarily unavailable and the build has not changed, wait briefly and retry the test within a small budget.
  • If the package version was removed or policy-blocked, stop the release and ask for an approved dependency decision.
  • If a cached, signed artifact is explicitly allowed, replan around that artifact, record its identity, and run the same acceptance checks against it.

The resulting choice is based on observed state and policy, not on an agent’s desire to finish. No particular production outcome is implied.

Make stop conditions explicit and enforce them outside the model

A safe loop has ordinary exits and hard stops. Exits include verified completion, cancellation, or a stated limit. Hard stops include missing authorization or capability, ownership conflicts, unapproved irreversible actions, and unreconciled outcomes.

Use independent limits for:

  • Turns or tool calls: prevent unbounded loops.
  • Elapsed time: ensure an agent does not continue after its task window.
  • Retries per operation: cap attempts, with backoff for transient conditions.
  • Cost or token budget: stop before a runaway expense.
  • Effect budget: limit the number or scope of writes.
  • Risk threshold: require a person for high-impact actions.

If the task is blocked, return a useful handoff: what was attempted, the last confirmed state, the uncertainty, the action needed from a person, and the exact condition for resuming. Avoid declaring success or quietly substituting a different goal.

Turn traces into tests

Agent evaluations need to grade the full trajectory and final environment state, not just the final answer. Anthropic’s evaluation guidance distinguishes a task, trial, grader, transcript, outcome, and harness. For planning loops, include a normal path, safe transient retry, timeout after a possible commit, stale version or conflict, changed assumption, missing approval, repeated no-progress observation, and a success claim that contradicts external state.

Use deterministic graders for operation keys, duplicate effects, version checks, retry budgets, and agreement with the final environment. Run multiple trials when behavior varies. Review traces, but do not treat fluent explanations as proof; external verification must establish the outcome.

A small implementation pattern

An application can keep the control policy simple and auditable:

while budget remains:
    observation = read_authoritative_state()
    if acceptance_criteria_met(observation):
        return verified_result(observation)

    decision = choose_from(progress, observation, policy, remaining_budget)

    if decision == CONTINUE:
        execute(next_bounded_action)
    elif decision == RETRY and retry_is_safe(operation):
        reconcile(operation_key)
        retry_same_payload_with_backoff()
    elif decision == REPLAN:
        preserve_confirmed_state()
        choose_new_legal_path()
    elif decision == ASK:
        return handoff(last_confirmed_state, question, resume_condition)
    else:
        return stopped(last_confirmed_state, reason)

A design review checklist

Before shipping a planning loop, ask:

  • Can success be checked against authoritative state?
  • Can a timeout hide a committed side effect?
  • Are retries safe, bounded, and idempotent?
  • Do replans preserve completed work and current versions?
  • Are permissions, budgets, and handoffs enforced outside the model?
  • Do evaluations cover conflicts, ambiguous outcomes, and non-progress?

A planning loop is reliable when its next step follows from evidence, its writes can be reconciled, and its stopping rules hold even when the model is wrong. “Continue,” “retry,” “replan,” and “stop” are different control decisions. Treating them as distinct states turns an attractive demo loop into an engineering component that can be inspected, tested, and operated.

References

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.