The OpenAI Agents API is a managed service, in public beta since September 10, 2026, that runs your agent on OpenAI's Codex harness. OpenAI keeps the session state, compacts context, orchestrates subagents and recovers from failures, and your application supplies tools, instructions and an optional sandbox. This OpenAI Agents API tutorial explains how it differs from the Responses API and the open-source Agents SDK, then builds a working agent in Python with a function tool, a follow-up turn, MCP and a hosted sandbox. It also covers what you pay and the beta limits that matter in production.

All endpoints, parameters and prices below come from OpenAI's announcement, the Agents API docs, the API changelog and the openai Python SDK 3.59.0, checked on November 26, 2026. This is a beta API, so the details below can change.

What the OpenAI Agents API actually is

OpenAI describes it as "build and run cloud agents with the Codex harness, fully managed by OpenAI." The harness is the agent loop that powers Codex: it decides when to call tools, runs code in a sandbox, summarizes old context when the window fills up, splits work across subagents and resumes after interruptions. Before this API, you either wrote that loop yourself on top of the Responses API or ran it inside your own process with the Agents SDK.

The docs organize everything around four concepts:

  • Agent: model, instructions, tools and MCP servers. You can pass it inline per session or save it once with client.beta.agents.create(...) and reuse it by agent_id.
  • Environment: an optional sandbox. The three types are openai_hosted (OpenAI provisions it), self_hosted (your machine or VPC) and none (no sandbox at all).
  • Session: a durable agent instance. It keeps history and state between turns, so you send new input instead of resending the whole conversation.
  • Events and items: what you send in (messages, tool results, cancellations) and what comes out (streamed events, saved messages, tool calls, artifacts).

The REST surface is POST https://api.openai.com/v1/agents/sessions with the header OpenAI-Beta: agents=v1. The official SDKs add that header automatically and expose everything under client.beta.agents.

Timeline of the beta so far

Date (2026) Change
Sep 10 Agents API released in public beta
Sep 29 Computer use added to the Agents API (announced at DevDay)
Oct 2 Item history for individual root-agent turns
Oct 9 Pre-warmed hosted sandboxes; hosted sandbox compute billed only during active turns
Oct 16 Ultrafast mode via agent.service_tier; Artifact SDK and document skills in hosted sandboxes
Oct 23 Scheduled automations (one-time or recurring tasks)
Oct 30 Update tools on an existing session; opt-in auto_review for tool and permission requests; background context compaction by default

All of these come from the changelog. The DevDay 2026 recap dated September 29 lists "Agents API with Computer use" among the developer announcements.

Agents API vs Responses API vs Agents SDK

OpenAI now ships three ways to build an agent, and its own agents guide compares them. Here is that comparison in practical terms:

Agents API Agents SDK (open source) Responses API
Where the loop runs OpenAI runs the managed Codex harness Inside your application process Your code, one model call at a time
State between turns Saved session config, turns and items on OpenAI Your storage or SDK sessions Manual history, response chaining or Conversations
Sandbox OpenAI-hosted, self-hosted or none Your runtime plus sandbox integrations Your own environment
Integration effort (per OpenAI) Low Medium High
Context compaction, subagents Built in You configure it You build it
Zero Data Retention Not supported Depends on the APIs it calls Available per endpoint
Status Public beta GA library (openai-agents 0.26.0 on PyPI, Nov 24, 2026) GA

Pick the Agents API for long-running, tool-heavy tasks where you would otherwise build durable state, retries, compaction and sandbox plumbing yourself, such as research agents, coding agents, incident triage and document review. Pick the Agents SDK when you need the loop inside your own infrastructure, custom approval flows, or non-OpenAI models. Pick the Responses API for single requests, tight latency budgets, or when you need ZDR. If you are still on the Assistants API, our Assistants API to Responses API migration guide covers that move. The Agents API is a separate product, not the Assistants replacement.

OpenAI Agents API tutorial: your first agent in Python

Prerequisites

