Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 17

Dynamic Re-planning for Invalidated Plans

Recommended resources

Introduction

In our last lesson, we designed the core architecture for a plan-then-execute agent. We built a Decomposer that transforms a high-level goal into a structured TaskGraph, making the agent's strategy explicit before any action is taken. However, this plan is currently static—it's a perfect-world scenario created with only the initial information. As your background in distributed systems has taught you, a plan that doesn't account for failure is a plan that is destined to fail.

This lesson addresses that very problem by introducing dynamic re-planning. We will implement the logic that allows an agent to detect when its current plan is invalidated by real-world events—a failed tool, an unexpected result, or a changed precondition—and intelligently generate a new plan to get back on track. This capability is the fundamental difference between a brittle script and a resilient, autonomous system capable of navigating the complexities of service fulfillment.


When Plans Meet Reality: The Need for Adaptation

A pre-computed plan is an agent's best guess about the future. But the execution environment is dynamic. An API might be down, a file search might yield no results, or a previously valid assumption might become false. A purely reactive agent like ReAct handles this by making a new decision at every step, but it lacks a global strategy. Our plan-then-execute agent has a strategy, but it needs a feedback loop to adapt it.

This is not about simply retrying a failed step. It's about reassessing the entire situation. Imagine your plan is to drive to the airport, but you encounter a major highway closure. You don't just keep trying to drive through the roadblock. You observe the new state ("highway closed"), orient yourself with the new information, and decide on a new plan (take side streets, reroute via another highway). This is the essence of dynamic re-planning.

Implementing Planning Agentic Pattern From Scratch

This article offers a clear, intuitive example of why re-planning is necessary.

Read the section Why planning?. The analogy of making coffee and discovering you have no milk is a perfect illustration. The initial plan is invalidated, and a new step ("buy milk") must be inserted, forcing a re-evaluation of the entire procedure.

This feedback loop can be modeled using concepts like the OODA loop (Observe, Orient, Decide, Act), a framework for decision-making in dynamic environments. The execution of a task provides a new observation, which forces the agent to re-orient and potentially decide on a new course of action.

This flowchart shows the Agentic Loop based on the OODA model. After an action is taken (3. Act), the result updates the state (4. Update State), creating a new observation that informs the next cycle. Re-planning occurs in the "Orient & Decide" phase when the new observation invalidates the existing plan.

The Monitor: The Agent's Internal Sentry

To enable re-planning, our architecture needs a new component: a Monitor. The Monitor's job is to observe the execution of the plan and the state of the world, and to signal when the plan is no longer viable. It acts as a sentry, watching for three primary triggers:

  1. Explicit Action Failure: A tool call fails with an unrecoverable error (e.g., 401 Unauthorized, 503 Service Unavailable).
  2. Unexpected Outcome: A tool executes successfully, but its output indicates a problem. For example, a run_tests tool returns a list of failing tests, or a search_database tool returns zero results when some were expected.
  3. Precondition Mismatch: The state of the world has changed such that a required precondition for the next planned action is no longer met.

The Monitor encapsulates the logic for detecting these conditions. When a trigger is detected, the main agent loop must halt execution of the current plan and invoke the Planner again.

This diagram illustrates the complete workflow. A user request leads to a plan (1, 2). The agent executes the tasks (3) and updates its state (4). Crucially, this updated state can trigger a re-plan (5b), creating a new task list before responding to the user.

Implementing the Re-planning Logic from First Principles

Let's translate this into code. We will introduce a Monitor class and integrate it into the main agent loop. The core of this class will be a method, should_replan, which determines if the execution should be halted in favor of generating a new plan.

How to Implement Agent Planning - OneUptime

This article provides a complete, from-scratch implementation of a planning agent that includes a Monitor and re-planning logic. It's the perfect blueprint for what we need to build.

First, quickly review the intro and the diagram under What is Agent Planning? to see how re-planning fits into the overall process. Next, read the "Core Components" section, specifically the role of the Monitor component. Then, carefully study the Python code in the section "Implement the Monitor". The should_replan method (view code) is the heart of the detection logic. Understand how it checks for both failed actions and unmet preconditions. Finally, read the "Put It All Together: The Planning Agent" section. The run method of the PlanningAgent class (view code) shows exactly how the Monitor is used within the main execution loop to trigger a re-plan.

