What the OpenAI Agents API is

The OpenAI Agents API is a hosted runtime for durable agents. OpenAI runs a managed Codex harness: the loop that coordinates a model, tools, context, recovery, and optional delegated work. Your application creates sessions, supplies tasks and capabilities, receives events, handles any application-owned function calls, and decides where code execution happens.

That is different from merely sending a request to a model. It is also different from installing an agent library in your own service.

The API is designed for work that may span many model and tool calls: investigate a repository, prepare files, research across sources, operate in a sandbox, pause for an external result, delegate independent work, then continue in the same session.

As of September 16, 2026, the API is beta. Requests require the OpenAI-Beta: agents=v1 header when the client library does not add it. Field names, defaults, model availability, and limits can change. Treat the linked official documentation and API reference as the source of truth at implementation time.

This guide is platform-focused. The lifecycle applies whether your application is written in Python, JavaScript, Java, or another language that can call an HTTP API.

The architecture in one picture

your product or service
  ├─ creates and continues sessions
  ├─ sends input and steering messages
  ├─ consumes event streams or webhooks
  ├─ fulfills application function calls
  └─ stores product-level authorization and state
               │
               ▼
OpenAI-managed Codex harness
  ├─ model and agent loop
  ├─ instructions, tools, and skills
  ├─ session history and compaction
  ├─ subagent coordination
  └─ recovery and saved items
               │
               ▼
optional execution environment
  ├─ OpenAI-hosted sandbox
  ├─ self-hosted executor
  └─ no environment

Three boundaries deserve separate attention.

The harness

The harness is the OpenAI-hosted Codex instance. It runs the model/tool loop and maintains the agent session. It can issue tool calls, execute commands through an environment, steer subagents, summarize older work, and resume.

You do not host this process when using the Agents API.

The environment

The environment is compute and a filesystem used when the agent must run commands, modify files, install approved packages, or create artifacts. It may be OpenAI-hosted or supplied by you.

An environment is optional. A research or application agent can operate through hosted tools, remote MCP, and function tools without shell access.

Your application server

Your service connects the agent to your product. It owns user authentication, product authorization, session-to-user mapping, webhook handling, business rules, function tool handlers, and the user interface.

Using a managed harness does not transfer these responsibilities to the model or to OpenAI.

The core objects

Agent configuration

The agent configuration selects a model and declares instructions, tools, MCP servers, skills, and optional multi-agent behavior. Reusable stored agent definitions can reduce repeated configuration, but changes should be versioned and evaluated.

Instructions should define the goal, source priorities, forbidden actions, completion checks, and escalation behavior. Security rules still belong in tool handlers and infrastructure.

Session

A session is a durable instance of an agent working over time. It retains configuration, conversation, items, turns, and saved work. Store the session ID beside your application’s conversation or job record.

Sending input to an idle session starts another turn with existing context. Sending a steering message while work is in progress can guide the active turn. Do not create a new session merely because the user added a follow-up.

Turn

A turn is a unit of work initiated by input. During one turn, the harness may make several model calls, run tools, create subagents, and write files. A completed turn means the turn reached completion; it does not prove every requested tool action succeeded. Inspect saved items and the produced result.

Item

Items are saved inputs and outputs: messages, tool calls, tool results, command activity, coordination actions, and other session records. They are useful for rendering history and recovering after a disconnected stream.

Environment and artifacts

Files live in the session environment. In an OpenAI-hosted environment, files written under /workspace/outputs are published as immutable artifacts at turn completion. Those artifact copies can be downloaded after the live sandbox expires.

An artifact is not the same thing as the mutable workspace file. Download required outputs before deleting a session.

What the managed Codex harness provides

The value of the Agents API is not a different chat response shape. The hosted harness owns recurring agent-runtime work:

  • model and tool iteration;
  • durable session continuity;
  • context compaction;
  • recovery from interrupted connections;
  • command execution through an attached environment;
  • loading instructions, skills, and plugins;
  • remote or environment-local MCP connections;
  • steering during a turn;
  • subagent creation and coordination;
  • saved events and items for inspection.

