Inferensys

Prompt

Deadlock Detection and Human Intervention Prompt for Agents

A practical prompt playbook for using Deadlock Detection and Human Intervention Prompt for Agents 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 specific operational conditions, user roles, and system constraints where a deadlock detection prompt is the correct intervention, and when it is not.

This prompt is designed for agent platform engineers and SREs monitoring autonomous workflows where an agent can enter a non-productive state. The core job-to-be-done is to programmatically detect when an agent is stuck in a loop, cycling between conflicting tool calls, or unable to satisfy its termination condition, and to produce a structured intervention request. The ideal user is an engineer integrating this prompt into a middleware layer that observes agent state transitions, tool-call logs, and step history. The required context includes the agent's original objective, a trace of recent actions and observations, and the termination criteria. This prompt is not a general debugging tool; it is a specific circuit breaker for production agent pipelines.

Do not use this prompt for simple retry logic, network timeout errors, or single-step failures where a standard exponential backoff is sufficient. It is also inappropriate for workflows where the cost of pausing for human review exceeds the cost of letting the agent continue, such as low-stakes, stateless data transformations. The prompt assumes the agent's action history is available in a structured format. If your system cannot provide a clean trace of tool calls, parameters, and observations, the prompt will produce unreliable deadlock assessments. Furthermore, this prompt is not a replacement for deterministic cycle detection in a graph of tool calls; it is a semantic layer on top of that data to distinguish productive retries from true deadlocks.

When to use this prompt: You have an agent orchestrator that manages multi-step tasks with tool access. You need to detect when the agent's loop is no longer making progress toward its goal, such as when it repeatedly calls the same tools with the same arguments and receives no new information, or when it oscillates between two conflicting actions. The output should feed into a human review queue or an automated circuit-breaker that pauses the agent. When to avoid: The agent's task is idempotent and safe to retry indefinitely, the cost of a false-positive pause is unacceptable, or you lack the observability infrastructure to provide a structured trace. Next, review the prompt template to see how to format the agent's state for accurate deadlock classification.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and what you must have in place before deploying it in an agent loop.

01

Good Fit: Autonomous Multi-Step Agents

Use when: an agent orchestrates multiple tool calls across APIs, databases, or browsers where a single failed step can cascade into an infinite retry loop. Guardrail: Wire this prompt as a sidecar evaluator that samples the last N actions and tool responses, not as a blocking step on every turn.

02

Bad Fit: Stateless Single-Turn Requests

Avoid when: the system handles isolated Q&A or single-function calls with no stateful execution history. Risk: The prompt will hallucinate deadlocks from normal retries or produce false positives on legitimate iterative refinement. Guardrail: Gate invocation behind a minimum turn count or repeated-tool-call detector before running deadlock analysis.

03

Required Inputs

Must have: a structured execution trace containing tool names, input arguments, output summaries, and timestamps for the last 5-15 agent steps. Guardrail: If the trace is truncated or missing tool outputs, the prompt must return an insufficient_data status rather than guessing. Never feed raw unstructured logs without tool-level schema.

04

Operational Risk: False-Positive Escalations

What to watch: legitimate retry logic with exponential backoff or alternating tool calls can look like a deadlock to a naive classifier. Guardrail: Require a minimum of 3 repeated cycles with identical or near-identical arguments before flagging. Include a retry_pattern field in the output to distinguish productive retries from true loops.

05

Operational Risk: Silent Deadlock Misses

What to watch: agents that slowly drift across different but equally ineffective tool calls without repeating exact patterns. Guardrail: Track a semantic similarity score across consecutive actions, not just exact-match deduplication. Escalate when the agent has made no progress toward its declared subgoal for N consecutive steps, even if each step looks superficially different.

06

Latency and Cost Sensitivity

What to watch: running deadlock detection on every agent step adds inference cost and latency to fast-path executions. Guardrail: Trigger detection only after a configurable step threshold or when a tool returns an error, empty result, or unchanged state. Use a lightweight heuristic pre-filter before invoking the full LLM-based analysis.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for detecting agent deadlock and producing a structured intervention request.

