This prompt is for agent developers and AI SREs who have a production trace where an agent entered a loop: repeating the same action, cycling through a small set of tool calls without progress, or failing to reach a termination condition. The prompt reconstructs the planning-action-observation cycle from raw trace spans, identifies the first deviation from expected behavior, pinpoints the repeated action or missing stop condition, and produces a structured diagnosis report. Use this prompt when you have a single trace that exhibits looping behavior and you need to understand what broke before aggregating across sessions or modifying the agent's system prompt.
Prompt
Agent Loop Failure Diagnosis Prompt

When to Use This Prompt
Defines the job-to-be-done, ideal user, required context, and boundaries for the Agent Loop Failure Diagnosis Prompt.
The ideal user has access to a raw trace containing the agent's reasoning steps, tool calls, tool responses, and any termination checks. You should not use this prompt for latency analysis, cost attribution, or multi-trace incident correlation—those require separate specialized prompts. Before invoking this prompt, confirm that the trace actually contains a loop: look for repeated tool calls with identical or near-identical arguments, a cycle of 2-4 actions that repeats without state change, or a trace that exceeds the expected step count without reaching a terminal action. If the trace is incomplete or missing observation spans, run an end-to-end trace reconstruction prompt first to fill gaps.
This prompt works best with traces from agents that follow a planning-action-observation loop pattern, such as ReAct agents, tool-calling agents with reasoning steps, or multi-step retrieval agents. It is less effective for single-call workflows, streaming-only agents without logged reasoning, or agents that use opaque internal planners where the planning step is not captured in the trace. For agents with human-in-the-loop steps, ensure the trace includes approval or rejection events so the prompt can distinguish between a loop caused by the model and a loop caused by repeated human rejections.
The output of this prompt is a structured diagnosis report, not a fix. After receiving the diagnosis, you will typically need to take one of several actions: add or tighten a termination condition in the agent's system prompt, increase the maximum step count with a forced stop, modify the tool descriptions to prevent ambiguous responses that trigger retries, or add a state-tracking mechanism so the agent can detect when it is repeating itself. If the diagnosis points to a model reasoning failure rather than a prompt or tool defect, consider whether a different model or a fine-tuned variant is warranted for this agent workload.
Use Case Fit
Where the Agent Loop Failure Diagnosis Prompt works, where it fails, and what you must provide before running it.
Good Fit: Structured Agent Traces
Use when: you have a complete trace with planning, action, observation, and reflection steps clearly delineated. The prompt excels at identifying the first repeated action or missing termination condition in a well-instrumented agent loop. Guardrail: ensure your trace format includes step types and timestamps before invoking this prompt.
Bad Fit: Unstructured Chat Logs
Avoid when: the trace is a raw chat transcript without explicit agent scaffolding. The prompt relies on structured planning-action-observation cycles and will hallucinate loop boundaries in free-form conversation. Guardrail: pre-process chat logs into structured spans before diagnosis.
Required Input: Complete Cycle Data
Risk: missing observation steps or truncated action logs cause false negatives in loop detection. The prompt cannot diagnose what it cannot see. Guardrail: validate that every action in the trace has a corresponding observation before submitting. Flag traces with missing segments for manual review.
Operational Risk: Long Traces
Risk: traces exceeding 50+ cycles may exceed context windows, causing the prompt to miss late-stage loops or produce truncated analysis. Guardrail: implement a trace length check and split long traces into overlapping windows, or summarize early cycles before diagnosis.
Operational Risk: Non-Deterministic Loops
Risk: agents that loop with slight variations in actions or arguments may evade exact-match detection. The prompt may report no loop when a semantic loop exists. Guardrail: combine this prompt with embedding-based similarity checks on action sequences to catch near-duplicate cycles.
Bad Fit: Missing Termination Conditions
Avoid when: the agent's expected termination condition is not documented or encoded in the trace. The prompt cannot determine if a loop is valid without knowing when the agent should stop. Guardrail: always include the agent's termination policy or max step count in the prompt's input context.
Copy-Ready Prompt Template
Paste this prompt into your trace analysis workflow to reconstruct and diagnose an agent loop failure from raw trace data.
This prompt template is designed to be copied directly into your observability or debugging interface. It instructs the model to act as a diagnostic engine that reconstructs the planning-action-observation cycle from a raw agent trace, identifies the first deviation that led to a loop, and pinpoints the missing termination condition. Before using it, ensure you have extracted the relevant trace spans—including tool calls, their arguments, responses, and any intermediate reasoning tokens—from your tracing system (e.g., LangSmith, Arize, or a custom logger). Replace every square-bracket placeholder with concrete data from the trace you are investigating.
textYou are an agent reliability engineer diagnosing a production agent loop failure. Your task is to reconstruct the agent's planning-action-observation cycle from the raw trace data provided below and identify the root cause of the loop. ## TRACE DATA [RAW_TRACE_SPANS] ## AGENT CONFIGURATION - Max Steps Allowed: [MAX_STEPS] - Available Tools: [TOOL_LIST_WITH_DESCRIPTIONS] - Termination Condition: [TERMINATION_CONDITION] ## INSTRUCTIONS 1. Reconstruct the chronological sequence of agent steps. For each step, extract the Thought, Action, Action Input, and Observation. 2. Identify the first step where the agent's behavior deviated from a path toward termination. This could be a repeated action, a semantically identical thought, or an action that does not change the state. 3. Determine the root cause of the loop. Classify it into one of the following categories: - **Missing Termination Condition**: The agent achieved the goal but did not recognize it. - **Repeated Action**: The agent called the same tool with the same arguments multiple times. - **State Confusion**: The agent misinterpreted the observation and believed progress was made when it was not. - **Tool Failure Ignored**: A tool returned an error, but the agent did not adapt its plan. - **Infinite Sub-Goal**: The agent got stuck trying to complete a non-essential sub-task. 4. Provide a concise root-cause analysis summary. 5. Suggest one concrete fix to the system prompt, tool description, or termination logic that would prevent this loop. ## OUTPUT FORMAT Return a JSON object with the following schema: { "total_steps_observed": <integer>, "reconstructed_cycle": [ { "step_number": <integer>, "thought": "<string>", "action": "<tool_name | null>", "action_input": "<object | string>", "observation": "<string>", "is_repeat": <boolean>, "deviation_flag": <boolean> } ], "first_deviation_step": <integer | null>, "loop_root_cause": "<category>", "root_cause_analysis": "<string>", "suggested_fix": "<string>" }
To adapt this template, start by populating [RAW_TRACE_SPANS] with the full JSON or formatted log output from your tracing system. Be careful not to truncate the trace; loops often span many steps, and cutting off the data will hide the first deviation. The [TOOL_LIST_WITH_DESCRIPTIONS] placeholder should contain the exact function definitions the agent had access to, as misleading or incomplete tool descriptions are a common root cause of state confusion. The [TERMINATION_CONDITION] field is critical—explicitly state the rule the agent was supposed to follow (e.g., "Stop when the Final Answer tool is called" or "Stop when the user's question is answered"). If you are using this prompt in an automated pipeline, validate the output JSON against the schema before surfacing the diagnosis to an on-call engineer. For high-severity incidents where the loop caused a cost overrun or user-facing error, route the output for human review before applying the suggested fix to the system prompt.
Prompt Variables
Each placeholder the Agent Loop Failure Diagnosis Prompt expects. Wire these into your trace replay harness before calling the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRACE_LOG] | Raw agent trace containing the full planning-action-observation cycle for the session under review | {"steps":[{"step_id":1,"type":"plan","content":"..."},{"step_id":2,"type":"action","tool":"search","args":{}},{"step_id":3,"type":"observation","content":"..."}]} | Must be valid JSON. Parse check required. Reject if steps array is empty or missing step_id, type, or content fields. Minimum 3 steps required for loop detection. |
[AGENT_SYSTEM_PROMPT] | The system prompt that defines the agent's termination conditions, action limits, and loop-prevention rules | You are a research agent. Stop after 10 actions. If you repeat the same action twice, explain why before proceeding. | Required string. Must contain at least one termination condition (max steps, repeat guard, or timeout). Flag for human review if no termination policy is detectable. |
[TOOL_SCHEMAS] | JSON schema definitions for all tools available to the agent during the traced session | [{"name":"search","description":"Search the web","parameters":{"type":"object","properties":{"query":{"type":"string"}}}}] | Must be valid JSON array of tool definitions. Each entry requires name, description, and parameters. Validate against the tool names referenced in [TRACE_LOG] actions. Missing tool definitions should be flagged. |
[MAX_EXPECTED_STEPS] | The maximum number of steps the agent should have taken before terminating, as defined by the system prompt or application guard | 10 | Must be a positive integer. Compare against actual step count in [TRACE_LOG]. If actual steps exceed this value, loop detection confidence should increase. |
[TERMINATION_CONDITIONS] | Explicit termination rules extracted from the system prompt or application logic that the agent should have followed | Stop when answer is found. Do not repeat the same action with identical arguments. Halt after 10 steps. | Required string. Must be non-empty. Used as the ground truth for evaluating whether the agent violated its own stop rules. If null or empty, the diagnosis prompt should note that termination conditions were undefined. |
[SESSION_METADATA] | Contextual metadata about the session including model version, timestamp, and user identifier | {"model":"claude-3-opus-20240229","timestamp":"2025-07-15T14:32:00Z","session_id":"sess_abc123"} | Must be valid JSON. session_id and timestamp are required. model field recommended for version-specific behavior analysis. Reject if timestamp is missing or unparseable. |
Implementation Harness Notes
How to wire the Agent Loop Failure Diagnosis Prompt into an observability pipeline or debugging workflow.
This prompt is designed to be integrated into an automated trace analysis pipeline, not just used as a one-off debugging tool. The primary integration point is a trace ingestion system (e.g., LangSmith, Arize, or a custom OpenTelemetry collector) that captures agent execution spans. When a session is flagged for excessive step count, repeated actions, or a timeout, the raw trace data—including the full sequence of planning, action, and observation spans—should be programmatically extracted and formatted into the [TRACE_LOG] placeholder. The [AGENT_CONFIG] placeholder must be populated from the deployment's configuration store, pulling the system prompt, tool definitions, and the explicit termination condition (e.g., max_steps or a Final Answer tool).
To operationalize this, build a lightweight harness function that accepts a session_id and a trace_backend client. The function should first query the backend for all spans belonging to the session, sort them by timestamp, and serialize them into the structured text format required by the prompt. Next, it should fetch the agent's deployed configuration from a versioned artifact store (like an S3 bucket or a database) to populate [AGENT_CONFIG]. The harness then calls the LLM with the assembled prompt. The model choice here is critical: use a model with strong reasoning capabilities and a large context window (e.g., gpt-4o or claude-3.5-sonnet) because the trace log for a stuck agent can easily exceed 10,000 tokens. Implement a retry logic with exponential backoff for API failures, but do not retry on validation failures.
The output from the LLM must be parsed as JSON and validated against a strict schema before it is surfaced to an on-call engineer. The schema should enforce the presence of loop_start_step, repeating_pattern, root_cause_category, and termination_condition_missing fields. If parsing fails, log the raw output and the validation error, then fall back to surfacing the raw trace without the AI diagnosis. For high-severity incidents where the agent controls a critical system, route the diagnosis to a human reviewer for confirmation before closing the incident. Avoid wiring this prompt directly into an automated rollback or configuration change; it is a diagnostic tool, not a self-healing mechanism. The next step is to store the validated diagnosis as a structured annotation on the trace itself, enabling trend analysis across multiple loop failures to identify systemic prompt or tool design flaws.
Expected Output Contract
Field-level contract for the Agent Loop Failure Diagnosis Prompt output. Use this table to validate the JSON response before passing it to downstream tools or dashboards.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
diagnosis_id | string (UUID) | Must match ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ | |
trace_summary | object | Must contain 'total_turns' (integer >= 1) and 'loop_detected' (boolean) | |
loop_type | string (enum) | Must be one of: 'repeated_action', 'missing_termination', 'oscillation', 'infinite_planning', 'none' | |
first_deviation_turn | integer or null | If loop_type is not 'none', must be >= 1 and <= trace_summary.total_turns; otherwise null | |
repeated_action_sequence | array of strings | Each element must match a tool name or action label from the trace; required when loop_type is 'repeated_action' | |
missing_termination_condition | string or null | Must be a non-empty string when loop_type is 'missing_termination'; otherwise null | |
root_cause_hypothesis | string | Must be 1-3 sentences; cannot be empty or only whitespace | |
evidence_citations | array of objects | Each object must have 'turn' (integer) and 'observation' (string excerpt from trace); array length >= 1 when loop_type is not 'none' |
Common Failure Modes
What breaks first when diagnosing agent loops and how to guard against it.
Missing Termination Condition
What to watch: The prompt fails to identify that the agent's task was actually completed, but a missing or poorly defined stop condition caused it to continue cycling. The diagnosis incorrectly blames the action selection. Guardrail: Include an explicit check in the prompt harness for task-completion signals in the final observation before flagging a loop. Validate against the task's defined acceptance criteria.
First Deviation Misattribution
What to watch: The prompt identifies a repeated action as the root cause but misses an earlier, subtle deviation in the planning or observation step that triggered the loop. Guardrail: Instruct the prompt to reconstruct the full plan-action-observation cycle and diff each step against the initial plan. Require the output to cite the first step where the trace diverges from the expected sequence, not just the first repeated action.
Confusing Repetition with Retry Logic
What to watch: A legitimate retry with exponential backoff or a tool call that returns a 'pending' status is incorrectly classified as a failure loop. Guardrail: Add a pre-processing step in the harness that distinguishes between identical repeated calls and calls with incremental backoff or state changes. The prompt should be instructed to treat a sequence of calls with progressive delays as a retry pattern, not a loop.
Context Window Truncation Masking the Loop
What to watch: The trace is truncated due to context limits, cutting off the early steps where the loop began. The prompt then diagnoses a symptom from the middle of the trace as the root cause. Guardrail: The harness must first validate trace completeness. If the trace is truncated, the prompt output must include a trace_incomplete: true flag and refuse to provide a definitive root cause, instead listing hypotheses based on available data.
Ignoring Environmental State Changes
What to watch: The agent repeats an action because an external system state hasn't changed (e.g., a file hasn't appeared, an API returns the same error). The prompt blames the agent's planning instead of the external dependency. Guardrail: The prompt must be instructed to compare tool outputs across repeated calls. If the outputs are identical and indicate an external blocking condition, the diagnosis must classify the root cause as an environmental dependency failure, not a planning failure.
Hallucinating a Loop Where None Exists
What to watch: The prompt sees a long sequence of similar but distinct and productive actions (e.g., paginating through results) and falsely flags it as a loop. Guardrail: Require the prompt to verify that the action and its critical arguments are strictly identical before classifying a sequence as a loop. The harness should include a post-processing validation step that checks if the flagged actions are exact duplicates or valid iterative progress.
Evaluation Rubric
Use this rubric to test the Agent Loop Failure Diagnosis Prompt against known traces before integrating it into your observability pipeline. Each criterion targets a specific failure mode in loop detection.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
First Deviation Identification | Prompt correctly identifies the earliest planning-action-observation cycle step where behavior diverged from the expected path | Prompt reports a deviation at a step that matches the expected path or fails to identify any deviation in a known looping trace | Run against 10 traces with manually annotated first-deviation timestamps; require exact step-index match in 9 of 10 |
Repeated Action Detection | Prompt flags all repeated tool calls or actions with identical arguments that occurred more than twice in sequence | Prompt misses a repeated action that appears 3+ times consecutively or falsely flags a legitimate retry as a loop | Test with traces containing 0, 1, and 3+ repeated calls; measure precision and recall against human-labeled loops |
Missing Termination Condition Flag | Prompt identifies when the agent failed to check or satisfy a termination condition defined in the system prompt or task spec | Prompt does not mention termination conditions when the trace shows the agent continued past a defined stop signal | Use traces where termination conditions are embedded in [SYSTEM_PROMPT]; verify the output references the specific unmet condition |
Cycle Length Accuracy | Prompt reports the correct number of steps in the detected loop cycle, matching the repeating pattern length | Prompt reports a cycle length that does not match the actual repeating pattern in the trace | Validate against traces with known cycle lengths of 2, 3, and 5 steps; require exact match |
Root-Cause Classification | Prompt assigns the loop cause to one of the predefined categories: missing termination, repeated action, planning drift, or observation misinterpretation | Prompt classifies the cause incorrectly or uses a category not in the allowed set | Run against 20 labeled traces with known root causes; require classification accuracy above 85% |
Evidence Citation from Trace | Prompt cites specific trace spans, step indices, or log lines to support each diagnostic claim | Prompt makes diagnostic claims without referencing specific trace evidence or cites spans that do not exist in the input | Parse output for span ID or step index references; validate each citation exists in the input trace data |
Confidence Calibration | Prompt outputs a confidence score between 0.0 and 1.0 that correlates with diagnostic accuracy | Prompt assigns high confidence to incorrect diagnoses or low confidence to correct ones | Compare confidence scores against actual correctness across 50 traces; require Brier score below 0.25 |
Output Schema Compliance | Prompt output matches the expected JSON schema with all required fields present and correctly typed | Output is missing required fields, contains type errors, or is not valid JSON | Validate output against the [OUTPUT_SCHEMA] using a JSON Schema validator; require zero validation errors |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

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

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single trace dump and lighter validation. Replace structured output requirements with a free-text diagnosis. Accept that loop detection may miss subtle repeated patterns.
- Remove strict [OUTPUT_SCHEMA] and ask for a plain-language summary.
- Drop the requirement for exact span timestamps; accept approximate ordering.
- Use a smaller context window and truncate long tool-call sequences.
Watch for
- Missing schema checks letting malformed traces through
- Overly broad instructions causing false positives on legitimate retry loops
- No baseline comparison trace, so deviation detection is guesswork

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