Inferensys

Prompt

Agent Plan Patching Prompt for Loop Detection

A practical prompt playbook for using Agent Plan Patching Prompt for Loop Detection in production AI workflows.
Developer reviewing multi-agent chat interface on laptop, agent conversation logs visible, casual coding session at WeWork desk.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise operational conditions for invoking the loop-detection plan-patching prompt and clarifies when alternative interventions are required.

This prompt is a runtime recovery tool for agent orchestrators that have already identified a repetitive execution pattern. It is not a planning prompt; it is a surgical patching prompt. The target user is an agent runtime developer or platform engineer who has instrumented a loop-detection module—typically a state machine observer that tracks step history, tool-call signatures, and state transitions. When that module fires a loop-detected event, this prompt is the next step in the recovery pipeline. The prompt expects structured input describing the stuck agent's current plan, the detected cycle, and the execution trace leading up to the loop. Its job is to produce a minimal, verifiable plan patch that breaks the cycle through step reordering, constraint addition, or escalation.

Invoke this prompt when the agent has repeated the same tool call with identical or semantically equivalent arguments three or more times, cycled through a set of steps without advancing the completion state, or revisited a previously completed step as if it were still pending. The loop must be a planning or execution-logic failure, not an environmental one. Before calling this prompt, your detection module should classify the loop type: exact repetition (same tool, same arguments), semantic repetition (different arguments, same intent, no progress), or state oscillation (flipping between two or more steps). This classification must be included in the prompt's [LOOP_CLASSIFICATION] input. The prompt also requires the agent's current plan object, the last N execution steps, and any active constraints such as budget, time, or permission boundaries.

Do not use this prompt for initial plan generation, single-step error recovery, or cases where the loop is caused by an external system outage that requires an operational fix rather than a planning intervention. If the agent is stuck because an API is returning 503s, a database is down, or a credential has expired, use the Agent Plan Patching Prompt for Tool Failure or the Agent Plan Patching Prompt for Authentication Expiry instead. Similarly, if the loop is caused by a hallucinated tool schema or fabricated output from a prior step, route to the Agent Plan Patching Prompt for Model Hallucination Detection. Misrouting a systemic infrastructure failure into a planning patch will produce a patch that looks correct but fails identically on re-execution. Always verify that the root cause is a planning or reasoning defect before invoking this prompt.

PRACTICAL GUARDRAILS

Use Case Fit

Where the loop-detection plan patching prompt delivers value and where it introduces risk. Use these cards to decide if this prompt belongs in your agent runtime.

01

Good Fit: Autonomous Long-Running Agents

Use when: your agent executes multi-step plans over minutes or hours where human supervision is sparse. Loop detection prevents silent token waste and stalled workflows. Guardrail: pair with a maximum step counter and a cost ceiling so the patching prompt itself doesn't become a new loop vector.

02

Bad Fit: Single-Step Tool Calls

Avoid when: the agent makes exactly one tool call per user turn with no iterative planning. Loop detection adds latency and complexity with no benefit. Guardrail: gate the patching prompt behind a minimum step threshold—only invoke after N consecutive similar actions.

03

Required Input: Structured Execution Trace

What to watch: the prompt needs a timestamped log of recent steps, tool names, arguments, and outputs. Without structured traces, the model cannot reliably classify repetitive patterns. Guardrail: instrument your agent runtime to emit a JSON trace buffer of the last K steps before invoking the patch prompt.

04

Operational Risk: Patch Introduces New Loop

What to watch: a patched plan may contain the same structural flaw that caused the original loop, especially if the root cause is a missing tool or ambiguous goal. Guardrail: run a one-step simulation of the patched plan's first action before committing to full re-execution. Abort if the patch doesn't change the action signature.

05

Operational Risk: Premature Loop Classification

What to watch: legitimate retry logic or polling behavior can be misclassified as a loop, causing unnecessary replanning. Guardrail: require a minimum repetition count and temporal window before triggering loop detection. Distinguish between intentional retries and unintentional cycles in the trace schema.

06

Operational Risk: Termination Guarantee