Create an application API key in your OpenAI Platform project. The quickstart says it needs api.agents.read and api.agents.write for session operations plus api.responses.write for model inference. Then install the SDK:

pip install --upgrade openai
export OPENAI_API_KEY="your-api-key"

Keep the key outside any sandbox the agent can read. Code the agent writes can read environment variables in its own sandbox.

Step 1: an agent with a function tool

This agent answers order-status questions by calling a Python function in your application. It needs no sandbox, so the environment type is none. The SDK's tool_handlers argument maps a function name to a callable. When the agent requests that tool, the SDK runs your function and submits the result for you.

import json
from openai import OpenAI

ORDERS = {
    "A-1001": {"status": "shipped", "carrier": "UPS", "eta": "2026-11-28"},
    "A-1002": {"status": "processing", "carrier": None, "eta": None},
}

def get_order(args: dict) -> str:
    """Called by the SDK when the agent requests get_order."""
    order = ORDERS.get(args["order_id"])
    return json.dumps(order if order else {"error": "order not found"})

GET_ORDER_TOOL = {
    "type": "function",
    "name": "get_order",
    "description": "Look up an order's shipping status by order ID.",
    "parameters": {
        "type": "object",
        "properties": {"order_id": {"type": "string"}},
        "required": ["order_id"],
        "additionalProperties": False,
    },
}

client = OpenAI()  # reads OPENAI_API_KEY

with client.beta.agents.sessions.create(
    agent={
        "model": "gpt-6-astra",
        "instructions": "You are a support agent. Use get_order for order questions. Be brief.",
        "tools": [GET_ORDER_TOOL],
    },
    environment={"type": "none"},  # no sandbox needed for this agent
    input="Where are orders A-1001 and A-1002?",
    stream=True,
    tool_handlers={"get_order": get_order},
).with_result_collection() as stream:
    for event in stream:
        print(event.type)
    result = stream.get_final_result()

print(result.output_text)
session_id = result.session_id

Notes on what happens here:

  • sessions.create(..., stream=True) creates the session, submits the first task and streams events. The .with_result_collection() call, taken from the official quickstart, keeps the final messages so get_final_result() can return output_text and session_id.
  • The SDK runs registered tool handlers one after another, during iteration. If a handler raises, the SDK sends a generic failure result without your exception text, so log errors yourself, for example with the on_tool_error callback.
  • Function results must stay under 4 MiB. Serialize JSON to a string, as get_order does.
  • The model ID gpt-6-astra is the one OpenAI uses in every Agents API example. It is also expensive (see pricing below). Test cheaper models such as gpt-6.2-sol on your own task before you settle on one.

Step 2: continue the same session

The session keeps its history server-side. To send a follow-up, use sessions.stream, which subscribes to events before it submits your input so you do not miss early events:

# Same client, session_id and get_order as in step 1
with client.beta.agents.sessions.stream(
    session_id,
    input="Draft a one-line customer email for A-1002.",
    tool_handlers={"get_order": get_order},
).with_result_collection() as stream:
    followup = stream.get_final_result()
print(followup.output_text)

client.beta.agents.sessions.delete(session_id)  # also requests sandbox cleanup

sessions.stream requires an idle session. If a turn is still running, follow it with sessions.events.stream, or steer it by sending another message with sessions.events.create using the agent.session.input.message event type. The sessions guide also shows agent.session.input.cancel for stopping an active turn, and recommends an idempotency_key per message so a retried submission is not applied twice.

Step 3: know when a turn actually succeeded

The quickstart is explicit that an agent.session.turn.completed event does not guarantee every tool succeeded, and agent.session.idle by itself does not mean success. Treat events ending in turn.failed, turn.cancelled or session.failed as failures. If your stream disconnects, retrieve the session and its saved items (sessions.retrieve, sessions.items.list) and check session.required_actions for pending tool calls before you retry anything with side effects. Store function results durably by session, turn and call ID, so a retry can resend the saved result instead of charging a card twice.

Adding MCP servers, web search and a hosted sandbox