This can remove a large amount of orchestration code. It also means your application depends on a beta managed runtime with its own state, retention behavior, and regional constraints.

Choose an environment deliberately

Option 1: no environment

Choose no environment when the agent only needs model output and network-accessible tools. There is no command execution or session filesystem.

Good fits include research through approved search tools, triage through product function tools, or workflows that produce structured output directly in session items.

This is the smallest attack surface.

Option 2: OpenAI-hosted sandbox

OpenAI provisions an isolated workspace for the session. Configure required packages, initial files, plugins, and network policy. The harness can run commands directly in it.

Use it when you want managed compute and do not need access to a private network or a special machine image.

Each session has a separate workspace. According to the current docs, a hosted sandbox can be deleted after one hour without activity or keep-alives; that timeout is not configurable. Published artifacts survive environment expiration, but you should still copy required results into your own storage.

Option 3: self-hosted environment

You provide a laptop, container, virtual machine, job runner, or other compute. Inside it, codex exec-server connects outbound to the session using an environment ID, remote URL, and restricted environment key.

Use self-hosting for private networks, custom software, organization-managed isolation, or data that must remain in infrastructure you control during execution.

The harness remains OpenAI-hosted. Self-hosting the sandbox does not make the Agents API a self-hosted product, and current documentation says it does not make the API eligible for Zero Data Retention.

Your service must start, reconnect, monitor, and stop this compute. Each session gets its own environment ID and executor connection.

Sessions: create, observe, continue, recover, delete

A sound integration follows the session state rather than assuming an HTTP request equals one finished task.

Create

At session creation, provide:

  • model and instructions;
  • approved tools;
  • multi-agent settings if required;
  • environment type and configuration;
  • initial input when the selected mode requires it;
  • only the files and credentials needed for this job.

Persist the returned session ID before doing further work.

Observe

Use streaming events for live progress or webhooks for background state changes. Streams are not a durable queue and do not replay missed events. Open the event stream before sending follow-up input if early progress matters.

Watch for explicit turn completion, failure, or cancellation. An idle session alone is not proof of success.

Fulfill required actions

A session may pause because it needs:

  • a result from a function tool handled by your application;
  • a self-hosted environment to connect;
  • another supported external action.

Retrieve the current session, inspect required_actions, fulfill the exact pending action, and let the existing work continue. Do not submit the original task again unless recovery guidance says to do so.

Continue or steer

Reuse the session for follow-up work. Input sent while idle begins a new turn. Input sent while the agent is working can steer the active turn. Define product UI so users understand whether they are changing current work or requesting the next task.

Recover

If a stream disconnects, retrieve the session and saved items. The agent may still be running. Blindly retrying the create or input request can duplicate work and cost.

Delete

Delete sessions and artifacts when their product retention period ends. Save outputs first. Treat cleanup conflicts during active setup or execution as a bounded retry case, not a reason to abandon lifecycle management.

Tool types and where they run

OpenAI-hosted tools

The platform can provide tools such as web search. They have their own availability, pricing, data, and output behavior.

Function tools

Your application defines a schema, receives the requested call, applies product policy, executes trusted business logic, and returns the result. Use function tools for account-specific operations and internal APIs.

Function handlers must authenticate the session’s user context, authorize every target, validate arguments, and enforce idempotency. The fact that the harness requested a tool does not make the call authorized.

MCP tools

An MCP server publishes tool definitions and executes tool calls. A remote HTTP MCP server can be reached by OpenAI without a session environment. An executor MCP connection runs from the environment and can reach local software or private networks.

Restrict discoverable operations with allowed_tools. Mark a server required only when the turn should fail if initialization fails. Keep credentials out of reusable agent definitions, plugin archives, and model-readable logs.

Programmatic and environment capabilities

