Inferensys

Prompt

Stuck Agent Detection and Alert Prompt

A practical prompt playbook for using Stuck Agent Detection and Alert Prompt in production AI workflows.
Engineer reviewing agent handoff workflow on laptop, task routing diagrams visible, technical office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Stuck Agent Detection and Alert Prompt.

This prompt is for runtime monitors and agent operators who need to detect when an autonomous agent has stopped making forward progress. The job-to-be-done is classifying an agent's execution trace as stuck or healthy, then producing a structured alert with evidence and a recommended recovery action. The ideal user is an engineering team building agent harnesses that run multi-step workflows—where silent stalls waste tokens, violate latency budgets, and corrupt downstream state. You should use this prompt when you have access to a sequence of recent agent actions (tool calls, reasoning steps, or state transitions) and need a programmatic signal to trigger a retry, escalation, or replanning event.

This prompt is not a replacement for simple timeout-based detection. If your agent runs a single tool call with a known SLA, a wall-clock timeout is cheaper and more reliable. Use this prompt when stalls are semantic rather than temporal—for example, when an agent repeatedly calls the same tool with slightly different arguments, loops through identical reasoning patterns, or generates valid-looking outputs that don't advance the task state. The prompt requires a structured trace input containing timestamps, action types, and step descriptions. It works best when paired with a sliding window of recent actions (typically 5–20 steps) rather than a full session history, which can dilute the stall signal.

Before wiring this into production, define what 'stuck' means for your specific agent topology. A coding agent stuck in a test-fix loop requires different thresholds than a research agent cycling through search queries. Calibrate the repetition count, time budget, and progress indicators against your normal execution patterns. Always pair this prompt with a circuit breaker: if the detection prompt itself fails or returns ambiguous classifications, your harness should default to a safe action (escalate or pause) rather than silently continuing. The next section provides the copy-ready template you can adapt to your trace format and stall definitions.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Stuck Agent Detection and Alert Prompt works, where it fails, and what you must provide before deploying it into a production agent harness.

01

Good Fit: Long-Running Autonomous Agents

Use when: agents execute multi-step plans over minutes or hours without human polling. The prompt analyzes execution traces to detect silent stalls that would otherwise waste tokens and violate latency budgets. Guardrail: pair with a watchdog timer that triggers this prompt at configurable intervals, not on every step.

02

Bad Fit: Real-Time Chat or Single-Turn Calls

Avoid when: the system handles stateless, single-turn requests where there is no execution trace to analyze. Running stall detection on a single tool call produces false positives because the prompt expects multi-step patterns. Guardrail: gate invocation behind a minimum step count threshold (e.g., at least 5 tool calls) before analyzing for loops.

03

Required Input: Structured Execution Trace

What to watch: the prompt cannot detect stalls from unstructured logs or natural language summaries alone. It needs step IDs, timestamps, tool names, inputs, outputs, and status codes. Guardrail: enforce a trace schema before calling this prompt. Reject invocations where required fields are missing or timestamps are non-monotonic.

04

Operational Risk: False Positives on Legitimate Retries

What to watch: the prompt may classify intentional retry loops (e.g., polling an async job, waiting for external approval) as stalls. This triggers unnecessary alerts and recovery actions. Guardrail: include a retry policy context field in the prompt input that distinguishes expected polling from pathological loops. Suppress alerts when retries match the declared policy.

05

Operational Risk: Missed Semantic Stalls

What to watch: the agent may produce different-looking tool calls that make no semantic progress (e.g., searching with synonym variations, reading different but irrelevant pages). Pattern-matching alone misses these. Guardrail: include a progress delta check—compare the current state against the last checkpoint. If no meaningful state change occurred across N steps, escalate even if tool calls differ.

06

Integration Requirement: Recovery Action Contract

What to watch: the prompt produces a classification and recommended recovery action, but the calling harness must map that recommendation to executable logic. A recommendation to 'replan from step 4' is useless if the orchestrator has no replanning endpoint. Guardrail: define a closed enum of recovery actions (RETRY, SKIP, REPLAN, ESCALATE, ABORT) that the harness can execute. Validate the prompt output against this enum before acting.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template with square-bracket placeholders for detecting stuck agent patterns in execution traces.

