Agent SDK adapters
查看 MarkdownDex runs agents built with nine agent SDKs, plus the Dex Agent Framework. Every one of them runs on the same session Flow through its own adapter. This page lists the session features of each adapter, how it runs a turn as Steps, its limits, and what a turn costs. Use Dex with Agent SDKs explains the session Flow that they share. The rules for sessions on the Dex Agent Framework, such as plans, durable waits, and MCP servers, are in the Dex Agent Framework reference.
Sections that moved to other pages
Features by harness
Every harness gets a durable session, tool policies, approvals, Connectors as tools, queued messages, and live events on the AgentEvents Stream. Every one that runs in Python or TypeScript also gets Steer, cancel_turn, and delete_queued_message. Eino runs on the Go core, which has none of them.
| Framework | Languages | Each tool call in its own Step | Context compaction by Dex | Questions and plans |
|---|---|---|---|---|
| Claude Agent SDK | Python, TypeScript | Writes, reads that need approval, and Connector calls. Other reads run inside the model call's Step. | No. Claude Code compacts its own transcript. | No |
| Eino | Go | Yes. The tools of an agent tool's sub-agent run inside that tool's Step. | No. The Go core has no compaction. | No |
| Google ADK | Python | Yes | Yes | No |
| LangGraph | Python | Yes. Provider-run tools run at the provider. | Yes | No |
| Mastra | TypeScript | Yes, except tools that Mastra runs itself | Yes | No |
| OpenAI Agents SDK | Python, TypeScript | Function tools. Hosted tools run at the provider. | Yes | No |
| Pi | TypeScript | Yes | Yes | Yes |
| Pydantic AI | Python | Yes. Provider-run tools run at the provider. | Yes | No |
| Vercel AI SDK | TypeScript | Yes. Provider-executed tools run at the provider. | Yes | No |
| Dex Agent Framework | Python, TypeScript | Yes | Yes | Yes |
A tool call in its own Step runs again after a crash only by the rules of What runs again: Dex can retry a read or an idempotent write with the same key, and gives any other write one attempt per call. A new call from the model can still repeat an effect. A tool that runs inside the model call's Step, or at the provider, runs again when that Step retries.
Your agent SDK's terms in Dex
| In your agent SDK | In Dex | What changes for you |
|---|---|---|
| Thread, conversation, session | A session: one Flow run | It survives crashes and deploys. |
| Run the agent | The send_user_message RPC from a Client (sendUserMessage in TypeScript) | Dex saves the message first. Messages sent during a turn queue. |
| Turn | A turn: the Steps from one user message to the reply | In Python and TypeScript, Steer and Stop end the active turn early. That section says what happens to running tools and remote tasks. |
| LLM call | A RunModel Step, with one or more model calls | Dex saves the Step's result. |
| Tool call, function call | By default, its own Step: CallTool for a read or an idempotent write, CallSingleAttemptTool for any other write | The tool policy picks the Step. Features by harness lists the tools an agent SDK runs inside RunModel or at the provider. |
| Parallel tool calls | Tool Steps that run in parallel, then a ResumeTurn Step. Connector writes of one response run in order. | ResumeTurn waits for every result and gives them to the model. |
| Human in the loop, tool confirmation | An AwaitToolApproval Step, answered with the resolve_interrupt RPC (resolveInterrupt in TypeScript) or in Dex Web | The wait can last days and holds no Worker. |
| Checkpointer, durable execution plugin | Saved Step results. The adapter keeps the agent SDK's own state between Steps. | The agent code needs no determinism rules. |
| Chat history, short-term memory | The session's Attributes | A session keeps one conversation. A new session starts empty. |
| Streaming callbacks | The AgentEvents Stream | It is best effort. get_agent_snapshot (getAgentSnapshot in TypeScript) reads the saved conversation. |
| MCP servers, tool integrations | Tool sources. Official Connectors come in through ConnectorToolSource. | Each Connector call gets its credentials and an idempotency key. |
The session ID is the Flow ID. Between turns the session waits for the next user message and holds no Worker task slot. A stopped session stays readable for the retention period.
Steer and Stop
These rules apply to every Python and TypeScript harness, including the Dex Agent Framework. The Go core has no Steer or cancel_turn.
- Steer (
steer_user_message,steerUserMessagein TypeScript) applies a message at the turn's next safe Step boundary. It never interrupts a model call or a tool call that has started. Tool calls that have not started, and approvals, questions, and durable waits that are still waiting, record REJECTED with the cancellation reason STEERED. The turn then ends, and a new turn starts with every steered message, in order. Steer takes new text or themessage_idof a queued message. While no turn runs, steered text queues likesend_user_message, and a queued message stays queued. If another Step takes that queued message first, the RPC raisesChannelMessageNotFoundErrorand changes nothing; reload the snapshot. While a remote tool task runs, Steer waits for it. - Stop (
cancel_turn,cancelTurnin TypeScript) ends the turn with no new turn. It cancels a running model call or compaction Step at once and drops its uncommitted answer. Whether the provider request itself stops depends on the provider client's cancellation support. It cancels the Steps that wait for an approval, an answer, adurable_waitTimer, or a remote task's next poll. A tool call Step that has started runs to the end, and the turn ends after it. Calls that have not started record REJECTED with the cancellation reason TURN_CANCELLED. A started remote task is abandoned, and its call recordsoutcome_unknown; a runner that implementsToolTaskCancelleris asked to cancel the task. A model call that already saved its final answer completes the turn.cancel_turntakes an optional turn ID; pass the same one when you retry. A second call for the same turn changes nothing. While no turn is active,cancel_turnreturns false and changes nothing. - A turn that a Worker without steering started or advanced cannot be steered or stopped.
How your framework runs a turn
Most adapters stop the framework before a tool runs, so each tool call runs in its own Step, and most run in parallel (Connector writes of one response run in order): CallTool for a read or an idempotent write, CallSingleAttemptTool for any other write. A call that needs approval waits in AwaitToolApproval first. The next RunModel gives the framework the recorded results, so it does not run those calls again. A turn that looks up an order runs RunModel, CallTool, ResumeTurn, and RunModel. The Claude Agent SDK is the exception: it runs reads that need no approval inside RunModel. With Pi, Dex runs the loop itself, so every Pi tool call runs in its own Step.
The tabs show how each framework is stopped and resumed, and where a framework differs.
- Claude Agent SDK
- Eino
- Google ADK
- LangGraph
- Mastra
- OpenAI Agents SDK
- Pi
- Pydantic AI
- Vercel AI SDK
The Claude Agent SDK runs Claude Code as an agent. Its agent loop runs in the Claude Code CLI, a subprocess of the Worker. The Dex adapter runs that loop inside a durable session. It is available for Python and TypeScript.
When to use it
Use it when you want the Claude Code agent loop, its context management, and its tools. Use it when your agent already uses the Claude Agent SDK.
Use the Dex Agent Framework when you want one model call per Step, parallel tool Steps, or context compaction by Dex.
How a session runs
Claude Code runs a whole turn, so the adapter splits a turn into segments. One RunModel Step runs the CLI for one segment. Model calls run inside the segment. So do read tools that need no approval: a deferred read would restart the CLI. A read that needs approval leaves the segment like a write. A Connector tool call is the exception: it always leaves the segment, even a read. See Connect Connectors.
A write tool call ends the segment. It waits in AwaitToolApproval when it needs approval. Then it runs in its own Step: CallTool for an idempotent write, CallSingleAttemptTool for any other write. ResumeTurn then returns to RunModel, which resumes the same Claude session. The CLI gets the recorded result and does not run that call again.
A failed segment retries within its attempts and reruns whole. Model calls and reads inside it run again. A write that ran in its own Step does not run again when the segment retries.
A turn that looks up an order runs one RunModel Step. A turn that cancels an order runs RunModel, AwaitToolApproval, CallSingleAttemptTool, ResumeTurn, and RunModel.
CloudWeGo Eino is a Go framework for LLM applications. Its ADK builds agents such as the ChatModelAgent, with a model, tools, Handlers, and middlewares. The Dex adapter runs a ChatModelAgent inside a durable session. It is available for Go.
When to use it
Use it when your Go agent already uses Eino ADK. Keep the ChatModelAgentConfig, with its model, tools, Handlers, and tool middlewares, and let Dex own the session.
Use a Python or TypeScript harness when the agent needs Steer, cancel_turn, context compaction, questions, or plans. The Go core has none of them.
How a session runs
You pass the *adk.ChatModelAgentConfig to dexeino.NewAgentSessionFlow instead of adk.NewChatModelAgent. Each RunModel Step builds a fresh Eino agent and runner over the stored messages. The adapter's first Handler turns every tool call into an Eino interrupt, so the run stops after one model call.
Each tool call runs in its own Step, in parallel: CallTool for a read or an idempotent write, CallSingleAttemptTool for any other write. The Step runs the call through a one-call compose.ToolsNode with the agent's tool middlewares and Handler tool wrappers. It first checks the arguments against the tool's current schema.
The next RunModel is a new Eino run over the stored messages and the recorded results. No Eino CheckPointStore is used, so the instruction and the tools of the current deploy apply to every model call.
Give each Eino tool a Dex effect with WithToolEffects, WithToolPolicies, or a DexToolEffect method; Eino tools carry none. A turn that looks up an order runs RunModel, CallTool, ResumeTurn, and RunModel.
Google ADK, the Agent Development Kit, builds agents and multi-agent trees for Gemini and other models. The Dex adapter runs an ADK agent inside a durable session. It is available for Python.
When to use it
Use it when your agent already uses Google ADK, including sequential, loop, and parallel agents. Keep the agent tree and its tools, and let Dex own the session.
How a session runs
The adapter adds a plugin to the ADK App. For each tool call, the plugin asks ADK for a confirmation, so ADK pauses before the tool runs. Each RunModel Step advances the ADK run to its next tool calls or its final answer, usually with one model call, and stores the turn's ADK events.
The tool Step runs the tool under its policy. The next RunModel confirms the paused calls, and the plugin returns the recorded results instead of running the tools again.
LangChain create_agent builds a tool-calling agent on LangGraph. The Dex adapter runs a create_agent agent or a custom LangGraph graph inside a durable session. It is available for Python.
When to use it
Use it when your agent already uses LangChain create_agent or a LangGraph graph. Keep the graph, its middleware, and its tools, and let Dex own the session.
How a session runs
DurableToolCallMiddleware stops each tool call with a LangGraph interrupt, so no tool runs inside RunModel. The RunModel Step runs the graph to its next tool calls, usually with one model call, and stores the graph checkpoint.
The tool Step validates the arguments and calls the tool under its policy. The next RunModel restores the checkpoint and resumes the graph with the recorded results.
A custom graph builds its tool node with durable_tool_node instead of ToolNode. Its state must hold the conversation as LangChain messages.
Mastra is a TypeScript framework for agents, tools, and workflows. The Dex adapter runs a Mastra agent inside a durable session. It is available for TypeScript.
When to use it
Use it when your agent already uses Mastra. Keep the agent, its tools, and its model router, and let Dex own the session.
How a session runs
Every agent tool, read tools included, goes to Mastra as a client tool. So Mastra stops after the model call with the tool calls. Each RunModel Step makes one model call.
Each tool call runs the agent's original tool once, in its own Step. The next RunModel adds the recorded results and calls the model again.
The OpenAI Agents SDK defines an agent with instructions, function tools, and handoffs. The Dex adapter runs the SDK's runner inside a durable session. It is available for Python and TypeScript.
When to use it
Use it when your agent already uses the OpenAI Agents SDK, with or without handoffs. Keep the SDK's agent definition, tools, and guardrails, and let Dex own the session.
How a session runs
The adapter copies the agent graph once and intercepts every function tool. So the SDK stops right after each model call and returns the tool calls the model asks for. Each RunModel Step makes one model call.
Each function tool call runs in its own Step. The next RunModel restores the SDK's run state and gives it the recorded results. The tool does not run again.
A handoff runs inside RunModel, unlike a function tool, so a Step that hands off also makes the next agent's model call.
Pi is a TypeScript toolkit for agents. Its pi-ai package calls models from many providers, and its agent core defines tools. The Dex package runs a Pi agent's models and tools in a durable session. It is available for TypeScript.
When to use it
Use it when your agent already uses pi-ai models and Pi tools. Keep the models and the tools, and let Dex own the session and the loop.
Use it also when you move an agent from pi-durable, a durable harness for Pi, to Dex. Dex replaces pi-durable, not Pi. Your pi-ai models and most of your Pi tools carry over. The harness entry code changes: Harness.open, the root conversation, submit, and wait become a session Flow, a Worker, and Client calls.
How a session runs
Dex runs the agent loop, not Pi. The session Flow is the Dex Agent Framework's: createBuiltinAgentSessionFlow, with a model client from createPiAiModelClient and tools from piAgentFunctionTool. Pi's Agent and agentLoop are not used.
Each RunModel Step makes one pi-ai request. pi-ai's own retries are off, so a retry is a new RunModel attempt. Bedrock is the exception; see Limits.
Each Pi tool call runs in its own Step, in parallel: CallTool for a read or an idempotent write, CallSingleAttemptTool for any other write. Without an explicit effect, the tool's replay field picks it: safe is an idempotent write, and never is a non-idempotent write.
A turn that looks up an order runs RunModel, CallTool, ResumeTurn, and RunModel. The session stores each model response as a pi-ai message, so a session can change its model between turns.
Pydantic AI defines a typed agent with tools, dependencies, and output types. The Dex adapter runs a Pydantic AI agent inside a durable session. It is available for Python.
When to use it
Use it when your agent already uses Pydantic AI. Keep the agent, its tools, and its capabilities, and let Dex own the session. The adapter replaces Pydantic AI's own durable execution integrations.
How a session runs
Each RunModel Step runs the agent with a capability that marks every function tool as an external tool. Pydantic AI never runs an external tool, so the run ends right after the model asks for tools.
The tool Step runs the tool under its policy, through the agent, so the agent's tool hooks run there. The next RunModel resumes the run with the recorded results.
The Vercel AI SDK gives TypeScript one API for many model providers, with typed tools. The Dex adapter runs an AI SDK agent definition inside a durable session. It is available for TypeScript.
When to use it
Use it when your TypeScript application already uses AI SDK models and tools. Keep the model, the tools, and stopWhen, and let Dex own the session.
How a session runs
Every tool reaches the model without its execute, so the AI SDK returns the tool calls instead of running them. Each RunModel Step makes one model call with streamText.
Each tool call runs the tool's original execute in its own Step. The next RunModel adds the recorded results, checks stopWhen, and calls the model again.
Limits
Each tab lists the limits of one adapter that change how you write an agent, with what to do instead. The Dex Agent Framework has its own limits.
- Claude Agent SDK
- Eino
- Google ADK
- LangGraph
- Mastra
- OpenAI Agents SDK
- Pi
- Pydantic AI
- Vercel AI SDK
- One write call per segment leaves the turn. A reply with two writes costs one more segment and model call. The writes of one reply never run as parallel Steps.
- Tools that run inside the CLI, such as Bash or Edit, are at least once. They run again when a segment reruns. Files the CLI changes are not recorded.
- A segment must finish within the
RunModelmethod timeout, 15 minutes by default. Raise it withrun_model_limitin Python orrunModelLimitin TypeScript. - Claude Code compacts its own transcript, and context compaction by Dex stays off. A long session ends at the state limit, not the context window: the active state of one session, 64 MiB by default (Session limits).
- A recorded tool result keeps text only.
- A write call inside a subagent is denied. The model is asked to call it from the main conversation.
- The Claude Code CLI inherits the Worker's environment, including any other Anthropic or Claude Code sign-in setting. Set the options'
envso thatANTHROPIC_API_KEYis its only credential, as the examples'build_claude_cli_environmentdoes.
- Each
RunModelmakes exactly one model call. A configuration that makes more refuses to build:ModelRetryConfig,ModelFailoverConfig, and the summarization middleware. Tune retries withWithModelRetryPolicy, and choose the model per call with anAgentConfigBuilder. - Let each Handler's
WrapModelcall the model it receives and return its error.RunModelthen retries a rate limit or a server error with backoff (Model API errors). AWrapModelthat retries the model or falls back to a backup model still builds, because construction cannot see a Handler's model calls. When a model call fails, that retry or fallback is a second model call in the Step, so the turn ends as failed. ExitandToolsConfig.ReturnDirectlyend the turn on a tool result instead of a model answer. So they refuse to build.- A sub-agent runs as a tool, through
adk.NewAgentTool. It runs inside that tool's Step, again on each attempt, so give the tool the effect of what its sub-agent does.transfer_to_agentand the prebuilt supervisor, plan-execute, and deep agents are not accepted. - An agent tool made with
adk.WithFullChatHistoryAsInputreads the agent's history, which a tool Step does not have. So it refuses to build. Pass what the sub-agent needs in the call's arguments. - Every tool needs a Dex effect. Construction fails for a tool without one, unless you set
WithDefaultToolEffect. - The tool calls of one model response run as parallel Steps, so tools must be safe for concurrent use, in any order.
ToolsConfig.ExecuteSequentiallyrefuses to build. - Change the model's message in a Handler's
WrapModel, and earlier messages or tools inBeforeModelRewriteState. AnAfterModelRewriteStateorAfterChatModelthat changes them ends the turn as failed. - Each
RunModelis a new Eino run. Run-local values, session values, and middleware caches start empty at every model call. - The tool Step checks arguments against the tool's schema, which can be stricter than Eino's decoding. Mark optional
utils.InferToolfieldsomitempty, and convert other calls in aToolArgumentsHandler. - Return
*dexagents.ToolExecutionErrorfor a definite tool failure.utils.WrapToolWithErrorHandlerturns every error into result text, so a write that may have run would read as succeeded; leave Dex tools unwrapped. - The Go core covers the session core: approvals, tool effects, Connector tools, queued messages, and the AgentEvents Stream. It has no Steer,
cancel_turn,delete_queued_message, questions, tool input requests, plans, context compaction, images, MCP tool source, spend-limit hook, GenAI spans, or UI streams. Before you resend a message whose response was lost, look for it withGetAgentSnapshot, because a second copy stays queued and runs its own turn. A Connector call that waits for approval carries no approval display. Serve each agent Flow type with Workers of one language.
- The App root must be a
BaseAgent. ADK Workflow roots are not supported. - A tool runs outside the ADK run, with a fresh
ToolContext. Its state and artifact changes are discarded. Pass what it needs as arguments. - A tool that asks for a confirmation or a credential inside its Step fails.
- Agents that continue without tools make their model calls in the same
RunModel. - A
before_tool_callbackruns in theRunModelthat requests the call, and again if that Step retries. - Code executors other than
BuiltInCodeExecutorare refused. Run such code from a tool instead. - app: and user: state keys live in the Dex session, not across sessions.
- A graph whose nodes make several model calls before a tool node makes them all in one
RunModel. Summarization middleware and a planner node are examples. A retry repeats them all. - Provider-run tools repeat when
RunModelreruns. - History is append-only. A graph that edits or removes earlier messages does not change the stored history.
- Only the message list survives between turns. Other state keys start from their defaults on every turn; within one turn they survive. Keep a value that must last across turns in a store you own, read through a tool.
- Tools run outside the graph. They cannot use
ToolRuntime,InjectedState, orInjectedStore, and cannot return a graph Command.InjectedToolCallIdworks. - The graph may raise no interrupts of its own.
- Tools Mastra runs itself, such as sub-agents, workflows, and Memory tools, cannot run in a Step. The adapter offers one only when
toolPoliciesnames it as a read without approval. It then runs insideRunModeland repeats when that Step reruns. - The session stores every message and gives the agent the history, in place of Mastra Memory. Leave the Memory thread unset in the agent's defaults and scopes. For memory across sessions, give the agent a tool over a store you own, as How it works describes.
beforeToolCallandafterToolCallhooks run only for tools Mastra runs itself.- A tool result reaches the model as text.
toModelOutputis not applied. - A tool that calls
suspend()fails. Use the session's approval instead. - Tool names must be at most 63 characters of letters, digits, _, and -, and must not start with a digit or -.
- Only function tools get their own Steps. Hosted tools, such as web search, run at the provider during the model call. They repeat when
RunModelreruns. - Tools the SDK runs itself, such as tools of
Agent.mcp_serversand local shell tools, cannot wait for approval. The adapter refuses them by default.-
For an MCP server, pass it through
McpToolSourceintool_sourcesinstead ofmcp_servers. Each of its tools then runs in its own Step with a policy, and a tool markedreadOnlyHintis a read. This function from the quick start example adds an MCP server to the Python quick start agent; openai_agents_mcp.py has the imports:def build_durable_agent_with_mcp(
order_desk: OrderDesk, model: str | Model, mcp_servers: Sequence[McpServerConfig]
) -> AgentSessionFlow:
"""Returns the quick start agent with MCP tools, each call in its own Step.
The servers go through tool_sources, not Agent.mcp_servers, which the
adapter refuses. A tool marked readOnlyHint is a read.
"""
return openai_agents_session_flow(
build_plain_agent(order_desk, model),
flow_type="OpenAIAgentsMcpQuickStart",
tool_policies={
"look_up_order": ToolPolicy(ToolEffect.READ),
"cancel_order": ToolPolicy(ToolEffect.NON_IDEMPOTENT_WRITE),
},
tool_sources=[McpToolSource(mcp_servers)],
) -
Or set
allow_at_least_once_tools=True. Those tools then run insideRunModeland repeat when it retries, so use this only for reads. -
Wrap a write in a function tool to give it its own Step.
-
- Function tool names must be unique across the agent graph. The graph is copied when the Flow is built, so later changes to it do not reach the Flow.
- The session is the history. Do not use server-managed conversation state or SDK sessions. Send each new message with
send_user_message, and the session gives the agent the earlier turns. - An agent used as a tool runs its nested run inside one tool Step in Python. TypeScript rejects it; hand off instead.
- Dex runs the tool calls of one model response in parallel, so a tool with
executionMode: "sequential"is rejected. Make the tool safe to run in parallel, or combine the calls into one tool. - Dex ignores
AgentToolResult.terminate, and Pi'sfinishTurndoes not run. To end or continue a turn after tools, use thedecideTurnContinuationhook of the agent definition. - Pi's
beforeToolCallandafterToolCallhooks do not run. Tool policies decide approval, and a tool changes its own result. - The session compacts old messages in place of Pi's
transformContext. To change one request, use theprepareRequestoption ofcreatePiAiModelClient. - pi-ai's tool choice is auto or none, so a request that forces a tool fails. Keep
planningToolChoiceat auto. - The model sees the text of a tool result. It sees the result's images only when the session Flow has a media store; otherwise each image becomes a text note. The result's details are not stored.
- A pi-durable
defineTooltool runs throughpiDurableFunctionToolonly when it does not use api and returns no control. Rewrite such a tool as a PiAgentTool. - Move the tools and prompt of a pi-durable Extension into the agent definition. Extensions and fork are not supported.
- With Bedrock (
bedrock-converse-stream), the AWS SDK retries inside oneRunModelattempt, because pi-ai ignores its own retry setting there. One attempt may send up to 3 requests by default, and Dex'sRunModelretries multiply them. Each extra request can add model charges, and any work that the provider runs follows the provider's own rules. To keep one request per attempt, setAWS_MAX_ATTEMPTS=1or a profile'smax_attemptsin the Worker's AWS configuration.
- Retries that Pydantic AI sends to the model itself make another model call in the same
RunModelStep. Examples are invalid tool arguments and output that fails validation. - Output functions run inside
RunModeland are at least once. Put a write in a tool instead. - Provider-run tools, such as
WebSearchTool, repeat whenRunModelreruns. - A deferred tool returns text to the model. Images and files are lost.
- A tool that asks for approval only while it runs needs a
ToolPolicywithrequires_approval=True. UsageLimitsand tool retry budgets apply per Step, not per turn.
- A crash in
RunModelreruns that model call and any provider-executed tools in it. - A tool's execute gets
toolCallIdandabortSignal. Its messages are empty and its context is undefined. - Approval belongs to Dex. AI SDK
toolApprovalis not exposed, and aneedsApprovalfunction is rejected. Provider-executed tools never wait for approval. - Every tool runs in Dex, so a tool without execute, such as a browser-side tool, is rejected.
- Tool inputs and outputs must survive JSON.
prepareStep,activeTools, output, and stream transforms are not exposed.
Limits for long sessions has the server limits.
Latency and cost
Every session Step is SYNC: Dex saves its start before a Worker gets it, and its result before the session moves on. Take a turn whose model asks for three ordinary tools without approval, in one response, and then answers, with one model call in each RunModel. The turn runs two RunModel Steps, three tool Steps in parallel, and one ResumeTurn, so it waits on four Steps in a row. Performance measured a p50 of about 105 ms for a SYNC Step on a 2-vCPU server at half of its peak load. At that p50, the four Steps add about 0.4 seconds to the turn, on top of the model and tool time.
To retry an expensive model call fewer times, lower its attempts; Step timeouts lists the option and the defaults.
The complete files
The quick start program is three files per language. Apart from the example's order desk and settings, they use only Dex, Dex Agents, and your agent SDK:
| File | Python | TypeScript | Go |
|---|---|---|---|
| Your agent module, plain and durable, with every import | claude_agent_sdk · google_adk · langchain · openai_agents · pydantic_ai | claude-agent-sdk · mastra · openai-agents · pi · vercel-ai | eino |
| The runner: Registry, Worker, Client, and one turn with approvals | session.py | quick-start-session.ts | session.go |
| The smallest host: one Worker, one Client, one turn | embed.py | quick-start-embed.ts | embed.go |
| The entry point that asks for approval at the prompt | __main__.py | quick-start-main.ts | main.go |
The other packages that the install commands list are your agent SDK and the packages the example uses, such as its model client; install the ones your agent uses. Tools the agent SDK runs itself, such as MCP servers and hosted tools, need the changes in its Limits tab. The Order Support host registers the Claude agent only when ANTHROPIC_API_KEY is set, and serves the other harnesses without it.
Serve sessions from a web app
A web app splits the host across routes:
- The Registry, Worker, and Client. The Worker connects out to Dex, so it needs no open port. Both use a blob cache, a local cache for large values.
- A route that starts a session. The session ID is the Flow ID.
- A route that sends a user message, and one that reads the session snapshot with the agent's reply or streams it.
- A route that approves or rejects a waiting tool call; see Approve from your application.
The handler that sends a message queues it on the session and returns. It replaces the agent SDK call that waited for the reply:
| Agent SDK | Call it replaces |
|---|---|
| Claude Agent SDK | query |
| Eino | Runner.Query |
| Google ADK | Runner.run_async |
| LangGraph | agent.invoke |
| Mastra | agent.generate |
| OpenAI Agents SDK | Runner.run |
| Pi | agent.prompt |
| Pydantic AI | agent.run |
| Vercel AI SDK | generateText |
The reply arrives on the session's AgentEvents Stream, which a chat UI reads as server-sent events. Polling the snapshot suits scripts and tests. The Order Support Agent example has these routes over HTTP, for every agent SDK.
The whole module, quick_start/web.py, is a complete app: it hosts the Worker and the Client and serves every route a chat UI needs.
"""A complete web app for a durable agent: start, message, read, stream, approve.
It hosts the Worker and the Client in the web process. Add your own
authentication before you expose these routes: anyone who knows a session ID
can read and change that session here.
"""
from __future__ import annotations
import uuid
from pathlib import Path
from typing import Any
from dex_agents import AgentSessionFlow
from dex_agents.ui_stream import (
AGENT_EVENT_STREAM_HEADERS,
agent_snapshot_to_json,
stream_agent_event_frames,
)
from quart import Quart, Response, jsonify, make_response, request
from agent_harness_examples.quick_start.safe_send import send_user_message_once
from agent_harness_examples.quick_start.session import QuickStartApp
def create_web_app(
session_flow: AgentSessionFlow, server_address: str, blob_cache_dir: Path
) -> Quart:
"""Returns a Quart app whose routes run one durable agent's sessions."""
web = Quart(__name__)
apps: list[QuickStartApp] = []
send_user_message_once retries a send with best-effort duplicate detection; Retry a message send has the module and its limits.
例子: examples/python/agent-harnesses/agent_harness_examples/quick_start/web.py
The Go example serves the session routes with net/http. A Go app reads the session snapshot, or the AgentEvents Stream with AgentSessionClient.ReadAgentEvent; the Go core has no UI stream helpers. The other routes and helpers are in the full routes file.
// Register adds the routes to mux.
func (routes *SessionRoutes) Register(mux *http.ServeMux) {
prefix := "/products/agent-harnesses/" + routes.harnessName
mux.HandleFunc("POST "+prefix+"/sessions", routes.startSession)
mux.HandleFunc("POST "+prefix+"/messages", routes.sendUserMessage)
mux.HandleFunc("POST "+prefix+"/interrupts/resolve", routes.resolveInterrupt)
mux.HandleFunc("GET "+prefix+"/snapshot", routes.getAgentSnapshot)
}
// ...
func (routes *SessionRoutes) sendUserMessage(response http.ResponseWriter, request *http.Request) {
var body struct {
SessionID string `json:"session_id"`
Text string `json:"text"`
}
if !routes.readSessionRequest(response, request, &body, &body.SessionID) {
return
}
if strings.TrimSpace(body.Text) == "" {
http.Error(response, "text must be a non-empty string", http.StatusBadRequest)
return
}
isAccepted, err := routes.sessions.SendUserMessage(request.Context(), body.SessionID, body.Text)
if err != nil {
writeDexError(response, err)
return
}
writeJSON(response, map[string]bool{"accepted": isAccepted})
}
The Dex Agent Framework example's chat routes show the same pieces. /api/chat queues the message or the approval answers and streams the reply in the Vercel AI SDK UI message format. The second route resumes the stream after a reconnect. The helpers are in the full routes file.
router.post("/api/chat", async (request, response) => {
const body = requireBody(request);
const flowId = authorizeSession(request, requireString(body, "id"));
const lastMessage = Array.isArray(body.messages) ? (body.messages.at(-1) as JsonBody | undefined) : undefined;
const signal = abortSignalOf(response);
if (lastMessage?.role === "assistant") {
const approvals = readAgentToolApprovalResponses(lastMessage);
await sendFetchResponse(response, resolveAgentToolApprovalsWithUIMessageStream({ ...session, flowId, approvals, signal }));
return;
}
const parts = (Array.isArray(lastMessage?.parts) ? lastMessage.parts : []) as JsonBody[];
const text = parts.map((part) => (part.type === "text" ? String(part.text) : "")).join("");
await sendFetchResponse(response, sendAgentUserMessageWithUIMessageStream({ ...session, flowId, text, signal }));
});
router.get("/api/chat/:id/stream", async (request, response) => {
const resumeToken = request.header(agentResumeTokenHeaderName);
const options = { ...session, flowId: sessionIdOf(request), resumeToken, signal: abortSignalOf(response) };
await sendFetchResponse(response, createAgentUIMessageStreamResponse(options));
});