---
title: "Use Dex with Agent SDKs"
description: "The Dex adapter wraps the agent you built with your agent SDK in a durable Dex agent session, which runs each turn as Steps and keeps each committed Step result."
canonical_url: "https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks/"
source: "docs/content/agent-frameworks/agent-sdks.mdx"
locale: "en"
framework: "claude-agent-sdk"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Use Dex with Agent SDKs

This file shows the Claude Agent SDK version. Other frameworks: [Eino](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.eino.md) · [Google ADK](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.google-adk.md) · [LangGraph](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.langchain-langgraph.md) · [Mastra](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.mastra.md) · [OpenAI Agents SDK](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.openai-agents-sdk.md) · [Pi](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.pi.md) · [Pydantic AI](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.pydantic-ai.md) · [Vercel AI SDK](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.vercel-ai-sdk.md)

Code on this page is in Python. Other languages: [TypeScript](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.typescript.md)

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.

> **Diagram**: One agent turn as Steps, with a payment service that stores each refund's idempotency key and returns the existing result on a repeat. A user message arrives, and Dex saves it. The Worker runs the RunModel Step: the model asks for a refund tool, and Dex saves that result. The Worker runs a CallTool Step with the idempotency key session-42/turn-3/call-7, and the payment service applies the refund. The Worker stops before Dex saves the tool result. Another Worker retries the same call in the same CallTool Step with the same key, and the payment service finds the key and applies nothing new; Dex reuses the saved RunModel result. Dex saves the tool result. The model writes the reply, and Dex saves it. The coordinating ResumeTurn Step is left out.