What to watch: the patching prompt may suggest a plan that still lacks a clear exit condition, leading to repeated patch cycles. Guardrail: include a hard termination rule—if patching occurs more than N times for the same goal, escalate to a human operator and halt autonomous execution.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A ready-to-use template for generating a plan patch when an agent runtime detects a repetitive execution loop.

This template is designed to be injected into your agent's control loop the moment a loop detector fires. Its job is to produce a minimal, actionable patch that breaks the cycle—not to re-plan the entire mission. The prompt forces the model to classify the loop's root cause before proposing a fix, which makes the output auditable and prevents superficial patches that just reorder the same failing steps. You should call this prompt with the frozen execution trace, the current plan, and the loop signature as inputs.

text
SYSTEM: You are an agent plan patching specialist. Your only job is to analyze a detected execution loop and produce a minimal patch that breaks the cycle. You do not re-execute steps. You do not change the overall goal. You output a structured patch or a safe escalation.

USER:
# LOOP DETECTION REPORT
- Loop Signature: [LOOP_SIGNATURE]
- Repetition Count: [REPETITION_COUNT]
- Steps Involved: [LOOP_STEP_IDS]
- Time in Loop: [LOOP_DURATION]

# CURRENT PLAN STATE
[PLAN_STATE]

# EXECUTION TRACE (last [TRACE_WINDOW] steps)
[EXECUTION_TRACE]

# CONSTRAINTS
- Max Patch Steps: [MAX_PATCH_STEPS]
- Allowed Tools: [ALLOWED_TOOLS]
- Budget Remaining: [BUDGET_REMAINING]
- Deadline: [DEADLINE]
- Risk Level: [RISK_LEVEL]

# INSTRUCTIONS
1. Classify the loop root cause as exactly one of: [LOOP_CLASSIFICATION_OPTIONS]
2. If the loop is unrecoverable with available tools, output an escalation.
3. Otherwise, output a patch with these fields:
   - `patch_id`: string
   - `loop_root_cause`: string (from classification)
   - `patch_strategy`: string (one of: reorder_steps, add_constraint, substitute_step, insert_validation, reduce_scope, escalate)
   - `steps_to_remove`: [list of step IDs to drop from the current plan]
   - `steps_to_insert`: [list of new step objects with id, description, tool, and arguments]
   - `steps_to_modify`: [list of step ID and field-override pairs]
   - `termination_guarantee`: string (explain why this patch prevents the same loop from recurring)
   - `confidence`: number (0.0 to 1.0)
4. If confidence is below [CONFIDENCE_THRESHOLD], default to escalation.
5. Do not invent tools. Only use tools in the allowed list.
6. The patch must not exceed [MAX_PATCH_STEPS] total insertions and modifications.

# OUTPUT SCHEMA
[OUTPUT_SCHEMA]

To adapt this template, replace every square-bracket placeholder at runtime before the model call. [LOOP_SIGNATURE] should be a compact hash or description of the repeating pattern your detector identified—such as "steps 3-4-5 repeated 4 times with identical arguments." [PLAN_STATE] must include the full current plan with step statuses, not just the looping segment, so the model can assess downstream impact. [LOOP_CLASSIFICATION_OPTIONS] should be a domain-specific enum you define once per agent deployment; examples include identical_args_loop, oscillating_state_loop, tool_rejection_loop, empty_result_loop, and constraint_impossible_loop. The [OUTPUT_SCHEMA] placeholder should be replaced with your application's expected JSON schema, which your validator will check before the patch is applied. If your agent operates in a regulated domain, set [RISK_LEVEL] to high and ensure a human reviews any patch with confidence below 0.85 before execution resumes.

IMPLEMENTATION TABLE

Prompt Variables

Every placeholder the Agent Plan Patching Prompt for Loop Detection expects, why it matters, and how to validate it before sending to the model.

PlaceholderPurposeExampleValidation Notes

[CURRENT_PLAN]

The full plan being executed, including completed, in-progress, and pending steps with their statuses

