Inferensys

Prompt

Agent Loop Detection and State Reset Prompt

A practical prompt playbook for using Agent Loop Detection and State Reset Prompt in production AI workflows.
Developer designing multi-agent workflow on laptop, architecture diagram on screen, casual home office setup with afternoon light.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job, ideal user, required context, and constraints for the Agent Loop Detection and State Reset Prompt.

This prompt is for agent runtime operators and developers who need to detect when an autonomous agent is stuck in a non-productive loop—repeating the same tool calls, revisiting the same failed states, or cycling through the same reasoning without making progress toward its goal. The job-to-be-done is automated loop detection with an actionable diagnosis, not just a timeout or a step-count limit. The ideal user is an engineering lead or AI builder integrating this detection into an agent harness that already has access to structured action logs, state snapshots, and tool-call histories. You need at least a sequence of recent agent actions with their outcomes and the current task objective before this prompt can produce a useful diagnosis.

Use this prompt when your agent runtime observes repeated action patterns, identical tool-call arguments, or a cycle of state changes that return to a previously visited state without advancing the task. It is designed for production agent loops where the cost of continued execution exceeds the cost of detection and intervention. The prompt produces a structured loop diagnosis with evidence of repetition, identifies which state fields are affected, and proposes a concrete reset or strategy change. It includes explicit false-positive checks so you are not resetting state when the agent is making slow but real progress through a large or repetitive but necessary task sequence.

Do not use this prompt as a substitute for proper timeout mechanisms, step-count limits, or basic cycle detection in your application code. It is not a real-time safety interlock for high-frequency control loops, and it should not be the only guardrail preventing infinite token spend. This prompt is most effective when wired into a monitoring layer that triggers it after a configurable threshold—such as N repeated tool calls with identical arguments or M state revisits within a time window. For regulated or high-risk domains, always route the loop diagnosis and proposed reset to a human reviewer before executing state mutations, especially when the reset involves discarding partial work or changing the agent's goal parameters. Pair this prompt with the State Integrity Validation Prompt Template to verify that the reset state is internally consistent before resuming execution.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Agent Loop Detection and State Reset Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your agent architecture before wiring it into a runtime.

01

Good Fit: Long-Running Autonomous Agents

Use when: agents execute multi-step plans over minutes or hours without human supervision. Loop detection prevents silent token waste and repeated tool calls. Guardrail: pair with a maximum step budget so detection has a hard ceiling even if the prompt misses a subtle loop.

02

Bad Fit: Single-Pass Inference Pipelines

Avoid when: the model makes one call and returns. Loop detection adds latency and token overhead with no benefit. Guardrail: gate the prompt behind a step counter; only invoke after N consecutive actions with no observable state change.

03

Required Inputs

Must provide: recent action history with timestamps, current agent state snapshot, goal definition, and tool-call outcomes. Guardrail: validate that action history contains at least 3 steps before invoking detection; fewer steps produce unreliable loop signals.

04

Operational Risk: False-Positive Loop Classification

Risk: legitimate retry logic or multi-step data collection gets flagged as a loop, triggering unnecessary state resets. Guardrail: require the prompt to output a confidence score and list alternative explanations before resetting state. Escalate low-confidence detections to a human reviewer or a secondary model check.

05

Operational Risk: State Reset Data Loss

Risk: resetting agent state discards partially completed work or accumulated context that is still valid. Guardrail: never reset state automatically. The prompt must propose which state fields to preserve, which to reset, and why. Require explicit confirmation or a dry-run diff before applying changes.

06

When to Use Product Code Instead

Use product code when: loop detection can be expressed as deterministic rules (identical action sequences, no progress after N steps, repeated error codes). Guardrail: reserve this prompt for ambiguous cases where semantic similarity matters. Deterministic checks are cheaper, faster, and auditable without model variance.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for detecting agent loops and proposing state resets with evidence and false-positive checks.

This prompt template is designed to be injected into an agent's execution loop when a loop detection monitor fires. It receives the agent's recent action history, current internal state, and the original goal. The model's job is to diagnose whether a genuine non-productive loop exists, provide specific evidence, identify which state fields are stale or corrupted, and recommend a concrete reset or strategy change. The template includes explicit false-positive checks to prevent unnecessary resets when the agent is making legitimate progress through similar-looking steps.