This recording runs the [example](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.md#run-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](https://docs.superdurable.io/img/agent-frameworks/agent-sdks-dex-web.gif)

<a id="how-it-works"></a>

## How it works

<a id="a-durable-agent-session"></a>

<a id="what-a-session-remembers"></a>

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](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#term-map) maps threads, turns, and checkpointers to Dex, and [Features by harness](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#features-by-harness) lists the tools each agent SDK runs inside `RunModel`. [What runs again](https://docs.superdurable.io/reference/agents/failures.md#what-runs-again) and [Latency and cost](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#latency-and-cost) give the details.

<a id="install-the-adapter"></a>

## Install the adapter

<a id="use-it-in-your-own-agent"></a>

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.

**Python**

```bash
pip install dex-agents-claude-agent-sdk
```

Example: [agents/python/claude-agent-sdk](https://github.com/superdurable/dex/tree/main/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](https://docs.superdurable.io/reference/agents/credentials.md)). [Install the packages](https://docs.superdurable.io/reference/agents/install.md) lists the versions each adapter needs.

<a id="wrap-your-agent"></a>

## Wrap your agent

<a id="what-changes-in-your-code"></a>

<a id="make-it-durable"></a>

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.

**Python**

```python
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](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses/agent_harness_examples/quick_start/claude_agent_sdk_quick_start.py)

[The complete files](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#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](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#limits) tab.

<a id="give-each-tool-a-policy"></a>

## Give each tool a policy

<a id="tool-policy"></a>

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 class           | What the tool does                                                        | Attempts    | Waits for approval by default |
| ---------------------- | ------------------------------------------------------------------------- | ----------- | ----------------------------- |
| **read**               | Only reads.                                                               | Can retry   | No                            |
| `idempotent_write`     | Writes, and a repeat with the same idempotency key has no further effect. | Can retry   | No                            |
| `non_idempotent_write` | Writes, and a repeat can repeat the effect.                               | One attempt | Yes                           |
| **unclassified**       | Nothing is known about it. Dex treats it as a non-idempotent write.       | One attempt | Yes                           |

A Connector write with [bounded resends](https://docs.superdurable.io/reference/agents/connector-tools.md#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](https://docs.superdurable.io/reference/agents/approvals.md#require-approval) changes the approval default. [Tool call outcomes](https://docs.superdurable.io/reference/agents/failures.md#tool-call-outcomes) lists how each call ends and how to reconcile one whose outcome is unknown.

<a id="serve-it-from-your-app"></a>

## Serve it from your app

<a id="wire-it-into-your-app"></a>

<a id="what-changes-in-your-app"></a>

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](https://docs.superdurable.io/production-operations.md#where-to-run)).

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:

**Python**

```python
        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](https://github.com/superdurable/dex/tree/main/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](https://docs.superdurable.io/reference/agents/approvals.md#approve-from-your-application)). The full host files are under [The complete files](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#complete-files). Polling suits scripts and tests. A chat UI reads the [AgentEvents Stream](https://docs.superdurable.io/reference/agents/event-stream.md#read-the-stream) instead. [Serve sessions from a web app](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md#web-handler) has a complete web app with a route for each step, and the [Order Support Agent](https://docs.superdurable.io/examples/order-support-agent.md) example serves those routes for every agent SDK.

<a id="run-the-example"></a>

## Run the example

<a id="get-the-example"></a>

<a id="before-you-start"></a>

<a id="what-you-will-build"></a>

<a id="run-it"></a>

In one terminal, run `dexcli dev` ([Install](https://docs.superdurable.io/install.md)). 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.

**Python**

```bash
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](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses/agent_harness_examples/quick_start/__main__.py)

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

```text
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 SDK         | Language           | Run argument       | API key                                                         |
| ----------------- | ------------------ | ------------------ | --------------------------------------------------------------- |
| Claude Agent SDK  | Python, TypeScript | `claude-agent-sdk` | `ANTHROPIC_API_KEY`                                             |
| Eino              | Go                 | `eino`             | None; a local demo model                                        |
| Google ADK        | Python             | `google-adk`       | None; a local demo model                                        |
| LangGraph         | Python             | `langchain`        | None; a local demo model                                        |
| Mastra            | TypeScript         | `mastra`           | `OPENAI_API_KEY`                                                |
| OpenAI Agents SDK | Python             | `openai-agents`    | None; a local demo model                                        |
| OpenAI Agents SDK | TypeScript         | `openai-agents`    | `OPENAI_API_KEY`                                                |
| Pi                | TypeScript         | `pi`               | `OPENAI_API_KEY`, or another provider's key with `DEX_PI_MODEL` |
| Pydantic AI       | Python             | `pydantic-ai`      | None; a local demo model                                        |
| Vercel AI SDK     | TypeScript         | `vercel-ai`        | `OPENAI_API_KEY`                                                |

<a id="approve-a-write"></a>

<a id="stop-the-worker"></a>

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.

<a id="stop-while-a-tool-runs"></a>

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](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses#stop-it-while-a-tool-runs), [TypeScript](https://github.com/superdurable/dex/tree/main/examples/typescript/src/products/agent-harnesses#stop-it-while-a-tool-runs), or [Go](https://github.com/superdurable/dex/tree/main/examples/go/agent-harnesses#stop-it-while-a-tool-runs).

<a id="start-in-an-empty-folder"></a>

To start in an empty folder with published packages only, use the Python [one-file starter](https://github.com/superdurable/dex/tree/main/examples/python/agent-starter): the OpenAI Agents SDK agent with its Worker and Client. It calls a real model, so set `OPENAI_API_KEY` first:

```bash
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

- [Dex Agents CLI](https://docs.superdurable.io/build-ai-agents/dex-agents-cli.md): chat with a durable agent in your terminal, without writing code.
- [Connectors as Tools](https://docs.superdurable.io/build-ai-agents/connectors-as-tools.md): give your agent official Connector operations as tools.
- [Agent SDK adapters](https://docs.superdurable.io/reference/agents/agent-sdk-adapters.md): what your agent SDK supports, and its limits.
- [Production checklist](https://docs.superdurable.io/production-operations/production-checklist.md#agents): what to set up before launch.
