Idempotent AI Agent Tool Calls: Retry Without Duplicate Tickets
A help-desk agent asks your app to create a ticket. The database commits ticket 42, but the worker loses the response. It tries again. Both tool calls looked reasonable; now the queue has two tickets for the same problem.
Make the retry carry the same operation ID as the original request. Your application can then return the first ticket ID instead of creating a second one. This guide builds that check with Python and SQLite and tests the case that a happy-path demo misses: the write succeeded even though the caller saw a timeout.
Give the approved action its own ID
In a tool-calling workflow, the model proposes the call and your application runs it. The OpenAI function-calling guide uses a call ID to send each result back to the right call. Keep that protocol ID for its job. If your app re-plans or starts a new conversation after a crash, the model can issue a new call ID for the same user-approved action.
A useful boundary is the approval record: when a person approves one ticket, the application creates an operation ID and stores it with the workspace, action name and validated payload. Read those values from trusted application state on every attempt. The model can propose a title, but it should never choose the workspace or mint a fresh ID to dodge a conflict. Check permission before doing the write or replaying a result.
- Same operation and same inputs: return the original ticket ID.
- Same operation with changed inputs: stop and report a conflict. If the person meant to make a different change, get a new approval.
- Two approvals for the same title: they can create two tickets. A title is not an identity.
This follows the distinction in the Amazon Builders’ Library discussion of safe retries: two requests that look alike can still represent different intentions. A request ID lets the caller tell the service which one it means.
Build a local ticket tool with SQLite
Save this file as ticket_tool.py. The example uses only the standard library and was checked with Python 3.13.6 and SQLite 3.50.4. It writes to a temporary database when you run the demo, with no API key or network access.
"""Local-only example: one ticket per approved operation."""
import sqlite3
from contextlib import closing
SCHEMA = """
CREATE TABLE IF NOT EXISTS tickets (
id INTEGER PRIMARY KEY,
workspace TEXT NOT NULL,
title TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS receipts (
workspace TEXT NOT NULL,
approval_id TEXT NOT NULL,
title TEXT NOT NULL,
ticket_id INTEGER NOT NULL,
PRIMARY KEY (workspace, approval_id)
);
"""
class KeyConflict(ValueError):
"""The same approved operation arrived with a different title."""
def init_db(path):
with closing(sqlite3.connect(path)) as db:
db.executescript(SCHEMA)
def create_ticket(path, workspace, approval_id, title):
# Workspace and approval ID come from the application, not the model.
with closing(sqlite3.connect(path, timeout=5,
isolation_level=None)) as db:
db.execute("BEGIN IMMEDIATE")
try:
prior = db.execute(
"SELECT title, ticket_id FROM receipts "
"WHERE workspace = ? AND approval_id = ?",
(workspace, approval_id),
).fetchone()
if prior is not None:
if prior[0] != title:
raise KeyConflict("Approval already used for another title")
ticket_id = prior[1]
else:
ticket_id = db.execute(
"INSERT INTO tickets(workspace, title) VALUES (?, ?)",
(workspace, title),
).lastrowid
db.execute(
"INSERT INTO receipts VALUES (?, ?, ?, ?)",
(workspace, approval_id, title, ticket_id),
)
db.commit()
return ticket_id
except Exception:
db.rollback()
raiseThe ticket and its receipt commit together. If saving the receipt fails, the ticket rolls back too. If the process loses the reply after committing, a later call finds the receipt and returns the same ID. The receipt stores the title so a reused key with changed inputs cannot silently return an unrelated result.
BEGIN IMMEDIATE starts a write transaction before checking for the receipt. That means two writers cannot both read an empty result and proceed to insert a ticket. SQLite allows one writer at a time; the second writer waits up to the connection’s timeout and can still get a busy error. It should retry later with the same operation ID. See the SQLite transaction reference and Python sqlite3 documentation for the behavior of write locks and connection timeouts.
Test the timeout after the write
Put this in demo.py alongside the first file and run python demo.py. The timeout happens after the tool returns, which makes the timing explicit. The second call opens a new connection and reads the durable receipt.
import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory
from ticket_tool import create_ticket, init_db
def first_delivery(db):
create_ticket(db, "team-a", "op-42", "Fix login copy")
raise TimeoutError("Reply lost after commit")
with TemporaryDirectory() as work:
db = Path(work) / "demo.sqlite"
init_db(db)
try:
first_delivery(db)
except TimeoutError:
ticket = create_ticket(db, "team-a", "op-42", "Fix login copy")
with closing(sqlite3.connect(db)) as con:
count = con.execute("SELECT COUNT(*) FROM tickets").fetchone()[0]
print(f"ticket={ticket} count={count}")
assert (ticket, count) == (1, 1)On a fresh temporary database, the output is ticket=1 count=1. Inspect the count as well as the reply. A tool can return ticket 1 twice and still be broken if the retry also creates a second row.
For a regression suite, force a failure between the two inserts and verify that neither survives. Then call the tool from two workers, with separate database connections, and verify that both receive the same ticket ID. Finally, change the title but reuse the ID. That call should fail without growing the ticket count.
Use a different plan for writes outside your database
SQLite can roll back these two local inserts. It can’t take back a request to a separate help-desk API. If the API supports an idempotency key, pass the same stable provider key when you retry and check how long the provider remembers it. For example, Stripe documents its own replay and key-retention rules. Don’t assume another vendor uses the same rules.
If the remote service can’t deduplicate requests, store a pending or unknown outcome and look for the original action by a stable reference before trying again. For important writes, send unresolved cases to a human rather than inventing a success response or retrying indefinitely. An outbox can preserve jobs across crashes, but an outbox alone does not stop a remote service from applying a write twice.
The local example intentionally leaves out user authentication and approval storage. In a real dispatcher, bind the operation to the authenticated workspace, tool name and exact approved parameters. Keep receipts long enough to cover delayed delivery and recovery jobs. If you delete a receipt while a retry is still possible, that retry can look new again.
If you’re still designing the tool boundary, start with the Academy lesson on structured outputs and tool authorization. For the first test in your own app, drop one successful reply on purpose and check the database or the destination system. The final response is only half the evidence.





