Skip to content

< CollectionsWriting effective tools for agents · 6 of 8 ·105 · Level 04, Tool Calling

Make the Tool Safe to Call Twice

medium · debug · Tool Calling

A support agent's charge tool took a customer's money twice: the payment went through, the reply timed out, and the tool tried again with a new request. Fix charge_order(gateway, ledger, order_id, cents, attempts=3) so that a repeat can never charge twice.

gateway.charge(cents, key) (provided) takes the money and returns {"charge_id": ..., "cents": ...}. A key that has already charged takes nothing and returns the original charge. It raises Timeout when the reply is lost, and the money may or may not have moved. It raises Declined when the bank says no, and no money moved. ledger is a dict you keep between calls.

  1. One key per order. Build it from the order alone, so every attempt and every later call sends the same one.
  2. Retry a Timeout, up to attempts requests in all. Never retry Declined.
  3. On success, record the order in ledger, with the amount and charge id, and return {"status": "charged", "charge_id": ..., "repeat": False}.
  4. Already in ledger, same amount: return {"status": "charged", "charge_id": ..., "repeat": True} without contacting the gateway.
  5. Already in ledger, different amount: return {"status": "conflict", "charged_cents": ...} without contacting the gateway. If the gateway hands back a charge for another amount, an earlier lost request went through: record it, and return the same conflict.
  6. Declined: return {"status": "declined"} and record nothing, so a later call can try again.
  7. Every attempt timed out: return {"status": "unknown"} and record nothing.

The catch is rule 7. The tool does not know whether the money moved, and it must not say "failed": a model told that will try again some other way, or tell the customer nothing happened. A later call is safe because of rule 1. It carries the same key, so the gateway settles it.

Two orders for the same amount are two charges, which is why the key comes from the order and not the amount.