This prompt is for reliability engineers and agent developers who need to encode retry judgment directly into an AI agent's decision loop. The job-to-be-done is producing a binary decision—retry or abort—backed by explicit, auditable rationale when a tool call fails. The ideal user is someone integrating an agent into a production system where tool dependencies (APIs, databases, internal services) fail in ways that naive retry loops make worse. They need the agent to distinguish a transient network blip from a systemic outage, respect a retry budget, consider idempotency guarantees, and avoid cascading failures. The required context includes the error signature (status code, body, headers), the remaining retry budget, the tool's idempotency contract, and the downstream impact of both retrying and aborting.
Prompt
Tool Retry vs Abort Decision Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Tool Retry vs Abort Decision Prompt.
Do not use this prompt when the retry logic is better handled in the application layer with deterministic rules (e.g., a simple HTTP 429 with a Retry-After header). It is also inappropriate for agents operating in fully synchronous, low-latency environments where a retry loop of 2-3 attempts with exponential backoff is sufficient and the cost of a wrong decision is negligible. The prompt adds value when the decision is genuinely contextual: the error is ambiguous, the retry budget is nearly exhausted, the tool is not idempotent, or aborting triggers a complex fallback chain. In high-risk domains—payments, patient data, infrastructure provisioning—the prompt's output must be treated as a recommendation that requires human approval or a secondary policy check before execution.
Before wiring this into an agent loop, define the retry budget, idempotency guarantees, and abort fallback behavior as explicit configuration, not as hidden assumptions in the prompt. Test the prompt against a golden set of borderline cases: a 500 error on an idempotent GET with budget remaining (should retry), a 409 Conflict on a non-idempotent POST with no budget left (should abort), and a timeout where the request may or may not have succeeded on the server side (the hardest case). The next section provides the copy-ready template you can adapt to your tool ecosystem.
Use Case Fit
Where the Tool Retry vs Abort Decision Prompt works and where it introduces operational risk. This prompt encodes retry judgment into agents, but it is not a substitute for infrastructure-level circuit breakers or human incident command.
Good Fit: Structured Error Handling
Use when: the agent receives machine-readable error codes (HTTP 429, gRPC DEADLINE_EXCEEDED, database deadlock) and must decide whether to retry or abort. Guardrail: The prompt requires explicit error type, retry budget remaining, and idempotency status as inputs before producing a decision.
Bad Fit: Unstructured or Novel Failures
Avoid when: the failure is an unexpected stack trace, a malformed response body, or a novel error the model has never seen. Guardrail: Route unstructured failures to a separate root cause hypothesis prompt or human review before invoking retry logic.
Required Inputs
Required: error type, retry budget consumed, retry budget limit, idempotency guarantee (yes/no/unknown), downstream impact severity, and tool response latency. Guardrail: If any required input is missing, the prompt should return a MISSING_INPUT decision rather than guessing.
Operational Risk: Retry Storms
Risk: The agent retries a failing call that is contributing to backend saturation, amplifying the outage. Guardrail: The prompt must consider circuit breaker state and recent failure counts across all agents, not just the local retry budget.
Operational Risk: Non-Idempotent Side Effects
Risk: The agent retries a payment, write, or state mutation that already partially succeeded, causing double execution. Guardrail: The prompt must treat idempotency: false or idempotency: unknown as a hard constraint that forbids retry unless the tool provides a deduplication key.
Boundary: Not a Circuit Breaker Replacement
Risk: Teams use this prompt as the sole resilience mechanism, skipping infrastructure-level circuit breakers. Guardrail: This prompt is a decision aid inside the agent loop. Platform-level circuit breakers, rate limiters, and load shedders must still operate independently.
Copy-Ready Prompt Template
A reusable prompt template for making a binary retry-or-abort decision with structured rationale when a tool call fails.
This prompt template encodes the judgment an agent needs when a tool call returns an error. Instead of a naive retry loop that can amplify load on a degraded dependency, the prompt forces the model to reason about the error type, the remaining retry budget, idempotency guarantees, and downstream impact before producing a binary decision. The output is a structured JSON object that your application harness can parse to either re-queue the tool call, switch to a fallback, or escalate to a human operator. Use this template as the core decision node inside a retry governance layer, not as a standalone chat prompt.
textYou are a tool reliability decision engine. Your only job is to decide whether a failed tool call should be retried or aborted. ## INPUT - Tool name: [TOOL_NAME] - Error received: [ERROR_PAYLOAD] - HTTP status or gRPC code (if available): [STATUS_CODE] - Retry attempt number: [ATTEMPT_NUMBER] - Maximum retries allowed: [MAX_RETRIES] - Is this tool call idempotent? [IDEMPOTENT] - Downstream impact of aborting: [DOWNSTREAM_IMPACT] - Current circuit breaker state: [CIRCUIT_STATE] - Latency of the failed call (ms): [LATENCY_MS] - Recent failure rate for this tool (last 5 min): [FAILURE_RATE] ## OUTPUT_SCHEMA Return ONLY valid JSON with this exact structure: { "decision": "RETRY" | "ABORT", "confidence": 0.0-1.0, "rationale": "One-sentence explanation citing the strongest factor.", "retry_delay_ms": integer or null, "escalation_recommended": true | false, "fallback_tool": "[FALLBACK_TOOL_NAME]" | null } ## CONSTRAINTS 1. If the error is a client error (4xx) and NOT a 429 rate limit, always ABORT. Do not retry bad requests. 2. If the error is a server error (5xx) and the retry budget remains, prefer RETRY with exponential backoff. 3. If the circuit breaker is OPEN, always ABORT regardless of error type. 4. If the tool call is NOT idempotent and a partial success is possible, prefer ABORT to avoid double execution. 5. If the downstream impact of aborting is CRITICAL and the error is transient, prefer RETRY even if confidence is moderate. 6. If the failure rate exceeds 50% in the recent window, prefer ABORT and recommend escalation. 7. Set retry_delay_ms using exponential backoff: min(1000 * 2^attempt, 30000). Set to null if ABORT. 8. Only suggest a fallback tool if one is known and appropriate for the error type. ## EXAMPLES Example 1: Transient server error with budget remaining Input: Tool=payment-capture, Error=503 Service Unavailable, Status=503, Attempt=2, Max=3, Idempotent=true, Impact=CRITICAL, Circuit=CLOSED, Latency=1200, FailureRate=0.1 Output: {"decision":"RETRY","confidence":0.9,"rationale":"Transient 503 with idempotent operation and critical downstream impact; retry budget available.","retry_delay_ms":4000,"escalation_recommended":false,"fallback_tool":null} Example 2: Client error with no retry budget Input: Tool=user-lookup, Error=400 Bad Request, Status=400, Attempt=3, Max=3, Idempotent=true, Impact=LOW, Circuit=CLOSED, Latency=200, FailureRate=0.05 Output: {"decision":"ABORT","confidence":1.0,"rationale":"400 Bad Request is a client error; retries will not resolve the issue.","retry_delay_ms":null,"escalation_recommended":true,"fallback_tool":null} Example 3: Circuit breaker open Input: Tool=inventory-check, Error=504 Gateway Timeout, Status=504, Attempt=1, Max=3, Idempotent=true, Impact=MEDIUM, Circuit=OPEN, Latency=30000, FailureRate=0.8 Output: {"decision":"ABORT","confidence":1.0,"rationale":"Circuit breaker is OPEN; all calls must abort until half-open probe succeeds.","retry_delay_ms":null,"escalation_recommended":true,"fallback_tool":"inventory-cache"} ## INSTRUCTIONS Analyze the INPUT against the CONSTRAINTS. If constraints conflict, prioritize safety (ABORT) over availability (RETRY). Return only the JSON object.
To adapt this template for your own tool ecosystem, replace the placeholder values with data from your agent's runtime context. The [ERROR_PAYLOAD] should include the raw error body so the model can distinguish between, for example, a 503 caused by a deployment rollover versus a 503 caused by persistent database unavailability. If your system does not track circuit breaker state, remove that constraint and the [CIRCUIT_STATE] placeholder, but expect more false-positive RETRY decisions during outages. The examples are critical calibration data—add at least two examples that reflect your most common borderline cases, such as a non-idempotent payment retry or a rate-limit response that looks like a server error. After copying the template, run it through your evaluation harness with the test cases described in the Testing and Evaluation section of this playbook before deploying to production.
Prompt Variables
Required inputs for the Tool Retry vs Abort Decision Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check that the input is well-formed and safe.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_NAME] | Identifies the tool that failed so the model can apply tool-specific retry policies. | payment_capture_api | Must match a registered tool ID in the agent's tool registry. Reject if tool name is not in the allowlist. |
[ERROR_PAYLOAD] | The raw error response from the tool, including status codes, error messages, and headers. | {"status": 503, "body": {"error": "upstream_timeout"}, "headers": {"retry-after": "30"}} | Must be valid JSON if the tool returns JSON. Check for presence of status code or error type field. Null allowed if the tool call hung without response. |
[RETRY_COUNT] | Number of retry attempts already consumed for this operation. | 3 | Must be a non-negative integer. Compare against [MAX_RETRIES] to calculate remaining budget. Reject if negative. |
[MAX_RETRIES] | The total retry budget allocated for this operation before escalation is required. | 5 | Must be a positive integer. Must be greater than or equal to [RETRY_COUNT]. Reject if [RETRY_COUNT] exceeds [MAX_RETRIES]. |
[IDEMPOTENCY_KEY] | A unique key that guarantees the operation can be safely retried without duplicate side effects. | txn_abc123_attempt_4 | Must be a non-empty string if the operation is idempotent. Set to null if the operation is not idempotent. Validate that the key format matches the tool's idempotency contract. |
[DOWNSTREAM_DEADLINE_MS] | The remaining time in milliseconds before the calling workflow or user expects a response. | 4500 | Must be a positive integer. Compare against expected tool latency to determine if a retry can complete before the deadline. Reject if zero or negative. |
[ERROR_CATEGORY] | A pre-classified error category assigned by the agent's error handler before invoking this prompt. | TRANSIENT_NETWORK | Must match one of the allowed enum values: TRANSIENT_NETWORK, PERMANENT_CLIENT_ERROR, PERMANENT_SERVER_ERROR, TIMEOUT, RATE_LIMITED, AUTH_EXPIRED, UNKNOWN. Reject unrecognized categories. |
[CIRCUIT_BREAKER_STATE] | The current state of the circuit breaker for this tool, if one is configured. | HALF_OPEN | Must be one of: CLOSED, OPEN, HALF_OPEN, or null if no circuit breaker is active. If OPEN, retry should almost always be ABORT unless overridden by a manual probe. |
Implementation Harness Notes
How to wire the Tool Retry vs Abort Decision Prompt into a production agent loop with validation, state tracking, and safe defaults.
The retry vs abort prompt is not a standalone decision engine; it is a judgment module inside a broader tool-execution harness. The harness owns the retry budget, tracks attempt counts, enforces idempotency checks, and applies the model's decision. The prompt's job is to produce a structured, auditable rationale given the current failure context. The harness must never delegate retry budget enforcement to the model—the model advises, the harness governs. This separation prevents prompt injection, hallucinated budgets, and runaway retry loops when the model misclassifies a persistent failure as transient.
Wire the prompt into the agent's tool-call error handler. When a tool returns a failure, the harness assembles the prompt context: the tool name, the error type and body, the current retry count and maximum budget, whether the operation is idempotent, the downstream impact if the call fails permanently, and any circuit-breaker state. The prompt returns a JSON decision object with action (retry, abort, escalate), rationale, suggested_delay_ms, and confidence. The harness validates this output against a strict schema before acting. If action is retry but the budget is exhausted, the harness overrides to abort and logs the conflict. If confidence is below a configurable threshold (e.g., 0.7), the harness escalates to a human or a fallback path rather than trusting a low-confidence retry. This validation layer is critical because the cost of a wrong retry in production—duplicate charges, corrupted state, cascading timeouts—is far higher than the cost of an unnecessary abort.
For high-risk domains such as payments, provisioning, or clinical data writes, add a human-in-the-loop gate before executing a retry decision. The harness can pause the workflow, surface the prompt's rationale and the raw error to a review queue, and resume only after approval. Log every decision—model output, harness override, human approval—as structured audit events with trace IDs that link the tool call, the prompt invocation, and the final action. When testing, build a harness-level test suite that simulates common failure signatures: 429 with Retry-After headers, 5xx without headers, connection resets, timeout mid-response, and malformed error bodies. Verify that the harness correctly overrides the model when the retry budget is zero, when the error is non-retryable by policy, and when the model returns malformed JSON. The harness, not the prompt, is the reliability boundary.
Expected Output Contract
Validation rules for the binary retry/abort decision and supporting rationale fields. Use this contract to parse, validate, and route the agent's output before acting on it.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
decision | enum: | Must be exactly one of the two allowed string values. Reject any other value or ambiguous phrasing. | |
rationale_summary | string (<= 280 chars) | Must be present and non-empty. Length must not exceed 280 characters. Reject if missing or empty. | |
error_classification | enum: | Must match one of the allowed enum values. Reject if missing or unrecognized. | |
retry_budget_remaining | integer (>= 0) | Must be a non-negative integer. If | |
recommended_delay_ms | integer (>= 0) | null | If | |
idempotency_safe | boolean | Must be | |
downstream_impact_risk | enum: | Must match one of the allowed enum values. If | |
escalation_required | boolean | Must be |
Common Failure Modes
Production tool calls fail in predictable patterns. These failure modes break retry-vs-abort decisions when the prompt relies on naive heuristics instead of structured reasoning.
Retrying Non-Idempotent Operations
What to watch: The agent retries a payment capture, order creation, or email send after a timeout, causing duplicate side effects. The prompt fails to distinguish between transient network errors and completed-but-unacknowledged writes. Guardrail: Require the prompt to check idempotency guarantees before authorizing retry. If the tool lacks idempotency keys, default to abort-and-escalate for any write operation where the initial response was ambiguous.
Retry Budget Exhaustion Without Escalation
What to watch: The agent burns through its entire retry budget on a persistent downstream outage, then fails silently or returns a generic error to the user. The prompt treats all retries as equal-cost operations. Guardrail: Include a retry budget counter in the prompt context and require explicit escalation logic when budget reaches zero. The output must distinguish between 'retry with remaining budget N' and 'budget exhausted, escalate to fallback or human.'
Misclassifying 429 Rate Limits as Transient
What to watch: The agent treats HTTP 429 responses as generic transient errors and retries immediately, compounding the rate limit violation and triggering longer backoff windows or IP bans. Guardrail: Require the prompt to parse Retry-After headers and classify 429 as a distinct error category. The decision output must include a backoff duration and distinguish between 'retry after delay' and 'abort due to persistent throttling.'
Ignoring Downstream Dependency Impact
What to watch: The agent retries a low-priority tool call while blocking a critical user-facing workflow, or retries a call to a degraded dependency that is already triggering cascading failures. Guardrail: Include a dependency criticality field in the prompt context. The decision logic must weigh whether the retry delay is acceptable for the calling workflow and whether the downstream tool is already in a degraded state.
Ambiguous Error Code Interpretation
What to watch: The agent encounters a provider-specific error code or a generic 500 response and defaults to retry because the prompt lacks a structured error taxonomy. This causes retries on permanent failures like invalid credentials or missing resources. Guardrail: Provide a classification table in the prompt mapping error categories (permanent, transient, rate-limit, auth, resource-not-found) to retry eligibility. Require the output to cite the matched error category in its rationale.
Retry Loop Without Circuit Awareness
What to watch: The agent retries a tool call that has already been failing for multiple requests across different sessions, unaware that a circuit breaker has opened upstream. Each retry adds latency and load with zero chance of success. Guardrail: Include circuit breaker state in the prompt context when available. The decision must check whether the circuit is open before authorizing retry, and if open, immediately route to fallback or abort.
Evaluation Rubric
Use this rubric to test the Tool Retry vs Abort Decision Prompt before deployment. Each criterion targets a specific failure mode observed in production agent tool loops.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Idempotent POST Retry | Decision is Retry when error is 500-level and tool is documented as idempotent. | Abort decision on retryable idempotent error. | Inject a 503 response for a tool with |
Non-Idempotent Side-Effect Abort | Decision is Abort when error is 500-level and tool is non-idempotent with side effects. | Retry decision on a non-idempotent payment or write operation. | Inject a 504 response for a |
Retry Budget Exhaustion | Decision is Abort when [RETRY_COUNT] >= [MAX_RETRIES]. | Retry decision when retry budget is already consumed. | Set [RETRY_COUNT] equal to [MAX_RETRIES] and inject a retryable error. Verify Abort decision and rationale mention budget exhaustion. |
4xx Client Error Abort | Decision is Abort for 400, 401, 403, 404, 422 errors regardless of retry budget. | Retry decision on a 401 Unauthorized or 422 Unprocessable Entity. | Inject a 401 error. Verify Abort decision and rationale state that client errors are not retryable. |
Downstream Impact Awareness | Abort rationale explicitly names the user-facing or pipeline impact of further retries. | Rationale is generic or only mentions the tool error without downstream consequences. | Inject a timeout on a tool in a critical checkout flow. Verify the rationale mentions checkout failure or user experience degradation. |
Rate Limit Retry with Backoff | Decision is Retry for 429 Too Many Requests, with rationale mentioning backoff. | Abort decision on a 429 error or Retry decision without any backoff mention. | Inject a 429 response with a |
Ambiguous Timeout Classification | Decision is Retry for a network timeout when [RETRY_COUNT] < [MAX_RETRIES], with rationale noting uncertainty. | Abort decision on a first-time network timeout without evidence of systemic failure. | Inject a connection timeout error. Verify Retry decision and rationale classify the error as transient. |
Structured Output Compliance | Output is valid JSON matching the [OUTPUT_SCHEMA] with no extra keys. | Output is plain text, missing required fields, or includes hallucinated fields. | Parse the output with a JSON schema validator. Verify |
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 simple JSON schema for the decision output. Use a hardcoded retry budget of 3 and a static list of retryable error codes (5xx, 429, connection reset). Skip idempotency checks and downstream impact analysis. Focus on getting the binary retry/abort decision right for the most common HTTP error codes.
code[ERROR_PAYLOAD] = raw error from tool call [RETRY_COUNT] = current attempt number [MAX_RETRIES] = 3
Watch for
- Treating all 4xx errors as non-retryable (409 Conflict may be retryable)
- No timeout classification—transient network blips look the same as dead backends
- Missing rationale in output makes debugging impossible

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