Inferensys

Prompt

Agent Tool Retry Logic Test Prompt

A practical prompt playbook for using the Agent Tool Retry Logic Test Prompt in production AI workflows.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
PROMPT PLAYBOOK

When to Use This Prompt

For reliability engineers and AI quality engineers who need to validate an agent's retry behavior before production deployment.

This prompt is designed for reliability engineers and AI quality engineers who need to systematically validate an agent's retry behavior before it reaches production. The job-to-be-done is generating a structured test plan that exercises both transient and persistent tool failures, defining the expected retry strategy—including maximum attempts, backoff policy, idempotency handling, and escalation after exhaustion. You should use this prompt when you have a defined tool contract and need to verify that your agent's retry logic handles failure modes correctly rather than looping infinitely, abandoning tasks silently, or violating idempotency guarantees. The ideal user has access to the tool's API specification, understands the agent's retry configuration, and needs a repeatable test artifact that can be shared across the engineering and QA teams.

This prompt is not a substitute for integration tests that exercise real tool endpoints, nor is it designed for testing the tool's own internal retry behavior. It focuses exclusively on the agent's client-side retry logic—the decisions the agent makes when a tool call fails. You should avoid using this prompt when the agent has no configurable retry policy, when the tool is stateless and idempotent by default, or when you are testing the tool provider's infrastructure rather than your agent's resilience. The prompt assumes you can provide a tool contract that includes the endpoint signature, expected error codes, idempotency key semantics, and any documented retry-after headers or rate-limit responses. Without this context, the generated test plan will be generic and less actionable.

Before running this prompt, gather the tool's OpenAPI spec or equivalent contract documentation, the agent's current retry configuration (max retries, backoff multiplier, jitter settings, timeout thresholds), and any existing incident reports where retry behavior caused production issues. The output test plan should be treated as a living document—update it when the tool contract changes, when the agent's retry policy is tuned, or when new failure modes are discovered in production. If the tool performs irreversible side effects (writes, sends, deletes), require human review of the test plan before execution and ensure tests run against a sandbox or staging environment, never against production endpoints.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Agent Tool Retry Logic Test Prompt delivers value and where it introduces risk. Use this to decide if the prompt fits your reliability engineering workflow before integrating it into a test harness.

01

Good Fit: Pre-Production Reliability Gates

Use when: you are validating an agent's retry behavior against a known tool contract before deployment. The prompt generates structured test scenarios with expected retry counts, backoff windows, and escalation paths. Guardrail: pair with a mocked tool harness that can inject precise failure modes (timeouts, 5xx, rate limits) so the agent's actual behavior can be compared against the generated expectations.

02

Good Fit: Idempotency Contract Verification

Use when: your tool contract declares idempotency guarantees and you need to verify the agent respects idempotency keys during retries. The prompt generates scenarios that reuse idempotency keys across retry attempts and defines expected side-effect-free outcomes. Guardrail: require the test harness to assert that duplicate requests with the same idempotency key produce identical results and no duplicate side effects.

03

Bad Fit: Real-Time Production Retry Decisions

Avoid when: you need the prompt itself to make live retry decisions inside a running agent. This prompt is a test generation tool, not a runtime retry policy engine. Guardrail: use the prompt's output to configure your agent's retry middleware or circuit breaker; do not call the prompt during production tool invocations.

04

Bad Fit: Non-Deterministic or Side-Effect-Heavy Tools

Avoid when: the tool under test has non-deterministic outputs or irreversible side effects (e.g., sending emails, creating financial transactions) and you lack a sandbox environment. The prompt's test scenarios assume controllable, repeatable tool responses. Guardrail: always run retry tests against mocked or sandboxed tool endpoints; never test retry logic against production systems with real side effects.

05

Required Input: Complete Tool Contract with Error Taxonomy

What to watch: the prompt cannot generate meaningful retry scenarios without a full tool contract that includes error codes, retryable vs. non-retryable failure classifications, timeout thresholds, and idempotency key behavior. Guardrail: provide the tool's OpenAPI spec, gRPC proto, or MCP tool definition with explicit error schemas; missing error taxonomy produces generic, low-value test cases.

06

Operational Risk: Test Scenario Drift Over Tool Versions

What to watch: generated retry scenarios become stale when the tool contract changes—new error codes, changed rate limits, or deprecated endpoints invalidate prior test expectations. Guardrail: version-lock the tool contract used for test generation and re-run the prompt after every contract change; integrate with your tool contract version compatibility test prompt for automated drift detection.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