When an environment exists, Codex can use configured command and filesystem capabilities. This is powerful because generated actions become real process execution. Limit network destinations, mounted paths, operating-system identity, package sources, CPU, memory, and runtime.

Subagents

Multi-agent mode allows the coordinator to break work into independent tasks and delegate them. The harness supplies coordination operations to create, message, wait for, and interrupt subagents.

Enable it at session creation and set a concurrency cap. The current documentation states that the default maximum is six concurrent subagents, excluding the coordinator, but set an explicit value so a future default does not silently change your cost profile.

The coordinator and subagents share one environment filesystem. Creating a subagent does not create another sandbox. That makes file coordination possible, but it also creates race and overwrite risks. Assign separate paths or explicit file ownership.

Subagents inherit configured MCP capabilities, credentials, allowed MCP tools, web-search settings, and environment access. Current docs state that subagents do not support application function tools. Design delegation with that limit in mind.

Use subagents when work is genuinely independent: inspect three packages, research separate sources, or run distinct evaluations. Do not split a five-step dependent workflow merely to appear sophisticated. Delegation adds model calls, coordination items, and more ways to produce inconsistent conclusions.

Context and compaction

Long sessions accumulate user messages, model output, tool results, commands, and delegated work. Re-sending every byte forever raises latency and eventually exceeds a model’s context capacity.

The managed harness can summarize previous work to reduce active context. Compaction should preserve the information needed to continue, not every raw transcript line.

This has practical consequences:

  • keep authoritative artifacts and product facts outside the conversational summary;
  • design tool output with pagination and selection;
  • record key decisions in structured files or items before the context becomes crowded;
  • do not expect a compacted summary to act as an audit log;
  • inspect quality across long-session tests, not only first turns.

OpenAI also documents compaction for the Responses API, but do not assume its direct endpoint behavior is identical to harness-managed session compaction. Follow the Agents API session documentation for this runtime.

Plugins and skills

In the Agents API, a plugin packages reusable skills, MCP configuration, or both.

A plugin root contains a .codex-plugin/plugin.json manifest. Skills are instruction packages, commonly stored in folders containing SKILL.md. MCP settings can live in the plugin’s .mcp.json.

For a self-hosted environment, place the plugin in the environment and add its root to capability_directories. For an OpenAI-hosted environment, a plugin can be supplied as a ZIP in the environment configuration or reused through an environment template.

Keep three boundaries clear:

  • a skill teaches the harness how to perform a kind of work;
  • an MCP server exposes live capabilities;
  • a plugin packages those pieces for reuse.

A plugin is not a trusted security module. Review its instructions, executable dependencies, MCP destinations, requested credentials, and network needs. Do not put secrets inside the archive.

Setup flow without binding to one language

Step 1: confirm product fit

Use the API when you want OpenAI to run a durable Codex harness. If you want a direct response or a loop entirely inside your service, compare the alternatives later in this guide.

Step 2: create a scoped application key

The quickstart currently requires api.agents.read, api.agents.write, and api.responses.write for session operations and inference. Keep this application key outside the sandbox.

For a self-hosted executor, use a separate restricted environment key with unrelated permissions disabled. Rotate and revoke it independently.

Step 3: choose the execution boundary

Start with no environment if tools are enough. Use a hosted sandbox for managed files and commands. Choose self-hosted only when private connectivity or custom compute requires it.

Document filesystem roots, egress, package policy, secret injection, cleanup, and artifact retention.

Step 4: configure one focused agent

Give it a specific outcome, a small tool set, and explicit completion checks. Leave multi-agent mode off initially. Add an environment only if the task needs one.

Step 5: create one session and stream events

Send a representative task. Save the session ID. Consume events until an explicit turn outcome. Inspect items and any command or tool failures before accepting the result.

Step 6: test a follow-up and recovery

Send a follow-up to the same session. Disconnect a development stream, then retrieve state and items. A durable-agent product is not ready if it works only while one terminal remains connected.

