Your Agent Retried and Booked Twice: Idempotency for Tool Calls

2026-12-02来源 dev.toEnglish

Here's a failure that doesn't show up in demos. An agent calls a booking tool. The booking goes through, but the response times out on the way back. The agent sees an error, decides the call failed, and tries again. Now the customer has two bookings, or two charges, or two emails.

Nothing was wrong with the model. It did exactly what a reasonable retry policy says to do. The problem is that the tool can't tell a retry from a new request.

The fix is old and boring: idempotency keys. Every action gets a key that identifies the intent, not the attempt. If the same key shows up twice, the tool returns the first result instead of doing the work again.

import hashlib import json def idempotency_key(run_id: str, step: str, args: dict) -> str: payload = json.dumps({"run": run_id, "step": step, "args": args}, sort_keys=True) return hashlib.sha256(payload.encode()).hexdigest() def book_slot(store, booking_api, run_id: str, customer_id: str, slot: str) -> dict: key = idempotency_key(run_id, "book_slot", {"customer": customer_id, "slot": slot}) existing = store.get(key) if existing is not None: return existing # a retry: hand back the original result result = booking_api.create(customer_id=customer_id, slot=slot, idempotency_key=key) store.set(key, result) return result 

A few details that matter.

Build the key from the intent: run ID, step name and the arguments that matter. Leave out timestamps and random request IDs, or every retry looks brand new.

Pass it downstream when you can. Many payment and booking APIs accept an idempotency key, Stripe being the well-known example. If the provider supports it, use theirs, because it also covers the case where your process dies after the call but before you saved the result.

Treat "unknown" differently from "failed". A timeout doesn't mean the action didn't happen. Check the provider for the key or the resource first, and only retry once you know it really didn't go through.

Let the agent see what happened. Return a short note like "already booked, returning the existing booking" so the model doesn't keep trying to fix something that isn't broken.

This matters more with agents than with normal code, because agents retry creatively. They don't just repeat the call. They rephrase it, nudge an argument, or reach for a different tool. Keying on intent instead of the exact payload catches more of those.

We build AI agents for businesses at Binate AI, and any tool that touches money, bookings or customer messages gets an idempotency key before it goes near production.

原文:https://www.a8q9.cn/en/article/your-agent-retried-and-booked-twice-idempotency-for-tool-calls-cf21a9.html

相关文章