Home/Agentic AI/Replanning/Implementation

Replanning Strategies

Master adaptive replanning strategies to build robust agents that recover gracefully from failures

Building Robust Agents

Theory is great, but implementation matters. Here are practical code patterns for adding replanning capabilities to your agentic systems. These patterns work with any LLM or agent framework and can be adapted to your specific use case.

Interactive: Code Examples

Explore implementation patterns from simple to advanced

Basic Retry & Replan

Simple pattern: retry N times, then replan

async function executeWithReplanning(task, maxRetries = 3) {
  let retryCount = 0
  let currentPlan = await generateInitialPlan(task)
  
  while (retryCount < maxRetries) {
    try {
      const result = await executePlan(currentPlan)
      return { success: true, result }
    } catch (error) {
      retryCount++
      
      if (retryCount >= maxRetries) {
        // Trigger replanning
        console.log('Max retries exceeded, replanning...')
        currentPlan = await generateNewPlan(task, error)
        retryCount = 0 // Reset retry counter
      } else {
        // Exponential backoff
        await sleep(Math.pow(2, retryCount) * 1000)
      }
    }
  }
  
  return { success: false, error: 'Failed after replanning' }
}

Implementation Best Practices

Do: Log Everything

Track every retry, failure, and replanning decision with timestamps and context

logger.info('Replanning triggered', {
  reason: 'MAX_RETRIES_EXCEEDED',
  attempts: 3,
  lastError: error.message,
  timestamp: Date.now()
})

Do: Set Timeout Limits

Prevent infinite replanning loops with maximum attempt limits

const MAX_REPLAN_ATTEMPTS = 3
const MAX_TOTAL_TIME = 5 * 60 * 1000 // 5 minutes

if (replanCount >= MAX_REPLAN_ATTEMPTS) {
  throw new Error('Max replan attempts exceeded')
}

Do: Preserve Context

Pass failure information to the replanning function

const context = {
  originalPlan: plan,
  completedSteps: getCompletedSteps(),
  failedStep: currentStep,
  error: error,
  attemptHistory: attempts
}

newPlan = await replan(task, context)

Don't: Replan Blindly

Don't generate a new plan without analyzing why the old plan failed. You might just recreate the same broken plan!

Don't: Ignore Costs

Each replan costs LLM tokens. Track costs and set budgets to prevent runaway expenses.

Replanning Loop Architecture

┌─ Start Task
├─ Generate Initial Plan
├─┬─ Execute Plan
│ │
│ ├─ Success? → Return Result ✅
│ │
│ └─ Failure? → Analyze Error ❌
│ │
├─ Transient? → Retry (with backoff)
│ │
├─ Retries Exhausted? → Trigger Replan 🔄
│ │
├─ Generate New Plan (with error context)
│ │
└─ Loop Back to Execute
└─ Max Attempts? → Abort ⛔