Idempotency keys for AI agent tool calls
Give an agent's API calls an idempotency key that stays the same across crashes and retries, so Stripe-style APIs drop the duplicate.
Why the key must survive a crash
An idempotency key only helps if the retry sends the same key. A key generated fresh on each attempt (or by the model) changes after a crash, and the API sees a new request. The key should come from the run and the action: the same order and the same arguments give the same key.
Keys expire
APIs keep keys for a limited time. Stripe documents that keys are kept for at least 24 hours. A retry after the key is forgotten is a new request again. So "retry with the same key" is only safe within the key's lifetime; after that, the outcome is unknown: get an authoritative answer from the provider, or ask a person.
A stable key from a run record
import call4agents as c4a
c4a.init()
@c4a.effect(idempotent_for=24 * 3600) # the API remembers keys for 24 h
def charge(amount: int, to: str) -> dict:
return requests.post(STRIPE_URL, data={"amount": amount, "customer": to},
headers=c4a.idempotency_headers()).json()
with c4a.run("order-42"):
charge(10, "cus_123")
If the process died during the call, the next call resends it with the same key while the first attempt is
younger than idempotent_for, and the API returns the original charge. After that it raises
EffectInDoubt instead of risking a second charge. For PayPal, pass
c4a.idempotency_headers("PayPal-Request-Id").
pip install call4agents
call4agents quickstart # offline, no API keys: 2 emails without the kit, 1 with it