This template analyzes agent execution traces to identify stall patterns—repeated tool calls without progress, looped reasoning, or steps exceeding time budgets—and produces a structured stuck-state classification with evidence and a recommended recovery action. The prompt is designed to be wired into an agent runtime monitor that fires when a configurable condition is met, such as N consecutive tool calls with no state change or a step exceeding its time budget by a threshold.

text
You are an agent execution monitor. Your job is to analyze the provided execution trace and determine whether the agent is stuck in a non-productive loop, stalled without progress, or proceeding normally.

## INPUT

[EXECUTION_TRACE]

## TASK

1. Examine the sequence of actions, tool calls, reasoning steps, and state changes in the trace.
2. Identify any of the following stall patterns:
   - **Repetition loop**: The same tool call or reasoning pattern repeats [REPETITION_THRESHOLD] or more times with no change in inputs, outputs, or state.
   - **No-progress stall**: The agent has taken [STALL_THRESHOLD] or more actions without advancing toward the stated goal, producing new information, or changing state.
   - **Time-budget exceedance**: A single step or the overall trace has exceeded its configured time budget of [TIME_BUDGET] without completion.
   - **Circular reasoning**: The agent revisits the same decision point multiple times without resolving it or gathering new evidence.
3. Classify the trace as one of: `STUCK`, `STALLED`, or `PROGRESSING`.
4. If `STUCK` or `STALLED`, identify the specific pattern, cite evidence from the trace, and recommend a recovery action from: `ABORT`, `REPLAN`, `ESCALATE_TO_HUMAN`, `SKIP_STEP`, or `RETRY_WITH_CONSTRAINT`.

## OUTPUT SCHEMA

Return a valid JSON object with this exact structure:

{
  "classification": "STUCK" | "STALLED" | "PROGRESSING",
  "pattern_detected": "repetition_loop" | "no_progress_stall" | "time_budget_exceeded" | "circular_reasoning" | null,
  "evidence": [
    {
      "trace_index": <integer referencing the action or step in the trace>,
      "observation": "<specific description of what indicates the stall>"
    }
  ],
  "recovery_action": "ABORT" | "REPLAN" | "ESCALATE_TO_HUMAN" | "SKIP_STEP" | "RETRY_WITH_CONSTRAINT" | null,
  "recovery_rationale": "<one-sentence explanation of why this recovery action is appropriate>",
  "confidence": <float between 0.0 and 1.0>
}

## CONSTRAINTS

- Do not classify as STUCK or STALLED unless you can cite specific evidence from the trace.
- A single repeated action is not a loop unless it meets the repetition threshold.
- If the agent is making slow but observable progress, classify as PROGRESSING.
- If you are uncertain, set confidence below 0.7 and prefer ESCALATE_TO_HUMAN as the recovery action.
- Do not invent trace events. Only reference actions present in [EXECUTION_TRACE].

Adaptation guidance: Replace [EXECUTION_TRACE] with the structured log of agent actions, tool calls, and reasoning steps from your runtime. Set [REPETITION_THRESHOLD], [STALL_THRESHOLD], and [TIME_BUDGET] to values appropriate for your agent's expected step latency and tolerance for retries. For high-risk domains such as healthcare or finance, set lower thresholds and always require human review when classification is STUCK with confidence below 0.9. The output schema is designed for direct ingestion by an orchestration layer that can trigger the recommended recovery action programmatically.

Validation and testing: Before deploying, run this prompt against a golden dataset of known traces: normal progress, genuine loops, slow-but-valid progress, and edge cases like a single repeated tool call that is actually productive. Verify that the classification matches expected labels and that evidence citations reference real trace indices. Add an eval check that rejects outputs where classification is STUCK but evidence is an empty array, or where recovery_action is null for non-PROGRESSING classifications. For production, log every classification decision with the trace ID, classification, confidence, and recovery action taken so operators can audit false positives and tune thresholds over time.

IMPLEMENTATION TABLE

Prompt Variables

Each variable must be populated before the prompt is assembled. Missing or malformed inputs are the most common cause of false negatives in stuck-agent detection.

PlaceholderPurposeExampleValidation Notes

[EXECUTION_TRACE]

Full sequence of agent actions, tool calls, observations, and reasoning steps for the current session

