DEV Community

Cover image for How to use the OpenAI Agents API ?
Hassann
Hassann

Posted on Originally published at apidog.com

How to use the OpenAI Agents API ?

The OpenAI Agents API runs OpenAI’s open-source Codex harness for you. Send POST https://api.openai.com/v1/agents/sessions with the OpenAI-Beta: agents=v1 header, an agent definition, and a task. OpenAI runs the model and tool loop, persists the session, and can provision a sandbox. There is no Agents API fee: you pay for tokens, tools, and hosted container time ($0.03 to $0.48 per 20-minute session for 1 GB to 16 GB sandbox sizes). It entered public beta on September 10, 2026, and OpenAI added computer use at DevDay on September 29.

Try Apidog today

This guide covers a first REST session, progress events, MCP tools, subagents, and the computer-use approval flow. For a comparison with OpenAI’s other agent surfaces, read Agents API vs Responses API vs Agents SDK. For the rest of the event, see the DevDay 2026 roundup. Every call is plain HTTP, so you can send it from Apidog before writing application code.

OpenAI Agents API at a glance

Item Value
Status Public beta since Sep 10, 2026; computer use added Sep 29
Create a session POST /v1/agents/sessions
Beta header OpenAI-Beta: agents=v1 (the OpenAI SDKs add it)
Key permissions api.agents.read, api.agents.write, api.responses.write
Pricing No Agents API fee; model tokens at API rates, tools at standard rates (web search $10 per 1K calls)
Hosted containers $0.03 (small, 1 GB), $0.12 (medium, 4 GB), $0.48 (large, 16 GB) per 20-minute session
Environments none, openai_hosted, self_hosted
Model in the docs’ examples gpt-6-astra
Data controls US data residency only; no Zero Data Retention (ZDR)
Max request size 4 MiB

Sources: Introducing the Agents API, the Agents API overview, and the pricing page.

The four concepts

The API is built around four pieces:

  • Agent: The model, instructions, tools, and MCP servers. Pass it inline, or save and reuse its agent_id.
  • Environment: An optional sandbox or computer where the agent reads files and runs commands.
  • Session: A durable instance of an agent that persists configuration, conversation, and saved work.
  • Events and items: Events report live progress; items are saved messages and tool calls.

A message sent to an idle session starts a new turn. A message sent during a turn steers it. The harness—the hosted Codex instance that runs the model and tool loop, according to the architecture guide—also handles context compaction.

Pick an environment

Use environment.type to decide where commands run:

  • none: No compute. Remote MCP servers and function tools still work, but built-in Bash, apply-patch, workspace files, and executor MCPs do not.
  • openai_hosted: OpenAI manages a Linux sandbox with Python and Node.js in /workspace. Set container_size to small (1 GB), medium (default, 4 GB), or large (16 GB). Configure network.access as enabled, disabled, or restricted with allowed_domains. Files in /workspace/outputs become artifacts when a turn completes. An idle sandbox without keep-alives can be deleted after an hour.
  • self_hosted: Your infrastructure. Run codex exec-server on a laptop, container, or remote sandbox. It connects outbound using a separate environment key.

The launch post lists sandbox partners Blaxel, Cloudflare, Daytona, DigitalOcean, E2B, Modal, Oracle, Runloop, and Vercel. The self-hosted environment guide also adds AWS Lambda MicroVMs.

Your first session over REST

Export a key with the required permissions as OPENAI_API_KEY, then create a streaming session with a small container:

curl --no-buffer 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",
      "container_size": "small"
    },
    "input": "Create tree.py, a script that prints a tree of the files in the current directory. Run it and show the output.",
    "stream": true
  }'
Enter fullscreen mode Exit fullscreen mode

With stream: true, the response is the first turn’s event stream. Save the session ID from that stream, then use the same session resource for the rest of the lifecycle:

Action Request
Follow up or steer POST /v1/agents/sessions/{id}/events with an agent.session.input.message event
Cancel the active turn Same endpoint with event type agent.session.input.cancel
Read saved work GET /v1/agents/sessions/{id}/items?order=asc&limit=100
Clean up DELETE /v1/agents/sessions/{id}