This template is designed to be injected into an agent's control loop when the system suspects a deadlock condition. It takes the agent's recent action history, tool outputs, and current task as input, and produces a structured assessment that distinguishes productive retries from true deadlocks. Use this prompt when your agent has exceeded a retry threshold, is cycling between conflicting tool calls, or has failed to make progress toward its goal after a configurable number of steps. Do not use this prompt for simple error handling or single-step failures—those should be caught by retry logic or validation layers before reaching this escalation point.

text
You are an agent deadlock detector. Your job is to analyze an agent's recent execution trace and determine whether it is stuck in a true deadlock or is making legitimate progress through retries.

## INPUT

[AGENT_TASK]: The original task assigned to the agent.

[EXECUTION_TRACE]: A chronological log of the agent's last N actions, tool calls, and observations. Each entry includes:
- step_number
- action_type (thought, tool_call, observation, error)
- action_detail (the specific action taken or tool invoked)
- result_summary (the outcome or observation received)

[DEADLOCK_THRESHOLD]: The number of repeated or unproductive cycles observed.

[TOOL_SCHEMAS]: The available tools and their descriptions, to assess whether the agent is using them correctly.

## OUTPUT_SCHEMA

Return a JSON object with the following structure:
{
  "deadlock_detected": boolean,
  "deadlock_type": "loop" | "conflict" | "incapacity" | "none",
  "confidence": 0.0-1.0,
  "summary": "One-sentence description of the deadlock state or progress status.",
  "evidence": [
    {
      "step_numbers": [int, int],
      "pattern": "Description of the repeating or conflicting pattern observed."
    }
  ],
  "intervention_required": boolean,
  "intervention_recommendation": "If intervention is required, specify: pause agent, request human input, provide clarification, or modify tool access. If not required, explain why the agent is still making progress.",
  "suggested_next_action": "If no deadlock, suggest the next productive step. If deadlock, suggest the specific human intervention needed."
}

## CONSTRAINTS

- A true deadlock requires evidence of a repeating pattern, not just multiple retries.
- Distinguish between: (a) productive retries where the agent is trying different approaches, (b) unproductive loops where the same action repeats with the same failed outcome, (c) tool conflicts where two tools are called in opposition, and (d) incapacity where the agent lacks the necessary tools or information to proceed.
- If the agent is making progress (even slowly), deadlock_detected must be false.
- Do not escalate for transient errors or single failures.
- If confidence is below 0.7, set intervention_required to true as a precaution.

## EVALUATION CRITERIA

Your output will be evaluated on:
1. Accuracy: Correctly distinguishing true deadlocks from productive retries.
2. Evidence quality: Specific step numbers and patterns cited, not vague impressions.
3. Appropriate escalation: Not over-escalating on normal retries, not under-escalating on genuine stalls.
4. Actionability: The intervention recommendation must be specific enough for a human operator or orchestration layer to act on immediately.

To adapt this template, adjust the [DEADLOCK_THRESHOLD] based on your agent's typical task complexity—simple tasks may warrant a lower threshold, while complex multi-step workflows may need more tolerance. The [EXECUTION_TRACE] should include enough history to reveal patterns; too few steps will produce false negatives, while too many will increase token cost without improving accuracy. Wire the output into your agent orchestration layer so that when intervention_required is true, the agent pauses and the intervention_recommendation is routed to a human review queue or a supervisor agent. Always log the full prompt and response for post-mortem analysis of escalation accuracy.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the deadlock detection prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[AGENT_LOG]

Full execution trace including tool calls, responses, timestamps, and error messages from the agent run

Step 1: search_database(query='active_users') → 0 results Step 2: search_database(query='users') → 0 results Step 3: search_database(query='active_users') → 0 results

Must contain at least 3 steps. Parse check: verify each step has action, input, and output fields. Reject if log is empty or contains only final result without intermediate steps.

