Inferensys

Prompt

Tool Use with Idempotency and Safe Retry Prompt Template

A practical prompt playbook for teaching agents idempotent write operations and safe retry patterns through worked examples, reducing duplicate mutations 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

Define the job, reader, and constraints for the Tool Use with Idempotency and Safe Retry prompt.

This prompt is for agent developers and platform engineers who are building AI systems that perform non-idempotent write operations—such as creating database records, sending emails, initiating payments, or updating external system state—where a duplicate call could cause double-spend, duplicate records, or corrupted data. The job-to-be-done is teaching the model, through concrete few-shot examples, to generate and attach idempotency keys, recognize already-completed operations, and decide when a retry is safe versus when it requires human intervention. The ideal user is someone integrating an LLM agent with production APIs and databases who already understands the basics of function calling but needs the model to handle the failure modes that turn a prototype into a reliable system.

Use this prompt when your agent's tool set includes at least one write operation that is not safe to repeat, when you have a defined idempotency key strategy (such as UUID generation or deterministic key derivation from input parameters), and when you can provide examples of both successful idempotent calls and failure scenarios. The prompt is designed for few-shot demonstration: you supply worked examples showing the model generating an idempotency_key before a write, detecting a 409 Conflict or duplicate response, and either returning the existing result or retrying with a corrected payload. Do not use this prompt for read-only agents, for systems where every operation is naturally idempotent, or when your tool definitions already enforce idempotency at the API gateway level and the model does not need to reason about it.

Before adopting this prompt, confirm that your tool schemas expose the idempotency_key parameter explicitly and that your API responses include status codes or fields the model can use to detect duplicates. If your tools do not return clear signals for 'already completed,' the model will hallucinate completion status. Pair this prompt with a validation harness that checks every tool call for the presence of an idempotency key on write operations, logs duplicate detection events, and escalates to a human reviewer when the model retries a write without a key or after receiving an ambiguous response. Start with a small set of 3–5 contrasting examples covering: a clean first attempt, a safe retry with the same key, an unsafe retry that should be blocked, and a duplicate detection that returns the cached result.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and the operational conditions required for safe deployment.

01

Good Fit: Write Operations with Side Effects

Use when: The agent performs database inserts, payment captures, or state mutations where duplicate execution is dangerous. Guardrail: The prompt template teaches the model to generate and attach an idempotency key before any write call, using a deterministic hash of the intent.

02

Bad Fit: Read-Only or Stateless Queries

Avoid when: The tool calls are purely idempotent by nature (e.g., search, read, calculate). Risk: Adding idempotency logic to read operations wastes tokens and can cause false-positive conflict errors if the model incorrectly applies retry semantics to a simple lookup.

03

Required Inputs: Tool Response Signatures

Risk: The model cannot infer safe retry conditions without knowing the specific error codes or response shapes of the downstream API. Guardrail: The prompt must be fed with a strict schema of retryable errors (e.g., 429, 5xx) and terminal errors (e.g., 400, 422) to prevent infinite retry loops.

04

Operational Risk: Idempotency Key Collisions

What to watch: The model generates a non-unique key (e.g., a simple timestamp) causing a legitimate new request to be mistaken for a duplicate. Guardrail: The few-shot examples must demonstrate high-entropy key generation (UUID v4 or content-hash) and explicitly show that a new intent requires a new key.

05

Operational Risk: Phantom 'Already Completed' Detection

What to watch: The model assumes a previous operation succeeded based on a vague API response, skipping a critical retry. Guardrail: The prompt must teach strict matching on explicit 'idempotency key replay' signals rather than inferring completion from generic success messages or empty payloads.

06

Variant: Human-in-the-Loop Override

Use when: The cost of a false positive (blocking a real payment) is higher than a duplicate. Guardrail: Extend the prompt to route 'conflict detected' states to a human approval queue instead of auto-resolving, ensuring the agent never silently drops a potentially valid user action.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template with square-bracket placeholders for teaching an agent to use idempotency keys and safe retry logic through few-shot examples.

This template provides a system prompt and a set of few-shot demonstration slots designed to teach a language model the critical distinction between safe and unsafe retries for tool calls. Instead of relying on abstract rules, the prompt uses contrasting examples of correct idempotency key generation, conditional retry logic, and detection of already-completed operations. The primary goal is to prevent duplicate mutations—such as creating a second identical resource, charging a customer twice, or sending a duplicate notification—when an agent encounters a network error or timeout after a write operation.

