---
title: "Order Support Agent"
description: "An order support agent that looks up orders and cancels them, built once for each agent framework. Every cancellation waits for a person to approve it."
canonical_url: "https://docs.superdurable.io/examples/order-support-agent/"
source: "docs/content/use-cases/order-support-agent.mdx"
locale: "en"
framework: "claude-agent-sdk"
language: "python"
---

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

# Order Support Agent

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

Code on this page is in Python. Other languages: [TypeScript](https://docs.superdurable.io/examples/order-support-agent.typescript.md)

An order support agent that looks up orders and cancels them, built once for each agent framework. Every cancellation waits for a person to approve it.

**SDKs:** Python · TypeScript · Go

**Shows:** [Tool calls](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.md#give-each-tool-a-policy), [Approvals](https://docs.superdurable.io/reference/agents/approvals.md), [Sessions](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.md#how-it-works), and [Connectors as Tools](https://docs.superdurable.io/build-ai-agents/connectors-as-tools.md).

## Product requirements

<a id="what-it-does"></a>

The agent has two tools on an in-memory order desk. Order 1001 has shipped, and order 1002 is still processing.

| Tool            | Policy               | What Dex does                                                                      |
| --------------- | -------------------- | ---------------------------------------------------------------------------------- |
| `look_up_order` | read                 | Runs without approval and retries on failure.                                      |
| `cancel_order`  | non-idempotent write | Waits in `AwaitToolApproval`. An approved call runs in a single-attempt tool Step. |

`cancel_order` cancels an order only while it is still processing. A new tool call for the same order can still repeat the write; see [New calls can repeat an effect](https://docs.superdurable.io/reference/agents/failures.md#tool-runs-twice). This demo's in-memory cancel takes no key. A real cancellation passes a stable key that the order service deduplicates. With a Slack connection named `support-slack`, each agent also gets a Slack thread reply tool, which waits for approval too.

## Core implementation

<a id="define-the-agent"></a>

Each framework defines the same two tools in its own way. Dex runs the agent as a session Flow, and the tool policies give each tool its effect. Pick a framework, and every framework tab on the page follows.

**Python**

```python
def build_claude_agent_sdk_order_support_flow(
    order_desk: OrderDesk, model: str, slack_connection: slack.Connection | None
) -> AgentSessionFlow:
    """Builds the session Flow; ``model`` is a Claude model name, such as "claude-opus-5-5"."""

    # The tools are closures, so they call the OrderDesk passed in here.
    @tool(
        "look_up_order",
        "Look up one order by its order ID and return its items and status.",
        {"order_id": str},
    )
    async def look_up_order(arguments: dict[str, Any]) -> dict[str, Any]:
        order = order_desk.describe_order(arguments["order_id"])
        return {"content": [{"type": "text", "text": order}]}

    @tool(
        "cancel_order",
        "Cancel one order that has not shipped yet.",
        {"order_id": str, "reason": str},
    )
    async def cancel_order(arguments: dict[str, Any]) -> dict[str, Any]:
        result = order_desk.cancel_order(arguments["order_id"], arguments["reason"])
        return {"content": [{"type": "text", "text": result}]}

    # Every session gets the same options, so the factory does not read its context.
    def build_options(context: ClaudeAgentOptionsContext) -> ClaudeAgentOptions:
        return ClaudeAgentOptions(
            model=model,
            env=build_claude_cli_environment(os.environ),
            system_prompt=ORDER_SUPPORT_INSTRUCTIONS,
            # No Claude Code built-in tools: the agent uses only the order tools.
            tools=[],
            # Settings files could approve a tool before Dex asks for approval.
            setting_sources=[],
        )

    return claude_agent_session_flow(
        build_options,
        [look_up_order, cancel_order],
        flow_type=CLAUDE_AGENT_SDK_ORDER_SUPPORT_FLOW_TYPE,
        tool_sources=build_slack_tool_sources(slack_connection),
        tool_policies={
            "look_up_order": ToolPolicy(ToolEffect.READ),
            "cancel_order": ToolPolicy(ToolEffect.NON_IDEMPOTENT_WRITE),
        },
    )
```

Example: [examples/python/agent-harnesses/agent_harness_examples/claude_agent_sdk_order_support.py](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses/agent_harness_examples/claude_agent_sdk_order_support.py)

<a id="session-routes"></a>

## Session routes

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

One app per language runs a Worker for every framework's session Flow and serves the same HTTP routes for each. Each route uses the Dex Agents operation listed below, the same one your app uses:

| What the route does           | Python                                                                        | TypeScript                                           | Go                                    |
| ----------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------- | ------------------------------------- |
| Start a session               | `AgentSessionClient.start_session`                                            | `startAgentSession`                                  | `AgentSessionClient.StartSession`     |
| Send a user message           | `AgentSessionClient.send_user_message`                                        | the `sendUserMessage` RPC, or `sendAgentUserMessage` | `AgentSessionClient.SendUserMessage`  |
| Read the session              | `read_agent_event_stream_snapshot` or `AgentSessionClient.get_agent_snapshot` | the `getAgentSnapshot` RPC, or `readAgentSnapshot`   | `AgentSessionClient.GetAgentSnapshot` |
| Approve or reject a tool call | `AgentSessionClient.resolve_interrupt`                                        | the `resolveInterrupt` RPC                           | `AgentSessionClient.ResolveInterrupt` |

The URL paths, JSON shapes, and error codes belong to the example and differ a little between languages. Starting a session returns a session token, an HMAC of the session ID under `DEX_AGENT_SESSION_KEY`. Every other route checks it in the **X-Agent-Session-Token** header and answers 403 without it. Without `DEX_AGENT_SESSION_KEY`, the app picks a random key, so a restart ends every token. A real application uses its own sign-in instead.

**Python**

```python
    @blueprint.post("/sessions")
    async def start_session() -> Response:
        # The server picks the session ID, so a caller cannot claim an existing session.
        session_id = f"{harness_name}-order-support-{uuid.uuid4()}"
        await sessions.start_session(session_id)
        session_token = sign_session_id(app_state.config.session_key, session_id)
        return jsonify(session_id=session_id, session_token=session_token)

    @blueprint.post("/messages")
    async def send_user_message() -> Response:
        body, session_id = await session_request()
        accepted = await sessions.send_user_message(session_id, _required_string(body, "text"))
        return jsonify(accepted=accepted)

    @blueprint.post("/interrupts/resolve")
    async def resolve_interrupt() -> Response:
        body, session_id = await session_request()
        interrupt_id = _required_string(body, "interrupt_id")
        if not isinstance(approved := body.get("approved"), bool):
            raise BadRequest("approved must be a boolean")
        rejection_message = body.get("rejection_message")
        if rejection_message is not None and not isinstance(rejection_message, str):
            raise BadRequest("rejection_message must be a string")
        accepted = await sessions.resolve_interrupt(
            session_id, interrupt_id, approved=approved, rejection_message=rejection_message
        )
        return jsonify(accepted=accepted)

    @blueprint.get("/snapshot")
    async def get_agent_snapshot() -> Response:
        session_id = request.args.get("session_id", "")
        if not session_id:
            raise BadRequest("session_id is required")
        authorize_session(session_id)
        try:
            snapshot = await read_agent_event_stream_snapshot(
                app_state.client, example.session_flow, session_id
            )
        except FlowNotActiveOrNotFoundError as error:
            raise NotFound("the agent session is missing or no longer retained") from error
        return jsonify(snapshot.to_json())
```

Example: [examples/python/agent-harnesses/agent_harness_examples/http_routes.py](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses/agent_harness_examples/http_routes.py)

[Serve it from your app](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.md#serve-it-from-your-app) lists the Registry, Worker, and Client pieces behind these routes.

## Run it

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

Each tab runs the agent from a clone of the repository, outside the playground that [Run an example from the playground](https://docs.superdurable.io/install.md#run-an-example-from-the-playground) starts. Each tab has three steps. Start Dex with the session graph, so Dex Web shows the session and its approval controls. Start the example in a second terminal. Then start a session, ask the agent to cancel order 1002, and approve the call. These commands use `jq`.

First terminal:

**Python**

```bash
cd examples/python/agent-harnesses
uv sync --locked
mkdir -p definitions
uv run --frozen dex-agents-session-graph --flow-type ClaudeAgentSDKOrderSupport \
  --permission order-support.operate --out definitions/claude-agent-sdk.json
dexcli dev --flow-rendering-dir ./definitions
```

Example: [examples/python/agent-harnesses](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses)

Second terminal:

**Python**

```bash
cd examples/python/agent-harnesses
ANTHROPIC_API_KEY=... uv run --frozen python -m agent_harness_examples
```

Example: [examples/python/agent-harnesses](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses)

Third terminal:

**Python**

```bash
base=http://127.0.0.1:8081/products/agent-harnesses/claude-agent-sdk
session=$(curl -s -X POST "$base/sessions" -H 'Content-Type: application/json' -d '{}')
id=$(echo "$session" | jq -r .session_id)
token=$(echo "$session" | jq -r .session_token)
curl -s -X POST "$base/messages" -H 'Content-Type: application/json' \
  -H "X-Agent-Session-Token: $token" -d "{\"session_id\": \"$id\", \"text\": \"Cancel order 1002\"}"
until interrupt=$(curl -s "$base/snapshot?session_id=$id" -H "X-Agent-Session-Token: $token" \
  | jq -re '.snapshot.pending_interrupts[0].interrupt_id'); do sleep 1; done
curl -s -X POST "$base/interrupts/resolve" -H 'Content-Type: application/json' \
  -H "X-Agent-Session-Token: $token" \
  -d "{\"session_id\": \"$id\", \"interrupt_id\": \"$interrupt\", \"approved\": true}"
```

Example: [examples/python/agent-harnesses](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses)

The loop reads the snapshot until the agent asks to run `cancel_order`. The call waits for your approval. The approve request only records your decision. Poll the snapshot until the turn has finished, then read the agent's answer. With a session graph, you can also approve the call in Dex Web, at the address `dexcli dev` prints, such as `http://127.0.0.1:8802`.

Each framework reads its model from one variable:

| Framework         | Model variable               | Default                                                           | Provider key                                                      |
| ----------------- | ---------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------- |
| Claude Agent SDK  | `DEX_CLAUDE_AGENT_SDK_MODEL` | `claude-opus-5-5`                                                 | `ANTHROPIC_API_KEY`, required                                     |
| Eino              | `DEX_EINO_MODEL`             | `mock/order-support`                                              | `OPENAI_API_KEY`, for an OpenAI model such as `gpt-5-mini`        |
| Google ADK        | `DEX_GOOGLE_ADK_MODEL`       | `mock/order-support`                                              | `GOOGLE_API_KEY`, for a Gemini model such as `gemini-2.5-flash`   |
| LangGraph         | `DEX_LANGCHAIN_MODEL`        | `mock/order-support`                                              | The provider's key, such as `OPENAI_API_KEY` for `openai:gpt-5.2` |
| Mastra            | `DEX_MASTRA_MODEL`           | `openai/gpt-5-mini`, a Mastra model router ID                     | The router's provider key, such as `OPENAI_API_KEY`               |
| OpenAI Agents SDK | `DEX_OPENAI_AGENTS_MODEL`    | Python: `mock/order-support`. TypeScript: `gpt-5-mini`.           | `OPENAI_API_KEY`, for TypeScript or an OpenAI model               |
| Pi                | `DEX_PI_MODEL`               | `openai/gpt-5-mini`, a `<provider>/<model ID>` of pi-ai's catalog | The provider's key, such as `OPENAI_API_KEY`                      |
| Pydantic AI       | `DEX_PYDANTIC_AI_MODEL`      | `mock/order-support`                                              | The provider's key, such as `OPENAI_API_KEY` for `openai:gpt-5.2` |
| Vercel AI SDK     | `DEX_VERCEL_AI_MODEL`        | `gpt-5-mini`                                                      | `OPENAI_API_KEY`, required                                        |

`mock/order-support` is a local demo model that needs no key. It calls `look_up_order` for "look up order 1001" and `cancel_order` for "cancel order 1002". The Eino example needs Go 1.26 or later, and Pi needs Node.js 22.19 or later.

The source is in [examples/python/agent-harnesses](https://github.com/superdurable/dex/tree/main/examples/python/agent-harnesses), [examples/typescript/src/products/agent-harnesses](https://github.com/superdurable/dex/tree/main/examples/typescript/src/products/agent-harnesses), and [examples/go/agent-harnesses](https://github.com/superdurable/dex/tree/main/examples/go/agent-harnesses).

## Next

- [Order Processing](https://docs.superdurable.io/examples/order-processing.md)
- [Use Dex with Agent SDKs](https://docs.superdurable.io/build-ai-agents/use-dex-with-agent-sdks.md)
- [Approvals](https://docs.superdurable.io/reference/agents/approvals.md)
- [Connectors as Tools](https://docs.superdurable.io/build-ai-agents/connectors-as-tools.md)
