SPB Git

Repository Public

self-hosted.md 10.2 KB 231 lines markdown

1# Self-hosted sandboxes23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45Connect your own environment when you want more control over the agent's environment or want to use compute you trust. The environment can be a laptop, a container, or a remote sandbox. To have OpenAI provision the environment, use an [OpenAI-hosted sandbox](https://developers.openai.com/api/docs/guides/agents-api/environments/openai-hosted).678910## How the connection works1112OpenAI runs the [agent harness](https://developers.openai.com/api/docs/guides/agents-api/architecture#the-pieces). You run `codex exec-server`, the executor, inside your environment. It runs shell commands, reads and writes files, and uses local MCP servers at the harness's request.1314The executor registers with the API using an environment ID and a restricted API key. It then connects over WebSocket to receive commands and return results. All connections are outbound. The executor reconnects if the connection drops.1516<picture>17  <source18    media="(max-width: 640px)"19    srcSet="/images/api/agents-api/self-hosted-sandboxes-1-mobile.webp"20    width="680"21    height="876"22  />23  <img src="https://developers.openai.com/images/api/agents-api/self-hosted-sandboxes-1.webp"24    width="1400"25    height="444"26    alt="The sandbox executor initiates an outbound connection to the Agents API and exchanges commands and results. The sandbox holds the environment key and environment ID."27    loading="lazy"28  />29</picture>3031323334## Prepare your environment3536Prepare the files and dependencies your agent needs. Isolate environments by user or workload. Agents that share an environment can access the same files, credentials, and other resources.3738Create the working directory and install the Codex CLI inside the environment. This example uses `/workspace`:3940```bash41mkdir -p /workspace42npm install -g @openai/codex@alpha43```4445464748### Network access4950Allow outbound connections to these hosts:5152- `https://api.openai.com` for environment registration.53- `wss://codex-cloud-environments.chatgpt.com` for commands and results.5455### Authentication5657Use `OPENAI_API_KEY` for application requests. Grant it `api.agents.read` and `api.agents.write` for session operations, plus `api.responses.write` for model inference. Add `api.vaults.read` and `api.vaults.write` if your application manages vaults.5859Create a separate environment key on the [Agents tab](https://platform.openai.com/agents?tab=environments&environment_view=keys) in the platform dashboard. It must belong to the same organization, project, and user or service account that owns the session. Set every other permission to **None**.6061Set `OPENAI_EXECUTOR_API_KEY` to this environment key in your application or provisioning service. Pass its value into the sandbox as `CODEX_API_KEY`, which `codex exec-server` reads. Keep your application's `OPENAI_API_KEY` outside the sandbox.6263Agent-generated code can read the environment key, but the key only permits connecting environments. It cannot authorize any other API action. Keep it out of source code, container images, and logs. Rotate or revoke it when needed.6465666768## Create a session6970Run this example in your application, outside the environment. If you already have a self-hosted session, reuse it.7172Create a session with your own environment7374```javascript75import OpenAI from "openai";76const client = new OpenAI();7778const session = await client.beta.agents.sessions.create({79  agent: {80    model: "gpt-6-astra",81    instructions:82      "You are a helpful coding assistant. Write clean code and verify that it works.",83  },84  environment: {85    type: "self_hosted",86    workspace_directory: "/workspace",87  },88});8990console.log(session);91```9293```python94from openai import OpenAI9596client = OpenAI()9798session = client.beta.agents.sessions.create(99    agent={100        "model": "gpt-6-astra",101        "instructions": "You are a helpful coding assistant. Write clean code and verify that it works.",102    },103    environment={"type": "self_hosted", "workspace_directory": "/workspace"},104)105print(session.to_json())106```107108```go109import (110	"context"111	"fmt"112113	"github.com/openai/openai-go/v3"114)115116ctx := context.Background()117client := openai.NewClient()118result, err := client.Beta.Agents.Sessions.New(ctx,119	openai.BetaAgentSessionNewParams{120		Agent: openai.BetaAgentSessionNewParamsAgent{121			Model:        openai.String("gpt-6-astra"),122			Instructions: openai.String("You are a helpful coding assistant. Write clean code and verify that it works."),123		},124		Environment: openai.EnvironmentParamUnion{125			OfParamSelfHosted: &openai.EnvironmentParamSelfHosted{WorkspaceDirectory: "/workspace"},126		},127	})128if err != nil {129	panic(err)130}131fmt.Println(result)132```133134```java135import com.openai.client.OpenAIClient;136import com.openai.client.okhttp.OpenAIOkHttpClient;137import com.openai.models.beta.agents.EnvironmentParam;138import com.openai.models.beta.agents.sessions.SessionCreateParams;139140OpenAIClient client = OpenAIOkHttpClient.fromEnv();141var result =142    client143        .beta()144        .agents()145        .sessions()146        .create(147            SessionCreateParams.builder()148                .agent(149                    SessionCreateParams.Agent.builder()150                        .model("gpt-6-astra")151                        .instructions(152                            "You are a helpful coding assistant. Write clean code and verify"153                                + " that it works.")154                        .build())155                .environment(156                    EnvironmentParam.SelfHosted.builder()157                        .workspaceDirectory("/workspace")158                        .build())159                .build());160System.out.println(result);161```162163```ruby164require "openai"165166client = OpenAI::Client.new167result = client.beta.agents.sessions.create(168  agent: {169    model: "gpt-6-astra",170    instructions: "You are a helpful coding assistant. Write clean code and verify that it works."171  },172  environment: {173    type: "self_hosted",174    workspace_directory: "/workspace"175  }176)177puts result178```179180181Store `session.id` with your application's conversation state. Pass `session.environment.id` and `session.environment.remote_url` to the executor. Use the remote URL unchanged, including when reconnecting. See [Configuring Agents](https://developers.openai.com/api/docs/guides/agents-api/configuration#reuse-an-agent-across-sessions) to use a stored agent.182183184185186You can reuse your environment image, `workspace_directory`, and `capability_directories` across sessions. Each session has its own environment ID and needs its own executor. API [environment templates](https://developers.openai.com/api/docs/guides/agents-api/tools/plugins#reuse-a-hosted-plugin-setup) apply only to OpenAI-hosted environments.187188## Start the executor189190Open the [session event stream](https://developers.openai.com/api/docs/guides/agents-api/sessions/events#consume-a-stream) from your application to receive connection events. Then run this command inside the environment with the environment key configured as `CODEX_API_KEY` above. Replace the placeholders with the environment values returned by the API:191192```bash193codex exec-server \194  --remote "<session.environment.remote_url>" \195  --environment-id "<session.environment.id>"196```197198Leave the executor running while the agent works.199200201202203## Send work and monitor the connection204205[Send input](https://developers.openai.com/api/docs/guides/agents-api/sessions#send-input) from your application while the event stream stays open. The agent needs both a connected environment and user input to start work.206207The stream reports these connection states:208209- `agent.session.environment.pending`: The session is waiting for the executor to connect.210- `agent.session.environment.connected`: The environment is ready.211- `agent.session.environment.failed`: The connection failed. Check the environment error and executor logs.212213Continue following the stream for the turn's outcome and output. See [Environment lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle) to manage startup, reconnection, and shutdown from your application or through webhooks.214215## Sandbox providers216217Choose a sandbox provider to run code and work with files. See [Sandbox lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle) to compare application-managed and webhook-managed provisioning.218219| Provider                          | Guide                                                                                 |220| --------------------------------- | ------------------------------------------------------------------------------------- |221| Modal                             | [Modal setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/modal)               |222| Cloudflare                        | [Cloudflare setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/cloudflare)     |223| Vercel                            | [Vercel setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/vercel)             |224| Daytona                           | [Daytona setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/daytona)           |225| Blaxel                            | [Blaxel setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/blaxel)             |226| E2B                               | [E2B setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/e2b)                   |227| Runloop                           | [Runloop setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/runloop)           |228| DigitalOcean                      | [DigitalOcean setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/digitalocean) |229| Oracle Cloud Infrastructure (OCI) | [OCI setup](https://developers.openai.com/api/docs/guides/agents-api/environments/providers/oci)                   |230231For webhook-managed provisioning, implement a handler using [Sandbox lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle#start-compute-from-webhooks) and your provider's SDK or API. Keep provisioning ownership and cleanup policies explicit.
Files main
Menu

Theme