{"steps": [{"id": "1", "status": "completed", "action": "search_docs"}, {"id": "2", "status": "in_progress", "action": "summarize"}]}

Must be valid JSON with a steps array. Each step requires id, status, and action fields. Status must be one of: completed, in_progress, pending, failed. Reject if plan contains circular dependencies or missing step references.

[LOOP_PATTERN]

The detected repetitive step sequence that triggered loop detection, including step IDs and repetition count

{"pattern": ["2", "3", "2", "3"], "repetitions": 3, "duration_ms": 45000}

Must be valid JSON with pattern array and repetitions integer. Pattern array must contain step IDs present in CURRENT_PLAN. Repetitions must be >= 2. Reject if pattern length is 0 or repetitions is null.

[EXECUTION_HISTORY]

Ordered log of step executions with timestamps, inputs, outputs, and tool call details for the detected loop window

[{"step_id": "2", "timestamp": "2024-01-15T10:30:00Z", "tool": "web_search", "input": {"query": "X"}, "output": {"results": []}}]

Must be a JSON array ordered by timestamp ascending. Each entry requires step_id matching CURRENT_PLAN, timestamp in ISO 8601, and tool name. Validate that history covers the full loop pattern window. Reject if timestamps are out of order or missing.

[AVAILABLE_TOOLS]

Schema definitions for all tools the agent can call, used to verify patch feasibility

[{"name": "web_search", "parameters": {"query": "string"}}, {"name": "escalate_to_human", "parameters": {"reason": "string"}}]

Must be a JSON array of tool definitions. Each tool requires name and parameters schema. Validate that at least one tool exists. Reject if tool names contain duplicates or parameters schema is malformed.

[CONSTRAINTS]

Active constraints governing execution: budget, time limits, permission boundaries, and safety policies

{"max_steps": 20, "max_duration_seconds": 300, "allowed_tools": ["web_search", "summarize"], "require_human_approval_for": ["file_write"]}

Must be valid JSON with at least one constraint field. Validate that max_steps and max_duration_seconds are positive integers if present. allowed_tools must be a subset of AVAILABLE_TOOLS names. Reject if constraints contradict each other.

[LOOP_CLASSIFICATION]

Pre-computed classification of the loop type to guide patch strategy selection

{"type": "oscillation", "confidence": 0.92, "root_cause_hypothesis": "search returning empty results causes retry with identical query"}

Must be valid JSON with type field. Type must be one of: oscillation, stall, divergence, redundant_recomputation, deadlock. Confidence must be a float between 0.0 and 1.0. Reject if type is unrecognized or confidence is outside range.

[OUTPUT_SCHEMA]

Expected JSON schema for the patch output, defining required fields and their types

{"type": "object", "properties": {"patch_type": {"enum": ["reorder", "add_constraint", "escalate", "insert_wait", "modify_step"]}, "affected_step_ids": {"type": "array"}}, "required": ["patch_type", "affected_step_ids", "rationale"]}

Must be a valid JSON Schema object. Required array must include patch_type, affected_step_ids, and rationale at minimum. Validate that patch_type enum values are recognized. Reject if schema is not parseable by a standard JSON Schema validator.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the loop-detection patching prompt into an agent runtime so it fires reliably and the output is validated before the agent acts on it.

The loop-detection patching prompt is a recovery component, not a primary planner. It should be wired into the agent's execution loop as a monitor that fires when a repetitive pattern is detected. The harness must classify the loop type before calling the prompt, because the prompt's effectiveness depends on receiving accurate loop metadata—step sequence, repetition count, tool signatures, and state deltas. Do not invoke this prompt on every step; instead, trigger it from a loop detector that tracks step hashes, tool-call fingerprints, or state-action pairs over a sliding window. The detector should fire when it observes N consecutive cycles with no forward progress, where N is tuned to your latency tolerance and cost budget.