code
You are an agent loop detector and state reset advisor. Your task is to analyze the agent's recent execution trace and determine whether it is stuck in a non-productive loop, or whether the repeated actions represent legitimate progress.

## INPUTS

[AGENT_GOAL]
[RECENT_ACTION_HISTORY]
[CURRENT_AGENT_STATE]
[LOOP_DETECTION_THRESHOLD]
[TOOL_CAPABILITIES]

## INSTRUCTIONS

1. **Analyze the action history** for repeated patterns. Look for:
   - Identical tool calls with identical arguments repeated [LOOP_DETECTION_THRESHOLD] or more times.
   - Cyclic sequences where the agent returns to a previous state without making progress toward [AGENT_GOAL].
   - Tool calls that produce errors or empty results but are retried without parameter changes.

2. **Perform false-positive checks** before declaring a loop:
   - Is each repeated action producing a different, valid output? If yes, this may be legitimate iteration.
   - Is the agent processing a list or paginated results where similar calls are expected? If yes, check whether the offset or cursor is advancing.
   - Is the agent exploring a search space with different parameters that happen to share a call structure? If yes, verify parameter variation.
   - Is there evidence of forward progress in [CURRENT_AGENT_STATE] that the action history alone might miss?

3. **If a genuine loop is detected**, produce a diagnosis with:
   - **Loop type**: exact-repeat | cyclic | error-retry | state-oscillation
   - **Evidence**: specific action indices, timestamps, or state comparisons that prove no progress.
   - **Affected state fields**: which parts of [CURRENT_AGENT_STATE] are stale, corrupted, or driving the loop.
   - **Root cause hypothesis**: why the agent is stuck (e.g., stale state field, missing tool, incorrect assumption, goal ambiguity).

4. **Propose a reset or strategy change**:
   - **State reset fields**: specific fields to clear, revert, or mark as uncertain.
   - **Strategy change**: alternative approach, different tool, or decomposition change.
   - **Escalation trigger**: if the loop has persisted beyond recovery, recommend human escalation with a summary.

5. **If no genuine loop is detected**, explain why the apparent repetition is legitimate and what progress indicators confirm this.

## OUTPUT SCHEMA

Return a JSON object with this exact structure:
{
  "loop_detected": boolean,
  "false_positive_check": {
    "legitimate_iteration": boolean,
    "pagination_or_cursor_advancing": boolean,
    "parameter_variation_present": boolean,
    "state_progress_evidence": string
  },
  "diagnosis": {
    "loop_type": "exact-repeat" | "cyclic" | "error-retry" | "state-oscillation" | null,
    "evidence": [string],
    "affected_state_fields": [string],
    "root_cause_hypothesis": string
  },
  "reset_recommendation": {
    "fields_to_reset": [string],
    "fields_to_mark_uncertain": [string],
    "strategy_change": string,
    "escalation_recommended": boolean,
    "escalation_summary": string
  },
  "confidence": 0.0-1.0,
  "reasoning_summary": string
}

## CONSTRAINTS

- Do not declare a loop without citing specific, timestamped evidence from [RECENT_ACTION_HISTORY].
- If confidence is below 0.7, recommend observation over reset.
- Never recommend clearing state fields that contain user-provided information or irreversible action records.
- If [RISK_LEVEL] is "high", always set escalation_recommended to true for any detected loop.

Adaptation guidance: Replace the square-bracket placeholders with your agent runtime's actual data structures. [AGENT_GOAL] should be the original objective string. [RECENT_ACTION_HISTORY] should be a structured log of the last N actions with timestamps, tool names, arguments, and results. [CURRENT_AGENT_STATE] should be the full state object your agent maintains. [LOOP_DETECTION_THRESHOLD] is an integer (typically 3-5) that defines how many repeats trigger analysis. [TOOL_CAPABILITIES] should list available tools so the model can suggest alternatives. [RISK_LEVEL] should be "low", "medium", or "high" based on the cost or irreversibility of the agent's actions. Wire this prompt into your agent's monitor callback so it fires before the next action is dispatched, not after additional wasted calls. Validate the output JSON against the schema before applying any state resets, and log every loop diagnosis for post-mortem analysis.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Agent Loop Detection and State Reset Prompt. Validate each placeholder before calling the model to prevent runtime failures and misleading loop diagnoses.

