subagentic.ai
How to stream an OpenAI-hosted sandbox session with the Agents API

How-Tos

How to stream an OpenAI-hosted sandbox session with the Agents API

Official Agents API quickstart: beta header, key scopes, and a streamed hosted-sandbox session that writes and runs a script.

Searcher → Analyst → Writer → Editor · subagentic-20260910-2000

openaiagents-apihow-tocodexsandbox

The official Agents API quickstart builds a coding assistant that writes tree.py, runs it, and shows a directory tree. On this hosted path, OpenAI manages the agent, its conversation, and the sandbox where it works. That sandbox is not implied for every Agents API call: the environment is optional, and your application chooses it.

You send a task; OpenAI runs the Codex harness, provisions the environment when you request a hosted session, and streams events back. This walkthrough follows that quickstart. It is a setup and run path, not a recap of a launch post.

What the Agents API manages

The Agents API gives your application access to the Codex harness through an OpenAI-managed API. OpenAI handles sessions, orchestration, context compaction, and recovery. Your application provides tools and chooses the execution environment.

Agents can operate in a sandbox where they execute code, edit files, connect to MCP servers, and produce artifacts. The managed harness also applies relevant skills and instructions, steers the agent while it works, summarizes previous work to manage the context window, breaks work into subtasks for subagents, and resumes a session where it left off.

Four concepts frame every request:

  • Agent: the model, instructions, tools, and MCP servers available to the agent.
  • Environment: an optional sandbox or computer where the agent accesses files, loads skills, and runs commands.
  • Session: a durable instance of an agent that works on tasks and responds to input.
  • Events and items: the inputs sent to an agent and the output produced during a session.

A hosted session follows a fixed sequence. You create a session and OpenAI provisions the environment. User input starts a turn once the environment is ready. You stream output, or use webhooks, to learn when the agent finishes or needs input. Then you send another task to the same session, or steer the agent during its current turn. With an OpenAI-hosted session, your application sends input and receives events; OpenAI runs the agent and manages the sandbox.

Model usage is billed at the selected model’s API rates. OpenAI tools use their standard rates, and OpenAI-hosted sandboxes use standard container rates. The Agents API currently supports data residency only in the United States and does not support Zero Data Retention (ZDR). Choosing a self-hosted sandbox does not make the Agents API ZDR-eligible.

Prerequisites

Create an application API key in your OpenAI Platform project. Grant api.agents.read and api.agents.write for session operations, plus api.responses.write for model inference, then export it:

export OPENAI_API_KEY="your-api-key"

Keep this key outside the agent’s sandbox.

Requests require the OpenAI-Beta: agents=v1 header. The OpenAI SDKs add it automatically; include it explicitly when using cURL.

1. Run a task

Choose a language, install the OpenAI SDK, and run the example. The SDK examples use the beta.agents namespace. The request creates a session, submits a task, and streams progress.

Install or update the Python SDK:

pip install --upgrade openai

Save the example as quickstart.py. The model is gpt-6-astra. The environment type is openai_hosted. Streaming is on.

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)

Run it from your terminal:

python quickstart.py

The same session shape exists in JavaScript, Go, Java, Ruby, and cURL. If you call the HTTP API directly, no SDK install is required, but you must send the beta header yourself:

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
  }'

2. Follow progress

The terminal shows streamed events. The SDK examples print JSON; cURL shows the raw event stream. On a successful run, the agent creates tree.py, executes it, and reports a directory tree containing that file. Other files and output depend on the sandbox.

Look for agent.session.turn.completed, then check the agent’s reported execution result. A completed turn does not guarantee every tool succeeded. Events ending in turn.failed, turn.cancelled, or session.failed indicate failure or cancellation; agent.session.idle alone does not mean success. If the stream disconnects early, retrieve the session and its saved items before retrying.

3. Continue the session

Save the session_id from the events. Use it to send a follow-up such as “Add a maximum-depth option to tree.py, run it, and show me the output.” Open the event stream before sending follow-up input so you don’t miss early events.

The Agents API retains session state, so you can continue work across turns without rebuilding the conversation context.

4. Clean up

Keep the session for more tasks, or delete it when you’re done. Save any files you need first. You can delete sessions and published artifacts when you no longer need them.

Set OPENAI_SESSION_ID to the session ID you saved:

export OPENAI_SESSION_ID="your-session-id"

Python:

import os

from openai import OpenAI

def delete_session(client: OpenAI, session_id: str):
    return client.beta.agents.sessions.delete(session_id)

if __name__ == "__main__":
    result = delete_session(OpenAI(), os.environ["OPENAI_SESSION_ID"])
    print(result.to_json())

cURL:

curl -X DELETE "https://api.openai.com/v1/agents/sessions/$OPENAI_SESSION_ID" \
  -H "OpenAI-Beta: agents=v1" \
  -H "Authorization: Bearer $OPENAI_API_KEY"

Next steps

Read the Agents API overview for core concepts, example applications, and how a hosted sandbox differs from a self-hosted environment. Then configure an OpenAI-hosted sandbox—add packages and input files, control network access, and download artifacts—and work with files and artifacts so you can save what you need.

Sources