{"steps": [{"id": "1", "action": "web_search", "input": "...", "observation": "...", "timestamp": "2025-01-01T00:00:00Z"}]}

Must be valid JSON array with at least 1 step. Each step requires id, action, and timestamp. Null or empty array should trigger an input validation error before model call.

[PLAN_REFERENCE]

The original plan or subtask list the agent was expected to follow

{"tasks": [{"id": "t1", "description": "Research competitors", "status": "in_progress"}]}

Must be valid JSON with a tasks array. If no plan exists, pass an empty tasks array explicitly. Do not pass null; it will cause the model to hallucinate a plan.

[TIME_BUDGET_MINUTES]

Maximum allowed wall-clock time in minutes for the current objective or subtask

30

Must be a positive integer. Values below 1 should be rejected. If no budget is set, pass a sentinel value like 0 and the prompt will skip time-based checks rather than fabricating thresholds.

[MAX_REPETITION_THRESHOLD]

Number of identical or near-identical tool calls allowed before classifying as a loop

3

Must be an integer >= 2. Lower values increase sensitivity and false positives. Validate that the value is not so high that loops burn through the entire context window before detection.

[STALL_WINDOW_STEPS]

Number of consecutive steps without observable progress that triggers a stall classification

5

Must be an integer >= 3. This should be tuned against the agent's typical step latency. Validate that the window is smaller than the total expected step count for the plan.

[OUTPUT_SCHEMA]

Expected JSON schema for the stuck-state classification output

{"type": "object", "properties": {"is_stuck": {"type": "boolean"}, "stuck_type": {"type": "string", "enum": ["loop", "stall", "budget_exceeded", "none"]}}}

Must be a valid JSON Schema object. The prompt will use this to constrain output format. Validate schema parseability before injection. A malformed schema will cause output parsing failures downstream.

[RECOVERY_OPTIONS]

List of allowed recovery actions the agent can recommend

["retry_last_step", "replan_from_checkpoint", "escalate_to_human", "abort"]

Must be a non-empty JSON array of strings. Each string must match a known recovery action in the agent runtime. Unknown recovery actions will cause the orchestrator to reject the recommendation.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the stuck agent detection prompt into a production monitoring pipeline with validation, retries, and escalation.

This prompt is designed to run as a sidecar evaluator inside an agent runtime, not as a user-facing chat interaction. The primary integration point is the agent's execution loop: after every N tool calls or at a configurable heartbeat interval, the runtime should assemble the recent trace window and invoke this prompt. The output is a structured classification that your harness must parse and act on—either logging a warning, triggering a replanning step, or escalating to a human operator. Do not treat this as a passive logging prompt; its value comes from the automated control flow decisions it enables.

Wiring pattern: Wrap the prompt call in a lightweight async function that accepts a trace window and returns a typed result. Validate the output against a strict schema before acting on it. If the model returns stuck_state: true, immediately increment a stall counter. On the first detection, inject a replanning prompt into the agent's context. On the second consecutive detection for the same step, pause the agent and route to a human review queue with the full trace and the model's recovery_action recommendation. If the output fails schema validation, retry once with a stricter system instruction; if it fails again, treat it as an unknown state and escalate conservatively. Log every invocation with the trace window hash, model response, validation result, and action taken for post-incident analysis.

Model choice and latency: This prompt benefits from models with strong instruction-following and structured output capabilities. Use a fast model (e.g., GPT-4o-mini, Claude Haiku) for the detection call to keep overhead low—this is a monitoring path, not a reasoning path. Set a tight timeout (under 5 seconds) and configure your harness to treat a timeout as a degraded signal: log it, do not block the main agent loop, and fall back to a simple heuristic check (e.g., identical consecutive tool calls > 3 times). For high-stakes production systems, pair this prompt with a deterministic pre-filter that catches obvious loops (exact duplicate tool calls, repeated reasoning strings) before invoking the LLM, reducing both cost and latency.