markdown
[SYSTEM_INSTRUCTION]
You are an agent that performs actions using external tools. Your primary directive is safety for write operations. Before calling any tool that creates, updates, or deletes data, you must generate a unique idempotency key. If a tool call fails with a retryable error (e.g., network timeout, 5xx status), you must check the tool's description to see if it supports idempotency keys. If it does, retry the call with the same idempotency key. If it does not, or if the error is a definitive failure (e.g., 409 Conflict, 422 Unprocessable Entity), you must not retry and instead report the failure to the user. Your response must be a JSON object with the keys "thinking", "tool_calls", and "final_response".

[TOOLS]
```json
[AVAILABLE_TOOL_SCHEMAS]

[EXAMPLES]

Example 1: Safe Retry with Idempotency

User: Create a new project named "Q3 Audit". Assistant Thought: The create_project tool is a write operation. I must generate an idempotency key. Assistant:

json
{
  "thinking": "Generating an idempotency key for the project creation to ensure safety on retry.",
  "tool_calls": [
    {
      "id": "call_1",
      "name": "create_project",
      "arguments": {
        "name": "Q3 Audit",
        "idempotency_key": "proj-q3-audit-2024-001"
      }
    }
  ]
}

Tool Result (Error): {"error": "Network timeout", "status": 504} Assistant Thought: The error is a retryable server error. The create_project tool supports idempotency keys. I will safely retry with the same key. Assistant:

json
{
  "thinking": "Retrying the project creation with the same idempotency key 'proj-q3-audit-2024-001' to avoid creating a duplicate project.",
  "tool_calls": [
    {
      "id": "call_2",
      "name": "create_project",
      "arguments": {
        "name": "Q3 Audit",
        "idempotency_key": "proj-q3-audit-2024-001"
      }
    }
  ]
}

Tool Result (Success): {"id": "123", "name": "Q3 Audit", "status": "active"} Assistant:

json
{
  "thinking": "Project created successfully after a safe retry.",
  "final_response": "I've created the 'Q3 Audit' project for you. Its ID is 123."
}

Example 2: Unsafe Retry Prevention

User: Send the monthly invoice to client Acme Corp. Assistant Thought: The send_invoice tool is a write operation that triggers a financial action. I must generate an idempotency key. Assistant:

json
{
  "thinking": "Generating an idempotency key for the invoice sending operation.",
  "tool_calls": [
    {
      "id": "call_3",
      "name": "send_invoice",
      "arguments": {
        "client": "Acme Corp",
        "period": "2024-06",
        "idempotency_key": "inv-acme-2024-06-001"
      }
    }
  ]
}

Tool Result (Error): {"error": "Invoice for period 2024-06 already sent.", "status": 409} Assistant Thought: The error is a 409 Conflict, indicating the operation already succeeded. This is not a retryable error. I must not retry and should inform the user. Assistant:

json
{
  "thinking": "The 409 Conflict error indicates the invoice was already sent. Retrying would be unsafe and could result in a duplicate charge. I will report this to the user.",
  "final_response": "It looks like the June 2024 invoice for Acme Corp has already been sent. I did not resend it to avoid a duplicate charge. Can you verify on your end?"
}

Example 3: Non-Idempotent Tool Failure

User: Log a debug event "cache-cleared". Assistant Thought: The log_event tool is a write operation but its schema does not list an idempotency_key parameter. It is not idempotent. Assistant:

json
{
  "thinking": "The log_event tool does not support idempotency. I will attempt the call once.",
  "tool_calls": [
    {
      "id": "call_4",
      "name": "log_event",
      "arguments": {
        "event_type": "debug",
        "message": "cache-cleared"
      }
    }
  ]
}

Tool Result (Error): {"error": "Internal server error", "status": 500} Assistant Thought: The tool failed with a server error, but it does not support idempotency keys. Retrying could cause a duplicate log entry, which is low-risk, but the principle is to not retry non-idempotent writes. I will report the failure. Assistant:

json
{
  "thinking": "The log_event tool failed and does not support safe retries. I will report the failure to the user.",
  "final_response": "I wasn't able to log the 'cache-cleared' event due to a server error. The operation was not retried because the logging tool doesn't support idempotency keys."
}

[INPUT] [USER_QUERY]

To adapt this template for your own agent, replace the [AVAILABLE_TOOL_SCHEMAS] placeholder with the actual JSON Schema definitions for your tools. Crucially, ensure your tool definitions explicitly declare whether they support an idempotency_key parameter. The examples use a mix of idempotent and non-idempotent tools to teach the model the conditional logic. You should curate your own set of 3-5 examples that mirror your specific tool set and the most dangerous failure modes you want to prevent, such as double payments, duplicate resource creation, or redundant state transitions. The [USER_QUERY] placeholder is where the live user input will be injected at runtime, typically as the final message in the prompt array.

Before deploying, validate this prompt against a golden test set of user queries that should trigger retries, prevent retries, and escalate for human review. Pay special attention to edge cases where the model might hallucinate an idempotency key for a tool that doesn't support one, or fail to generate a key for a dangerous write operation. The eval harness should check the final JSON output for the presence of idempotency_key in the arguments of write operations and assert that retries only occur for retryable errors on idempotent tools.

IMPLEMENTATION TABLE

Prompt Variables

Inputs required for the Tool Use with Idempotency and Safe Retry prompt template. Each placeholder must be populated before the prompt is sent to the model.

PlaceholderPurposeExampleValidation Notes

[TOOL_DEFINITIONS]

JSON Schema or OpenAPI definitions for all available tools, including idempotency key parameters

{"name": "create_invoice", "parameters": {"idempotency_key": {"type": "string", "required": true}}}

Schema parse check: must be valid JSON. Each tool must declare idempotency support in its description or parameter list.

[CONVERSATION_HISTORY]

Prior user messages and tool call results in chronological order

[{"role": "user", "content": "Create invoice for Acme Corp"}, {"role": "assistant", "content": null, "tool_calls": [{"name": "create_invoice", "arguments": {"idempotency_key": "acme-inv-2025-03"}}]}]

Array length check: must include all prior turns. Tool call entries must contain complete argument payloads, not summaries.

[CURRENT_USER_REQUEST]

The latest user message or system event triggering tool execution

"Send the payment reminder to invoice #INV-0042"

Non-empty string required. Must not contain pre-resolved tool arguments or injected idempotency keys.

[IDEMPOTENCY_KEY_STRATEGY]

Rules for generating deterministic idempotency keys from request context

"Use {entity_type}-{entity_id}-{operation}-{date} format. For invoices: inv-{invoice_number}-{action}-{YYYY-MM-DD}"

Strategy must produce collision-resistant keys. Validate that keys are deterministic for identical logical operations.

[RETRYABLE_ERROR_PATTERNS]

List of error types, status codes, or messages that permit safe retry

["HTTP 429", "HTTP 503", "timeout", "connection reset", "rate_limited"]

Must be an explicit allowlist. Validate that non-retryable errors like 400, 401, 403, 404, 409 are absent from this list.

[NON_RETRYABLE_ERROR_PATTERNS]

List of error types that must trigger escalation or abort, never retry

["HTTP 400", "HTTP 401", "HTTP 403", "HTTP 404", "HTTP 409 Conflict", "invalid_signature"]

Must include all client errors and permanent failures. Validate that 409 Conflict is explicitly listed to prevent duplicate creation retries.

[MAX_RETRY_COUNT]

Hard limit on consecutive retry attempts before escalation

3

Integer >= 1 and <= 5. Validate that the agent tracks retry count per operation, not globally across all operations.

[IDEMPOTENCY_CHECK_TOOL]

Tool or endpoint for checking whether an operation already succeeded before retrying

"get_operation_status" with parameter "idempotency_key"

Must be a defined tool in [TOOL_DEFINITIONS]. Validate that the agent calls this before any retry of a write operation, not after.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the idempotency and safe retry prompt into a production agent loop with validation, logging, and human review gates.

This prompt is designed to sit inside an agent's tool-calling loop, directly before a write operation is executed. It is not a standalone chat prompt; it is a decision gate that receives the proposed tool call, the conversation history, and the idempotency registry state. The application must supply the [TOOL_CALL] object, the [IDEMPOTENCY_REGISTRY] of previously completed operations, and the [RETRY_POLICY] that defines which error classes are safe to retry. The model's job is to output a structured decision: execute, retry_with_key, skip_completed, or escalate_to_human. The application layer then enforces that decision, never the model alone.

Wire this prompt into your agent framework as a pre-execution hook. Before the agent calls any POST, PUT, PATCH, or DELETE operation, serialize the proposed tool call to JSON and pass it alongside the idempotency registry. The registry should be a simple key-value store (e.g., Redis or DynamoDB) mapping idempotency_key -> {status, result, timestamp}. The application must check the registry before calling the model: if a key exists with status completed, skip the model call entirely and return the cached result. If the key is missing or status is failed, invoke this prompt to decide the next action. After the model returns a decision, the application must validate the output against the [OUTPUT_SCHEMA]—reject any decision that invents a key not derived from the input or that classifies a non-retryable error as retryable. Log every decision, the model's rationale, and the final action taken to an audit trail.

For high-risk operations such as payment processing, user deletion, or permission changes, add a human review gate after the model's decision. If the model returns execute or retry_with_key for an operation above a configured risk threshold, queue the proposed action for human approval before the application executes it. The prompt's [RISK_LEVEL] parameter should be set by the application based on the tool's risk classification, not by the model. Never allow the model to downgrade the risk level. For retry logic, implement a circuit breaker: if the same idempotency key fails more than three times, force escalation regardless of the model's output. This prevents infinite retry loops that the model might incorrectly authorize. Finally, instrument the entire path with metrics: decision latency, escalation rate, retry rate, and human approval rate. These metrics will tell you when the prompt needs tuning or when the tool's error behavior has changed.

IMPLEMENTATION TABLE

Expected Output Contract

Validate the structure and safety of every tool call generated by the prompt. Use this contract to build a post-processing harness that rejects unsafe or malformed outputs before execution.

Field or ElementType or FormatRequiredValidation Rule

tool_call_id

string

Must be a UUID v4 string. Reject if null, empty, or non-UUID format.

tool_name

string

Must exactly match a key in the [AVAILABLE_TOOLS] schema. Reject unknown or hallucinated tool names.

arguments

object

Must be a valid JSON object. Reject if missing, null, or if it fails to parse.

idempotency_key

string

Must be present for any tool tagged as 'write' in [TOOL_POLICIES]. Reject if missing for write operations. Validate format matches [IDEMPOTENCY_KEY_PATTERN].

retry_policy

object

If present, must contain 'max_retries' (integer, >=0) and 'retry_on' (array of error codes). Reject if 'max_retries' > [MAX_RETRY_LIMIT].

safe_to_retry

boolean

Must be 'true' if idempotency_key is present and the operation is idempotent. Reject if 'true' for non-idempotent operations without an idempotency_key.

already_completed_check

object

If present, must contain 'check_method' (string) and 'completed_status' (string). Reject if 'check_method' is not in [ALLOWED_CHECK_METHODS].

rationale

string

Must be a non-empty string explaining why the tool was selected and why retry is safe or unsafe. Reject if length < 10 characters or contains only whitespace.

PRACTICAL GUARDRAILS

Common Failure Modes

Idempotency and safe retry logic fails silently in production. These are the most common breakages and how to prevent them before they cause duplicate mutations.

01

Missing Idempotency Key

What to watch: The model calls a write tool without generating an idempotency key, making every retry a potential duplicate mutation. This happens most often when the prompt shows tool call examples that omit the key field. Guardrail: Include at least one negative example where a missing key triggers a pre-flight validation error, and add a schema constraint that marks the key as required in the tool definition.

02

Non-Deterministic Key Generation

What to watch: The model generates a new random key on each retry instead of reusing the original key, defeating the purpose of idempotency. This occurs when the prompt treats the key as a fresh UUID per attempt rather than a stable identifier derived from the operation intent. Guardrail: Demonstrate key derivation from deterministic inputs such as operation_type + entity_id + timestamp_bucket in few-shot examples, and test that retries produce identical keys.

03

Retrying Non-Retryable Errors

What to watch: The agent retries on 4xx client errors such as validation failures, permission denials, or not-found responses that will never succeed on retry. This wastes resources and delays escalation. Guardrail: Add a tool response classification example that separates retryable errors such as 429, 5xx, and network timeouts from non-retryable errors such as 400, 401, 403, and 404, and show the agent escalating instead of retrying.

04

Duplicate Detection Blindness

What to watch: The tool returns an already_completed or idempotency_conflict response, but the agent ignores it and retries with a new key or treats the response as an error. Guardrail: Include a worked example where the agent receives a 409 Conflict or duplicate response, extracts the existing result, and reports success to the user without retrying.

05

Unsafe Retry Without Backoff

What to watch: The agent retries immediately in a tight loop on rate-limit or transient errors, causing thundering-herd pressure on the downstream API and potentially triggering stricter rate limits. Guardrail: Show an example that includes exponential backoff with jitter in the retry sequence, and add a constraint in the system prompt that limits maximum retries and enforces a minimum delay between attempts.

06

Partial Completion Retry Hazard

What to watch: A multi-step write operation succeeds partially before failing, and the retry logic replays the entire sequence without checking which steps already completed. This creates duplicate side effects for the successful steps. Guardrail: Demonstrate checkpoint-style idempotency where each sub-step carries its own key or the agent queries current state before retrying, and include a negative example showing the damage from blind full-sequence replay.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating model outputs against idempotency and safe retry requirements before production deployment.

CriterionPass StandardFailure SignalTest Method

Idempotency key presence

Every write operation includes a unique, deterministic [IDEMPOTENCY_KEY] in the tool call arguments

Missing key field in tool call arguments for POST, PUT, PATCH, or DELETE operations

Schema validation: assert idempotency_key field exists and is non-null for all write tool calls in test suite

Idempotency key determinism

Same logical operation produces identical [IDEMPOTENCY_KEY] across retries; key derived from operation identity, not random or timestamp-based

Different keys generated for the same intended operation on retry; keys containing raw timestamps or random UUIDs without operation binding

Replay test: submit identical input twice and assert [IDEMPOTENCY_KEY] values match exactly

Safe retry condition detection

Model identifies already-completed operations by checking response status codes (409 Conflict, 200 OK with existing record) and does not retry

Model retries on 409 Conflict or re-executes on 200 OK when operation already completed; infinite retry loop on idempotency rejection

Simulate idempotency rejection responses and assert model returns completion status without re-invoking tool

Retry eligibility classification

Model retries only on transient errors (429, 503, network timeout); does not retry on permanent errors (400, 401, 403, 422)

Retry attempted on 400 Bad Request or 422 Unprocessable Entity; retry with identical arguments after permanent failure

Error injection test: return each HTTP error class and verify retry behavior matches retry eligibility rules

Duplicate mutation prevention

No duplicate side effects when tool call succeeds but response is lost; model uses idempotency key to safely re-request

Two records created, two charges applied, or two state mutations when only one was intended

Network interruption simulation: drop success response after tool execution and verify single mutation via idempotency replay

Argument correction on retry

When retry is safe, model corrects only the argument that caused the transient failure; preserves all other arguments unchanged

Model changes unrelated arguments on retry; model drops required fields that were present in original call

Diff test: compare original tool call arguments to retry arguments and assert only error-indicated fields changed

Escalation on retry exhaustion

After [MAX_RETRIES] attempts, model stops retrying and returns structured [ESCALATION_PAYLOAD] with failure summary and next steps

Infinite retry loop; silent failure without user notification; retry count exceeds configured maximum

Retry exhaustion test: force persistent failure and assert output contains escalation payload after exactly [MAX_RETRIES] attempts

Read-only operation safety

GET and read operations never include idempotency keys; model does not apply write-operation retry logic to reads

Idempotency key attached to GET requests; retry logic triggered on read timeouts without idempotency protection

Operation-type audit: run test suite and assert no read operations contain idempotency_key field in arguments

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with a minimal few-shot template showing 2-3 idempotency patterns. Use inline comments instead of a separate validation harness. Focus on teaching the model to generate an [IDEMPOTENCY_KEY] and check for [COMPLETION_STATUS] before acting.

code
Example 1: Payment with idempotency key
User: Process payment of $50 from account A to B
Assistant: Checking for existing payment with key [PAY-A-B-2025-03-15-001]... No existing payment found. Proceeding with charge.

Example 2: Duplicate request
User: Process payment of $50 from account A to B
Assistant: Found existing payment with key [PAY-A-B-2025-03-15-001]. Status: completed. Returning existing result without re-charging.

Watch for

  • Model inventing idempotency keys from thin air instead of deriving them from request fields
  • No distinction between "in-progress" and "completed" states
  • Overly broad instructions that don't specify which operations require idempotency
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.