PlaceholderPurposeExampleValidation Notes

[ACTION_HISTORY]

Ordered list of recent agent actions with timestamps, tool names, and outcomes

["2025-01-15T10:03:00Z: web_search('pricing') -> 3 results", "2025-01-15T10:03:12Z: web_search('pricing') -> 3 results"]

Must contain at least 5 entries for reliable loop detection. Each entry must have timestamp, action name, and outcome. Null or empty array triggers insufficient-data refusal.

[CURRENT_GOAL]

The active objective or subtask the agent is attempting to complete

"Extract competitor pricing for product X from public sources"

Must be a non-empty string. Vague goals like 'do research' increase false-positive loop flags. Validate goal specificity score before passing to prompt.

[STATE_SNAPSHOT]

Current agent state including completed tasks, in-progress items, and known facts

{"completed": ["identified 3 competitors"], "in_progress": "pricing extraction", "known_facts": {"competitor_A_price": null}}

Must be valid JSON with completed, in_progress, and known_facts fields. Stale snapshots older than 5 action cycles should be refreshed before detection.

[LOOP_DETECTION_THRESHOLD]

Minimum number of similar actions within a window to trigger loop classification

3 similar actions within 10 cycles

Must be an integer >= 2. Lower values increase false positives. Validate against action history length to ensure threshold is achievable.

[TOOL_CAPABILITIES]

List of available tools with descriptions to distinguish intentional retries from missing capabilities

["web_search", "scrape_url", "database_query", "calculator"]

Must be a non-empty array of tool names. Missing tool descriptions cause the model to misclassify capability gaps as loops. Validate tool list matches actual runtime tools.

[FALSE_POSITIVE_CHECKS]

Explicit conditions that override loop classification even when action patterns repeat

["different query parameters each call", "paginated results across calls", "explicit user instruction to retry"]

Must be an array of strings describing legitimate repeat scenarios. Empty array allowed but increases false-positive rate. Validate each check is testable against action history.

[MAX_RETRY_CONTEXT]

Upper bound on how many past actions to include in the analysis window

20 actions

Must be an integer between 5 and 50. Values above 50 increase token cost and latency without proportional accuracy gain. Validate against context window budget.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the loop detection prompt into an agent runtime with validation, retries, and safe state mutation.

The loop detection prompt is not a standalone diagnostic; it is a guardrail that sits inside the agent's execution loop. After every N actions—or when a configurable staleness threshold is exceeded—the agent runtime should call this prompt with the recent action log, current state summary, and the original goal. The prompt returns a loop diagnosis, but the harness is responsible for deciding whether to trust it, act on it, or escalate. Treat the prompt output as a recommendation, not a command. In high-risk or irreversible workflows, require human approval before executing any state reset or strategy change proposed by the model.

Wire the prompt into the agent runtime as a synchronous check with a timeout. Pass the last [ACTION_COUNT] actions (default 10–20), the [CURRENT_STATE] object, and the [ORIGINAL_GOAL]. The model should return a structured JSON object with loop_detected (boolean), confidence (0–1), evidence (array of repeating action patterns with timestamps), affected_state_fields (array of state keys that appear stale or corrupted), and recommended_actions (array of reset, skip, replan, or escalate directives). Validate the output against this schema before acting on it. If confidence is below 0.7, log the diagnosis but do not trigger a reset automatically. If the output fails schema validation, retry once with a stricter prompt that includes the validation error. After two failures, escalate to a human operator with the raw action log and the failed outputs.

Implement a false-positive circuit breaker. Track how many times the loop detector fires within a session. If it fires more than [MAX_DETECTIONS] times (start with 3) without a human confirming a real loop, suppress automatic resets and escalate. This prevents the agent from thrashing between state resets when the underlying problem is a poorly scoped goal or an unavailable tool, not a true loop. Log every detection event with the full prompt input, model output, validation result, and the action taken (ignored, reset, escalated). These logs are essential for tuning the detection threshold and for postmortem analysis when an agent silently fails in production.

Model choice matters here. Use a model with strong instruction-following and structured output support for the detection prompt—GPT-4o, Claude 3.5 Sonnet, or equivalent. Avoid smaller or older models that may hallucinate loop patterns in random action sequences. If latency is critical, consider running the loop detector on a separate, cheaper model (like GPT-4o-mini or Claude Haiku) with a higher confidence threshold for action, and only escalate to a larger model when the small model flags a potential loop. Always include the [FALSE_POSITIVE_CHECKS] section in the prompt template, which asks the model to explicitly list reasons why the observed pattern might not be a loop (e.g., legitimate retries, progressive refinement, or tool unavailability). This reduces over-triggering.