Testing and eval: Before deploying, build a regression suite of trace windows with known labels: normal progress, genuine loops, slow-but-valid progress, and edge cases like tool calls that look repetitive but produce different side effects. Measure precision and recall against your operational tolerance—false positives that interrupt valid workflows are more damaging than missed detections in most systems. Include eval checks for output schema compliance, evidence field specificity (it must cite concrete step IDs or timestamps, not vague summaries), and recovery_action feasibility (it must reference actual available tools or escalation paths). Run these evals on every prompt or model version change as a CI gate.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured JSON payload the prompt must return. Use this contract to validate the model's output before routing alerts or triggering recovery actions.

Field or ElementType or FormatRequiredValidation Rule

stuck_status

enum: STUCK | NOT_STUCK | UNCERTAIN

Must be exactly one of the three enum values. Reject any other string.

confidence_score

number (0.0 - 1.0)

Must be a float between 0 and 1 inclusive. If stuck_status is UNCERTAIN, confidence must be ≤ 0.6.

detected_pattern

string or null

If stuck_status is STUCK, must be a non-empty string naming the stall pattern (e.g., 'repeated_tool_call', 'looped_reasoning', 'time_budget_exceeded'). If NOT_STUCK, must be null.

evidence_summary

string

Must be a non-empty string summarizing the specific trace evidence. Must reference concrete step IDs, timestamps, or tool names from the [EXECUTION_TRACE] input.

repetition_count

integer or null

If detected_pattern is 'repeated_tool_call' or 'looped_reasoning', must be an integer ≥ 2. Otherwise, must be null.

recommended_action

enum: CONTINUE | RETRY | SKIP_STEP | REPLAN | ESCALATE | ABORT

Must be exactly one of the six enum values. If stuck_status is NOT_STUCK, must be CONTINUE. If ESCALATE, the escalation_reason field is required.

escalation_reason

string or null

Required only if recommended_action is ESCALATE. Must be a non-empty string explaining why human intervention is needed. Otherwise, must be null.

affected_step_ids

array of strings

Must be a JSON array of step identifiers from the [EXECUTION_TRACE]. If stuck_status is NOT_STUCK, must be an empty array. Duplicate IDs are not allowed.

PRACTICAL GUARDRAILS

Common Failure Modes

Stuck agent detection prompts fail in predictable ways. These are the most common failure modes observed in production runtime monitors, with concrete guardrails to catch them before they corrupt downstream recovery actions.

01

False Negatives on Slow Progress

What to watch: The prompt classifies an agent as healthy when it is making micro-progress that will never complete within the time budget—such as iterating through a 10,000-row CSV one row per tool call. The trace shows forward movement, so the detector sees no stall. Guardrail: Add a rate-of-progress check comparing steps completed against total estimated steps and wall-clock time. Trigger a warning when projected completion exceeds the deadline by 2x, even if individual steps are not repeated.

02

Loop Detection Blind to Semantic Repetition

What to watch: The agent varies tool call arguments slightly on each attempt—different search queries, rephrased API parameters, or offset pagination—so exact-match repetition detectors miss the loop. The model burns tokens retrying the same intent with cosmetic variation. Guardrail: Include an embedding-based similarity check on consecutive action descriptions or tool call signatures. Classify as a loop when three or more consecutive actions exceed a cosine similarity threshold, even if arguments differ.

03

Over-Classification of Exploratory Behavior

What to watch: The prompt flags legitimate exploration as a stall—such as an agent trying three different API endpoints to find the correct one, or testing multiple search strategies. False positives trigger unnecessary escalations that erode operator trust. Guardrail: Distinguish between divergent exploration and convergent retries. Exploration tries different approaches; retries repeat the same approach with minor variations. Add a diversity check: if each attempt targets a meaningfully different resource or strategy, suppress the stall classification.

04

Timeout Boundary Misclassification

What to watch: The prompt receives a truncated trace because the agent hit a step-level timeout mid-action. The detector sees an incomplete final step and classifies it as a stall, when the root cause is a timeout configuration issue, not agent behavior. Guardrail: Check whether the last action in the trace was interrupted by an external timeout signal before classifying. If the trace ends with a timeout marker rather than a completed action, route to timeout handling logic instead of stuck-agent recovery.

05

Evidence Drift Across Long Traces

What to watch: The prompt analyzes a 50-step trace and correctly identifies a stall pattern in steps 30-35, but misses that the agent self-recovered at step 38 and is now making progress. The stale classification triggers an unnecessary abort. Guardrail: Weight recent steps more heavily than older steps in the stall classification. Require that the stall pattern persists through the most recent N steps before recommending intervention. Include a recency decay factor in the evidence scoring.