Paste this prompt into your test generation workflow to produce structured retry test scenarios from a tool contract and retry policy.

This prompt template generates a comprehensive test plan for validating an agent's retry logic against a specific tool. It takes your tool contract, failure modes, and retry policy as inputs and produces structured test scenarios with clear pass/fail criteria. The output is designed to be directly consumed by a test harness or reviewed by a reliability engineer before automation.

text
You are a reliability test engineer designing retry behavior tests for an AI agent that calls external tools.

Your task is to generate a structured test plan that validates the agent's retry logic against the provided tool contract, failure modes, and retry policy.

## INPUTS

### Tool Contract
[TOOL_CONTRACT]

### Failure Modes to Test
[FAILURE_MODES]

### Retry Policy
[RETRY_POLICY]

### Idempotency Configuration
[IDEMPOTENCY_CONFIG]

### Additional Constraints
[CONSTRAINTS]

## OUTPUT SCHEMA

Return a JSON object with the following structure:

{
  "test_plan_id": "string",
  "tool_under_test": "string",
  "retry_policy_summary": "string",
  "scenarios": [
    {
      "scenario_id": "string",
      "failure_mode": "string",
      "failure_type": "transient | persistent | mixed",
      "injected_fault": {
        "attempt": "integer",
        "error_code": "string",
        "error_message": "string",
        "latency_ms": "integer",
        "response_body": "object | null"
      },
      "expected_agent_behavior": {
        "should_retry": "boolean",
        "max_retries_expected": "integer",
        "backoff_strategy": "string",
        "idempotency_key_behavior": "reuse | regenerate | none",
        "escalation_trigger": "string | null",
        "fallback_action": "string | null",
        "user_communication": "string | null"
      },
      "assertions": [
        {
          "assertion_id": "string",
          "condition": "string",
          "expected_value": "string | boolean | integer",
          "measurement_point": "string"
        }
      ],
      "pass_criteria": "string",
      "failure_impact": "string"
    }
  ],
  "idempotency_tests": [
    {
      "test_id": "string",
      "description": "string",
      "key_reuse_scenario": "string",
      "expected_deduplication": "boolean",
      "side_effect_check": "string"
    }
  ],
  "global_assertions": [
    "string"
  ],
  "test_execution_order": ["string"],
  "known_limitations": ["string"]
}

## INSTRUCTIONS

1. Parse the tool contract to identify all endpoints, methods, and expected response shapes.
2. For each failure mode in the input list, generate at least one transient scenario (resolves before max retries) and one persistent scenario (exceeds max retries).
3. Map each scenario to the retry policy: max attempts, backoff multiplier, jitter, and retryable error codes.
4. Include idempotency key reuse checks where the tool contract specifies idempotency support.
5. For persistent failures, define the escalation path and fallback behavior explicitly.
6. Write assertions that can be verified in logs or traces, not just output inspection.
7. Flag any gaps between the retry policy and the failure modes that need human review.

## RISK LEVEL: [RISK_LEVEL]

If RISK_LEVEL is "high", add a human review gate before any destructive or state-mutating retry scenario and include rollback verification assertions.

Adapt this template by replacing each square-bracket placeholder with your concrete specifications. The [TOOL_CONTRACT] should include the full API schema, authentication method, and expected response codes. The [FAILURE_MODES] should enumerate specific error conditions you want to test—timeouts, 429 rate limits, 503 service unavailable, malformed JSON responses, and authentication expiry. The [RETRY_POLICY] must specify max attempts, backoff strategy (exponential, linear, fixed), jitter configuration, and which error codes are retryable versus non-retryable. The [IDEMPOTENCY_CONFIG] should describe how idempotency keys are generated, stored, and validated. Set [RISK_LEVEL] to "high" for tools that mutate state, handle payments, or operate in regulated domains—this activates additional safety assertions and human-review gates in the generated test plan.

After generating the test plan, validate it against your actual retry implementation. Common gaps include: missing tests for idempotency key collisions, no scenarios for partial success responses, and retry policies that don't account for tool-side deduplication windows. Run the generated scenarios in a staging environment before promoting to your CI pipeline. If the tool contract changes, regenerate the test plan and diff it against the previous version to catch regressions in retry coverage.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to generate reliable retry test scenarios. Validate each before invoking the prompt to prevent malformed test plans or missing failure modes.