The JavaScript SDK uses the same shape. This example adds web search, subagents, and a vault:

import OpenAI from "openai";

const client = new OpenAI();

const session = await client.beta.agents.sessions.create({
  agent: {
    model: "gpt-6-astra",
    tools: [{ type: "web_search" }],
    multi_agent: {
      enabled: true,
      max_concurrent_subagents: 3,
    },
  },
  vault_ids: [process.env.VAULT_ID],
  environment: { type: "openai_hosted" },
  input: "Summarize breaking changes in the latest release notes.",
});

console.log(session.id);
Enter fullscreen mode Exit fullscreen mode

Follow progress: stream or webhooks

Stream events

Open GET /v1/agents/sessions/{id}/events?stream=true with Accept: text/event-stream before sending input so you do not miss early events.

Watch for:

  • agent.session.turn.output_text.delta and agent.session.turn.output_text.done for text output.
  • agent.session.turn.completed, agent.session.turn.failed, or agent.session.turn.cancelled for the final turn outcome.
  • agent.session.requires_action when the agent needs a function result, environment connection, or computer-use approval.

Avoid these common mistakes:

  1. agent.session.idle does not mean the turn succeeded.
  2. A completed turn can still contain failed tool calls.
  3. Closing an SSE stream does not stop the running task.
  4. Streams do not replay missed events. After a disconnect, open a new stream and retrieve the session and its items.

Use webhooks for long-running work

Subscribe to:

  • agent.session.created
  • agent.session.action_required
  • agent.session.in_progress
  • agent.session.idle
  • agent.session.failed

The event names differ slightly:

  • Stream: requires_action
  • Webhook: action_required

Webhook payloads omit call details. In your webhook handler, retrieve the session and inspect required_actions. Verify every signature using a webhook signature verification flow. For the architecture behind this pattern, see long-running API operations.

MCP tools, tool search, programmatic tool calling, and subagents

Add an MCP server

Add an MCP server to agent.tools:

{
  "type": "mcp",
  "server_label": "openai_docs",
  "transport": {
    "type": "http",
    "server_url": "https://developers.openai.com/mcp"
  },
  "required": true
}
Enter fullscreen mode Exit fullscreen mode

By default, OpenAI creates the connection with connection_origin: "service", so the server must be reachable from OpenAI.

Use these alternatives when needed:

  • Set connection_origin: "environment" for a private-network server.
  • Use stdio to start a server inside the sandbox.
  • Pass transport.authorization for credentials scoped to one session.
  • Attach a vault credential (static_bearer or mcp_oauth) through vault_ids.

Use tool search for large tool sets

MCP tools are discovered automatically when the model supports tool search.

For many function tools, add:

{ "type": "tool_search" }
Enter fullscreen mode Exit fullscreen mode

Then mark functions that should load only when needed:

{
  "defer_loading": true
}
Enter fullscreen mode Exit fullscreen mode

Programmatic tool calling

Programmatic tool calling is enabled by default. The agent gets an exec tool that runs JavaScript in an isolated V8 runtime. It can loop over tool calls and trim large results before adding them to model context.

Disable it when you need every tool call handled directly:

{
  "type": "programmatic_tool_calling",
  "enabled": false
}
Enter fullscreen mode Exit fullscreen mode

Enable subagents

Enable subagents with a concurrency limit:

{
  "multi_agent": {
    "enabled": true,
    "max_concurrent_subagents": 3
  }
}
Enter fullscreen mode Exit fullscreen mode

The default limit is 6. Subagents share the environment filesystem and inherit MCP tools and web search, but they cannot use function tools. A turn’s subagent_id is null for the main agent.

Computer use: the DevDay addition

Computer use gives the agent a hosted browser. Add the tool and enable a desktop in a hosted environment:

{
  "agent": {
    "model": "gpt-6-astra",
    "tools": [
      {
        "type": "computer_use",
        "include_screenshots": true
      }
    ]
  },
  "environment": {
    "type": "openai_hosted",
    "desktop": {
      "enabled": true
    },
    "network": {
      "access": "enabled"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The browser requires user approval before visiting every new website origin, including public sites.

When you receive agent.session.requires_action:

  1. Retrieve the session.
  2. Find computer_use_approval_request entries.
  3. Inspect the nested request.type.
  4. Send the appropriate result through the events endpoint.

There are two request types:

  • browser_origin_access: Show origin and reason, then submit approve, deny, or cancel.
  • browser_authentication: Show the sign-in fields, optional login options, and credential_origin. Submit action: "submit" with user-provided values, or action: "cancel".

Submit an origin approval result like this:

curl "https://api.openai.com/v1/agents/sessions/$SESSION_ID/events" \
  -H "OpenAI-Beta: agents=v1" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      {
        "type": "agent.session.input.computer_use_approval_request_result",
        "request_id": "REQUEST_ID",
        "response": {
          "type": "browser_origin_access",
          "decision": "approve"
        }
      }
    ]
  }'
Enter fullscreen mode Exit fullscreen mode

Browser work is stored as computer_use_call items. Each item can include id, turn_id, title, status, and output. When include_screenshots is enabled and a screenshot is available, output carries a base64 JPEG.

Do not write screenshots to logs. They can expose account data.

The computer use guide highlights these implementation constraints:

  • Origin approval is not action confirmation. Approving a site does not make the agent ask before each purchase or delete. If you need that control, restrict the browser to resources that cannot take those actions or use a browser runtime you control.
  • Sign-in covers email, passwords, and verification codes. Passkeys and QR-code sign-in are not supported.
  • Only the main agent can request authentication. Subagents cannot.
  • Disable automatic retries on credential submissions. Use maxRetries: 0 in the SDK or --retry 0 with curl.
  • A 202 means accepted, not successful. Navigation or sign-in may still fail. Authentication requests expire after five minutes.
  • Origin approval does not override network policy. Add the site and its redirect domains to network allow rules too.

The recap says computer use ships “through the API and in Codex and ChatGPT Work on Pro 500 and Enterprise.” For UI-driven testing with the same model, see GPT-6 Astra computer use for API testing.

Give the agent your API, not your UI

A browser is a fallback for software without an API. If you own the system, wrap it in an MCP server instead:

  • Expose typed tools.
  • Avoid origin approval prompts.
  • Return structured, checkable results.

Computer use vs structured APIs covers the trade-off. The Apidog MCP Server can feed your API specification to the coding assistant that writes the wrapper.

Test the Agents API in Apidog before writing code

The API is in beta, so validate every request shape manually in Apidog first:

Apidog interface

  1. Create an Apidog environment with OPENAI_API_KEY, VAULT_ID, and SESSION_ID.
  2. Send Bearer {{OPENAI_API_KEY}} and OpenAI-Beta: agents=v1 on every request.
  3. Send the create-session request without stream. Assert a 2xx status and a non-empty id, then extract id into SESSION_ID.
  4. Open the event stream as an SSE request. Send input from a second request and verify that events arrive.
  5. Save approval and cancellation payloads as reusable requests for each required_actions case.
  6. Chain requests into a test scenario and run it in CI with the Apidog CLI.

The AI agent API testing guide includes assertion patterns for non-deterministic output. Download Apidog to follow along.

FAQ

Is the OpenAI Agents API free?

There is no platform fee, but you pay for model tokens, tool calls, and hosted container time.

Which models work with the Agents API?

The docs’ examples, including every computer-use example, use gpt-6-astra. The pages do not list other supported models, so test yours first.

Does the Agents API support Zero Data Retention?

No. It supports US data residency only and is not ZDR-eligible, even with a self-hosted sandbox.

How is it different from the Agents SDK or the Responses API?

The SDK runs the loop inside your application. The Responses API is the model call that you build a loop around. See the full comparison.

Start with one read-only session

Begin with a read-only session. Add one MCP server, then add computer use behind an approval handler that denies by default.

When ChatGPT should react to events from your own server instead, MCP Events is the matching piece.

Top comments (0)