Skip to main content

Use Dex with Agent SDKs

View as Markdown

The Dex adapter wraps the agent you built with your agent SDK in a durable Dex agent session. The session runs each turn as Steps: model calls run in a RunModel Step, and by default each tool call runs in its own Step. Use it when your agent already uses an agent SDK and must survive crashes, deploys, and approvals that wait for days. Your prompts, tools, and model stay the same.

This recording runs the example with the OpenAI Agents SDK, stops it while cancel_order waits for approval, and starts it again.

Dex Web: the example session's Events tab shows each model call and tool call as a Step, run by worker-1; cancel_order waits for approval after the program stops; the program starts again as worker-2; cancel_order is approved in Dex Web; the same session finishes the turn with its earlier history, and the new Steps show worker-2

How it works

A session is one Flow run, and the session ID is the Flow ID. Dex saves each Step's result when the Step finishes. After a crash or a deploy, the session continues from the saved results, so a Step whose result Dex saved does not run again. A Step that was cut off before Dex saved its result can run again. A retried RunModel Step runs its model calls again, and also the tools that run inside it or at the model provider, such as the Claude Agent SDK's reads and CLI tools. A tool in its own Step retries if it is a read or an idempotent write; any other write gets one attempt. A wait for an approval or the next message holds no Worker and runs nothing again.

A session remembers one conversation: its messages, tool calls, and results. A new session starts empty, so keep long-term memory in a store you own and give the agent tools that read and write it.

Your agent SDK's terms in Dex maps threads, turns, and checkpointers to Dex, and Features by harness lists the tools each agent SDK runs inside RunModel. What runs again and Latency and cost give the details.

Install the adapter

Install your agent SDK's adapter. In Python and Go it brings in Dex Agents, the package that builds the session Flow. In TypeScript the core and the Dex SDK are peer packages, so the command lists them.

pip install dex-agents-claude-agent-sdk

Example: agents/python/claude-agent-sdk

Set the model provider's key, such as ANTHROPIC_API_KEY for the Claude Agent SDK, in the Worker's environment, never in session input (Credentials). Install the packages lists the versions each adapter needs.

Wrap your agent

Build the agent as your agent SDK alone would, with the same model and prompt. Then pass it, with a policy for each tool, to the adapter's session Flow. Each tab shows the plain agent and the durable one; the Claude Agent SDK example also configures the CLI and its tool list.

claude_agent_sdk_quick_start.pyPython
def build_plain_agent(order_desk: OrderDesk, model: str) -> ClaudeAgentOptions:
"""Returns the agent's options as the Claude Agent SDK alone writes them."""
orders = create_sdk_mcp_server("orders", tools=build_order_tools(order_desk))
return ClaudeAgentOptions(
model=model,
system_prompt=ORDER_SUPPORT_INSTRUCTIONS,
mcp_servers={"orders": orders},
allowed_tools=["mcp__orders__look_up_order", "mcp__orders__cancel_order"],
)

def build_durable_agent(order_desk: OrderDesk, model: str) -> AgentSessionFlow:
"""Returns the same agent as a durable Dex agent session."""

# Dex passes the tools to the CLI itself and decides when each one runs.
def build_options(context: ClaudeAgentOptionsContext) -> ClaudeAgentOptions:
return ClaudeAgentOptions(
model=model,
env=build_claude_cli_environment(os.environ),
system_prompt=ORDER_SUPPORT_INSTRUCTIONS,
tools=[],
setting_sources=[],
)

return claude_agent_session_flow(
build_options,
build_order_tools(order_desk),
flow_type="ClaudeAgentSDKQuickStart",
tool_policies={
"look_up_order": ToolPolicy(ToolEffect.READ),
"cancel_order": ToolPolicy(ToolEffect.NON_IDEMPOTENT_WRITE),
},
)

Example: examples/python/agent-harnesses/agent_harness_examples/quick_start/claude_agent_sdk_quick_start.py

The complete files lists each file with every import. Tools that your agent SDK runs itself, such as MCP servers and hosted tools, need the changes in its Limits tab.

Give each tool a policy

Classify each tool by what a repeat of its external effect would do. For an ordinary tool that Dex runs in its own Step, the policy decides whether Dex may run a call again after a failure, and whether the call waits for a person:

Effect classWhat the tool doesAttemptsWaits for approval by default
readOnly reads.Can retryNo
idempotent_writeWrites, and a repeat with the same idempotency key has no further effect.Can retryNo
non_idempotent_writeWrites, and a repeat can repeat the effect.One attemptYes
unclassifiedNothing is known about it. Dex treats it as a non-idempotent write.One attemptYes