Before shipping, build a small eval set of 20–30 action sequences: 10 with known loops (repeated tool calls with identical arguments, cycling through the same 3 actions, revisiting completed subtasks), 10 with legitimate repetition (retrying after a transient error, iterating through paginated results, re-checking a condition that changed), and 5–10 edge cases (empty action logs, single-action sessions, rapid context switches). Measure precision and recall on this set. Tune the [ACTION_COUNT] window and the confidence threshold until false positives are acceptable for your risk tolerance. In regulated domains, keep a human in the loop for all state resets until the detector has demonstrated >95% precision over 1,000 production decisions.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the loop detection and state reset output. Use this contract to parse, validate, and route the model response before acting on reset recommendations.

Field or ElementType or FormatRequiredValidation Rule

loop_detected

boolean

Must be true or false. If false, all other fields except evidence_summary may be null.

loop_type

string (enum)

true when loop_detected=true

Must match one of: action_repetition, state_oscillation, no_progress_stall, tool_call_loop, reasoning_loop. Reject unknown values.

confidence_score

float (0.0-1.0)

Must be a number between 0.0 and 1.0. Values below [CONFIDENCE_THRESHOLD] should trigger human review before reset.

evidence_summary

string

Must be non-empty. If loop_detected=false, must explain why no loop was found. Max [MAX_EVIDENCE_LENGTH] characters.

repeated_actions

array of objects

true when loop_detected=true

Each object must contain action_name (string), count (integer >= 2), and last_timestamps (array of ISO-8601 strings). Array must not be empty when loop_detected=true.

affected_state_fields

array of strings

true when loop_detected=true

Each string must reference a valid state field from [STATE_SCHEMA]. Array must not be empty. Reject references to undefined fields.

reset_recommendations

array of objects

true when loop_detected=true

Each object must contain action (string enum: clear_field, rollback_checkpoint, change_strategy, escalate, inject_variation), target (string), and rationale (string). Array must not be empty.

false_positive_check

object

Must contain passed (boolean) and checks_performed (array of strings). If passed=false, loop_detected must be false. Checks must include at least: progress_verification, context_window_review, tool_output_variance.

PRACTICAL GUARDRAILS

Common Failure Modes

Loop detection prompts fail in predictable ways. These are the most common failure modes and how to guard against them before they waste tokens, corrupt state, or cause silent stalls in production.

01

False-Positive Loop Detection

What to watch: The prompt flags normal iterative refinement or legitimate retries as a loop, triggering an unnecessary reset that discards valid progress. This is most common when similarity thresholds are too tight or when the prompt compares surface-level action text rather than semantic intent. Guardrail: Require the prompt to distinguish between productive iteration (output quality improving, new evidence arriving) and unproductive looping (identical outputs, no state change). Include explicit false-positive checks in the output schema, such as a productive_variation_detected field with evidence before declaring a loop.

02

Loop Diagnosis Without Evidence

What to watch: The prompt declares a loop but provides only vague reasoning like 'the agent seems stuck' without citing specific repeated actions, timestamps, or state comparisons. This makes the diagnosis unactionable and unverifiable, leading to either ignored warnings or blind resets. Guardrail: Require the output to include a structured evidence block with exact repeated action sequences, count of repetitions, time window, and a diff of state changes (or lack thereof). Add a schema constraint that the evidence array must be non-empty before a loop can be confirmed.

03

Overly Aggressive State Reset

What to watch: The prompt recommends resetting too much state—discarding completed subtasks, user preferences, or validated intermediate results—when only a small portion of the state is actually corrupted or stale. This forces the agent to redo work and can frustrate users who see progress vanish. Guardrail: Require the prompt to produce a granular reset recommendation that specifies exactly which state fields should be cleared, which should be preserved, and which should be marked as 'needs revalidation.' Include a reset_scope field with values like full, partial, or targeted and require justification for anything beyond targeted.

04

Loop Detection on Stale or Incomplete Context

