Urgent.News

What's breaking now, across hundreds of outlets.

AI

Stop Your AI Agent From Doing Things Twice: Idempotency Keys for Tool Calls

AI agents retry. The model calls a tool, the request times out, the framework retries, or the model decides to call the same tool again a few steps later because it isn't sure the first call worked. For read-only tools that's harmless. For tools that send an email, create an invoice or charge a card, it means doing the thing twice. The fix is old and boring: idempotency keys. Here's how to apply…

AI agents can inadvertently execute the same tool call multiple times due to retries or model uncertainty. This is problematic for tools that perform actions like sending emails, invoices, or charging cards, as it may result in duplicate outcomes. The solution is to implement idempotency keys - unique identifiers that represent the intent of a tool call, rather than its execution attempt.

By incorporating key fields that define the action, such as customer ID and invoice period, retries with identical intent can safely return the previously stored result instead of performing the action again. The key should be generated in your code from the tool arguments, ensuring the same key is produced for repeated calls with the same intent.

The implementation involves creating a database to store the key, its status (pending or done), and the result if the action was successfully completed. A helper function `run_once` is used to attempt to claim the key, storing the result if it's the first execution. If the key already exists, the function returns the stored result, marking it as "already_done" to signal to the model that the action has occurred.

This approach ensures retries are harmless and avoids issues like sending duplicate invoices. It's recommended to use any provider-specific idempotency keys they offer, and communicate the "already_done" flag to the model to indicate that the action has already been processed. By implementing this simple key-based mechanism, AI agents can reliably handle tool calls without causing unintended side effects.

Rewritten by urgent.news; may contain errors — check the original.

Source: dev.to

Read the original at dev.to →

More from Dev.to on urgent.news

Get the news by email. Yesterday's most-covered stories, every morning.

See today's edition · More options

More in AI

More from Friday, 4 December 2026 →