[TASK_DESCRIPTION]

The original task or goal the agent was instructed to complete

Find all active users who logged in within the last 7 days and export their email addresses to the marketing list

Must be non-empty and under 2000 tokens. Parse check: verify task is a complete sentence describing a goal, not a status update or partial instruction.

[AGENT_CAPABILITIES]

List of tools, APIs, and actions available to the agent with their descriptions

search_database: query a SQL database with a natural language query send_email: send an email to a specified recipient export_csv: export query results to a CSV file

Must list at least 1 tool. Parse check: each capability should have a name and description. Reject if capabilities list is empty or contains only tool names without descriptions.

[MAX_RETRY_THRESHOLD]

Maximum number of identical or near-identical retries allowed before flagging as potential deadlock

3

Must be an integer between 2 and 10. Parse check: validate integer range. Values below 2 cause false positives on normal retries; values above 10 risk missing real deadlocks.

[CYCLE_DETECTION_WINDOW]

Number of recent steps to analyze for repetitive patterns

5

Must be an integer between 3 and 20. Parse check: validate integer range. Window too small misses longer cycles; window too large increases latency and noise from old context.

[OUTPUT_SCHEMA]

Expected JSON structure for the intervention request output

{"deadlock_detected": boolean, "deadlock_type": string, "cycle_description": string, "stuck_step_index": integer, "intervention_recommendation": string, "confidence_score": float}

Must be a valid JSON Schema or example object. Parse check: validate JSON structure. Reject if schema is missing required fields deadlock_detected, deadlock_type, and intervention_recommendation.

[ESCALATION_POLICY]

Rules defining when human intervention is required versus when the agent can self-recover

Escalate to human when deadlock_type is 'infinite_loop' or 'conflicting_tool_calls'. Allow self-recovery retry when deadlock_type is 'transient_error' and confidence_score > 0.8.

Must be non-empty and specify at least one escalation condition. Parse check: verify policy contains explicit escalation triggers. Reject if policy is 'always escalate' or 'never escalate' without conditions.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the deadlock detection prompt into an agent orchestration loop with validation, logging, and human review gates.

Integrating this prompt into an agent platform requires embedding it within the orchestration layer's monitoring loop, not as a one-off call. The prompt should be invoked after a configurable threshold of repeated tool calls or state cycles is breached. A common pattern is to maintain a rolling window of the last N agent actions and their outcomes. When the window contains a repeated pattern—such as the same tool call with identical arguments failing more than twice, or a cycle of two conflicting tools undoing each other's work—the harness should assemble the [AGENT_LOG], [CURRENT_TASK], and [AVAILABLE_TOOLS] placeholders and invoke the model. The prompt's output should be parsed as structured JSON, and the intervention_required boolean field should gate the next action: if true, the agent must pause and the intervention_payload must be routed to the human review queue.

Validation of the model's output is critical before pausing an agent. The harness must check that the JSON schema is valid, that intervention_required is a boolean, and that if it is true, the deadlock_type field is one of the expected enum values (e.g., loop, conflict, stall). If the model returns intervention_required: false but the cycle count continues to increase, the harness should implement a hard circuit breaker after a maximum retry limit to force an escalation. Log every invocation of this prompt with the full input context, the raw model output, the parsed decision, and the cycle count at the time of invocation. This audit trail is essential for tuning the detection threshold and diagnosing false negatives where the agent was stuck but the prompt failed to detect it.

For high-stakes autonomous workflows, never allow the model's intervention_required: false decision to be the sole gate. Implement a secondary, deterministic check in the harness: if the agent has executed more than a hard-coded maximum number of steps (e.g., 50) without reaching a terminal state, force an intervention regardless of the model's output. This defends against prompt failure modes where the model hallucinates a plausible 'progress' summary while the agent remains stuck. Route the generated intervention_payload to a human review interface that displays the deadlock summary, the recent agent log, and one-click actions for the reviewer to inject a new instruction, modify tool arguments, or terminate the task. Close the loop by capturing the human reviewer's action and using it to update the agent's state before resuming the orchestration loop.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the deadlock detection and human intervention prompt output. Use this contract to parse, validate, and route the model response before presenting it to a reviewer or logging system.