06

Recovery Action Mismatch with Root Cause

What to watch: The prompt correctly detects a stall but recommends a generic recovery action—"retry the current step"—when the root cause is a missing tool capability or an impossible constraint. The agent retries, stalls again, and the cycle repeats. Guardrail: Require the prompt to classify the stall type before recommending a recovery action. Map stall types to recovery strategies: tool-unavailable stalls need capability fallback, impossible-constraint stalls need goal re-scoping, and transient-error stalls need retry with backoff.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the Stuck Agent Detection and Alert Prompt's output quality before shipping. Each criterion targets a specific failure mode common in runtime monitoring prompts. Run these checks against a golden dataset of execution traces with known stall patterns.

CriterionPass StandardFailure SignalTest Method

Stuck-State Classification Accuracy

Correctly classifies the trace as 'stuck', 'progressing', or 'uncertain' for all labeled examples in the test set.

Misclassifies a known loop as 'progressing' or a normal trace as 'stuck'. F1 score below 0.9 on classification.

Run against a golden dataset of 50 traces with known labels. Measure precision, recall, and F1 per class.

Evidence Extraction Completeness

For every 'stuck' classification, the output includes at least one concrete evidence item: a repeated tool call, a timestamp gap, or a reasoning loop excerpt.

Output returns 'stuck' classification with an empty or null evidence array, or evidence that does not reference trace data.

Parse the [EVIDENCE] array. Assert length > 0 when classification is 'stuck'. Validate each item references a trace event ID or timestamp.

Recovery Action Validity

The recommended [RECOVERY_ACTION] matches one of the allowed enum values and is appropriate for the detected stall pattern.

Action is missing, not in the allowed enum, or nonsensical for the pattern (e.g., 'retry' for a loop that already retried 10 times).

Validate [RECOVERY_ACTION] against the allowed enum: 'retry', 'skip_step', 'rollback', 'escalate', 'abort'. Spot-check 20 outputs for pattern-action fit.

Confidence Score Calibration

The [CONFIDENCE] score correlates with classification difficulty: high confidence for clear stalls, low confidence for ambiguous traces.

Confidence is always 0.9+ regardless of trace ambiguity, or confidence is below 0.5 for obvious loops.

Plot confidence scores against human-labeled difficulty ratings. Check that ambiguous traces have confidence < 0.7.

Output Schema Compliance

Every output strictly matches the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed.

Missing required fields, extra unexpected fields, or type mismatches (e.g., string where array is expected).

Validate all outputs against the JSON Schema. Reject any output that fails schema validation. Measure schema pass rate across 100 outputs.

Loop Pattern Specificity

When a loop is detected, the [STALL_PATTERN] field names the specific pattern observed (e.g., 'repeated_tool_call', 'reasoning_cycle', 'no_op_sequence').

Pattern is 'unknown' or a generic description that does not help an operator diagnose the issue.

Check that [STALL_PATTERN] is non-null and matches a known pattern label when classification is 'stuck'. Review 30 loop outputs for pattern specificity.

Timestamp Freshness Check

The output includes the [LAST_PROGRESS_TIMESTAMP] from the trace, and the alert correctly identifies when the gap exceeds the [STALL_THRESHOLD].

Timestamp is missing, stale, or the alert fires when the gap is within the configured threshold.

Inject traces with known timestamp gaps. Assert alert fires only when gap > [STALL_THRESHOLD]. Measure false-positive rate.

Idempotency Under Repeated Input

The same trace produces the same classification, evidence, and recovery action across multiple identical calls.

Classification flips between 'stuck' and 'progressing' on repeated calls with no input change.

Run the same trace 5 times. Assert classification and action are identical across all runs.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single trace window. Use a lightweight JSON schema with only stuck_detected, pattern, and recommendation. Skip time-budget enforcement and confidence thresholds. Run against a small set of recorded agent traces.

Watch for

  • False positives on legitimate retry loops where progress is actually being made
  • Overly broad pattern matching that flags any repeated tool call
  • Missing trace timestamps causing incorrect stall classification
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.