The implementation flow: (1) The loop detector identifies a candidate loop and captures the last K steps with their inputs, outputs, and tool signatures. (2) The harness populates the prompt template with [LOOP_PATTERN], [AGENT_STATE], [PLAN_CONTEXT], and [CONSTRAINTS]. (3) The model returns a structured patch—typically a JSON object with patch_type (reorder, insert_constraint, escalate, abort_branch), affected_steps, new_steps, and termination_guarantee (a boolean or confidence score). (4) Before applying the patch, the harness runs validation checks: verify that the patch references only existing step IDs, that any new steps use available tools from [TOOL_SCHEMA], that the patch does not reintroduce the detected loop pattern, and that termination_guarantee is asserted. If validation fails, the harness should retry once with the validation errors appended to [CONSTRAINTS]. If the retry also fails, escalate to a human operator or fall back to a safe abort.

For production deployments, log every loop-detection event with the loop fingerprint, the generated patch, validation results, and whether the patch resolved the loop. This data feeds eval regression tests: periodically replay historical loop traces against prompt updates to verify that patch quality does not degrade. Set a hard limit on patch attempts per execution session—if the agent applies more than M patches without reaching a termination state, force an abort and human review. Avoid the trap of letting the patching prompt itself become a loop source; the harness should track patch application as a distinct step type and include it in the loop detector's window to catch recursive patching failures.

IMPLEMENTATION TABLE

Expected Output Contract

The JSON structure the model must return for a loop-detection plan patch. Each field includes a validation rule your harness should enforce before accepting the patch.

Field or ElementType or FormatRequiredValidation Rule

patch_id

string (UUID v4)

Must be a valid UUID v4 string; reject if missing or malformed.

patch_type

enum: loop_break

Must equal 'loop_break'; reject any other value.

loop_classification

object

Must contain 'pattern' (string), 'repetition_count' (integer >= 3), and 'cycle_length' (integer >= 1). Reject if any field missing or out of range.

root_cause

string

Must be one of: 'missing_termination_condition', 'stale_state', 'oscillating_plan', 'tool_output_loop', 'dependency_cycle'. Reject unknown values.

affected_step_ids

array of strings

Must be a non-empty array of step IDs present in the current plan. Reject if empty or contains IDs not in the plan.

patch_actions

array of objects

Each object must have 'action' (enum: 'reorder', 'add_constraint', 'insert_termination', 'escalate', 'skip'), 'target_step_id' (string), and 'payload' (object). Reject if any action references a step not in affected_step_ids.

termination_guarantee

string

Must be a non-empty string explaining why the patch prevents infinite repetition. Reject if empty or shorter than 20 characters.

escalation_required

boolean

Must be true if any patch_action is 'escalate'; otherwise false. Reject if inconsistent with patch_actions.

PRACTICAL GUARDRAILS

Common Failure Modes

Loop detection patching fails silently when the classifier mislabels noise as a loop, the patch doesn't break the cycle, or the termination guarantee is missing. These cards cover the most common production failures and the guardrails that catch them before the agent wastes more tokens or takes harmful actions.

01

False Positive Loop Classification

What to watch: The loop detector flags legitimate iterative refinement, multi-step research, or paginated API calls as a loop. The patching prompt then rewrites a valid plan, destroying progress and wasting tokens. Guardrail: Require a minimum repetition threshold (e.g., 3 identical step signatures) and exclude known iterative patterns before invoking the patch prompt. Log every classification with the evidence that triggered it for post-hoc review.

02

Patch Fails to Break the Cycle

What to watch: The generated patch reorders steps or adds a constraint, but the underlying dependency or tool behavior that caused the loop remains. The agent applies the patch and immediately re-enters the same loop. Guardrail: After applying a patch, run a one-step dry-run validation that checks whether the next planned step differs from the loop signature. If the signature matches, escalate to a human operator instead of retrying.

03

Root Cause Misattribution

What to watch: The prompt identifies a symptom (e.g., repeated tool calls) but misattributes the root cause (e.g., blaming tool failure when the real issue is an ambiguous goal constraint). The patch addresses the wrong problem, and the loop re-emerges in a different form. Guardrail: Require the patch prompt to output an explicit root cause classification before proposing a fix. Validate that the proposed patch directly addresses the classified cause. If confidence is low, default to escalation.

04