A Connector write with bounded resends can send again after an unknown outcome, within its send cap.

Every attempt of one call carries the same idempotency key. A new tool call from the model gets a new key, so it can repeat an external effect, for example after an unknown outcome. Have the service also drop a repeat by a business key, such as the order ID.

Require approval changes the approval default. Tool call outcomes lists how each call ends and how to reconcile one whose outcome is unknown.

Serve it from your app

Your request handler sends the user's message to the session and returns. The reply arrives on the session's event stream or in its snapshot. Your app also runs a Worker, which runs the session's Steps, and Dex Server, which stores them, in Dex Cloud or on your own infrastructure (Where to run Dex Server).

The smallest host registers the session Flow that your durable wrap returns, starts a Worker and a Client in one process, and waits until the Worker is registered. This excerpt of it then starts a session, sends one message, and reads the snapshot until the turn ends:

embed.pyPython
        sessions = AgentSessionClient(client, session_flow)
await sessions.start_session(session_id)
await sessions.send_user_message(session_id, message)
while True:
snapshot = await sessions.get_agent_snapshot(session_id)
state = snapshot.state
if state and state.turn_count >= 1:
if state.status == AgentSessionStatus.WAITING_FOR_USER_MESSAGE:
return snapshot
if state and state.status == AgentSessionStatus.FAILED:
raise RuntimeError(f"the session failed: {state.last_turn_error}")
await asyncio.sleep(0.5)

Example: examples/python/agent-harnesses/agent_harness_examples/quick_start/embed.py

A turn that waits for an approval ends only after your app answers it with resolve_interrupt (Approve from your application). The full host files are under The complete files. Polling suits scripts and tests. A chat UI reads the AgentEvents Stream instead. Serve sessions from a web app has a complete web app with a route for each step, and the Order Support Agent example serves those routes for every agent SDK.

Run the example

In one terminal, run dexcli dev (Install). In a second terminal, download the example for your language and ask the agent about an order. Python needs 3.11 or later with uv, TypeScript needs Node.js 22 (22.19 or later) or 24, and Go needs 1.26 or later.

curl -sL https://codeload.github.com/superdurable/dex/tar.gz/main | tar -xz --strip-components=3 dex-main/examples/python/agent-harnesses
cd agent-harnesses
uv sync --locked
uv run --frozen python -m agent_harness_examples.quick_start openai-agents "Look up order 1001"

Example: examples/python/agent-harnesses/agent_harness_examples/quick_start/__main__.py

The program prints the session ID and the agent's reply:

Session openai-agents-quick-start-3980a512
Agent: Local demo response: Order 1001: 2 notebooks, shipped.

Replace openai-agents with your agent SDK's run argument:

Agent SDKLanguageRun argumentAPI key
Claude Agent SDKPython, TypeScriptclaude-agent-sdkANTHROPIC_API_KEY
EinoGoeinoNone; a local demo model
Google ADKPythongoogle-adkNone; a local demo model
LangGraphPythonlangchainNone; a local demo model
MastraTypeScriptmastraOPENAI_API_KEY
OpenAI Agents SDKPythonopenai-agentsNone; a local demo model
OpenAI Agents SDKTypeScriptopenai-agentsOPENAI_API_KEY
PiTypeScriptpiOPENAI_API_KEY, or another provider's key with DEX_PI_MODEL
Pydantic AIPythonpydantic-aiNone; a local demo model
Vercel AI SDKTypeScriptvercel-aiOPENAI_API_KEY

Ask it to cancel order 1002, and it waits for your approval at the prompt. Stop the program while it waits, then run the same command with --session-id SESSION_ID in place of the message. The session carries on from where it stopped, and the model calls from before the restart stay done.

To kill the program while a tool runs and see the tool call retried in the session history, follow the steps for your language: Python, TypeScript, or Go.

To start in an empty folder with published packages only, use the Python one-file starter: the OpenAI Agents SDK agent with its Worker and Client. It calls a real model, so set OPENAI_API_KEY first:

mkdir order-agent && cd order-agent
python3 -m venv .venv && source .venv/bin/activate
pip install dex-agents-openai-agents==0.5.0 dex-python-sdk==1.45.0
curl -fsSLO https://raw.githubusercontent.com/superdurable/dex/main/examples/python/agent-starter/agent.py
python agent.py "Cancel order 1002, it was a mistake"

Next