The overview page's example combines a docs MCP server, web search, programmatic tool calling and subagents. Here is the same configuration with an OpenAI-hosted sandbox and restricted network access:

session = client.beta.agents.sessions.create(
    agent={
        "model": "gpt-6-astra",
        "instructions": "Answer technical questions accurately. Delegate independent research to subagents.",
        "tools": [
            {"type": "programmatic_tool_calling"},
            {
                "type": "mcp",
                "server_label": "openai_docs",
                "transport": {"type": "http", "server_url": "https://developers.openai.com/mcp"},
            },
            {"type": "web_search"},
        ],
        "multi_agent": {"enabled": True, "max_concurrent_subagents": 4},
    },
    environment={
        "type": "openai_hosted",
        "container_size": "medium",
        "network": {"access": "restricted", "allowed_domains": ["pypi.org", "files.pythonhosted.org"]},
    },
    input="Compare the MCP setup steps in the docs with what changed recently, and summarize.",
)
print(session.id)

What the Agents API's "MCP connections" guide adds:

  • Where the connection runs. HTTP MCP servers connect from OpenAI by default (connection_origin: "service"), so the server must be reachable from the internet. Set connection_origin: "environment" or use a stdio transport for servers inside your private network. Both of those need a sandbox.
  • Authentication. Pass transport.authorization or transport.headers for one session (the API encrypts them and leaves them out of the returned session), or store credentials in a vault and attach it with vault_ids. Vault credentials only apply to connections made from OpenAI.
  • Scope. Use allowed_tools to limit which tools the agent can see. Set required: true if the turn should fail when the server cannot start.

If you are writing your own server, our guide to building an MCP server and the summary of the MCP 2026-07-28 spec changes cover the protocol side.

Hosted sandbox options

The OpenAI-hosted sandbox page lists three sizes: small (1 vCPU, 1 GB), medium (2 vCPU, 4 GB, the default) and large (4 vCPU, 16 GB). Network access is enabled by default; disabled blocks everything, and restricted allows 1 to 100 exact host names in allowed_domains, with no wildcards. Hosted stdio MCP servers currently need enabled. A sandbox can be deleted after an hour without activity or keep-alives, and that timeout is not configurable, so save outputs through the files and artifacts APIs.

For a self-hosted sandbox, OpenAI documents integrations with providers including Cloudflare, Daytona, E2B, Modal and Vercel, plus AWS Lambda MicroVMs and Databricks.

Computer use

Since September 29, agents can work in an OpenAI-hosted browser through the computer use tool (documented under the Agents API tools section). Your application handles website access approvals and sign-in. For how that compares with earlier approaches, see our look at OpenAI Operator vs Anthropic computer use.

OpenAI Agents API pricing

OpenAI's announcement says: "There are no additional fees for using the Agents API." You pay for three things:

  1. Model tokens at the chosen model's normal API rates.
  2. Built-in tools at their standard rates. Web search, for example, is listed at $10 per 1,000 calls plus search content tokens at model rates.
  3. OpenAI-hosted sandboxes at standard container rates. The pricing page lists containers at $0.03 (1 GB), $0.12 (4 GB), $0.48 (16 GB) and $1.92 (64 GB) per 20-minute session, with eligible sessions billed by the minute and a 5-minute minimum. Since October 9, hosted sandbox compute is billed only during active turns.

Current short-context standard rates per 1M tokens from the pricing page:

Model Input Cached input Output
gpt-6-astra (used in Agents API examples) $10.00 $1.00 $50.00
gpt-6.2-astra (current flagship) $8.00 $0.40 $40.00
gpt-6.2-sol $2.00 $0.10 $10.00
gpt-6.1-sol $2.00 $0.10 $10.00
gpt-6.1-terra $1.00 $0.05 $5.00
gpt-6-luna $0.10 $0.01 $0.50