Field or ElementType or FormatRequiredValidation Rule

deadlock_detected

boolean

Must be true if intervention is requested. Reject if false but intervention_reason is populated.

intervention_reason

string

Must be one of: loop_detected, conflicting_tools, task_impossible, resource_unavailable, timeout, permission_denied. Reject if not in enum.

deadlock_summary

string

Must be 50-500 characters. Must reference specific agent actions or tool calls observed. Reject if generic or empty.

agent_trace_snippet

array of objects

Each object must have timestamp, action, tool_name, status fields. Minimum 3 entries required. Reject if fewer than 3.

confidence_score

float

Must be between 0.0 and 1.0. Reject if below 0.7 when deadlock_detected is true. Flag for review if above 0.95 without clear loop evidence.

suggested_intervention

string

Must be one of: pause_agent, rollback_step, provide_clarification, escalate_to_human, retry_with_constraints. Reject if not in enum.

human_readable_context

string

Must summarize the agent's goal, last successful step, and the blocking condition. Reject if missing any of these three elements.

escalation_priority

string

If present, must be low, medium, high, or critical. Default to medium if null. Reject if present but not in enum.

PRACTICAL GUARDRAILS

Common Failure Modes

Deadlock detection prompts fail in predictable ways. These cards cover the most common failure modes when detecting agent deadlocks and generating intervention requests, with concrete guardrails to prevent each one.

01

Confusing Productive Retries with Deadlocks

What to watch: The prompt flags an agent as deadlocked when it is making legitimate progress through retries—such as polling an eventually-consistent resource, waiting for a side effect, or iterating toward convergence. Guardrail: Require the prompt to distinguish between identical repeated actions and similar-but-progressing actions. Include a minimum cycle count threshold and check for state change across cycles before declaring deadlock.

02

Missing Deadlocks with Long Cycle Times

What to watch: The agent cycles between conflicting tool calls with long delays between iterations, causing the detection window to expire before enough cycles accumulate. Slow deadlocks evade detection entirely. Guardrail: Track cumulative time-in-loop alongside cycle count. Use a dual threshold: escalate if either cycle count exceeds N or wall-clock time in the same unresolved state exceeds T seconds.

03

Over-Escalation on Transient Tool Failures

What to watch: A downstream tool returns errors for 2-3 consecutive calls due to a temporary outage, and the prompt immediately escalates as a deadlock instead of allowing standard retry with backoff. Guardrail: Separate tool-failure loops from decision-conflict loops. Require the prompt to classify the deadlock type and only escalate decision-conflict deadlocks. For tool failures, recommend retry with exponential backoff before escalating.

04

Incomplete Deadlock State Summaries

What to watch: The intervention request omits critical context—such as the specific conflicting tool calls, the agent's current goal, or the sequence that led to the loop—forcing the human reviewer to reconstruct the deadlock from raw logs. Guardrail: Require a structured output schema that includes: the agent's stated goal, the last N actions with timestamps, the conflicting constraints or tool outputs, and a one-sentence deadlock hypothesis. Validate completeness before routing to human review.

05

False Negatives from Ambiguous Progress Signals

What to watch: The agent changes minor parameters (e.g., slightly different search queries, reordered arguments) without making substantive progress, and the prompt treats this as forward motion rather than a deadlock variant. Guardrail: Define progress as a change in observable state or information gain, not just action variation. Include an eval check that compares the semantic content of consecutive actions, not just their surface form.

06

Intervention Fatigue from Noisy Deadlock Thresholds

What to watch: The cycle-count threshold is set too low, generating frequent false-positive escalations that desensitize human reviewers and cause real deadlocks to be ignored. Guardrail: Calibrate thresholds against historical agent traces. Measure the false-positive rate on known-productive runs and set thresholds to achieve a target precision. Log every escalation with the evidence that triggered it for post-hoc threshold tuning.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the deadlock detection prompt's output quality before deploying it in a production agent harness. Each criterion targets a specific failure mode that breaks automated intervention workflows.

