agent_signal
← All templates
OpenAI Agents SDK · v0.24.0 · Python ✓ Tested

Tested on OpenAI Agents SDK (openai-agents 0.24.0, pinned in requirements.txt)

Idempotent approved side effects

The Agents SDK runs an approved tool once per resume, but side effects still repeat on a duplicate resume of the same RunState or a whole-run retry after a crash. Shows both failures (2 charges) and the fix (1 charge).

What it shows

  • A) Duplicate resume: The same saved RunState snapshot is resumed twice (double-click, two workers, queue redelivery). NAIVE: 2 charges. FIXED: 1.
  • B) Retry after a crash: The tool ran, then the next model call failed (simulated 503) and the app retried the whole run from scratch. NAIVE: 2 charges. FIXED: 1.
  • FIXED: charge_fixed takes ToolContext and sends the key f"{order_id}:{tool_name}" (order id from the run context) to a payment API that removes duplicate requests by key.
Mocked vs real. MOCKED: the model (fake_model.ScriptedModel, a real agents.Model subclass; FlakyAfterTool raises once to simulate the outage) and the payment API (FakePaymentAPI, in-process, dedupes the way Stripe idempotency keys do). REAL: Runner, needs_approval interruptions, to_state().to_string() / RunState.from_string(..., context_override=...), approve(), resume, and ToolContext.
Pro template. Below is a preview: the setup, the naive version and the real run output. The fixed, runnable code is in the Signal Pro pack.

Code preview

idempotent_approval_preview.pysrc
"""OpenAI Agents SDK 0.24.0: keep an approved side effect from running twice.
Real failure modes shown (the SDK itself does NOT re-run an approved tool on a single resume):
  A) duplicate resume: the same saved RunState gets resumed twice (double-click, worker retry, queue redelivery)
  B) whole-run retry: the run crashes AFTER the tool ran (here: the model call fails), app retries from scratch
NAIVE tool: charges every time it's invoked.  FIXED tool: idempotency key from stable run data
(order_id from the run context + tool name), deduped by the (fake) payment API.
MOCK: only the model (fake_model.ScriptedModel, a real agents.Model subclass) and the payment API."""
import asyncio
from dataclasses import dataclass
from agents import Agent, Runner, RunConfig, RunState, RunContextWrapper, function_tool
from agents.tool_context import ToolContext
from fake_model import ScriptedModel

class FakePaymentAPI:
    def __init__(self): self.charges = []; self.by_key = {}
    def charge(self, amount, key=None):
        if key and key in self.by_key: return self.by_key[key]
        cid = f"ch_{len(self.charges)+1}"; self.charges.append((cid, amount))
        if key: self.by_key[key] = cid
        return cid

@dataclass
class Ctx:
    order_id: str
    api: FakePaymentAPI

@function_tool(needs_approval=True)
def charge_naive(ctx: RunContextWrapper[Ctx], amount: int) -> str:

# ... PREVIEW ENDS HERE: first 28 of 84 lines (setup + the NAIVE version).
# The FIXED version and the runnable scenarios are in the Signal Pro pack.
requirements.txtsrc
openai-agents==0.24.0
run_output.txtsrc
RunState context of type Ctx is not serializable; storing empty context. Provide context_serializer to preserve it.
RunState context of type Ctx is not serializable; storing empty context. Provide context_serializer to preserve it.
== NAIVE / A) duplicate resume ==
  paused: ['charge_naive'], charges=0
  after 2 resumes of same snapshot: charges=[('ch_1', 1999), ('ch_2', 1999)]
== NAIVE / B) retry after crash ==
  attempt 1: failed after tool ran (model API 503 (simulated)); charges so far=1; retrying from scratch
  attempt 2: ok -> Model saw tool outputs: call_0=ch_2
  final charges=[('ch_1', 1999), ('ch_2', 1999)]
== FIXED / A) duplicate resume ==
  paused: ['charge_fixed'], charges=0
  after 2 resumes of same snapshot: charges=[('ch_1', 1999)]
== FIXED / B) retry after crash ==
  attempt 1: failed after tool ran (model API 503 (simulated)); charges so far=1; retrying from scratch
  attempt 2: ok -> Model saw tool outputs: call_0=ch_1
  final charges=[('ch_1', 1999)]
LICENSEsrc
MIT License

Copyright (c) 2026 Agent Signal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Upgrade gotchas

  • ToolContext.tool_call_id is stable across resumes of one snapshot (covers case A), but on a fresh retry the model generates a new call id (does not cover case B). Use business data (order id, payment intent id) plus the tool name.
  • In 0.24.0 an unserializable dataclass context is dropped from the snapshot with "RunState context of type Ctx is not serializable; storing empty context". Pass context_override= or a context_serializer / context_deserializer when restoring; strict_context=True makes it an error.
  • The key only works if the downstream API honours it. Otherwise keep your own ledger with a unique constraint and check it before the call.
  • Only deserialize RunState from trusted storage, because it contains approvals.

Free starter pack

The approval-flow starter pack

Tested human-in-the-loop approval starters for LangGraph, OpenAI Agents SDK, Vercel AI SDK and Google ADK, plus the weekly Agent Signal newsletter. Free.

FAQ

Does the Agents SDK re-run an approved tool on resume?

Not on a single resume: the tool executes once, after state.approve(). Duplicates come from resuming the same snapshot twice or retrying the whole run.

Why not use tool_call_id as the idempotency key?

It is stable across resumes of one snapshot, but a fresh retry gets a new model-generated call id. Use stable business data plus the tool name.

What is in the free preview vs the Pro pack?

The page shows the setup, the NAIVE tool and the real run output. The FIXED tool, the flaky model and both scenarios are in the Signal Pro pack.

Which version was it tested on?

openai-agents 0.24.0 on Python 3.13, Oct 15, 2026. MIT-licensed.