As you saw in the code from "How to Implement Agent Planning," the agent's main loop is transformed. It's no longer a simple for loop over the plan's actions. Instead, it's a while loop that continues as long as the plan is not complete and a re-plan limit hasn't been reached. Inside this loop, after each action, the Monitor is consulted:




# Conceptual agent loop with re-planning
replan_count = 0
plan = planner.create_plan(goal, world_state)

while not plan.is_complete() and replan_count < MAX_REPLANS:
    action = plan.current_action()
    



    # 1. Execute the current action
    success = executor.execute(action)
    



    # 2. Update the world state with the result
    self._apply_effects(action)
    



    # 3. Ask the Monitor if the plan is still valid
    needs_replan, reason = monitor.should_replan(plan, self.world_state)
    
    if needs_replan:



        # 4a. If invalid, generate a new plan with the updated state
        print(f"Replanning due to: {reason}")
        plan = planner.create_plan(goal, self.world_state)
        replan_count += 1
    else:



        # 4b. If valid, advance to the next step
        plan.advance()

When the planner.create_plan method is called for a re-plan, it's crucial that it receives the most current world_state. This state contains the history of what has already been accomplished and, importantly, the error or unexpected result that triggered the re-plan. The prompt for the planner should be updated to reflect this context, guiding the LLM to create a new plan that adapts to the failure rather than just starting over.


Reliability and the "Harness Engineering" Mindset

Implementing a re-planning loop elevates your agent's capability, but building a production-grade system requires thinking about the failure modes of the re-planning process itself. This is where the concept of "harness engineering" becomes relevant—building a deterministic software scaffold around the non-deterministic LLM to ensure reliability.

Andrej Karpathy's Math Proves Agent Skills Will Fail. Here's What to Build Instead.

This video discusses the challenges of achieving high reliability in agentic workflows and introduces "harness engineering" as a solution. This mindset is directly applicable to making our re-planning logic robust.

First, watch the section from the beginning, which introduces Andrej Karpathy's "march of nines" concept. This explains why simply prompting an LLM isn't enough for business-critical reliability and why an engineering "harness" is necessary. Then, watch the segment on validation loops. This introduces the idea that re-planning can be triggered not just by hard failures, but by programmatic checks that determine if an agent's output meets a required quality bar.

Your re-planning logic is a key part of this harness. To make it robust, you must consider the pitfalls:

  • Infinite Re-planning: What happens if the agent repeatedly generates a plan that fails in the same way? Your harness must include a circuit breaker, such as a max_replans counter, to prevent infinite loops and escalate the task for human review.
  • Overly Optimistic Plans: An LLM might generate a new plan that still skips critical steps. Your Monitor's precondition checks are the safeguard here, ensuring that the agent doesn't attempt an action before its requirements are met.
  • State Drift: The agent's internal world_state could become inconsistent with the real-world system it's interacting with. A robust harness might periodically refresh its state from external sources of truth rather than relying solely on the predicted effects of its actions.

These considerations, drawn from your experience with reliable systems, are what turn a clever prototype into a production-ready engine.


Conclusion

Today, we've infused our agent with a crucial survival skill: the ability to adapt. We've moved beyond the optimistic path of a static plan and embraced the reality of a dynamic world where things go wrong.

Your key takeaways from this lesson are:

  • Dynamic re-planning is a feedback loop: It consists of executing a step, observing the outcome, and deciding whether to continue or generate a new plan.
  • The Monitor is a key architectural component: It is responsible for detecting plan invalidity by checking for action failures, unexpected outcomes, and unmet preconditions.
  • The main agent loop must be modified: It needs to integrate the Monitor's checks after every action and branch to either advance the plan or trigger the Planner again with an updated world state.
  • Reliability requires a "harness": Production-grade re-planning logic includes safeguards like retry limits and validation loops to prevent getting stuck and to ensure the quality of the agent's work.

We have now given our agent the ability to formulate a plan, decompose it, and adapt that plan when it fails. But what if the plan doesn't fail, but simply isn't very good? In our next lesson, we will implement a self-critique loop, empowering the agent to proactively evaluate and refine its own outputs and plans even when they succeed on the first pass, pushing its performance from merely functional to exceptional.