Long-context prompts cost more. For GPT-6.1 Sol, OpenAI's launch note puts the short-context limit at 272K input tokens. A rough way to estimate one agent turn: a turn that reads 200K tokens (150K of them cached), writes 20K output tokens and uses a medium sandbox for 10 minutes on gpt-6.2-sol costs about 50K × $2 + 150K × $0.10 + 20K × $10 per million tokens, which is $0.10 + $0.015 + $0.20 = $0.315 in tokens. Add sandbox minutes on top. On gpt-6-astra, the same token mix is $0.50 + $0.15 + $1.00 = $1.65. Agents re-read their context on every model call, so caching matters a lot. Our prompt caching guide explains how to keep prefixes stable. Two more cost controls exist in the SDK's session parameters, spend_control and prompt_cache_options. The changelog also notes that background compaction (the default since October 30) may increase token usage.

Beta limits and gotchas to plan around

  • No Zero Data Retention. The overview states the Agents API does not support ZDR, and using a self-hosted sandbox does not change that. Session state is retained until you delete it.
  • US-only data residency. The docs say data residency is currently supported only in the United States. That rules it out for some EU workloads today.
  • One writer per session. The SDK's sessions.stream helper documents that only one caller may submit input to a session while it runs, because the input endpoint does not return a turn ID for correlating concurrent writers. Serialize writes per session in your app.
  • Closing a stream does not stop the agent. To stop work, send a cancel event, or delete the session.
  • Tool updates replace the whole list. Since October 30 you can update tools on a live session, but the update replaces the full list. Function and MCP changes apply on the next model call, built-in tools by the next turn. You cannot change instructions or multi_agent on an existing session; create a new one.
  • Auto review costs tokens. review: "auto_review" lets a model approve or deny supported tool and permission requests, and that review is billed as additional tokens.
  • Debug the raw events. When something looks wrong, print event.to_json() and paste it into a JSON formatter to read the nested payloads.

Frequently Asked Questions

Is the OpenAI Agents API the same as the Agents SDK?

No. The Agents SDK (openai-agents on PyPI) is an open-source library whose runner executes the agent loop inside your application. The Agents API is a hosted service where OpenAI runs the Codex harness and stores session state. You can use either, and OpenAI's docs compare them side by side.

How much does the OpenAI Agents API cost?

There is no separate fee for the API itself. You pay the selected model's token rates, standard rates for built-in tools such as web search, and container rates for OpenAI-hosted sandboxes, which are billed only during active turns since October 9, 2026.

Which models work with the Agents API?

OpenAI's Agents API examples use gpt-6-astra. The docs do not publish a single list of supported models on the overview page, and session updates fail if the chosen model does not support the requested settings. Test your target model, for example gpt-6.2-sol, before you commit to it.

Does the Agents API support MCP?

Yes. You can connect HTTP MCP servers from OpenAI's side, or from your sandbox for private networks, and run stdio MCP servers inside a sandbox. Credentials can be passed per session or stored in a vault and attached with vault_ids.

Can I run the agent's sandbox in my own cloud?

Yes. Set environment.type to self_hosted and connect your own machine or VPC, or use a supported provider integration. Session state and data residency rules still apply, because the harness itself runs on OpenAI.

Is the Agents API production ready?

It is a public beta as of November 2026. It has no ZDR, only US data residency, and OpenAI has been changing it every few weeks. It is reasonable for internal tools and non-sensitive workloads. For regulated data, wait for GA terms or use the Responses API with your own loop.

Conclusion

The OpenAI Agents API takes the hardest parts of running agents off your plate: durable sessions, context compaction, subagents, sandboxes and recovery. You pay only for tokens, tools and sandbox minutes. A working agent is about 40 lines of Python with client.beta.agents.sessions.create, a function tool and tool_handlers. Your remaining jobs are choosing a model whose cost per task makes sense, keeping tool results idempotent, and checking that the beta's data rules (no ZDR, US-only residency) fit your workload. Start with environment={"type": "none"} and function tools, add MCP and a hosted sandbox when the task needs them, and keep the Responses API or Agents SDK for cases where you need the loop in your own hands.