Missing Termination Guarantee

What to watch: The patch prompt produces a revised plan that looks plausible but contains no explicit stopping condition or maximum step limit. The agent resumes execution and enters a new, undetected loop because the guardrail only checked the old pattern. Guardrail: Append a hard constraint to the patching prompt: the revised plan must include an explicit termination condition or a bounded step count. Validate the output for this field before accepting the patch.

05

Patch Introduces Deadlock

What to watch: The patch breaks the loop by inserting a dependency or waiting step that cannot be satisfied with available tools or state. The agent stalls indefinitely instead of looping. Guardrail: Run a dependency satisfiability check on the patched plan before execution. Verify that every prerequisite step has an available tool and that no circular wait conditions exist. If unsatisfiable, fall back to a safe abort-and-escalate path.

06

Escalation Threshold Too High

What to watch: The system applies patch after patch, each failing to resolve the loop, because the escalation threshold is set too high or undefined. The agent burns tokens in a patch-retry death spiral. Guardrail: Enforce a hard limit of one patch attempt per detected loop instance. If the patched plan still triggers the loop detector, immediately escalate to a human operator with the full loop trace, classification, and attempted patch. Never allow more than one automated patch per cycle.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks against a golden dataset of known loop scenarios to validate the Agent Plan Patching Prompt for Loop Detection before production deployment.

CriterionPass StandardFailure SignalTest Method

Loop Classification Accuracy

Correctly labels the loop type (e.g., infinite retry, oscillating plan, redundant step) for >= 95% of golden cases

Misclassifies loop type or returns 'no loop detected' for a known loop scenario

Run prompt against 20 labeled loop traces; compare output classification to ground truth label

Root Cause Identification

Identifies the specific step, condition, or state that caused the loop in >= 90% of cases

Returns a generic cause ('planning error') without pointing to the triggering step or condition

Check that output contains a step ID or condition reference matching the annotated root cause in the golden trace

Patch Termination Guarantee

Proposed patch breaks the detected cycle without introducing a new loop in >= 95% of cases

Patch reorders steps but preserves the same cyclic dependency or creates a new cycle

Simulate the patched plan in a dependency graph validator; confirm no cycles remain

Patch Minimality

Patch modifies only the steps necessary to break the loop; does not rewrite unrelated plan segments

Patch replaces the entire remaining plan or modifies steps not involved in the loop

Count the number of modified steps in the patch; compare to the minimum required modifications identified in the golden annotation

Constraint Preservation

Patched plan satisfies all original constraints (budget, time, permissions, tool availability)

Patch violates a stated constraint (e.g., exceeds token budget, uses unavailable tool, skips required approval)

Validate patched plan against the constraint schema from the original plan; flag any violation

Escalation Appropriateness

Escalates to human review when the loop cannot be safely broken by the agent alone

Attempts to patch an unrecoverable loop (e.g., auth failure loop) without escalation, or escalates a trivially patchable loop

Check escalation flag against golden annotation for each scenario; measure false-positive and false-negative escalation rate

Output Schema Adherence

Returns valid JSON matching the [PATCH_SCHEMA] with all required fields present

Missing required fields, malformed JSON, or extra fields not in schema

Parse output with schema validator; reject any response that fails strict validation

Idempotency Check

Applying the same patch twice to the same plan state produces the same result without cumulative damage

Second application of the patch modifies already-patched steps or produces a different plan

Apply patch output to the plan state twice; diff the results and confirm they are identical

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single model call. Focus on loop classification and patch generation without heavy schema enforcement. Accept that the model may produce verbose or slightly malformed patches.

  • Remove strict JSON output requirements; accept markdown or plain text patches.
  • Drop the termination_guarantee field and rely on manual review of the patch logic.
  • Use a simple [LOOP_DESCRIPTION] placeholder instead of structured loop trace input.

Watch for

  • Patches that describe the problem without actually breaking the cycle.
  • Overly broad patches that discard valid progress instead of surgically fixing the loop.
  • Missing root cause classification when the model jumps straight to a patch.
Prasad Kumkar

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.