PlaceholderPurposeExampleValidation Notes

[TOOL_CONTRACT]

Full tool definition including endpoint, method, argument schema, output schema, and declared retry behavior

{"name": "create_order", "method": "POST", "endpoint": "/api/orders", "arguments": {"items": "array", "idempotency_key": "string"}, "retry_policy": {"max_attempts": 3, "backoff": "exponential"}}

Schema check: must contain retry_policy or idempotency_key field. Reject if endpoint or method is missing. Validate JSON structure before prompt assembly.

[FAILURE_MODE_CATALOG]

List of failure modes to generate test scenarios for, drawn from the tool's error taxonomy

["timeout", "5xx_server_error", "rate_limit_429", "idempotency_key_reuse", "partial_write"]

Enum check: each entry must match a known failure class. Reject unknown modes. At least one transient and one persistent failure required. Null allowed if prompt should infer from contract.

[RETRY_STRATEGY]

Declared retry strategy the agent is expected to follow, including max attempts, backoff type, and escalation path

{"max_attempts": 3, "backoff": "exponential", "base_delay_ms": 200, "max_delay_ms": 5000, "escalation_after_exhaustion": "human_approval"}

Schema check: max_attempts must be integer >= 1. backoff must be one of fixed, exponential, or linear. escalation_after_exhaustion must be a non-empty string. Reject if max_attempts > 10 without explicit override flag.

[IDEMPOTENCY_CONTRACT]

Rules for idempotency key behavior: key source, reuse detection, and expected outcome on replay

{"key_field": "idempotency_key", "key_source": "client_generated_uuid4", "reuse_behavior": "return_original_response", "reuse_window_seconds": 86400}

Schema check: key_field must match a field in TOOL_CONTRACT arguments. reuse_behavior must be one of return_original_response, reject_duplicate, or create_new_resource. Null allowed if tool has no idempotency support.

[OUTPUT_SCHEMA]

Expected structure of the generated test plan output, defining test case fields and assertion format

{"test_cases": [{"scenario_id": "string", "failure_mode": "string", "attempt_number": "integer", "injected_response": "object", "expected_agent_behavior": "string", "assertions": ["string"]}]}

Schema check: must include test_cases array with scenario_id, failure_mode, and expected_agent_behavior fields. Reject if assertions is empty or missing. Validate against JSON Schema before prompt execution.

[CONSTRAINTS]

Boundary conditions for test generation: max scenarios, safety limits, and excluded destructive operations

{"max_scenarios": 20, "exclude_destructive": true, "require_idempotency_key_reuse_test": true, "timeout_threshold_ms": 30000}

Parse check: max_scenarios must be integer 5-50. exclude_destructive must be boolean. Reject if require_idempotency_key_reuse_test is true but IDEMPOTENCY_CONTRACT is null. timeout_threshold_ms must be positive integer.

[CONTEXT]

Additional operational context: environment, tool dependencies, and known production failure patterns

{"environment": "staging", "dependent_tools": ["inventory_check", "payment_capture"], "known_flaky_endpoints": ["/api/orders"], "observed_failure_rate_pct": 2.3}

Parse check: environment must be one of development, staging, or production. dependent_tools must be array of strings matching known tool names. observed_failure_rate_pct must be float 0-100. Null allowed for greenfield tools.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the retry logic test prompt into a CI pipeline or manual QA workflow with validation, logging, and model selection guidance.