What to watch: The prompt analyzes only recent action history and misses that the agent is actually making progress across a longer time horizon, or it operates on a truncated context window that has lost critical evidence of state changes. This produces loop detections that are artifacts of context-window management rather than real agent behavior. Guardrail: Include a context_adequacy_check in the prompt instructions that asks whether the available history is sufficient for a reliable loop diagnosis. If context is truncated, require the prompt to flag this as a limitation and reduce confidence in the loop declaration. Pair with a checkpoint system that preserves key state transitions outside the main context window.

05

Reset Strategy That Repeats the Same Failure

What to watch: The prompt recommends a strategy change or state reset, but the new strategy is functionally identical to what the agent was already doing—just rephrased. The agent resets, follows the 'new' plan, and hits the same dead end again, creating a meta-loop of detection and ineffective reset. Guardrail: Require the prompt to compare the proposed reset strategy against the original approach and explicitly identify what is different. Add a strategy_divergence_check that must confirm the new approach changes at least one of: tool selection, execution order, goal decomposition, or information-gathering method. If no meaningful divergence exists, the prompt should escalate rather than recommend a cosmetic reset.

06

Silent Loop Masking by Tool Call Variation

What to watch: The agent varies surface-level tool call parameters (different search queries, slightly modified API arguments) without changing the underlying strategy, so action-level similarity checks miss the loop. The agent burns tokens on endless variations of the same ineffective approach while appearing to make progress. Guardrail: Add semantic similarity checks that compare the intent and expected outcome of actions, not just their surface form. Instruct the prompt to look for patterns where different tool calls serve the same unresolved subgoal without advancing it. Include a goal_progress_stalled flag that triggers when a subgoal remains open across N or more distinct but semantically equivalent attempts.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the Agent Loop Detection and State Reset Prompt output before deploying it in production. Each criterion targets a specific failure mode common in loop detection and state reset scenarios. Run these checks against a golden set of agent traces containing known loops, false positives, and normal progress.

CriterionPass StandardFailure SignalTest Method

Loop Detection Accuracy

Correctly identifies >=95% of true loops in the test set

Missed loops or detection rate below threshold

Run against 50+ labeled agent traces with known loop patterns; measure recall

False Positive Rate

Flags <5% of normal progress traces as loops

Excessive false alarms causing unnecessary resets

Run against 50+ normal progress traces; measure false positive rate

Evidence Quality

Every loop diagnosis includes >=2 concrete action-timestamp pairs as evidence

Vague claims like 'agent seems stuck' without specific evidence

Parse output for evidence array; verify each entry has action, timestamp, and repetition count

Affected State Fields Accuracy

All listed affected state fields are actually modified by the looping actions

Listing fields not touched by the loop or missing fields that are corrupted

Cross-reference output state fields against the trace's actual state mutations

Reset Recommendation Safety

Reset actions are reversible or scoped to non-destructive state fields

Recommending deletion of completed work or irreversible external actions

Review reset recommendations against a safety checklist; flag destructive proposals

State Reset Completeness

Reset proposal addresses all state fields corrupted by the loop

Partial reset leaving stale or contradictory state entries

Diff the proposed reset state against known-good state; check for residual corruption

Strategy Change Specificity

Proposes a concrete alternative strategy, not just 'try again'

Generic advice like 'retry' or 'change approach' without specifics

Check that strategy field contains a new action plan with >=1 different tool or order

Output Schema Compliance

Output matches the required JSON schema with all mandatory fields present

Missing fields, wrong types, or extra fields that break downstream parsers

Validate output against the defined JSON schema; reject on any schema violation

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt\nStart with the base loop-detection prompt but relax the evidence requirements. Instead of requiring `[LOOP_EVIDENCE]` with exact timestamps, accept a plain-language description of the repeating pattern. Use a simpler output schema with only `loop_detected`, `confidence`, and `recommendation` fields. Skip the false-positive checklist during early testing.\n\n```markdown\n## Simplified Output Schema\nReturn JSON with:\n- loop_detected: boolean\n- confidence: "low" | "medium" | "high"\n- recommendation: string\n```\n\n### Watch for\n- Over-triggering on legitimate retries (e.g., a tool that requires 3 polling attempts)\n- Missing false-positive patterns because the checklist was removed\n- Confidence scores that don't match observable behavior\n- The model treating any repeated action as a loop without checking for progress

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.