CriterionPass StandardFailure SignalTest Method

Deadlock State Identification

Output correctly identifies the specific loop pattern (e.g., tool-call cycle, conflicting constraints, repeated failure) with at least one concrete example from the trace.

Output describes a generic 'stuck' state without naming the loop type or citing trace evidence.

Run against 10 known deadlock traces with varied loop patterns; check that loop type matches ground truth label in at least 9 cases.

Intervention Request Completeness

Intervention payload includes all required fields: deadlock summary, last successful step, conflicting actions or constraints, suggested intervention points, and trace excerpt.

Missing one or more required fields; summary is too vague for a human operator to act without re-investigating the trace.

Validate output against [OUTPUT_SCHEMA] using a JSON schema validator; fail if any required field is null or empty string.

Productive Retry vs. True Deadlock Distinction

Prompt correctly classifies productive retries (e.g., exponential backoff, polling for external state change) as non-deadlock and does not escalate them.

Prompt escalates a retry loop that is making observable progress or waiting on an external condition with a reasonable timeout.

Test with 5 productive-retry traces and 5 true-deadlock traces; require precision >= 0.9 and recall >= 0.9 on the deadlock class.

Trace Evidence Citation

Every claim about agent behavior or loop state is supported by a specific trace excerpt, tool-call ID, or step reference from the provided [AGENT_TRACE].

Output makes assertions about agent state without referencing trace evidence, or cites trace lines that do not support the claim.

Manual review of 10 outputs: for each factual claim, verify the cited trace excerpt exists and supports the claim. Pass if >= 95% of claims are grounded.

Intervention Urgency Calibration

Urgency level matches the operational impact: infinite loops with resource consumption get high urgency; stalled workflows with no cost impact get low urgency.

All deadlocks receive the same urgency level regardless of resource consumption, SLA risk, or downstream blocking effects.

Test with 10 traces spanning high/medium/low true urgency; check that predicted urgency matches ground truth within one level in at least 8 cases.

Suggested Intervention Actionability

Suggested intervention points include at least one concrete, executable action (e.g., 'cancel tool call X and restart from step Y', 'inject clarification for constraint Z').

Suggestions are vague (e.g., 'review the workflow', 'check what went wrong') and require the operator to diagnose the problem from scratch.

Human evaluator review: 3 operators rate actionability on a 1-5 scale; average score must be >= 4 across 10 deadlock scenarios.

False-Positive Resistance on Complex but Valid Workflows

Prompt does not escalate complex multi-step workflows that are making forward progress, even if they involve many tool calls or revisiting prior steps.

Prompt flags a valid workflow as deadlocked because it exceeds a step count or revisits a tool with different parameters.

Test with 10 complex but valid agent traces; require false-positive rate <= 10% (no more than 1 false escalation).

Output Format Compliance Under Stress

Output remains valid JSON matching [OUTPUT_SCHEMA] even when the agent trace is extremely long, malformed, or contains unusual tool-call patterns.

Output breaks schema (e.g., truncated JSON, wrong types, missing closing braces) when trace exceeds typical length or contains edge-case characters.

Fuzz test with 20 traces of varying length (up to 2x context window), injected special characters, and partial trace data; require 100% schema-valid outputs.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base deadlock detection prompt but strip strict output schema requirements. Use a simple text summary format instead of structured JSON. Focus on detecting obvious loops (same tool call repeated 3+ times) and stalled progress (no state change in 5+ steps). Add a [MAX_STEPS] variable set high (20-30) to catch runaway agents during development.

Watch for

  • False positives on legitimate retry loops (network errors, rate limits)
  • Missing distinction between productive retries and true deadlocks
  • No logging of agent trajectory for post-mortem analysis
  • Overly broad deadlock criteria that trigger on normal multi-step tasks
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.