dex-agents-openai-agents
dex-agents-openai-agents (import dex_agents_openai_agents) runs
OpenAI Agents SDK agents as
durable Dex agent sessions. It plugs the SDK into the shared session Flow of
dex-agents. The plan is
agent-framework-adapters.md.
One Flow execution is one agent session; the Flow ID is the session ID. The
session runs in Step mode. Every model call is one RunModel Step. Every
function tool call, READ included, is its own Step, and the calls of one model
response run in parallel. A crash repeats at most the one model call or tool
call that was running, and a single-attempt write is never repeated silently.
Installation
The package needs Python 3.11 or later. It requires dex-agents at the same
version, the released dex-python-sdk==1.45.4, and openai-agents>=0.24,<0.25
(0.24.0 is locked and tested):
pip install dex-agents-openai-agents
Develop the package inside this repository with uv 0.12.2. There it resolves
dex-agents from ../core by path through [tool.uv.sources]; the published
wheel requires dex-agents==<same version> from PyPI instead:
cd agents/python/openai-agents
uv sync --locked
DEXCLI=/path/to/dexcli ./ci.sh
Example
import asyncio
import contextlib
from agents import Agent, function_tool
from dex import AsyncClient, AsyncWorker, BlobCacheConfig, ClientOptions, Registry
from dex import WorkerOptions, open_blob_cache
from dex_agents import AgentSessionClient, ToolEffect, ToolPolicy
from dex_agents_openai_agents import (
get_current_deferred_tool_execution,
openai_agents_session_flow,
)
@function_tool
def search_orders(customer_id: str) -> str:
"""Find a customer's open orders."""
return f"customer {customer_id} has order 7"
@function_tool
async def create_refund(order_id: str) -> str:
"""Refund one order."""
execution = get_current_deferred_tool_execution()
key = execution.idempotency_key if execution else order_id
return f"refunded order {order_id} with idempotency key {key}"
agent = Agent(
name="Support",
instructions="Help the customer with their orders.",
tools=[search_orders, create_refund],
)
flow = openai_agents_session_flow(
agent,
flow_type="SupportAgent",
tool_policies={
"search_orders": ToolPolicy(ToolEffect.READ),
"create_refund": ToolPolicy(ToolEffect.NON_IDEMPOTENT_WRITE),
},
)
async def main() -> None:
registry = Registry([flow], allow_async_handlers=True)
cache = open_blob_cache(BlobCacheConfig(".dex-cache", 64 * 1024 * 1024))
worker = AsyncWorker(registry, cache, WorkerOptions(server_address="localhost:8801"))
client = AsyncClient(registry, cache, ClientOptions(server_address="localhost:8801"))
serving = asyncio.create_task(worker.start())
try:
await worker.wait_pull_registered(timeout=30)
sessions = AgentSessionClient(client, flow)
await sessions.start_session("session-42", "Refund my open order. I am customer 3.")
while True:
snapshot = await sessions.get_agent_snapshot("session-42")
if snapshot.pending_interrupts:
interrupt = snapshot.pending_interrupts[0]
await sessions.resolve_interrupt(
"session-42", interrupt.interrupt_id, approved=True
)
elif snapshot.state is not None and snapshot.state.turn_count == 1:
print(snapshot.messages[-1].text)
break
await asyncio.sleep(0.5)
finally:
await client.close()
await worker.stop()
with contextlib.suppress(asyncio.CancelledError):
await serving
cache.close()
asyncio.run(main())
The agent uses the SDK's default OpenAI model, so set OPENAI_API_KEY, and run
dexcli dev first. The first RunModel stops after the model asks for
search_orders. CallTool runs the search, ResumeTurn collects the result,
and the next RunModel gives it to the model, which asks for create_refund.
That call waits in AwaitToolApproval. After approval it runs once in
CallSingleAttemptTool, and the last RunModel answers. A UI would poll the
snapshot or read AgentSessionClient.read_agent_event instead of the loop
above.
OpenAIAgentsRunner is the runner itself. Use it with AgentSessionFlow
directly when you build AgentSessionOptions yourself, and call
runner.validate_tool_policies(...) with the same policies.
Effects and policies
Policies are keyed by the tool's qualified name (FunctionTool.qualified_name):
the tool name, or <namespace>.<name> for a namespaced tool. Every policy must
name a function tool of the agent graph. A tool without a policy gets
default_tool_effect, which defaults to unclassified. A function tool
converted from MCP with readOnlyHint defaults to read, and one with
idempotentHint to idempotent_write.
| Effect | Step | Retry | Crash mid-call | Default approval |
|---|---|---|---|---|
read |
CallTool |
Up to 3 attempts; then failed |
Runs again | No |
idempotent_write |
CallTool |
Up to 3 attempts, key <flowId>/<turnId>/<toolCallId>; then outcome_unknown |
Runs again with the same key | No |
non_idempotent_write |
CallSingleAttemptTool |
One attempt; then outcome_unknown |
Outcome unknown | Yes |
unclassified |
CallSingleAttemptTool |
One attempt; then outcome_unknown |
Outcome unknown | Yes |
A tool the application marked with needs_approval waits in
AwaitToolApproval whatever its policy. A needs_approval callable decides
per call, through the SDK's own evaluation: when argument validation changes
the values, such as by filling a default, the call needs approval without
calling the callable, exactly as in a plain SDK run.
A tool call Step first parses the arguments and validates them against a
decorated tool's parameters. Invalid arguments record failed with the SDK's
Invalid JSON input for tool <name> message, and the tool does not run. The
Step then runs the tool's own on_invoke_tool with a ToolContext. The SDK's
tool failure formatter is off there, so an exception reaches Dex. Raise
dex_agents.ToolExecutionError for a failure the model should see; the
session records failed and does not retry. Any other exception fails the
Step and follows the table above. Inside the tool,
get_current_deferred_tool_execution() returns the call's idempotency key and
attempt. Tools that run inside an agent tool's nested run get None, so they
never reuse the outer call's key.
The Step runs the tool's input guardrails after argument validation and
before the body. A reject_content result records failed with the
guardrail's message, and a tripwire records failed with the guardrail's
name; in both cases the body does not run. The resumed RunModel does not run
input guardrails again. Output guardrails run when the resumed RunModel
receives the recorded result.
A tool with an output type (function_tool(output_type=...)) records the JSON
its type adapter dumps, and the resumed run validates it again. A failed,
rejected, or unknown result reaches the model as the SDK's tool error output,
which skips the output schema.
When a turn fails after tool calls finished, the session stores a turn-failure
note through build_user_message. The runner stores it as a user input item,
so the next turn's model sees which calls already ran.
Tool sources and connector tools
tool_sources takes the core's tool sources, such as ConnectorToolSource,
which offers reviewed Connector operations (install dex-agents[connectors]).
See Connector tools
for what the manifest decides.
from dex_agents.connectors import ConnectorToolSource, connector_tool
stripe = new_project_connection(project, "billing-stripe")
flow = openai_agents_session_flow(
agent,
flow_type="SupportAgent",
tool_sources=[
ConnectorToolSource([
connector_tool(stripe.operations.create_refund(), stripe.reference),
]),
],
)
- The SDK fixes an agent's tools, so the runner adds a gated function tool to
every copied agent for each tool of a source's
cached_tools(), with the source's name, description, and JSON Schema. A source withoutcached_toolsoffers nothing;ConnectorToolSourcecaches its whole listing. EachRunModellists every source, and a model call offers only the tools its listing has.validate_tool_policiesaccepts source tools. - Every call of a source tool defers, reads included, and runs once in its own
tool Step through the source's
execute_deferred_tool_call, never inside the framework. A connector call derives its Call ID from the Step execution ID and keeps its fence marker in the Step's heartbeat checkpoint. - The source builds each call, so it decides the effect class, the approval,
and whether the call is an ordered write;
tool_call_step_optionsgives the tool Step the operation's timeout and retry policy. Atool_policiesentry for a connector tool changes only its approval. - Writes of one model response run one at a time in the model's order, as in a
built-in loop agent. Once one does not succeed, the later ones record
failedwithskipped. - Definition fails with
ValueErrorwhen two sources share asource_name, or a source'sdeclared_tool_namesrepeat a function tool, a handoff, or an accepted at-least-once tool, or another source's tool. The same names listed at run time fail thatRunModelattempt. - The runner polls no tool tasks. A source call that starts one records
failedfor areadcall andoutcome_unknownotherwise. A source whose listing fails or takes longer thantool_source_listing_timeoutoffers no tools in that model call. A tool the turn already called but the listing lacks is replay-only: the resumed run replays its recorded call from the source'scached_tools(), and a new call of it is refused inside the framework (the tool stays offered so the SDK can resume its recorded call, and its body returns the refusal: " did not run: its tool source does not offer this tool now."), so it never reaches a tool Step. - A recorded result replays once, for the call that paused, and only under the
tool name it was recorded for; a later call that reuses its tool call ID
fails the
RunModelattempt instead of reading that result.
How it works
- History: each stored
AgentMessageholds one item ofRunResult.to_input_list()inframework_item, plus a display projection. A new turn replays every stored item as client-managed input. - Gate: the runner copies the agent and every handoff target once, at
construction. Later changes to those agents do not reach the runner. Agents
used as tools are not copied, so changes to them and their tools do. Each copied
FunctionToolgets aneeds_approvalcallable that always returnsTrue, so the SDK stops withresult.interruptionsright after the model asks for tools. They becomeToolCallsRequested, in model order, withRunState.to_json()as the framework run state. - Resume:
RunState.from_jsonrestores the run. The runner approves each interruption whose record is final, so the copied tool returns the recorded result, or thedescribe_tool_call_outcometext for failed and unknown calls, instead of running. It rejects rejected calls with their rejection message. The copied tool never runs the real tool. - One model call: a
RunModelmakes one model call. A handoff is not a function tool, so the SDK runs it and makes the next agent's model call in the sameRunModel; that Step reports both calls. - Streaming: output text and reasoning-summary deltas go to
AgentEvents, coalesced to about 64 characters per Stream message, or flushed after 100 ms without a new event. - Usage: each
RunModelreports its own model calls and tokens from the run'sUsage. - Tracing: each
RunModelreturnsModelCallMetadatafor itschatspan.request_modelis the model name the SDK resolves:RunConfig.modelwhen it is a string, otherwise the calling agent'sAgent.modelwhen it is a string. AModelinstance names no model, and without a name the model provider picks one, so the field stays unset then.response_idis theModelResponse.response_idof the call, unless it is missing or the SDK's placeholder ID for Chat Completions. ARunModelwith a handoff makes several model calls, so its span isINTERNAL, carries no response ID, and keepsrequest_modelonly when every agent of the graph resolves the same name.provider_name,response_model, andfinish_reasonsstay unset:ModelResponsecarries no provider, response model, or finish reason, and a Chat Completions model echoes its request name as the response's model.
Images
Since 0.5.0 the runner can show images to the model. Pass media_store to
openai_agents_session_flow or OpenAIAgentsRunner. Use the store that your
clients and tools upload to, such as S3MediaStore, or
LocalDirectoryMediaStore when every client and Worker runs on one machine.
from dex_agents.s3 import S3MediaStore
store = S3MediaStore("agent-media", "sessions")
flow = openai_agents_session_flow(agent, flow_type="SupportAgent", media_store=store)
reference = await store.put_image(Path("chart.png").read_bytes())
await sessions.send_user_message("session-42", "What does this chart show?", images=[reference])
- User images. The model sees one user message. Its
contentis aninput_textpart, then oneinput_imagepart per image, in order. - Tool images. A tool source's tool, such as a connector tool, returns
images with
ToolExecutionResult(output=..., images=[reference]). The model sees the SDK's own tool result form: afunction_call_outputwhoseoutputlist is aninput_textpart, then oneinput_imagepart per image. No extra message is added. The stored tool message carries the record'simages. A function tool returns text only: its output is recorded as text, so aToolOutputImageit returns reaches the model as JSON text. - References, never bytes. Stored items and the serialized
RunStateset each image part'simage_urlto the reference'suri. Every model call reads the bytes withload_imagesand sends each image as adata:URL of its MIME type. It does so in acall_model_input_filterthat runs after the run config's own filter, so your filter sees theuri. Run hooks'on_llm_startand model tracing with sensitive data see thedata:URLs. A failed read fails theRunModelattempt, which retries. - Without a store, the session refuses user images:
send_user_messagereturnsFalse. A tool result's images then reach the model only as the result's text. - Chat Completions models. The SDK's Chat Completions converter keeps only the text of a tool result, unless a LiteLLM or any-llm model preserves all of its content. Use a Responses model when the model must see tool images. User images reach both.
Compaction
Since 0.3.0 the runner can compact a session that would outgrow the model's
context window. Pass compaction=CompactionPolicy(context_window_tokens=...) to openai_agents_session_flow, and optionally summary_model; the summary call uses the run config's model, else the starting agent's. Without a policy nothing changes, and a session
started before the upgrade starts compacting once its Worker has one.
- It compacts only between turns, before the first model call of a turn. A model call that continues a turn after its tool calls does not compact, so one turn's growth must fit in the rest of the window. Lower the trigger ratio when a turn can add more than about 15 percent of the window.
- The summary enters the model input as a user message before the kept turns. It is never stored as a message, and every message stays readable until retention deletes it behind the summary.
- The estimate counts three bytes of each stored message as one token, plus the instructions and tool definitions the runner can see. Set the policy's reserved input tokens for the rest, such as dynamic instructions.
- The summary call gets the earlier turns as plain text, without tools.
- Responses API compaction items and
truncationchange only the provider's input. Dex stores every item either way and owns the record; use one of the two. Encrypted reasoning and compaction items are left out of the summary prompt.
See Compaction and the storage bound.
Limits
- Tools the SDK runs itself cannot be gated, so the runner refuses them by
default: tools of
Agent.mcp_servers, sandbox capabilities of aSandboxAgent, agents that overrideget_all_tools, andComputerTool,CustomTool,ApplyPatchTool,LocalShellTool, or a localShellTool. Withallow_at_least_once_tools=Truethey run insideRunModel, repeat when it retries, and let oneRunModelmake several model calls. MCP server tools take no policy, and a local MCP server that requires approval fails the turn. Wrap a write in afunction_toolto give it its own Step. - Provider-hosted tools (
WebSearchTool,FileSearchTool,CodeInterpreterTool,ImageGenerationTool,HostedMCPTool,ToolSearchTool,ProgrammaticToolCallingTool, and a hostedShellTool) run inside the model call and rerun with it. A hosted MCP approval request fails the turn; setrequire_approvalto"never"or useon_approval_request. Function tools that generated code calls throughProgrammaticToolCallingTooluse the same gated copies, but that path has no test yet. - Handoffs must be
Agentobjects orHandoffobjects made withhandoff(agent). Handoff callbacks and input filters run insideRunModel. Function tool names must be unique across the agent graph, because a tool call Step finds its tool by name. - An agent used as a tool (
Agent.as_tool()) is one tool call: its nested run, with its model calls and tools, runs inside that call's Step. The runner refuses a nested agent whose tool needs approval, and records the callfailedif a nested run still stops for approval, such as after a later change to the nested agent. The nested run's usage is not added to the session usage, because a tool call Step reports no usage. - A tool's output is recorded as text. Structured outputs without an output type, such as images, reach the model as their JSON text. A tool source returns images as references instead; see Images.
- A tool input guardrail that trips records the call
failedinstead of failing the run, as the SDK'sToolInputGuardrailTripwireTriggeredwould.pre_approval_tool_input_guardrailshas no effect, because input guardrails run in the tool call Step, after approval. - Run hooks, agent hooks, input and output guardrails run inside
RunModeland run again when it retries. A guardrail tripwire fails the attempt. max_turnscounts model calls across allRunModelSteps of one session turn.- The serialized
RunStateholds the turn's whole input, including history, while tool calls run. A mapping run context is written into it too. - Server-managed conversation state (
previous_response_id,conversation_id) and SDKSessionmemory are not used; the session is the history. - Realtime and voice agents are not supported.
- The gate and the error-output path use SDK internals pinned to
openai-agents0.24:evaluate_function_tool_approval,get_public_agent, the handoff target reference, the handled-failure flag onToolContext, the nested agent tool result store, and theRunStateitem deserializer thatbuild_unfinished_turn_messagesuses. - The core's limits apply: every call adds a Step round trip. See Compaction for long sessions.
steer_user_messageandcancel_turnwork as the core describes. The runner'sbuild_unfinished_turn_messagesstores the turn's items from theRunState, asto_input_list()gives them to a completed turn, with afunction_call_outputfrom the final record of every call that has none, such as the core's steering result. A failed turn stores them before the turn-failure note. The next model call sees every call with its result, and a steered or cancelled turn stores no note. It accepts onlyRunStateschema 1.21 and the item kinds it can reproduce exactly. A pending call of a tool with an output schema, a programmatic tool call, an unknown item, a result out of order, or a record of another tool makes the session log a warning and store its note instead.
Testing
tests/ runs a real Agent graph against a private dexcli dev --engine zd
engine and asserts each turn's Step shape from the Flow history. The scripted
model in tests/scripted_model.py implements the SDK Model interface and
derives every response from its input, so no model key is needed and a
retried RunModel gets the same response. It streams through
agents.testing's ScriptedModel and records every model call, so tests
count them. The Worker runs as a child process that the tests SIGKILL.
tests/test_connector_tools.py runs connector tools from a copy of the core
tests' fake ledger Connector (tests/fake_ledger): a Query in its tool Step,
an approved Mutation that runs once, a session policy that changes only
approval, a retry: safe Mutation retried with the same Call ID, uncertain
writes recorded outcome_unknown, two writes of one response in the model's
order, an unknown or rejected write that skips the later write, a withdrawn
tool whose new call is refused, a reused call ID, the operation's tool Step
options, an unexposed operation, and refused name collisions.
Metadata
Release files for dex-agents-openai-agents 0.6.14
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dex_agents_openai_agents-0.6.14.tar.gz | 44.7 kB | Without provenance | Details for dex_agents_openai_agents-0.6.14.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dex_agents_openai_agents-0.6.14-py3-none-any.whl | Python 3 | none | any | Details for dex_agents_openai_agents-0.6.14-py3-none-any.whl |
Total release size: 88.0 kB
Release files / dex_agents_openai_agents-0.6.14.tar.gz
| Download URL | dex_agents_openai_agents-0.6.14.tar.gz |
|---|---|
| Size | 44.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4bf7aa892b256413e5b3422003f66e94fc40b357bc0820a9eea376a7ed38799f
|
|
BLAKE2b-256 checksum How to use checksums |
c8f2f78b767c58a2587d17afff6f203d838cc4ae002565838cd3513c8f0d2fd4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.12.2 {"installer":{"name":"uv","version":"0.12.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / dex_agents_openai_agents-0.6.14-py3-none-any.whl
| Download URL | dex_agents_openai_agents-0.6.14-py3-none-any.whl |
|---|---|
| Size | 43.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2c425df0158d13f4ab8df17a8b276b9c912bd5b6bb1c5119b3aa92e9ce272316
|
|
BLAKE2b-256 checksum How to use checksums |
018efa35439adbb4f9390847ec368610cfb687837f39c4a95cb75157aaf57fc7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.12.2 {"installer":{"name":"uv","version":"0.12.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for dex-agents-openai-agents 0.6.14
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.