This prompt is designed to be run as part of a pre-release test suite for any agent that interacts with external tools. The primary integration point is a test runner that can call an LLM, parse the generated test scenarios, and then execute those scenarios against the agent under test. Do not run this prompt in production; it is a development-time quality gate. The prompt expects a tool contract (OpenAPI, JSON Schema, or a structured description of the tool's behavior) and a retry policy document as inputs. The output is a machine-readable test plan that can be fed into a test executor.

To wire this into a CI pipeline, wrap the prompt in a script that: (1) loads the tool contract and retry policy from the repository, (2) substitutes them into the [TOOL_CONTRACT] and [RETRY_POLICY] placeholders, (3) calls a capable model (GPT-4o, Claude 3.5 Sonnet, or equivalent) with a low temperature (0.1–0.2) to maximize deterministic output, (4) parses the JSON output and validates it against the expected test scenario schema, and (5) writes the validated scenarios to a test artifacts directory. For manual QA, the same prompt can be used in a chat interface, but you must still validate the output schema before executing the tests. Add a retry wrapper around the LLM call itself: if the model returns malformed JSON, retry once with the error message appended to the prompt. If it fails again, fail the pipeline and alert the developer.

The generated test scenarios should be executed by a separate test harness that mocks the tool endpoint. Each scenario defines a failure injection (e.g., 'return 503 on attempt 1, success on attempt 2') and an expected agent behavior (e.g., 'retries once with exponential backoff, then returns result'). The test harness must verify that the agent's actual retry count, backoff timing, idempotency key reuse, and escalation behavior match the expected values. Log every tool call attempt with its timestamp, idempotency key, and response status. After the test run, compare the log against the expected behavior from the prompt output. Fail any scenario where the agent retried too many times, too few times, reused an idempotency key incorrectly, or escalated prematurely. For high-risk tools (write operations, financial transactions), add a human review step before promoting the agent to production, even if all automated tests pass.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the test plan generated by the Agent Tool Retry Logic Test Prompt. Use this contract to validate the prompt output before feeding it into a test harness.

Field or ElementType or FormatRequiredValidation Rule

test_plan_id

string (UUID v4)

Must parse as valid UUID v4. Reject if missing or malformed.

tool_under_test

string

Must match a tool name from the provided [TOOL_CONTRACT]. Reject if empty or not in contract.

retry_strategy_summary

object

Must contain max_attempts (integer >= 1), backoff_policy (enum: fixed, exponential, linear), and base_delay_ms (integer >= 0). Reject if any field missing or out of range.

scenarios

array of objects

Must contain 3-10 scenario objects. Reject if empty or exceeds 10. Each scenario must have a unique scenario_id.

scenarios[].scenario_id

string

Must be unique within the array. Reject on duplicate.

scenarios[].failure_type

enum string

Must be one of: timeout, 5xx_error, 4xx_error, rate_limit, connection_error, malformed_response, auth_error. Reject on unrecognized value.

scenarios[].failure_persistence

enum string

Must be transient or persistent. Reject on unrecognized value.

scenarios[].expected_retry_count

integer

Must be >= 0 and <= max_attempts from retry_strategy_summary. Reject if out of bounds.

scenarios[].expected_final_outcome

enum string

Must be success_after_retry, failure_after_exhaustion, or escalation_after_exhaustion. Reject on unrecognized value.

scenarios[].idempotency_check

object

Must contain key_reuse_expected (boolean) and expected_behavior (string). Reject if key_reuse_expected is not true or false.

scenarios[].assertions

array of strings

Must contain at least 1 assertion. Each assertion must be a non-empty string. Reject if empty array or any empty string.

escalation_rules

object

Must contain trigger (enum: max_attempts_exhausted, persistent_failure_detected, circuit_open) and action (string). Reject if trigger not in enum or action is empty.

generated_at

string (ISO 8601)

Must parse as valid ISO 8601 datetime. Reject if unparseable.

PRACTICAL GUARDRAILS

Common Failure Modes

Retry logic fails silently in production when the prompt assumes the network is reliable and the tool is stateless. These are the failure modes that surface first—and the guardrails that catch them before users do.

01

Infinite Retry on Non-Transient Errors

What to watch: The agent retries 4xx auth errors, invalid argument responses, or quota-exceeded failures as if they were transient network blips. Each retry burns tokens, hits rate limits, and delays the real failure signal. Guardrail: Classify errors before retrying—retry only on 429, 5xx, and connection timeouts. For 4xx and 401/403, abort immediately and surface the error to the calling system.

02

Idempotency Key Collision on Partial Success

What to watch: The tool returns a timeout but the operation actually succeeded server-side. The agent retries with the same idempotency key and receives a duplicate response, then misinterprets it as a fresh result—doubling state or skipping the real outcome. Guardrail: After any timeout, query the resource state directly before retrying. If the idempotency key returns a cached response, treat it as the source of truth and stop retrying.

03

Backoff Collapse Under Load

What to watch: Multiple agent instances retry simultaneously with identical backoff schedules, creating thundering-herd pressure on an already-degraded tool. The retry strategy amplifies the outage instead of absorbing it. Guardrail: Add jitter to every backoff interval. Use exponential backoff with a randomized component (e.g., base_delay * 2^attempt + random(0, base_delay)). Cap total retry duration, not just attempt count.

04

Retry Budget Exhaustion Without Escalation

What to watch: The agent exhausts all retry attempts and then silently returns a stale or empty result, or worse, hallucinates a tool output to complete the task. The user never learns the tool failed. Guardrail: After max retries, the agent must produce a structured degradation signal—either a fallback response, a partial result with an error field, or an explicit escalation message. Never allow the agent to fabricate tool output after exhaustion.

05

State Mutation Across Retry Attempts

What to watch: A multi-step tool chain fails at step 3. The agent retries step 3 without rolling back the side effects of steps 1 and 2, leaving the system in an inconsistent state that downstream steps can't reconcile. Guardrail: Define a compensation or rollback action for each tool in the chain. If a mid-chain retry fails, execute the compensation chain before restarting. Test partial-failure recovery explicitly in the harness.

06

Retry-After Header Ignored

What to watch: The tool returns a 429 with a Retry-After header, but the agent ignores it and uses its own fixed backoff—either retrying too soon and getting throttled again, or waiting too long and degrading user experience. Guardrail: Parse Retry-After from 429 and 503 responses. Use the server-provided delay as the minimum wait time. If the header is absent, fall back to the agent's exponential backoff with jitter.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate whether the generated retry logic test scenarios are complete, correct, and safe to use in a CI pipeline before deployment. Each criterion targets a specific failure mode common in agent tool retry implementations.

CriterionPass StandardFailure SignalTest Method

Idempotency Key Reuse

At least one test scenario explicitly verifies that repeating a call with the same [IDEMPOTENCY_KEY] after a transient failure produces the same outcome and no duplicate side effects.

No test case covers idempotency key behavior; all retry scenarios assume new keys or ignore the key contract.

Static review: grep the generated test plan for 'idempotency' and confirm a dedicated test case exists.

Max Attempts Enforcement

The test plan defines a clear [MAX_RETRIES] boundary and includes a scenario where the agent stops retrying after exhausting attempts and escalates or returns a terminal error.

The generated scenarios describe indefinite retry loops or lack a terminal state after [MAX_RETRIES] is exceeded.

Parse the test plan for a numeric retry limit and trace the 'exhaustion' scenario to a defined escalation action.

Backoff Strategy Verification

At least one scenario validates that retry delays increase over time (e.g., exponential backoff) and do not fire synchronously in a tight loop.

All retry scenarios use fixed or zero-delay retries; no timing assertion exists.

Check for timing constraints or delay assertions in the test steps; confirm a 'backoff' or 'delay' keyword is present.

Transient vs. Persistent Failure Discrimination

The test plan includes separate scenarios for transient errors (HTTP 429, 503) that should be retried and persistent errors (HTTP 400, 401) that should not be retried.

The plan retries all error codes indiscriminately or fails to distinguish retryable from non-retryable failures.

Map each error code in the test plan to a retry decision; verify at least one non-retryable error aborts immediately.

State Consistency After Partial Failure

A multi-step tool chain scenario validates that when a mid-chain retry succeeds, the agent does not re-execute already-completed steps and maintains correct state.

The test plan only covers single-tool retries and ignores state contamination across a tool chain.

Look for a 'rollback' or 'state check' assertion in a multi-step scenario; confirm earlier step results are not duplicated.

Escalation Path Definition

After retry exhaustion, the test plan specifies whether the agent escalates to a human, calls a fallback tool, or returns a structured error to the calling system.

Exhaustion scenarios end with a generic 'fail' or 'error' message with no defined handoff or degradation path.

Inspect the exhaustion scenario output for a concrete escalation target: [FALLBACK_TOOL], [HUMAN_APPROVAL], or a structured error schema.

Retry Budget and Rate Limit Awareness

The test plan includes a scenario where the agent respects a [RATE_LIMIT_RESET] header or a global retry budget and does not exceed allowed call volume.

The agent retries aggressively without checking Retry-After headers or consuming the entire rate limit budget.

Search for 'Retry-After' or 'budget' in the test plan; confirm a scenario where the agent waits or degrades based on the header.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single tool and simplified retry rules. Replace the full [TOOL_CONTRACT] with a minimal schema containing only the endpoint, idempotency key field, and two error modes (transient 503, persistent 400). Reduce [MAX_RETRY_ATTEMPTS] to 2 and skip backoff complexity.

Watch for

  • The agent retrying non-retryable errors (400s) because the prompt doesn't distinguish error classes
  • Missing idempotency key reuse checks when the contract is underspecified
  • Overly broad instructions causing the agent to retry indefinitely without an abort condition
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.