Step 7: test required actions

Exercise a function tool or delayed self-hosted connection. Verify webhook signatures, queue work before acknowledging events, and make handlers idempotent.

Step 8: enforce cleanup and budgets

Set product-level limits for duration, turns, tool use, subagent concurrency, sandbox size, and model spending. Schedule deletion according to your retention policy.

A realistic platform workflow

Imagine a service that reviews an uploaded codebase and returns a migration plan.

  1. The product authenticates the user, authorizes repository access, and creates a job.
  2. It creates an Agents API session with a versioned agent definition and a hosted sandbox.
  3. The repository snapshot is uploaded without production secrets or .env files.
  4. The application opens the event stream and sends a task with explicit scope: analyze, do not publish or deploy.
  5. The harness inspects files, runs approved read-only commands, and writes findings to workspace files.
  6. If enabled, subagents inspect independent modules in assigned directories.
  7. The coordinator compares findings, runs validation commands, and writes /workspace/outputs/migration-plan.md.
  8. The turn completes. The application checks the turn outcome, lists artifacts, downloads the plan, scans it, and stores it with the job.
  9. The user asks a follow-up. The application reuses the session while the environment is available.
  10. At retention expiry, the product deletes artifacts and the session.

At no point should “the agent finished” substitute for checking the turn, artifact existence, command results, and product authorization.

Costs and observability

Pricing has several parts:

  • every root-agent model call at the selected model’s API rates;
  • every subagent model call;
  • OpenAI tool charges;
  • OpenAI-hosted sandbox container charges;
  • third-party MCP or service charges;
  • your self-hosted compute and storage.

One user task can create many calls. Include retries and delegation when estimating unit economics.

Session and turn usage fields are currently described as best-effort. They may be null, may update as accounting arrives, and are not the final bill. Some cache-related charges cannot be reconstructed from those fields alone.

Use platform traces and session history to inspect model calls, tools, commands, and subagents. In your own product, record session ID, user/job ID, outcome, elapsed time, tool errors, artifact status, and business success. Do not copy sensitive raw prompts into a second logging system without a retention reason.

Limits and beta constraints

Current documentation states:

  • the API is beta and uses the agents=v1 beta header;
  • Agents API data residency is United States only;
  • Zero Data Retention is not supported, including with a self-hosted sandbox;
  • hosted sandboxes can expire after one hour without activity or keep-alives;
  • session creation accepts up to 50 files;
  • inline files are limited to 5 MiB each and 10 MiB total before base64 encoding;
  • files copied from the Files API are limited to 50 MiB each;
  • one published artifact is limited to 200 MiB;
  • outputs published together are limited to 500 MiB;
  • artifact downloads are one file per request.

These values are especially likely to change during beta. Do not duplicate them as hard-coded business truth without checking the live reference and handling API errors.

Security and data handling

Keep application and environment credentials separate

The broad application key stays in your trusted service. A self-hosted executor receives only its restricted environment key. Tools obtain scoped credentials through trusted handlers or proxies.

Constrain sandbox egress

Allow only required destinations. An agent that can read source files and make arbitrary outbound requests has an exfiltration path. Review redirects, DNS behavior, package registries, and proxy policy.

Strip secrets before upload

Do not rely on instructions like “ignore secret files.” Build an allowlisted snapshot, scan it, and reject known credential patterns. Mount only required paths.

Authorize tool calls at execution

Bind each session to a product identity. Check tenant, resource, action, and current permissions inside every function handler. Validate paths and arguments. Use idempotency keys for side effects.

Verify webhooks

Validate signatures with a separately stored webhook secret. Queue durable work before returning success. Expect duplicate and out-of-order delivery where applicable, and retrieve current session state before acting.

Treat plugins and MCP servers as dependencies

Pin reviewed versions, limit allowed tools, isolate credentials, and monitor destination changes. Tool descriptions and remote output are untrusted content.

