This prompt is for agent runtime developers who need a structured, programmatic decision point when an agent's execution step fails or new evidence contradicts the current plan. The job-to-be-done is not to fix the plan, but to reliably classify the situation and output a machine-readable directive: continue, patch, rollback, or abort. The ideal user is an engineering lead or AI/ML engineer building a resilient agent execution loop in a production system where silent failures, infinite retries, or unsafe state mutations are unacceptable. Required context includes the original plan, the current execution state, the failure or contradiction event, and the agent's operational constraints (budget, time, safety policy).
Prompt
Agent Replanning Decision Prompt Template

When to Use This Prompt
Define the job, reader, and constraints for the Agent Replanning Decision Prompt.
Do not use this prompt when you need a creative workaround or a human-readable explanation of what went wrong. It is not for generating a new plan from scratch, nor for patching the plan directly—it is a decision router that precedes a specialized patching prompt. It is also inappropriate for low-risk, stateless, or idempotent workflows where a simple retry loop is sufficient. The prompt assumes you have already detected a failure or contradiction and have packaged the relevant state into the input. If your agent lacks a clear plan structure, step tracking, or constraint definitions, this prompt will produce unreliable decisions because it cannot reason about what it cannot see.
Before integrating this prompt, ensure your agent runtime can act on each decision type: continue means proceed to the next step despite the event; patch means invoke a plan-patching sub-agent with the specific failure mode; rollback means execute a compensation plan to undo prior side effects; abort means halt execution and escalate to a human or logging system. The prompt's value is in preventing the most common production failure modes—agents that loop, agents that proceed with corrupted state, and agents that waste tokens on unrecoverable paths. Wire this prompt into your execution loop immediately after any step failure, postcondition validation failure, or new-evidence trigger, and before any retry logic.
Use Case Fit
Where the Agent Replanning Decision Prompt works well, where it fails, and the operational prerequisites for production use.
Good Fit: Autonomous Agent Loops
Use when: the agent runtime must decide whether to continue, patch, rollback, or abort after a step failure without human intervention. Guardrail: always pair with a hard timeout and max-replan limit to prevent infinite replanning loops.
Good Fit: Evidence-Driven Replanning
Use when: new tool outputs or retrieved evidence contradict prior assumptions and the agent must re-evaluate the remaining plan. Guardrail: require the prompt to cite the specific evidence that triggered replanning and explain why it invalidates the current plan segment.
Bad Fit: Single-Step or Stateless Tasks
Avoid when: the workflow is a single tool call or a stateless request-response pattern with no plan to revise. Guardrail: route simple tasks to a direct execution path and only invoke the replanning prompt when a multi-step plan exists and a step has failed or new evidence has arrived.
Bad Fit: Real-Time or Sub-Second Latency Budgets
Avoid when: the system requires sub-second decisions and cannot tolerate an extra LLM call for replanning. Guardrail: use a deterministic fallback policy (retry once, then abort) for latency-sensitive paths and reserve the replanning prompt for asynchronous or background agent workflows.
Required Input: Current Plan State
Risk: the prompt cannot make a sound decision without knowing what steps completed, what failed, and what remains. Guardrail: always include a structured plan state with step statuses, outputs, and dependency graph before invoking the replanning prompt.
Operational Risk: Cost Amplification
Risk: each replanning call consumes tokens and adds latency; frequent replanning can multiply costs without improving outcomes. Guardrail: implement a replanning budget that tracks cumulative replanning calls per session and escalates to a human operator when the budget is exhausted.
Copy-Ready Prompt Template
A reusable prompt template for making structured replanning decisions when an agent step fails or new evidence contradicts the current plan.
The following prompt template is designed to be called by an agent runtime's replanning module. It forces a structured decision—continue, patch, rollback, or abort—instead of allowing the model to produce an open-ended narrative. Use this template as the core instruction set for your replanning node, wrapping it with your specific tool definitions, execution history, and safety policies. The square-bracket placeholders must be populated by your application before the model call; never pass unresolved placeholders to the model.
textYou are an agent replanning decision module. Your only job is to evaluate the current execution state and output a structured decision. ## Current Plan [PLAN_STEPS] ## Completed Steps with Outputs [COMPLETED_STEPS] ## Failure or Trigger Event [TRIGGER_EVENT] ## Available Tools [TOOL_LIST] ## Constraints - Max remaining budget: [BUDGET_REMAINING] - Deadline: [DEADLINE] - Safety policy: [SAFETY_POLICY] - Rollback capability: [ROLLBACK_AVAILABLE] ## Decision Rules 1. If the failure is recoverable with an available alternative tool or adjusted arguments, output `patch`. 2. If the failure invalidates prior steps that must be undone, output `rollback` only if rollback is available; otherwise output `abort`. 3. If the failure is non-recoverable and the plan cannot be salvaged, output `abort`. 4. If the trigger is new evidence that contradicts a planning assumption, identify all assumption-dependent steps and output `patch` with a revised plan segment. 5. If the trigger is a constraint violation (budget, time, policy), output `patch` with a constraint-satisfying revision or `abort` if no revision is feasible. 6. If none of the above apply and the plan can proceed, output `continue`. ## Output Schema Return ONLY a valid JSON object with no additional text: { "decision": "continue" | "patch" | "rollback" | "abort", "confidence": 0.0-1.0, "reasoning": "Concise explanation of why this decision was chosen, referencing specific evidence from the trigger event and plan state.", "affected_steps": ["step_ids"], "revised_plan": [ { "step_id": "string", "action": "string", "tool": "string or null", "arguments": {}, "depends_on": ["step_ids"], "rollback_action": "string or null" } ], "requires_human_approval": true | false, "escalation_reason": "string or null" } ## Critical Rules - If confidence is below 0.7, set `requires_human_approval` to true. - If the decision is `rollback`, include `rollback_action` for every reversible step in `revised_plan`. - If the decision is `abort`, `revised_plan` must be an empty array. - Never invent tools not present in the available tools list. - If the trigger event involves a safety policy violation, `requires_human_approval` must be true regardless of confidence.
To adapt this template for your agent runtime, replace each placeholder with live data from your execution state. [PLAN_STEPS] should contain the full ordered plan with step IDs, descriptions, and dependencies. [COMPLETED_STEPS] must include actual outputs and any validation results. [TRIGGER_EVENT] should be a structured description of what failed or what new evidence arrived—avoid passing raw error logs without summarization. Wire your tool registry into [TOOL_LIST] with full schemas so the model can reason about alternatives. Set [ROLLBACK_AVAILABLE] based on whether your execution environment supports compensating transactions or state reversal. After the model returns a decision, validate the JSON against the schema before acting on it. If the decision is patch or rollback, feed the revised_plan into your plan executor only after running precondition checks on each new step. For high-risk domains, always require human approval when requires_human_approval is true, and log the full decision payload for audit.
Prompt Variables
Required inputs for the Agent Replanning Decision Prompt. Each placeholder must be populated before the prompt is sent. Missing or malformed variables cause the model to default to unsafe behavior (abort or continue without evidence).
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ORIGINAL_PLAN] | The full plan as it existed before the triggering event, including completed, in-progress, and pending steps with dependencies. | {"plan_id": "plan-42", "steps": [{"id": "1", "status": "completed", "tool": "search", "args": {"query": "Q1 2025 revenue"}, "output_schema": "number"}, {"id": "2", "status": "in_progress", "tool": "calculator", "args": {"expression": "sum"}, "depends_on": ["1"]}]} | Must be valid JSON. Schema check: every step has id, status, tool, args. Status must be one of completed, in_progress, pending. Dependencies must reference existing step ids. Null not allowed. |
[TRIGGER_EVENT] | The event that caused the replanning decision. Includes type, source step, and diagnostic payload. | {"type": "tool_failure", "source_step_id": "2", "payload": {"error_code": "RATE_LIMITED", "retry_after_seconds": 30}} | Must be valid JSON. Type must be from allowed enum: tool_failure, unexpected_output, new_evidence, constraint_violation, human_override, partial_completion, deadlock, context_exhaustion, hallucination_detected, safety_policy_trigger, sub_agent_failure, goal_reprioritization, assumption_invalidated, loop_detected, rollback_required, auth_expiry, rate_limit, validation_failure, checkpoint_restore_failure. Source step id must exist in ORIGINAL_PLAN if applicable. Null allowed for global triggers. |
[CURRENT_STATE] | Snapshot of execution state at the moment of the trigger, including completed outputs, in-progress artifacts, and resource counters. | {"completed_outputs": {"1": 42000000}, "in_progress_artifacts": {"2": null}, "resources": {"tokens_used": 4500, "budget_tokens": 10000, "wall_time_seconds": 120, "deadline_seconds": 600}} | Must be valid JSON. Completed outputs must map step ids to their output values. Resource counters must be numeric. Budget and deadline fields required if plan has resource constraints. Null allowed for in-progress artifacts if step has not produced partial output. |
[AVAILABLE_TOOLS] | The current set of tools the agent can call, including tool name, schema, and capability description. | [{"name": "search", "description": "Web search returning structured results", "parameters": {"query": "string"}}, {"name": "calculator", "description": "Evaluate arithmetic expressions", "parameters": {"expression": "string"}}] | Must be valid JSON array. Each tool requires name, description, parameters. Schema check: parameters must be a valid JSON Schema object. Array must not be empty. If a tool from ORIGINAL_PLAN is missing here, the prompt must consider it unavailable. |
[CONSTRAINTS] | Active constraints on execution: budget, time, permissions, safety policies, and completion criteria. | {"max_steps": 10, "max_tokens": 10000, "max_wall_time_seconds": 600, "allowed_tool_categories": ["search", "calculation"], "safety_policy": "no_pii_processing", "completion_criteria": "all_steps_completed"} | Must be valid JSON. At least one constraint required. Safety policy must reference a defined policy name. Completion criteria must be one of: all_steps_completed, goal_achieved, human_approval_required. Null not allowed. |
[REPLANNING_HISTORY] | Log of prior replanning decisions in this session, including decision type, timestamp, and outcome. | [{"decision_id": "replan-1", "timestamp": "2025-01-15T10:30:00Z", "decision": "patch", "patch_description": "Replaced step 3 with alternative tool", "outcome": "success"}] | Must be valid JSON array. Each entry requires decision_id, timestamp, decision, outcome. Decision must be one of: continue, patch, rollback, abort. Outcome must be one of: success, failed, pending. Null allowed if no prior replanning has occurred. Array must not exceed 10 entries to avoid context pollution. |
[COST_MATRIX] | Estimated cost of each decision path: continue, patch, rollback, abort. Includes token cost, time cost, and risk of data loss. | {"continue": {"tokens": 200, "time_seconds": 10, "risk": "high", "risk_description": "Step 2 will fail again without change"}, "patch": {"tokens": 500, "time_seconds": 30, "risk": "medium"}, "rollback": {"tokens": 800, "time_seconds": 60, "risk": "low", "data_loss_risk": "none"}, "abort": {"tokens": 0, "time_seconds": 0, "risk": "low", "data_loss_risk": "all_unsaved"}} | Must be valid JSON. All four decision paths required. Token and time estimates must be numeric. Risk must be one of: low, medium, high, critical. Data loss risk required for rollback and abort paths. Null not allowed. |
Implementation Harness Notes
How to wire the replanning decision prompt into a resilient agent execution loop with validation, retries, and safe defaults.
The Agent Replanning Decision Prompt is designed to sit inside a tight runtime loop—not as a standalone chat interaction. It should be invoked immediately after a step failure, unexpected output, or contradictory evidence is detected by the agent's monitoring layer. The prompt expects a structured snapshot of the current plan state, the triggering event, and available tools. Your harness must assemble this context programmatically from the agent's execution trace, not from user input. The model's response is a structured decision object that your runtime must parse and act on: continue, patch, rollback, or abort. Do not expose this prompt to end users; it is an internal control-plane component.
Wire the prompt into your agent framework as a synchronous decision point with a strict timeout (e.g., 5 seconds) and a hardcoded fallback. If the model call fails, times out, or returns unparseable output, the harness must default to the safest action for the domain—typically abort for financial or safety-critical agents, or rollback for agents operating on mutable resources. Validate the response against a schema that requires decision (enum), rationale (string), and optional patch_plan (array of steps). Reject any response that proposes a patch referencing tools not present in the original [TOOLS] input. Log every decision with the full prompt, response, and validation result for audit and debugging. For high-risk domains, insert a human approval gate before executing any rollback or patch decision that modifies external state.
Model choice matters here. Use a model with strong instruction-following and structured output capabilities (e.g., GPT-4o, Claude 3.5 Sonnet) because the cost of a wrong decision—wasted agent steps, corrupted state, or unsafe execution—far exceeds the per-call token cost. Avoid using smaller or faster models unless you have validated decision accuracy against a golden test set of at least 50 failure scenarios. Implement a retry budget of 2 attempts with exponential backoff for transient model errors, but never retry on a decision: abort response. After deployment, monitor the ratio of patch to abort decisions; a sudden spike in patches often indicates that the agent is papering over a systemic tool or planning failure that requires root-cause investigation rather than more replanning.
Expected Output Contract
Defines the structured JSON object the model must return for the Agent Replanning Decision Prompt. Use this contract to validate outputs before the agent runtime acts on the decision.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
decision | enum: CONTINUE | PATCH | ROLLBACK | ABORT | Must be exactly one of the four allowed values. Reject any other string. | |
rationale | string | Must be non-empty and reference at least one specific fact from [FAILURE_CONTEXT] or [PLAN_STATE]. | |
patch | object | null | Required if decision is PATCH. Must contain a valid 'steps' array. If decision is not PATCH, must be null. | |
patch.steps | array of objects | Each step must include 'id', 'action', and 'tool' fields. 'id' must be a unique string. 'tool' must match a tool name in [AVAILABLE_TOOLS]. | |
rollback_target_step_id | string | null | Required if decision is ROLLBACK. Must match an existing step ID from [PLAN_STATE]. If decision is not ROLLBACK, must be null. | |
abort_reason_code | enum: SAFETY | BUDGET | PERMISSION | DEADLINE | IRRECOVERABLE | null | Required if decision is ABORT. Must be one of the allowed codes. If decision is not ABORT, must be null. | |
confidence | number | Must be a float between 0.0 and 1.0 inclusive. Values below 0.5 should trigger a human review flag in the harness. | |
assumptions_checked | array of strings | Must list which assumptions from [TRACKED_ASSUMPTIONS] were validated or invalidated. Cannot be empty. Each string must match an assumption ID. |
Common Failure Modes
Replanning prompts fail in predictable ways. These cards cover the most common failure modes for agent replanning decisions and how to guard against them before they reach production.
Overcorrection on Minor Failures
What to watch: The model abandons the entire plan and proposes a full rewrite when a single step fails with a recoverable error, wasting completed work and tokens. Guardrail: Include explicit severity thresholds in the prompt—distinguish between 'patch this step' and 'replan from scratch.' Test with injected transient errors to verify the model defaults to minimal patches.
Silent Continuation After Unrecoverable Failure
What to watch: The model marks a failed step as 'continue' without addressing the root cause, causing downstream steps to operate on corrupted or missing state. Guardrail: Require the decision output to include a mandatory failure_root_cause field. Add an eval that rejects any 'continue' decision where the root cause field is empty or generic.
Cost-Indifferent Replanning
What to watch: The model proposes a replan that re-executes expensive steps (API calls, large retrievals, human approvals) without weighing the cost of rework against the benefit of correction. Guardrail: Include cost metadata per step in the plan context. Add a constraint that the replan must estimate re-execution cost and justify it when exceeding a threshold.
Defaulting to Abort Under Ambiguity
What to watch: When the failure cause is unclear, the model conservatively aborts the entire plan even when a human could resolve the ambiguity with one clarification. Guardrail: Add an explicit 'request_clarification' decision option. Test with ambiguous but low-risk failures and verify the model escalates rather than aborts when uncertainty is high but consequences are bounded.
Rollback Scope Creep
What to watch: The model proposes rolling back more steps than necessary, undoing valid completed work because it cannot precisely identify which steps depend on the failed output. Guardrail: Include an explicit dependency graph in the plan context. Require the replan output to list exactly which steps are affected and why. Validate that unaffected steps are preserved.
Decision Inconsistency Across Similar Failures
What to watch: The model produces different decisions (patch vs. abort vs. rollback) for nearly identical failure scenarios, making agent behavior unpredictable in production. Guardrail: Build a regression test suite with canonical failure scenarios and expected decision types. Run eval before every prompt change and flag decision drift beyond an acceptable threshold.
Evaluation Rubric
Criteria for testing whether the replanning decision prompt produces safe, consistent, and cost-aware outputs before deploying into an agent runtime.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Decision Type Validity | Output contains exactly one decision from the allowed set: continue, patch, rollback, or abort | Missing decision field, multiple decisions, or value outside the allowed enum | Schema validation against allowed enum; parse check on decision field |
Evidence Grounding | Decision references at least one specific piece of evidence from [FAILURE_CONTEXT] or [NEW_EVIDENCE] in the rationale | Rationale contains only generic reasoning with no reference to provided context fields | Keyword match test: rationale must contain a substring present in the input context fields |
Safe Default Behavior | When [FAILURE_CONTEXT] is ambiguous or confidence is low, decision defaults to abort or escalate rather than continue | Model selects continue or patch when failure severity is marked unknown or confidence is below threshold | Run 10 ambiguous-failure test cases; assert abort rate >= 80% when confidence < [CONFIDENCE_THRESHOLD] |
Cost-Awareness Check | Patch and rollback decisions include an estimated step count or token cost impact in the rationale when [BUDGET_CONSTRAINT] is provided | Rationale ignores budget constraint entirely or proposes patch exceeding remaining budget without justification | Parse rationale for cost estimate; assert estimate present when [BUDGET_CONSTRAINT] is non-null |
Idempotency Consideration | Rollback decisions identify which completed steps have irreversible side effects and flag them for human review | Rollback plan assumes all steps are reversible without checking side-effect markers in [COMPLETED_STEPS] | Assert rollback output contains irreversible-step list when [COMPLETED_STEPS] includes steps marked non-idempotent |
Downstream Impact Analysis | Patch decisions list which pending steps in [REMAINING_PLAN] are affected by the proposed change | Patch proposal modifies a step without noting that dependent downstream steps may need revalidation | Parse patch output for affected-step references; assert at least one downstream step mentioned when dependency graph shows successors |
Escalation Appropriateness | Abort decisions include a specific escalation reason and preserve [COMPLETED_STEPS] state for handoff | Abort output is a bare stop command with no state summary or escalation rationale | Assert abort output contains both escalation_reason field and completed_steps_summary when decision is abort |
Decision Consistency | Same [FAILURE_CONTEXT] and [PLAN_STATE] produce the same decision type across 5 repeated runs with temperature 0 | Decision type varies across runs for identical deterministic inputs | Run 5 identical requests at temperature 0; assert all decision fields match exactly |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a frontier model and minimal validation. Replace the structured output schema with a simpler JSON block. Remove cost-awareness fields and keep only the core decision enum: continue, patch, rollback, abort. Run in a single-turn agent loop without retry logic.
codeYou are an agent replanning decision module. Given the [PLAN_STATE] and [FAILURE_EVIDENCE], output one of: continue, patch, rollback, abort. Provide a one-sentence reason.
Watch for
- Overly eager
continuedecisions when evidence clearly contradicts the plan - Missing rationale that makes debugging impossible
- No handling of partial failures or ambiguous evidence

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us