This prompt is built for evaluation engineers and agent platform teams who need to measure how an agent behaves when external tool calls fail. It is not a prompt you ship to end users; it is a prompt you run against agent traces in a test harness. The job-to-be-done is automated, repeatable grading of error-handling quality before you deploy an agent update. You should use this prompt when you have a recorded trace of an agent interacting with tools, that trace contains at least one failed tool call (timeout, permission denied, malformed response, or rate limit), and you need a structured score for error detection, retry decision quality, backoff behavior, and escalation correctness. The ideal user is someone who owns agent reliability and wants to replace manual spot-checking of error traces with a consistent, model-graded evaluation that can run in CI/CD or as part of a regression suite.
Prompt
Error Handling and Retry Logic Evaluation Prompt

When to Use This Prompt
Learn when to deploy the Error Handling and Retry Logic Evaluation Prompt and when a different evaluation surface is required.
Do not use this prompt when you need to evaluate tool selection correctness, argument accuracy, or call sequencing in successful tool calls. Those concerns belong to separate evaluation surfaces such as the Tool Selection Correctness Grading Prompt or the Function Argument Accuracy Evaluation Rubric. This prompt also should not be used to evaluate the agent's final answer quality or task completion rate; it focuses narrowly on the error-recovery path. If your trace contains only successful tool calls, this prompt will have nothing to grade. If your agent does not have retry logic, backoff configuration, or escalation paths, the prompt will still produce scores, but they will reflect the absence of those capabilities rather than their quality. In high-risk domains where error-handling failures could cause financial loss, data corruption, or safety incidents, pair this prompt's output with human review of a sample of graded traces and track score distributions over time to detect regressions.
Before using this prompt, ensure you have a representative set of agent traces that include diverse failure modes. A trace that only contains timeouts will not tell you how the agent handles permission errors. Build your evaluation dataset to cover the failure categories your agent is expected to encounter in production. Wire this prompt into a harness that extracts the relevant trace segments, formats them into the [AGENT_TRACE] placeholder, and collects the structured scores for aggregation. The next section provides the copy-ready prompt template you can adapt for your specific agent architecture and failure taxonomy.
Use Case Fit
Where this prompt works and where it does not. Use it to evaluate agent error-handling behavior, not to build the retry logic itself.
Good Fit: Agent Regression Testing
Use when: you have a suite of simulated tool failures (timeouts, auth errors, malformed responses) and need to score agent recovery behavior before deployment. Guardrail: run against a golden dataset of expected retry/abstention decisions and track score drift across prompt versions.
Bad Fit: Live Production Retry Logic
Avoid when: you need the prompt to perform the retry logic itself. This prompt evaluates behavior, it does not implement backoff, circuit breaking, or idempotency. Guardrail: implement retry logic in application code; use this prompt only in offline evaluation pipelines.
Required Inputs
What you must provide: a trace of the agent's tool calls and responses, the error conditions injected, and a rubric defining correct retry, backoff, and escalation behavior. Guardrail: missing error context or ambiguous escalation policies will produce unreliable scores.
Operational Risk: Score Drift
What to watch: the LLM judge may become more lenient or strict over time as models change, causing score drift without real behavior change. Guardrail: periodically calibrate against human-annotated traces and pin judge model versions in your evaluation harness.
Operational Risk: Silent Escalation Failures
What to watch: the agent may retry correctly but fail to escalate when retries are exhausted, or escalate too early and flood human reviewers. Guardrail: include explicit escalation test scenarios in your eval suite and weight escalation correctness heavily in aggregate scores.
Operational Risk: Backoff Timing Blindness
What to watch: text-based evaluation often misses timing violations—the agent may describe correct backoff but call tools without actual delays. Guardrail: pair this prompt with application-level timing assertions; the prompt evaluates decision quality, not wall-clock compliance.
Copy-Ready Prompt Template
A reusable prompt for evaluating agent error handling and retry logic with square-bracket placeholders for your test scenarios and evaluation criteria.
This prompt template evaluates how an AI agent handles tool-call failures. It scores the agent's ability to detect errors, decide whether to retry, apply appropriate backoff, and escalate when retries are exhausted. The template is designed to be dropped into an evaluation harness where you supply the agent's tool-call trace, the failure scenario, and your expected behavior criteria. Use it to catch brittle retry loops, missing error detection, and premature escalation before these failures reach production.
textYou are an evaluation judge grading an AI agent's error handling and retry behavior during a tool-use interaction. ## Evaluation Context [FAILURE_SCENARIO]: Description of the simulated failure (e.g., timeout after 30s, HTTP 403, malformed JSON response, rate limit 429). [AGENT_TRACE]: The full agent trace including the initial tool call, any error response, subsequent retry attempts, and final action. [TOOL_CATALOG]: The list of available tools with their schemas and documented error modes. [RETRY_POLICY]: The expected retry policy (e.g., max 3 retries, exponential backoff starting at 1s, escalate after exhaustion). [ESCALATION_PATH]: The expected escalation behavior when retries are exhausted (e.g., return error to user, call fallback tool, log and abort). ## Scoring Rubric Grade the agent on a 1-5 scale for each dimension: ### 1. Error Detection (1-5) - 5: Agent correctly identified the specific error type and extracted relevant details (status code, error message, retry-after header). - 3: Agent detected that a failure occurred but misclassified the error type or missed important details. - 1: Agent did not detect the failure and proceeded as if the call succeeded. ### 2. Retry Decision (1-5) - 5: Agent correctly decided whether to retry based on error type (retried on transient errors like 429/503, did not retry on permanent errors like 400/403). - 3: Agent retried appropriately for some errors but missed the distinction for others. - 1: Agent retried on permanent errors or failed to retry on clearly transient errors. ### 3. Backoff Behavior (1-5) - 5: Agent applied appropriate backoff strategy matching the retry policy (exponential, respecting retry-after headers, jitter). - 3: Agent retried with some delay but did not follow the specified backoff strategy. - 1: Agent retried immediately with no backoff or used fixed intervals contrary to policy. ### 4. Escalation Correctness (1-5) - 5: Agent escalated correctly after exhausting retries, following the specified escalation path with complete context. - 3: Agent escalated but with incomplete context or after the wrong number of retries. - 1: Agent did not escalate when required or escalated prematurely before retries were exhausted. ### 5. Context Preservation (1-5) - 5: Agent preserved all relevant context through retries and escalation (original intent, partial results, error history). - 3: Agent preserved some context but lost important details across retry attempts. - 1: Agent lost critical context, making escalation or debugging impossible. ## Output Format Return a JSON object with this exact schema: { "error_detection": { "score": <1-5>, "justification": "<string>" }, "retry_decision": { "score": <1-5>, "justification": "<string>" }, "backoff_behavior": { "score": <1-5>, "justification": "<string>" }, "escalation_correctness": { "score": <1-5>, "justification": "<string>" }, "context_preservation": { "score": <1-5>, "justification": "<string>" }, "aggregate_score": <float 1.0-5.0>, "failure_mode_summary": "<string describing the primary failure pattern, or 'none' if all scores >= 4>", "recommendation": "<string: 'pass', 'review', or 'fail'>" } ## Constraints - Score only the agent's behavior against the provided retry policy and escalation path. - Do not penalize the agent for tool-call failures caused by the simulated scenario. - If the agent trace is incomplete or ambiguous, note this in your justifications and score conservatively. - The aggregate_score is the mean of the five dimension scores. - Recommend 'pass' if aggregate >= 4.0, 'review' if >= 3.0, 'fail' if < 3.0.
To adapt this template, replace each square-bracket placeholder with your test scenario data. The [FAILURE_SCENARIO] should describe exactly what went wrong—be specific about error codes, timing, and response payloads. The [AGENT_TRACE] is the raw output from your agent framework showing every step. If your retry policy differs from the rubric's assumptions (e.g., you allow more retries or use circuit breakers), adjust the scoring descriptions accordingly. For high-stakes production systems, always pair this prompt with human review of failing traces and calibrate the judge against manual annotations before relying on automated pass/fail decisions.
Prompt Variables
Required inputs for the Error Handling and Retry Logic Evaluation Prompt. Each placeholder must be populated before the judge prompt can produce reliable scores.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[AGENT_TRACE] | Full agent execution log including tool calls, responses, timestamps, and error payloads | {"steps": [{"tool": "search", "status": "timeout", "duration_ms": 5001, "error": "ETIMEDOUT"}]} | Must be valid JSON array of step objects. Each step requires tool, status, and timestamp fields. Reject if trace is empty or missing error steps. |
[TOOL_CATALOG] | Schema definitions for all available tools including retry policies, timeout limits, and idempotency flags | {"tools": [{"name": "search", "timeout_ms": 5000, "retryable": true, "max_retries": 3, "backoff": "exponential"}]} | Must include timeout_ms, retryable, and max_retries per tool. Validate schema completeness before evaluation. Missing retry policy defaults to no-retry. |
[ERROR_POLICY] | Organization-specific rules for error classification, retry eligibility, escalation thresholds, and human handoff criteria | {"retryable_errors": ["timeout", "rate_limit", "503"], "max_total_retries": 5, "escalate_on": ["auth_error", "permission_denied"]} | Must define retryable_errors list and max_total_retries. Escalation rules required for safety-critical tools. Validate policy completeness against tool catalog. |
[EXPECTED_BEHAVIOR] | Golden reference describing correct error handling for each test scenario including retry decisions, backoff patterns, and escalation actions | {"scenario_id": "timeout_001", "expected": {"should_retry": true, "max_retries": 3, "backoff_type": "exponential", "should_escalate": false}} | Must align with ERROR_POLICY and TOOL_CATALOG. Validate consistency: expected behavior cannot contradict policy rules. Required for pass/fail gating. |
[SCORING_RUBRIC] | Weighted criteria for grading error detection, retry appropriateness, backoff correctness, and escalation accuracy | {"error_detection": 0.25, "retry_decision": 0.35, "backoff_behavior": 0.20, "escalation_correctness": 0.20} | Weights must sum to 1.0. Each criterion requires a pass threshold definition. Validate rubric covers all dimensions in EXPECTED_BEHAVIOR. |
[CONTEXT_WINDOW] | Preceding conversation or task context that the agent was operating within when errors occurred | {"task": "Find Q4 revenue data", "prior_steps": ["query_database", "parse_results"], "user_intent": "financial_reporting"} | Optional but recommended for timeout and partial-failure scenarios. Null allowed for isolated tool-call evaluation. Validate context relevance to error scenario. |
[MODEL_CONFIG] | Model generation parameters used during the agent run including temperature, max_tokens, and stop sequences | {"model": "claude-3-opus", "temperature": 0.1, "max_tokens": 4096} | Required for reproducibility. Temperature above 0.3 should trigger a warning in evaluation notes. Validate model name against known provider list. |
Implementation Harness Notes
How to wire the Error Handling and Retry Logic Evaluation Prompt into an agent evaluation pipeline with validation, retry controls, and human review gates.
This evaluation prompt is designed to run as a post-execution judge inside an agent trace analysis pipeline. After an agent completes a multi-step tool-use task—or fails partway through—you feed the full trace (tool calls, tool responses, agent reasoning, and final output) into this prompt along with a structured test scenario definition. The prompt returns a scored evaluation across four dimensions: error detection, retry decision appropriateness, backoff behavior, and escalation correctness. Wire this as a batch evaluation step that runs after each test suite execution, not as a real-time guard during live agent runs. The latency and cost profile of a detailed LLM judge is better suited for offline analysis and regression testing than for inline gating.
Integration pattern: Store test scenarios as structured JSON objects, each containing a scenario_id, error_type (e.g., timeout, permission_denied, malformed_response), expected_behavior (e.g., retry_with_backoff, escalate, abort), and the raw agent trace. Feed each scenario through the evaluation prompt and collect the four sub-scores plus the overall error_handling_score. Validate the output against a strict JSON schema before accepting it—reject and retry the judge call if fields are missing, types are wrong, or scores fall outside the 0.0–1.0 range. Log every evaluation result with the scenario_id, model_version, prompt_version, and timestamp so you can track score drift across prompt changes and model upgrades.
Retry and fallback for the judge itself: The evaluation prompt can fail—malformed JSON, refusal on sensitive-looking traces, or timeouts on very long agent transcripts. Implement a lightweight retry wrapper: up to 2 retries with exponential backoff (1s, 4s) if the output fails schema validation or the model returns an error. If the judge still fails after retries, flag the scenario for human review rather than silently assigning a default score. This is especially important for permission_denied and malformed_response scenarios where the agent's behavior may have security or data integrity implications. Store failed evaluations in a separate review queue with the raw trace and the judge's partial output attached.
Model choice and cost control: Use a capable model (GPT-4o, Claude 3.5 Sonnet, or equivalent) for the judge because error-handling evaluation requires nuanced reasoning about whether a retry was justified, whether backoff timing was appropriate, and whether escalation matched policy. Do not use a smaller or faster model for this judge unless you've calibrated its scores against human ratings and confirmed acceptable agreement. To manage costs, sample traces rather than evaluating every single agent run—evaluate 100% of runs during regression testing and prompt development, then drop to a statistically meaningful sample in production monitoring. Cache evaluation results by scenario_id + trace_hash to avoid re-evaluating identical traces.
Human review integration: For any scenario where the error_handling_score falls below 0.6 or where the escalation_correctness sub-score is below 0.5, route the evaluation to a human reviewer before accepting the result into your regression baseline. These thresholds indicate the agent either mishandled the error or the judge is uncertain—both cases warrant human inspection. Build a simple review UI that shows the agent trace, the judge's scores, and the judge's justification side by side. Let reviewers override scores with a note, and feed those overrides back into your calibration dataset to improve the judge prompt over time.
What to avoid: Do not use this evaluation prompt as a real-time circuit breaker during live agent execution—the latency is too high and the judge's own failure modes would compound the agent's error. Do not treat the judge's scores as ground truth without periodic calibration against human ratings, especially when you change the underlying model. Do not skip schema validation on the judge's output; an unvalidated score that slips into a dashboard or regression report will erode trust in your entire evaluation pipeline. Start with a small set of 10–15 hand-annotated test scenarios, calibrate the judge against them, and expand the scenario library as you discover new failure modes in production traces.
Expected Output Contract
Fields, types, and validation rules for the error handling and retry logic evaluation output. Use this contract to parse, validate, and store evaluation results in your agent testing pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
evaluation_id | string (UUID v4) | Must match regex ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$; generated by harness, not model | |
scenario_id | string | Must match a known scenario identifier from the test suite; non-empty; cross-reference against scenario catalog | |
error_detection_score | number (0.0-1.0) | Float between 0.0 and 1.0 inclusive; 1.0 means agent correctly identified the error type and message; parse as float and clamp to range | |
retry_decision | string (enum) | Must be one of: 'retry', 'retry_with_backoff', 'retry_with_fallback_tool', 'escalate', 'abort', 'ignore'; enum check against allowed values | |
retry_decision_correct | boolean | Strict boolean true or false; null not allowed; derived from comparison against expected decision in scenario ground truth | |
backoff_behavior | object or null | If retry_decision includes backoff, must contain 'strategy' (enum: 'fixed', 'exponential', 'decorrelated_jitter') and 'initial_delay_ms' (integer > 0); null if no backoff applied | |
escalation_target | string or null | If retry_decision is 'escalate', must be non-empty string identifying the escalation target (e.g., 'human_operator', 'fallback_model'); null otherwise | |
max_retries_exceeded | boolean | True if agent attempted more retries than the configured [MAX_RETRIES] threshold; false otherwise; must be consistent with retry_count field | |
retry_count | integer | Non-negative integer; must equal the number of retry attempts observed in the trace; 0 if no retries attempted | |
error_recovery_success | boolean or null | True if agent recovered and completed the task after error handling; false if recovery failed; null if scenario ended before recovery could be assessed | |
justification_quality | number (0.0-1.0) | Score for the reasoning trace explaining error handling decisions; 0.0 if no justification provided; parse as float and clamp to range; required when [REQUIRE_JUSTIFICATION] is true | |
failure_category | string or null | If retry_decision_correct is false, must be one of: 'missed_error', 'wrong_retry_strategy', 'premature_escalation', 'missing_escalation', 'infinite_retry_loop', 'incorrect_backoff'; null if decision was correct | |
trace_evidence | array of strings | Array of 1-5 direct quotes or references from the agent trace supporting the evaluation; each string non-empty; minimum 1 element required | |
overall_pass | boolean | True if error_detection_score >= [PASS_THRESHOLD] AND retry_decision_correct is true AND max_retries_exceeded is false; false otherwise; computed by validator, not model-generated | |
evaluation_timestamp | string (ISO 8601) | Must parse as valid ISO 8601 datetime in UTC; generated by harness at evaluation time; format: YYYY-MM-DDTHH:MM:SSZ |
Common Failure Modes
Error handling and retry logic evaluation breaks in predictable ways. These cards cover the most frequent failure modes when grading agent behavior during tool-call failures, along with concrete guardrails to prevent them.
False-Positive Retry Approval
What to watch: The evaluator marks a retry as correct because the agent eventually succeeded, ignoring that the retry violated backoff policy, exceeded max attempts, or retried a non-retryable error like a permission denial. Guardrail: Include explicit retry policy constraints in the rubric—max attempts, backoff requirements, and non-retryable error codes. Score retry correctness separately from eventual success.
Undetected Silent Failures
What to watch: The agent receives a malformed or empty tool response but treats it as valid data and continues execution without error detection. The evaluator misses this because no explicit error was raised. Guardrail: Require the evaluator to check whether the agent validated the tool response structure before using it. Add a specific rubric dimension for response validation behavior.
Escalation Timing Misjudgment
What to watch: The evaluator penalizes correct escalation as a failure or rewards premature escalation as cautious. This happens when the rubric lacks clear escalation triggers tied to error types and retry exhaustion. Guardrail: Define escalation criteria explicitly in the evaluation context—which error types, after how many retries, and with what information must be included in the escalation payload.
Backoff Policy Blindness
What to watch: The evaluator ignores timing entirely, scoring retries as correct even when the agent retries instantly without backoff, or applies the same backoff to all error types including 429s that need exponential backoff. Guardrail: Include backoff behavior as a scored dimension. Provide the evaluator with expected backoff patterns per error category and require explicit timing checks in the evaluation trace.
Context Contamination Across Retries
What to watch: The agent accumulates stale or conflicting data across retry attempts but the evaluator only checks the final output, missing that intermediate state corrupted downstream reasoning. Guardrail: Require the evaluator to inspect the full retry trace, not just the final outcome. Add a rubric check for whether the agent properly isolated retry state or carried forward stale context.
Error Type Misclassification by Evaluator
What to watch: The evaluator confuses error categories—treating a timeout as a permission error, or a malformed response as a server error—leading to incorrect scoring of the agent's response strategy. Guardrail: Provide the evaluator with a clear error taxonomy and expected agent behavior per category. Include few-shot examples showing correct scoring for each error type in the evaluation prompt.
Evaluation Rubric
Criteria for grading agent error handling and retry logic. Use this rubric to score each test scenario on a 0-4 scale before aggregating into a production readiness gate.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Error Detection Accuracy | Agent correctly identifies the error type (timeout, permission_denied, malformed_response) from the tool output or exception message within one turn | Agent misclassifies the error type or proceeds as if the call succeeded when it failed | Inject known error types into tool responses; verify classification label matches injected type using exact string match on error category |
Retry Decision Appropriateness | Agent retries only for transient errors (timeout, rate_limit, 5xx) and does not retry for permanent errors (permission_denied, invalid_argument, 4xx) | Agent retries a permanent error or fails to retry a transient error when retry budget remains | Run test suite with labeled transient vs permanent error scenarios; measure precision and recall of retry decisions against ground truth |
Backoff Behavior Correctness | Agent implements or respects exponential backoff with jitter when retrying; no immediate tight-loop retries | Agent retries immediately without delay or uses fixed-interval retries that risk thundering-herd patterns | Inspect retry timestamps in agent trace; verify inter-retry intervals increase and include variance; flag any interval under 1 second |
Retry Budget Adherence | Agent respects [MAX_RETRIES] and stops retrying after exhausting the budget; does not exceed configured limit | Agent exceeds [MAX_RETRIES] or gives up before exhausting budget on a transient error | Set [MAX_RETRIES] to a known value; count actual retry attempts in trace; assert count <= [MAX_RETRIES] and count == [MAX_RETRIES] only when error persists |
Escalation Correctness | Agent escalates to human or fallback path when retries exhausted or error is permanent and unrecoverable; escalation message includes error summary and context | Agent silently fails, loops without escalation, or escalates with insufficient context for human to act | Verify escalation action is triggered at correct boundary; check escalation payload contains error type, tool name, arguments, and last error message |
State Preservation During Retry | Agent preserves original intent, arguments, and partial results across retries; does not lose context or revert to earlier state | Agent resets arguments to defaults, drops user-provided values, or loses intermediate results from prior successful steps | Compare pre-retry and post-retry tool call arguments; assert non-error fields remain unchanged; verify partial results from prior calls are referenced in subsequent reasoning |
Logging and Observability | Agent emits structured log entries for each error detection, retry attempt, backoff duration, and escalation decision | Agent produces no error logs, unstructured logs, or logs missing key fields (attempt number, error type, delay) | Parse agent trace output; assert log entries contain required fields: timestamp, error_type, attempt_number, backoff_seconds, decision (retry|escalate|fail) |
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
Start with the base prompt and a small set of 5–10 hand-crafted test scenarios covering timeout, permission denied, and malformed response. Use a lightweight JSON output schema with fields for error_detected, retry_decision, and justification. Skip formal scoring rubrics initially—focus on whether the model correctly identifies the error type and proposes a reasonable next action.
Add a [TOOL_CATALOG] placeholder listing available tools and their expected error signatures. Keep the [TEST_SCENARIOS] block simple: describe the tool call, the error returned, and the expected agent state.
Watch for
- The model confusing transient errors (timeouts) with permanent errors (permission denied)
- Overly verbose justifications that don't match the binary retry decision
- Missing edge cases: empty error bodies, HTTP 429 rate limits, partial success responses

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