This prompt is for integration developers and AI quality engineers who need to verify that an agent's tool calls are safe to retry. When an agent invokes a payment API, a database write, or a resource provisioning endpoint, a network timeout can leave the system in an unknown state. Retrying without idempotency guarantees can double-charge a customer, create duplicate records, or corrupt state. This prompt generates a structured test plan that invokes the same tool call multiple times with identical idempotency keys and validates that the outcome is consistent, side-effect-free, and matches the declared idempotency contract. Use this prompt before deploying any agent that calls mutating external tools. It belongs in your pre-release test suite, not as a runtime guard.
Prompt
Agent Tool Idempotency Test Prompt

When to Use This Prompt
Defines the exact scenario, required context, and boundaries for using the Agent Tool Idempotency Test Prompt in a pre-release test suite.
The ideal user has access to the tool's API contract, including the idempotency key field name, the HTTP method, and the expected success and conflict responses. You will need to provide the tool's OpenAPI spec or equivalent schema, the idempotency key parameter, and the target environment (staging only—never run idempotency tests against production payment or provisioning endpoints). The prompt expects a [TOOL_CONTRACT] that defines the endpoint, the [IDEMPOTENCY_KEY_FIELD], and the [TEST_ENVIRONMENT] where the tests will execute. Without a clear idempotency contract from the tool provider, this prompt cannot produce valid test cases; in that scenario, first use the Tool Contract Validation Prompt to verify the contract exists.
Do not use this prompt for read-only GET operations, for tools that lack an explicit idempotency mechanism, or for workflows where the agent's retry logic is handled entirely by a message queue with exactly-once delivery guarantees. This prompt is also inappropriate for runtime use—it generates test plans, not live guardrails. If you need runtime idempotency enforcement, implement that in your API gateway or tool proxy layer, not in the agent's prompt. After generating the test plan, execute it in a sandboxed staging environment, review the results for any duplicate side effects, and ensure your agent's retry logic respects the idempotency keys before promoting to production.
Use Case Fit
Where the Agent Tool Idempotency Test Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your current testing stage and operational context.
Good Fit: Pre-Production Retry Verification
Use when: You are validating a tool's idempotency contract in a staging or CI/CD environment before deployment. Guardrail: Run this prompt against a dedicated test instance of the tool, never against production payment or write APIs, to confirm that repeated calls with the same idempotency key produce identical results and no duplicate side effects.
Bad Fit: Non-Idempotent or Unkeyed Tools
Avoid when: The target tool does not expose an idempotency key parameter or explicitly documents that repeated calls are not safe. Guardrail: If the tool lacks idempotency support, use the Agent Tool Failure Injection Test Prompt instead to verify that the agent handles duplicate submissions through application-level deduplication or human review.
Required Inputs: Contract and Key Semantics
What you must provide: The tool's OpenAPI or JSON Schema contract, the exact idempotency key field name, the key's scope (per-resource, per-account, or global), and the expected idempotency window duration. Guardrail: If the key semantics are undocumented, run the Tool Contract Validation Prompt first to surface ambiguities before generating test cases.
Operational Risk: Stateful Side-Effect Leakage
What to watch: Some tools return idempotent responses but still emit duplicate events, increment internal counters, or trigger downstream webhooks on retries. Guardrail: Pair this prompt with the Tool Output Hallucination Detection Prompt to compare the agent's reported outcome against actual system state, not just the API response body.
Operational Risk: Expired Idempotency Windows
What to watch: Tools that enforce short idempotency windows (e.g., 24 hours) may silently treat an expired key as a new request, creating duplicates in long-running agent workflows. Guardrail: Include test cases that simulate retries after the documented window expires and verify that the agent detects the expiration rather than assuming safety.
Operational Risk: Cross-Key Contamination
What to watch: Idempotency behavior may differ when multiple keys are used in rapid succession, especially if the tool shares backend state across keys. Guardrail: Add test cases that interleave calls with different idempotency keys and verify that responses remain isolated, with no cross-key state leakage or ordering dependencies.
Copy-Ready Prompt Template
A reusable prompt that generates idempotency test cases for a given tool contract, ready to paste into your evaluation harness.
This prompt template generates a structured test plan that invokes the same tool call multiple times with identical idempotency keys and validates that the outcome is consistent, side-effect-free, and matches the declared idempotency contract. Use it when you need to verify that a tool's retry behavior is safe before deploying an agent that may retry failed or timed-out calls. The template expects a tool contract as input and produces a set of test scenarios, each with a sequence of identical calls, expected responses, and pass/fail assertions.
textYou are an idempotency test designer for agent tool integrations. Your job is to generate a test plan that verifies a tool's idempotency behavior under repeated identical invocations. ## INPUT [TOOL_CONTRACT] ## CONSTRAINTS - The tool contract includes: name, description, argument schema, output schema, and a declared idempotency policy (key field, key source, retry window, expected behavior on duplicate calls). - Generate test cases that exercise the idempotency contract, not generic retry behavior. - Each test case must specify the exact arguments, the idempotency key value, the number of repeated calls, and the expected outcome for each call. - Cover these scenarios: identical key within retry window, identical key outside retry window, missing key, malformed key, key reuse across different argument sets, and concurrent duplicate calls. - For each scenario, define whether the expected behavior is: same result returned, operation executed once, error returned, or behavior undefined. - If the tool contract does not declare an idempotency policy, flag it as a contract gap and generate test cases that detect accidental non-idempotent behavior. - Do not generate destructive test cases that mutate production data. Mark any test that requires a live system with [REQUIRES_ISOLATED_ENVIRONMENT]. ## OUTPUT SCHEMA Return a JSON object with this structure: { "tool_name": "string", "idempotency_policy_summary": "string describing the declared policy or noting its absence", "contract_gaps": ["string flags for missing or ambiguous policy elements"], "test_cases": [ { "test_id": "string", "scenario": "string describing the idempotency scenario being tested", "idempotency_key": "string or null", "arguments": {}, "call_count": number, "expected_outcomes": [ { "call_index": number, "expected_http_status": number, "expected_response_signature": "string describing key fields that must match", "expected_side_effects": "string describing allowed or disallowed mutations", "idempotency_behavior": "one of: first_execution | duplicate_acknowledged | error | undefined" } ], "assertions": ["string pass/fail conditions"], "requires_isolated_environment": boolean } ], "eval_criteria": { "pass_conditions": ["string conditions that must all be true for the tool to pass"], "fail_conditions": ["string conditions that indicate a violation of the idempotency contract"], "warning_conditions": ["string conditions that are acceptable but worth monitoring"] } } ## EXAMPLES [EXAMPLES] ## RISK LEVEL [RISK_LEVEL] Generate the test plan now.
Adapt this template by replacing [TOOL_CONTRACT] with the full tool definition—including its argument schema, output schema, and any documented idempotency behavior. Populate [EXAMPLES] with one or two representative test cases if you have known patterns the model should follow. Set [RISK_LEVEL] to low, medium, or high to control the conservatism of the generated assertions; high-risk tools will get stricter pass/fail criteria and more explicit warnings about side-effect detection. After generation, validate the output against the declared JSON schema before feeding test cases into your test harness. For tools that mutate external state, always run generated tests in an isolated environment first.
Prompt Variables
Fill these variables before running the Agent Tool Idempotency Test Prompt. Each placeholder defines a required input for generating test cases that verify safe retry behavior with idempotency keys.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_NAME] | Identifies the tool under test so generated cases reference the correct function | create_order | Must match the registered tool name exactly; case-sensitive check against tool registry |
[TOOL_CONTRACT] | Provides the full tool schema including arguments, types, required fields, and output shape | {"name": "create_order", "parameters": {"type": "object", "properties": {"order_id": {"type": "string"}, "items": {"type": "array"}}, "required": ["order_id", "items"]}} | Validate as valid JSON Schema; must include properties, types, and required fields; null not allowed |
[IDEMPOTENCY_KEY_FIELD] | Specifies which argument serves as the idempotency key for deduplication | idempotency_key | Must exist in TOOL_CONTRACT parameters; field must be type string; confirm key is documented as idempotent in tool spec |
[IDEMPOTENCY_WINDOW_SECONDS] | Defines the time window in which repeated calls with the same key must return identical results | 3600 | Must be positive integer; parse as int and verify > 0; used to set test timing constraints |
[EXPECTED_SUCCESS_RESPONSE] | Provides the canonical success response the tool should return on first invocation | {"status": "created", "order_id": "ord_123", "created_at": "2025-01-15T10:00:00Z"} | Validate as valid JSON matching TOOL_CONTRACT output schema; must include all required output fields |
[SIDE_EFFECT_DESCRIPTION] | Describes the expected side effects of the tool so tests can verify no duplicate side effects occur | Creates exactly one order record in the database and sends one confirmation email | Must be a non-empty string describing observable state changes; used to define side-effect-free assertion |
[MAX_RETRY_ATTEMPTS] | Sets the number of identical calls to issue in the test to verify idempotency holds across retries | 3 | Must be integer >= 2; parse as int; values below 2 cannot test retry behavior; values above 10 may indicate test design issue |
[OUTPUT_COMPARISON_STRATEGY] | Defines how to compare repeated responses: exact match, semantic equivalence, or field-level comparison | field-level | Must be one of: exact, semantic, field-level; determines assertion strictness; field-level requires specifying which fields to compare |
Implementation Harness Notes
How to wire the idempotency test prompt into a CI pipeline or manual QA workflow with validation, retries, and logging.
The idempotency test prompt is designed to be invoked programmatically as part of a tool contract verification suite. It expects a structured input containing the tool's contract (description, argument schema, idempotency key field), the tool's declared idempotency behavior, and any relevant constraints such as rate limits or side-effect warnings. The output is a set of test cases—each specifying the tool call arguments, the idempotency key value, the number of repeated invocations, and the expected outcome—that can be fed into a test runner or manual review queue. This prompt is not a one-shot chat interaction; it is a generation step in a larger testing pipeline.
To integrate this prompt into an application, wrap it in a function that accepts the tool contract and configuration as input, calls the model with a low temperature (0.0–0.2) to maximize deterministic output, and parses the response into a typed array of test case objects. Each test case must include a unique test_id, the tool_name, arguments (with the idempotency key field populated), repeat_count, and expected_outcome (e.g., 'identical_result', 'no_duplicate_side_effect', 'idempotency_key_rejected_if_missing'). Validate the output against this schema immediately after generation. If validation fails, retry once with the validation errors appended to the prompt as [CONSTRAINTS]. Log every generation attempt, the raw model output, the parsed result, and any validation errors to your observability stack for debugging and audit. For high-risk tools (e.g., payment APIs, database writes, provisioning systems), route the generated test cases through a human approval step before execution. The approval UI should display the tool contract, the generated test cases, and a diff against any previously approved test set.
When executing the generated test cases, use a dedicated test harness that can invoke the actual tool or a mock with identical idempotency behavior. The harness must track the idempotency key across repeated calls and assert that the outcome matches the expected behavior defined in the test case. Common failure modes to monitor include: the model generating test cases that don't exercise the idempotency key field at all, producing duplicate test cases with different test_id values, or hallucinating expected outcomes that contradict the tool's documented contract. To catch these, add eval checks that verify every generated test case references the declared idempotency key field, that the set of test cases is deduplicated by argument signature, and that each expected outcome is consistent with the tool's stated idempotency guarantee. If the tool contract changes, re-run the prompt and diff the new test cases against the previous set to detect regressions or gaps in coverage.
Expected Output Contract
Fields, format, and validation rules for the generated idempotency test plan. Use this contract to build automated validation gates before running the test cases.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
test_plan_id | string (UUID v4) | Must parse as valid UUID v4. Generated once per plan. | |
tool_name | string | Must match the [TOOL_NAME] input exactly. Case-sensitive. | |
idempotency_key | string | Must match the [IDEMPOTENCY_KEY] input exactly. Non-empty. | |
test_cases | array of objects | Array length must be >= 3. Each element must conform to the test_case schema below. | |
test_cases[].invocation_id | string | Unique within the array. Format: inv-N where N is a zero-padded integer starting at 001. | |
test_cases[].description | string | Non-empty. Must describe the specific retry scenario (e.g., 'First call', 'Immediate retry with same key', 'Delayed retry after success'). | |
test_cases[].expected_side_effects_count | integer | Must be 0 or 1. 1 for the first invocation only; 0 for all subsequent retries with the same key. | |
test_cases[].expected_result_consistency | string (enum) | Must be one of: 'identical', 'equivalent', 'idempotent_replay'. 'identical' means byte-for-byte match. 'equivalent' means semantically same but formatting may differ. 'idempotent_replay' means the stored result is returned without re-execution. |
Common Failure Modes
Idempotency tests break when retries produce inconsistent side effects, keys are reused incorrectly, or the contract is ambiguous. Here's what fails first and how to prevent it.
Non-Idempotent Side Effects Leak Through
What to watch: The tool succeeds on the first call but produces a duplicate record, double charge, or extra side effect on the retry because the idempotency key isn't actually enforced server-side. Guardrail: Verify the outcome is identical after 3 identical calls with the same key—not just that no error is returned. Assert resource count, balance, or state hasn't changed.
Idempotency Key Collision Across Test Runs
What to watch: Hardcoded or predictable idempotency keys cause false passes when a previous test run already consumed the key, or false failures when keys collide across concurrent test executions. Guardrail: Generate unique idempotency keys per test case using UUIDs or a deterministic seed that includes the test run ID. Never reuse keys across independent test invocations.
Response Body Differs on Retry
What to watch: The tool returns a 200 OK on retry but the response body includes a different timestamp, request ID, or status field that downstream code treats as a state change. Guardrail: Define which response fields must be identical across retries and which may vary. Assert exact equality on immutable fields and tolerance ranges on mutable ones like created_at.
Concurrent Retries Race and Break Idempotency
What to watch: Two retries with the same idempotency key arrive simultaneously before the first request completes, and the server processes both because the idempotency store hasn't been populated yet. Guardrail: Include a concurrent retry test case that fires 3 identical requests in parallel within a 100ms window. Assert exactly one resource mutation occurred.
Idempotency Key Expiry Causes False Negatives
What to watch: The test waits too long between retries and the server's idempotency window expires, causing the retry to be treated as a new request. The test fails, but the tool behavior is correct. Guardrail: Document the tool's idempotency window and ensure test retries complete well within it. Add a separate test case that verifies the key is rejected after expiry.
Error Responses Are Not Idempotent
What to watch: The first call returns a 4xx validation error, but the retry with the same key returns a 409 Conflict because the server recorded the failed attempt differently. The agent treats this as a new error class and changes behavior. Guardrail: Test idempotency for error paths explicitly. Assert that the same error code and body are returned when an idempotent request that failed is retried with the same key.
Evaluation Rubric
Run these checks on the generated test plan before executing it. Each criterion verifies that the idempotency test cases are safe, complete, and aligned with the tool's declared contract.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Idempotency Key Reuse | Every test case that invokes the same logical operation reuses the identical [IDEMPOTENCY_KEY] value across multiple calls | Test plan uses different keys for repeated calls or omits key reuse entirely | Static scan of generated test plan for key consistency across repeated invocations |
Side-Effect Isolation | Test plan includes assertions that verify no duplicate side effects occurred (e.g., single resource creation, single charge, single notification) | Assertions only check HTTP status codes without verifying system state or side-effect count | Review assertion logic for state-verification steps; flag plans that lack post-condition checks |
Response Consistency | Expected output schema for repeated calls is identical: same status, same body shape, same resource identifier | Test plan allows divergent responses for calls with the same idempotency key (e.g., 200 then 409) | Schema comparison across expected responses for repeated invocations; flag any structural or status-code drift |
Concurrent Invocation Coverage | Test plan includes at least one scenario with near-simultaneous calls using the same [IDEMPOTENCY_KEY] | All test cases are strictly sequential with no concurrency or race-condition coverage | Count concurrent test scenarios; fail if zero concurrent or overlapping invocation cases exist |
Expiry and Replay Boundary | Test plan defines the idempotency window and includes a test case where the key is reused after expiry, expecting a distinct outcome | Test plan assumes infinite idempotency retention or omits expiry-boundary testing | Check for explicit expiry-window definition and at least one post-expiry replay test case |
Error Case Idempotency | Test plan verifies that a failed first attempt (e.g., 5xx) followed by a retry with the same key does not produce a duplicate side effect on success | Error cases only test retry without verifying idempotency guarantees across the failure boundary | Trace error-recovery test cases; confirm they assert single side effect after successful retry |
Idempotency Key Uniqueness Across Operations | Test plan verifies that different logical operations using distinct [IDEMPOTENCY_KEY] values produce independent outcomes | No test case validates that distinct keys produce distinct, non-colliding results | Identify at least one test case pairing distinct operations with distinct keys and independent outcome assertions |
Production Safety Constraints | Test plan includes pre-execution checks: read-only verification, non-destructive resource labeling, and cleanup steps for any created resources | Test plan contains destructive operations (deletes, irreversible mutations) without guardrails or cleanup | Scan for destructive verbs in tool calls; verify presence of pre-flight checks and cleanup instructions |
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 single tool contract. Use hardcoded idempotency keys like [IDEMPOTENCY_KEY_PREFIX]-001 and a small set of 3-5 test cases. Skip formal eval harnesses—manually inspect whether repeated calls with the same key return consistent results and produce no duplicate side effects.
Strip the prompt down to:
- The tool contract snippet
- The idempotency key field name
- A request to generate N test cases with expected outcomes
Watch for
- The model inventing idempotency key fields that don't exist in the actual contract
- Test cases that only test the happy path and ignore partial-failure retries
- No distinction between client-generated keys and server-assigned idempotency tokens

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