OpenAI shipped the Agents API into public beta on September 10, 2026, and it changes the default way developers wire up autonomous coding and research agents. Instead of stitching together the Responses API, a custom orchestration loop, and a sandbox provider, you now call a single managed endpoint that runs the same Codex harness OpenAI uses internally. Sessions, context compaction, multi-step recovery, and subagent delegation are handled server-side. This tutorial walks through account setup, the four core concepts, environment choices, streaming, tool calling, multi-agent delegation, pricing, and a complete working project, plus the pitfalls and errors you’ll actually hit along the way.
Don't miss new tech stories on Google
Add Tech Insider once in the Google app and our stories appear in your news suggestions.
What Is the OpenAI Agents API?
The OpenAI Agents API gives applications direct access to the Codex harness through a managed, hosted endpoint. According to OpenAI’s own developer documentation, the API handles “sessions, orchestration, context compaction, and recovery” while your application supplies tools and picks an execution environment. That’s a meaningful shift from the do-it-yourself agent loops most teams built on top of the Responses API over the past year.
Under the hood, the Agents API is organized around four building blocks documented at developers.openai.com/api/docs: agents (the model, instructions, and tools), environments (optional sandboxes), sessions (durable work instances), and events/items (the live and saved records of what happened). The showcase apps OpenAI has published alongside the beta — an incident-response bot, a Slack investigator, a read-only SQL data analyst, and a GitHub issue investigator — all use this same four-part shape, just with different tool configurations and environment choices plugged in.
The release landed alongside a related but separate milestone: the Assistants API, OpenAI’s original stateful agent primitive, sunset on August 26, 2026, roughly two weeks before the Agents API opened to all developers. OpenAI’s platform changelog frames the Agents API launch plainly: “Released the Agents API in public beta. Build agents with a managed Codex harness while OpenAI handles session orchestration, context compaction, and recovery.” There’s no separate platform fee for using it — you pay standard token rates for whichever model you select, plus standard rates for any tools, MCP connections, or hosted sandboxes the agent touches, all listed on OpenAI’s pricing page.
Agents built through this API default to gpt-6-astra, OpenAI’s flagship model that shipped in early September 2026 and is described in the platform’s own model guidance as “our most capable model, built for the hardest end-to-end work.” You can swap in a cheaper model like gpt-5.6-terra or gpt-5.6-luna for lower-stakes agent tasks, which matters once you start comparing per-session costs later in this guide.
Agents API vs. Responses API vs. Assistants API vs. Agents SDK
OpenAI now ships four different surfaces that all touch “agents,” and picking the wrong one wastes a week of integration work. The Assistants API is gone. The Responses API is the general-purpose foundation for stateless and lightly-stateful model calls. The Agents API is the new managed orchestration layer for long-running, multi-step, tool-using agents. The Agents SDK is an open-source Python/TypeScript framework for teams that want to run their own orchestration loop against the Responses API instead of paying for OpenAI’s managed harness.
| Surface | Status (Sept 2026) | State management | Best for |
|---|---|---|---|
| Assistants API | Retired Aug 26, 2026 | Hosted threads/runs | Nothing — migrate off it |
| Responses API | Recommended foundation | Server-side via previous_response_id / Conversations API | Single-turn or lightly-stateful model calls, custom orchestration |
| Agents API | Public beta since Sept 10, 2026 | Durable sessions, managed by OpenAI | Long-running agents that need sandboxes, subagents, and recovery |
| Agents SDK | Open-source, actively maintained | You manage state in your own process | Teams that want full control of the orchestration loop |
If you’ve been assembling agent behavior yourself with LangGraph, LangChain, or CrewAI on top of the Responses API, the Agents API doesn’t replace those frameworks outright, but it does absorb a chunk of what they exist to do: session persistence, context-window management, and delegating subtasks to secondary agents. The practical tradeoff is control versus plumbing. Frameworks give you full visibility into every orchestration decision; the Agents API asks you to trust OpenAI’s harness in exchange for not writing that harness yourself.
There’s also a separate, lighter-weight option worth knowing about: the open-source openai-agents-python SDK. It runs your own orchestration loop against the Responses API rather than handing session management to OpenAI’s hosted harness. Pick the SDK when you need to inspect or override every orchestration decision yourself; pick the hosted Agents API when you’d rather not maintain that loop at all. Both are documented from the same entry point in OpenAI’s agents guide, which is a useful page to bookmark since it gets updated as the beta evolves.
Prerequisites: Accounts, SDKs, and Versions You’ll Need
Before starting, get these in place. You’ll need an OpenAI Platform account with billing enabled, since the Agents API is not available on free-tier keys. You’ll need a project-scoped API key — OpenAI’s quickstart explicitly recommends against reusing an org-wide key for agent workloads. Grant the key api.agents.read and api.agents.write permissions for session operations, plus api.responses.write for the underlying model calls the harness makes on your behalf.
- An OpenAI Platform account with an active payment method attached
- The latest
openaiPython package (runpip install --upgrade openai— you need a build from September 2026 or later to seeclient.beta.agents) - Node.js 18 or later if you’re using the JavaScript SDK (
npm install openai) - A terminal with cURL if you want to test the raw HTTP endpoints before writing any application code
- Business or Enterprise workspace admins: agent access may need to be enabled at the org level before individual developers can create sessions
The Agents API also currently supports data residency only in the United States, and it does not support Zero Data Retention, even if you connect a self-hosted sandbox. If your organization has strict data-residency or ZDR requirements, confirm this against OpenAI’s data controls documentation before building anything customer-facing on top of it.
If You’re Still on the Assistants API, Read This First
The Assistants API endpoints stopped working on August 26, 2026 — they now return errors instead of running your threads and runs. If your app hasn’t migrated yet, you have two real destinations, not one. For simple, mostly-stateless assistant behavior, move to the Responses API, which OpenAI says has folded in “the best parts of Assistants into Responses, including code interpreter and persistent conversations,” as OpenAI put it in its community deprecation notice. For assistants that ran multi-step, tool-heavy, long-running work — the kind that needed a code interpreter sandbox and could take minutes to finish — the Agents API is the closer match, since it inherits that sandboxed, multi-turn shape natively instead of requiring you to rebuild it on top of a stateless endpoint.
Don’t try to map your old Assistants API code onto the new APIs field-by-field. Threads and runs don’t correspond one-to-one with sessions and turns, and the tool-calling shape changed enough between the two that a mechanical port will produce subtle bugs. Treat this as a rewrite of your orchestration layer using the new primitives, not a renaming exercise.
Step 1: Create a Scoped API Key
Log into platform.openai.com, open your project settings, and generate a new API key. As of September 10, 2026, OpenAI added the ability to set expiration dates on project API keys, and administrators can enforce a maximum key lifetime at the org or project level. For an agent that will run unattended in a sandbox, set a short expiration and rotate the key rather than issuing a long-lived credential. Export it in your shell before running any of the examples below:
export OPENAI_API_KEY="your-api-key"
Keep this key outside the agent’s own sandbox. If the agent can read its own credential, a prompt injection through a tool result or a fetched web page could exfiltrate it. Every request to the Agents API also needs an OpenAI-Beta: agents=v1 header — the official SDKs add it automatically, but you must set it by hand if you’re calling the REST endpoints directly with cURL.
Step 2: Install the SDK for Your Language
OpenAI’s official SDKs cover Python, JavaScript/TypeScript, Go, Java, and Ruby, all exposing the same beta.agents namespace. Pick whichever matches your stack:
# Python
pip install --upgrade openai
# JavaScript / Node.js
npm install openai
# Go
go mod init agents-quickstart
go get github.com/openai/openai-go/v3@latest
# Ruby
gem install openai
If you’d rather skip the SDK entirely and talk to the REST API directly, cURL works fine for prototyping — every code example in this tutorial has a raw HTTP equivalent, since the Agents API is a plain JSON-over-HTTPS service at https://api.openai.com/v1/agents/sessions.
Step 3: Understand the Four Core Concepts
Everything in the Agents API builds on four primitives, and understanding them up front saves you from re-reading the docs three times later.
- Agent — the model, instructions, tools, and MCP servers available to a given run
- Environment — the optional sandbox or compute where the agent accesses files and runs commands
- Session — a durable instance of an agent that works on tasks and responds to input over time
- Events and items — events are the live stream of what’s happening right now; items are the saved messages and tool calls you can retrieve later
A session moves through turns. A turn is one cycle of work: a message sent to an idle session starts a new turn, while a message sent during an active turn steers that turn instead of queuing behind it. Turns run asynchronously, and your application follows progress either by keeping a stream open or by registering a webhook.
Step 4: Choose an Environment for Your Agent
The environment setting decides whether your agent gets compute at all, and it’s the single biggest architectural decision in this whole setup. There are three options.
| Environment type | Who manages compute | What the agent can do | Typical use case |
|---|---|---|---|
none | Nobody — no sandbox exists | Call remote MCP tools and your function tools only; no built-in shell or file access | Q&A agents, agents that only call external APIs |
openai_hosted | OpenAI | Run shell commands, edit files, execute code, produce artifacts | Coding assistants, data analysis agents, most quickstart use cases |
self_hosted | You | Same as hosted, but on your own infrastructure, private network, or custom image | Agents that need internal data access, custom dependencies, or compliance controls |
With self_hosted, your code starts the compute and connects an executor to the session; OpenAI’s harness then sends that executor commands to run, but you own provisioning, reconnection, and shutdown. That’s real infrastructure work, so most teams should start with openai_hosted and only move to a self-hosted sandbox once they hit a concrete limitation — usually network access to internal systems, or a need for a specific runtime image the hosted sandboxes don’t offer.
Step 5: Create and Stream Your First Agent Session
This is the canonical quickstart from OpenAI’s own docs: an agent that writes a small Python script, runs it inside an OpenAI-hosted sandbox, and reports the output back to you.
from openai import OpenAI
with OpenAI() as client:
with client.beta.agents.sessions.create(
agent={
"model": "gpt-6-astra",
"instructions": "Write clean code, run it, and report the actual output.",
},
environment={"type": "openai_hosted"},
input="Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
stream=True,
) as events:
for event in events:
print(event.to_json(indent=None), flush=True)
The equivalent raw HTTP call, if you want to see exactly what’s crossing the wire:
curl --no-buffer --fail-with-body https://api.openai.com/v1/agents/sessions \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"agent": {
"model": "gpt-6-astra",
"instructions": "Write clean code, run it, and report the actual output."
},
"environment": { "type": "openai_hosted" },
"input": "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
"stream": true
}'
Run the Python version and you’ll see a stream of JSON events scroll past as the sandbox spins up, the model reasons about the task, a shell command executes, and the agent reports what it found. Save the session_id from the first event — you’ll need it for every follow-up request.
Step 6: Handle Turn Outcomes and Recover From Disconnects
A completed stream doesn’t automatically mean success. Watch for three terminal event types: agent.session.turn.completed, agent.session.turn.failed, and agent.session.turn.cancelled. Critically, an agent.session.idle event on its own does not confirm the turn succeeded — you have to inspect the actual output, because a completed turn doesn’t guarantee every tool call inside it succeeded.
Streams also don’t replay missed events. If your connection drops mid-turn, don’t just retry the original request — that risks starting a duplicate turn. Instead, retrieve the session and its saved items to see what actually happened before deciding whether to resend anything:
def list_items(client: OpenAI, session_id: str):
return client.beta.agents.sessions.items.list(session_id, order="asc", limit=100)
Events show live progress; items are the durable record — the saved messages, tool calls, and completed responses tied to that session. Build your recovery logic around items, not around assuming the stream you lost will somehow come back.
Step 7: Send Follow-Up Messages and Steer a Running Agent
Sessions are durable, so you don’t rebuild the conversation on every call the way you would with a stateless chat completion. Send a new agent.session.input.message event to the same session ID. If the session is idle, that starts a fresh turn; if the agent is actively working, the same message steers the turn already in progress instead of queuing behind it.
def send_message(client: OpenAI, session_id: str, text: str) -> None:
client.beta.agents.sessions.events.create(
session_id,
events=[
{
"type": "agent.session.input.message",
"input": [
{
"role": "user",
"content": [{"type": "input_text", "text": text}],
}
],
}
],
)
Subscribe to the session’s event stream before sending the follow-up message, not after — otherwise you’ll miss the earliest events the agent emits in response, including the acknowledgment that it received your steering input at all.
Step 8: Add Tools — Function Calling, Web Search, and MCP Servers
Agents get more useful once they can reach outside their own sandbox. The Agents API supports the same tool categories as the Responses API — function tools you host yourself, OpenAI’s built-in web search, and Model Context Protocol (MCP) server connections — plus a native programmatic_tool_calling mode that lets the harness call tools without a full model round-trip for every invocation.
session = client.beta.agents.sessions.create(
agent={
"model": "gpt-6-astra",
"instructions": "Use the OpenAI documentation MCP and web search to answer technical questions accurately.",
"tools": [
{"type": "programmatic_tool_calling"},
{
"type": "mcp",
"server_label": "openai_docs",
"transport": {
"type": "http",
"server_url": "https://developers.openai.com/mcp",
},
},
{"type": "web_search"},
],
},
environment={"type": "none"},
input="Research how to connect an MCP server to an OpenAI agent and summarize the setup.",
)
Notice the environment is set to none here — this agent only needs to call remote tools, so it doesn’t need a sandbox at all, which keeps the run cheaper. Function tools work differently from MCP connections: your application receives each function call as an event, executes it locally, and returns the result. If your function-tool handler is offline or slow, the agent can sit there waiting indefinitely for a result that never arrives, so treat that handler with the same uptime expectations as any other production webhook.
Step 9: Turn On Multi-Agent Delegation
The Agents API can break a task into subtasks and hand them off to subagents running concurrently, which is one of the more genuinely new capabilities compared with building an agent loop by hand. Enable it with a multi_agent block on the agent config:
session = client.beta.agents.sessions.create(
agent={
"model": "gpt-6-astra",
"instructions": "Delegate independent research tasks to subagents when useful.",
"tools": [{"type": "web_search"}],
"multi_agent": {"enabled": True, "max_concurrent_subagents": 4},
},
environment={"type": "self_hosted", "workspace_directory": "/workspace"},
input="Compare the last three release notes for this library and summarize what changed.",
)
OpenAI’s own example for this feature is comparing release notes across versions and combining subagent findings into one answer — a task that’s naturally parallelizable, which is exactly the shape of workload where subagent delegation earns back its added token cost. Don’t reach for multi-agent mode on simple, single-threaded tasks; running four subagents to answer a question one agent could handle just multiplies your bill.
Step 10: Retrieve Items, Cancel Turns, and Clean Up Sessions
Long-running agents occasionally need to be stopped mid-task — a user cancels a request, a cost cap gets hit, or you detect the agent going down the wrong path. Cancel the active turn without destroying the session or its prior work:
def cancel_turn(client: OpenAI, session_id: str) -> None:
client.beta.agents.sessions.events.create(
session_id, events=[{"type": "agent.session.input.cancel"}]
)
When you’re finished with a session entirely, delete it — but save any artifacts you need first, since deletion removes them:
def delete_session(client: OpenAI, session_id: str):
return client.beta.agents.sessions.delete(session_id)
There’s no automatic session expiry mentioned in OpenAI’s documentation for the Agents API beta, so if you’re spinning up sessions programmatically — one per support ticket, one per pull request, whatever your use case is — you’re responsible for deleting them once the work is done. Leaving thousands of idle sessions around won’t necessarily cost you tokens, but it will make your session list unmanageable and complicate any auditing you need to do later.
Step 11: Add Webhooks for Production Monitoring
Keeping a stream connection open for every active agent session doesn’t scale past a handful of concurrent users. For production deployments, register a webhook endpoint instead and let OpenAI push session state changes to you. Your webhook handler can retrieve results, execute function-tool calls, or manage a self-hosted sandbox’s lifecycle without your application holding an open connection the whole time.
This matters more than it sounds like it should. Function tools specifically need a handler that’s reachable and fast — if your webhook endpoint is down when the agent needs a tool result, the turn stalls rather than failing loudly, and you’ll spend more time debugging a “stuck” agent than you would debugging a clean error.
Step 12: Price Out Your Agent Before You Ship It
There’s no Agents API line-item fee — you pay for the model tokens, the tools, and the sandbox compute your agent actually uses, at OpenAI’s standard published rates. Here’s what that looks like broken down by component, using OpenAI’s own pricing page.
| Model (short context) | Input / 1M tokens | Cached input / 1M | Output / 1M tokens |
|---|---|---|---|
| gpt-6-astra | $10.00 | $1.00 | $50.00 |
| gpt-5.6-sol | $4.00 | $0.40 | $20.00 |
| gpt-5.6-terra | $2.00 | $0.20 | $12.00 |
| gpt-5.6-luna | $0.20 | $0.02 | $1.20 |
Sandbox compute is billed separately and by the container size you configure, per 20-minute session: 1 GB runs $0.03, 4 GB runs $0.12, 16 GB runs $0.48, and 64 GB runs $1.92, billed by the minute with a 5-minute minimum. Web search adds $10.00 per 1,000 calls for reasoning-model agents (search content tokens billed at model rates), or $25.00 per 1,000 calls for non-reasoning models with search content included free. File search runs $2.50 per 1,000 tool calls plus $0.10/GB-day for storage beyond the first free gigabyte.
The practical takeaway: swapping gpt-6-astra for gpt-5.6-terra on a routine, low-stakes agent cuts output cost by roughly 75% with almost no code changes — just change the model field. Reserve Astra for tasks where getting it wrong is genuinely expensive, and route everything else to a cheaper model.
Worked example: a documentation-lookup agent running 500 sessions a day, each averaging 2,000 input tokens and 500 output tokens on gpt-6-astra with no sandbox, works out to roughly $0.045 in model tokens per session — about $22.50 a day, or close to $675 a month, using the short-context rates above. Route the identical workload to gpt-5.6-terra instead and the per-session cost drops to about $0.01, since Terra’s output rate is $12 per million tokens against Astra’s $50, bringing the monthly total down to roughly $150 — close to the 75% reduction mentioned above. Add a 4 GB sandbox to 100 of those sessions a day for occasional code execution and you’re adding roughly $12 a day in container time, which is real money at scale but still small next to model spend, which is usually where teams should focus their cost-cutting first.
Complete Working Project: A Documentation Research Agent
Here’s a self-contained agent that answers technical questions by searching the web and an MCP-connected documentation source, then reports back a structured answer. This mirrors the pattern OpenAI uses in its own showcase apps, including a published Slack bot and a GitHub issue investigator built on the same primitives.
import time
from openai import OpenAI
client = OpenAI()
def ask_research_agent(question: str) -> str:
events = client.beta.agents.sessions.create(
agent={
"model": "gpt-6-astra",
"instructions": (
"You are a technical research assistant. Use web search and the "
"connected documentation MCP server to answer accurately. Cite "
"sources by URL in your final answer."
),
"tools": [
{"type": "web_search"},
{
"type": "mcp",
"server_label": "openai_docs",
"transport": {
"type": "http",
"server_url": "https://developers.openai.com/mcp",
},
},
],
},
environment={"type": "none"},
input=question,
stream=True,
)
final_text = ""
session_id = None
with events:
for event in events:
if session_id is None and hasattr(event, "session_id"):
session_id = event.session_id
event_type = getattr(event, "type", "")
if event_type == "agent.session.turn.completed":
final_text = getattr(event, "output_text", final_text)
elif event_type in ("agent.session.turn.failed", "agent.session.turn.cancelled"):
raise RuntimeError(f"Turn ended without success: {event_type}")
return final_text
if __name__ == "__main__":
answer = ask_research_agent(
"What changed between the OpenAI Assistants API and the new Agents API?"
)
print(answer)
Save this as research_agent.py, export your API key, and run python research_agent.py. Because the environment is set to none, this agent never spins up a sandbox — it only reaches out through web search and the MCP connection — which keeps per-run cost close to just the model tokens and the $10-per-1,000-call web search rate. To extend this into a full application, wrap ask_research_agent in a Flask or FastAPI route, store the returned session_id per user so follow-up questions reuse context, and add a webhook handler for anything that runs longer than a typical HTTP request timeout.
Sample Output You Should Expect
Running the quickstart tree-script example produces a stream of JSON events similar to this abbreviated sequence — a session-created event, one or more tool-call events as the sandbox executes the script, and a final completion event carrying the output text:
{"type": "agent.session.created", "session_id": "sess_68f2a1c9..."}
{"type": "agent.session.item.added", "item": {"type": "tool_call", "name": "shell", "input": "python tree.py"}}
{"type": "agent.session.item.added", "item": {"type": "tool_result", "output": ".\n├── tree.py\n"}}
{"type": "agent.session.turn.completed", "output_text": "I created tree.py, ran it, and it printed the directory tree shown above."}
Exact field names in your own output may vary slightly by SDK version, but the pattern — creation, tool activity, completion — holds across every example in OpenAI’s documentation.
5 Common Pitfalls When Building on the Agents API
1. Treating an idle session as a successful one. An agent.session.idle event only means the agent stopped working — not that it succeeded. Always check for agent.session.turn.completed and inspect the actual output before telling a user their task is done.
2. Reusing an org-wide API key for agent sessions. Agents that run code in a sandbox are a bigger blast radius than a normal chat completion call. Generate scoped, short-lived keys specifically for agent workloads instead of your default org key.
3. Retrying a dropped stream by resending the original request. Since streams don’t replay missed events, blindly resending risks kicking off a duplicate turn. Retrieve the session’s saved items first to see what already happened.
4. Reaching for multi-agent mode on tasks that don’t parallelize. Subagent delegation adds real token cost. It pays off on genuinely parallel work like comparing multiple documents; it’s wasted overhead on a single linear task.
5. Assuming Zero Data Retention or non-US data residency is available. As of this beta, the Agents API only supports US data residency and does not support ZDR, even with a self-hosted sandbox. Confirm this against your compliance requirements before building anything regulated on top of it.
Troubleshooting: 8 Issues and How to Fix Them
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 Unauthorized on session creation | Missing or malformed OpenAI-Beta: agents=v1 header | Add the header explicitly on raw HTTP calls; SDKs add it automatically |
| 403 Forbidden despite a valid key | Key lacks api.agents.read/api.agents.write scopes, or org hasn’t enabled agent access | Regenerate the key with the correct scopes; ask a workspace admin to enable Agents API access |
| Agent appears “stuck” mid-turn | A function tool’s handler is offline or unresponsive | Check your function-tool webhook uptime; the harness will wait indefinitely for a result |
| Stream disconnects with no error | Network interruption or long idle period between events | Retrieve the session’s saved items via the items endpoint instead of assuming the stream will resume |
| Turn completes but output is empty or wrong | Completion doesn’t guarantee every tool call inside the turn succeeded | Inspect individual tool-call items, not just the final completion event |
| Self-hosted sandbox never connects | Executor wasn’t started or wasn’t linked to the session ID | Confirm your executor process is running and pointed at the correct session before sending input |
| Unexpectedly high bill for a single agent | Multi-agent delegation running more concurrent subagents than needed, or gpt-6-astra used for routine tasks | Lower max_concurrent_subagents; route low-stakes tasks to gpt-5.6-terra or gpt-5.6-luna |
| Follow-up message doesn’t seem to reach a running agent | Event stream wasn’t subscribed before sending the follow-up | Open the session’s event stream first, then send the agent.session.input.message event |
What’s Still Rough in a Public Beta
Treat this as a beta, because it is one. OpenAI hasn’t published a dedicated Agents-API-specific rate-limit table the way it has for the Responses API and Chat Completions — expect limits to inherit from your account’s usage tier until OpenAI documents Agents-specific numbers separately. Data residency is US-only for now, with no Zero Data Retention option even on self-hosted sandboxes, which rules the API out for some regulated workloads today regardless of how well it fits the technical shape of your agent. And because this is a day-three-to-day-ten product as of this writing, expect the SDK method signatures, event type names, and configuration options documented here to keep shifting faster than a mature, generally-available API would — pin your SDK version in production and read the changelog before upgrading.
None of that is a reason to avoid the beta if your use case fits — the underlying primitives (sessions, environments, events/items) are stable concepts even if field names shift — but it is a reason to avoid betting a hard production deadline on beta-only behavior that OpenAI could still change before general availability.
Advanced Tips for Production-Grade Agents
Once the basics work, a few adjustments separate a demo from something you’d actually run in front of customers. First, set environment.type to none whenever an agent doesn’t need to run code — it’s the cheapest option and removes an entire class of sandbox-related failure modes. Second, pair MCP connections with programmatic_tool_calling where your workload allows it; OpenAI positions this as a way to reduce full model round-trips for routine tool invocations, which lowers both latency and token spend on tool-heavy agents.
Third, if you’re migrating existing Responses API orchestration logic rather than starting fresh, don’t try to port it wholesale. The Agents API’s session and turn model doesn’t map one-to-one onto a hand-rolled loop built around previous_response_id chaining — treat the migration as a rewrite of your orchestration layer, not a find-and-replace on endpoint names. Fourth, build your monitoring around items and webhooks rather than raw event streams for anything long-running; open streams don’t survive process restarts, deploys, or load balancer timeouts, but sessions and their saved items do.
Finally, budget for the sandbox tier you actually need rather than defaulting to the largest one. Most coding and file-editing agents run comfortably in a 4 GB container at $0.12 per 20-minute session; reserve the 64 GB tier for agents doing genuinely memory-heavy work like large dataset analysis.
Testing and Evaluating an Agent Before You Ship It
An agent that works on your three test prompts and falls over on the fourth real user request isn’t ready for production. Before pointing traffic at any agent built on this API, run it against a batch of representative inputs offline and check three things independently: whether the turn actually completed (not just went idle), whether the tool calls inside the turn succeeded, and whether the final output matches what a human reviewer would consider correct. OpenAI’s platform documentation groups this under evaluation tooling for agent workflows, separate from the basic quickstart — worth reading once your agent moves past a personal prototype and starts handling real user input, since silent partial failures are the failure mode this API makes easiest to miss.
A cheap first pass that catches a surprising number of bugs: log every session’s final output_text alongside its list of tool-call items, and manually spot-check a sample of ten to twenty sessions a day for the first few weeks. Most early integration bugs show up as either a tool call that silently returned an error the agent then talked past, or a subagent whose findings never made it into the final synthesized answer — both are visible in the item log even when the top-level turn status reads as completed.
Frequently Asked Questions
Is the OpenAI Agents API free to use?
There’s no separate fee for the API itself. You pay standard token rates for the model your agent uses, plus standard rates for any tools, web search calls, or sandbox compute it consumes.
What happened to the Assistants API?
It was retired on August 26, 2026. OpenAI’s guidance points existing Assistants API users toward the Responses API for general use, or the new Agents API for long-running, tool-using, multi-step workloads.
Which model do Agents API examples use by default?
OpenAI’s official quickstart and configuration examples use gpt-6-astra, the company’s flagship model released in early September 2026. You can substitute a cheaper model like gpt-5.6-terra or gpt-5.6-luna for routine tasks.
Do I need a sandbox for every agent?
No. Set environment.type to none for agents that only need to call remote tools like web search or an MCP server. Sandboxes (openai_hosted or self_hosted) are only needed when the agent must run code, edit files, or produce artifacts.
Does the Agents API support languages besides Python and JavaScript?
Yes. OpenAI publishes official SDKs for Python, JavaScript/TypeScript, Go, Java, and Ruby, all exposing the same underlying beta.agents functionality, plus raw REST access for any other language via cURL or a generic HTTP client.
Can I connect my own infrastructure instead of using OpenAI’s hosted sandboxes?
Yes, using environment.type: "self_hosted". You provision the compute and connect an executor to the session; the harness sends it commands, but you’re responsible for provisioning, reconnection, and shutdown.
Does the Agents API support data residency outside the US, or Zero Data Retention?
Not currently. As of this beta, the Agents API only supports US data residency and does not support Zero Data Retention, even when you connect a self-hosted sandbox.
How is this different from just using LangGraph or CrewAI?
Those frameworks give you full control over orchestration but require you to build session persistence, context management, and multi-agent delegation yourself. The Agents API bundles those capabilities into a managed endpoint, trading some control for less orchestration code to write and maintain.