Preserve a human boundary

The Agents API can run long tasks, but your product still decides what must pause. Publication, deployment, deletion, purchases, external messages, and permission changes should require explicit product controls.

Agents API vs Agents SDK vs Responses API

These are different runtime choices, not newer and older names for one feature.

Choose the Agents API when

  • you want an OpenAI-managed Codex harness;
  • work needs durable hosted sessions and recovery;
  • the agent must operate in hosted or connected execution environments;
  • managed compaction, plugin loading, and subagent coordination fit the job;
  • the beta’s data residency and retention properties are acceptable.

Choose the Agents SDK when

  • you want the agent runner inside your application;
  • your service should own the loop and runtime process;
  • built-in handoffs, guardrails, tracing, sessions, and resumable approvals help;
  • you need TypeScript or Python SDK patterns rather than a hosted Codex session.

The SDK calls models and tools, but your application runs the agent lifecycle. It is not the same hosted harness as the Agents API.

Choose the Responses API when

  • you want direct control of model responses and output items;
  • you are building a custom loop or a smaller model-powered feature;
  • you want to choose your own state, branching, and tool routing;
  • an agent runtime would add more machinery than the task needs.

With Responses, your code owns repeated calls and orchestration. Conversation objects or previous_response_id can preserve state, but they do not turn the endpoint into the managed Codex harness.

A practical decision

Start from ownership:

  • Own each model turn and loop: Responses API.
  • Run a library-managed loop in your service: Agents SDK.
  • Use an OpenAI-managed Codex harness and durable session: Agents API.

Then check data controls, environment needs, language support, latency, cost, and operational skill.

For provider-level tradeoffs beyond these OpenAI runtime choices, see OpenAI vs Anthropic APIs.

Common mistakes

Assuming session completion means every command worked. Inspect items, tool results, and artifacts.

Giving the sandbox the application key. Use separate restricted environment credentials.

Enabling subagents before measuring one agent. Delegation adds cost and coordination risk.

Treating a stream as durable state. Recover from the session and saved items.

Uploading an entire repository including secrets. Build a filtered snapshot.

Leaving sessions forever. Define retention and deletion.

Calling the Agents SDK the Agents API. One runs in your application; the other is a hosted harness.

Ignoring beta and regional limits. Validate them before architecture commitment.

FAQ

Is the Agents API a replacement for the Assistants API?

Do not infer a migration path from similar names. The Agents API is documented as a managed Codex harness. Review OpenAI’s current migration guidance and your existing API’s lifecycle before changing production systems.

Must every session have a sandbox?

No. Use environment.type: "none" when remote tools and model output are sufficient.

Can a self-hosted environment keep all data away from OpenAI?

No. The managed harness and model still operate through OpenAI’s service. Current docs also state that self-hosting does not make the Agents API ZDR-eligible.

Are subagents separate sandboxes?

No. The coordinator and subagents share the session environment and filesystem.

Can I use MCP?

Yes. Remote HTTP MCP can be reached by OpenAI, while executor MCP can run from the session environment for local or private access. Scope tools and credentials carefully.

How should I handle missed streaming events?

Retrieve the session and saved items. Do not assume that closing the stream cancelled the task, and do not blindly resend input.

Is usage data the invoice?

No. Current session and turn usage is best-effort and may be incomplete or revised. Use billing data for final charges.

Takeaways

The OpenAI Agents API places a managed Codex harness between your application and an optional execution environment. Sessions preserve work; turns perform bounded jobs; tools connect external capabilities; compaction controls growing context; plugins package skills and MCP; and subagents handle selected parallel work.

The API reduces runtime code, but it does not own your product’s authorization, retention policy, cost controls, artifact checks, or approval UX. Begin with one focused agent, the smallest environment, explicit lifecycle handling, and a recovery test.

Because the service is beta, verify all limits and data controls against current official documentation before shipping.

Continue learning

Official sources and further reading