SPB Git

Repository Public

openai-hosted.md 12.2 KB 263 lines markdown

1# OpenAI-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.45An OpenAI-hosted sandbox gives your agent a Linux workspace with Python, Node.js,6and command-line tools. OpenAI provisions and connects it; your application supplies7the task and retrieves the results. Choose a [self-hosted sandbox](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted)8when you need your own image, compute, or private network.910## Configure the sandbox1112Set `environment.type` to `openai_hosted` and add only the settings your workload13needs. The working directory is `/workspace`.1415- `packages`: Install Python, system, or global `npm` packages with `python`, `system`, or `npm` lists. Pin versions when needed, such as `pandas==2.2.3`.16- `setup_commands`: Run ordered shell commands before the agent starts, such as `[{ "command": "mkdir -p reports" }]`. Each command has its own optional `cwd`, defaulting to `/workspace`.17- `files`: [Supply input files](https://developers.openai.com/api/docs/guides/agents-api/environments/files#upload-files) by Files API ID or inline base64 content.18- `env`: Set string-valued environment variables. Runtime-reserved names, including `PATH`, `CODEX_*`, and `OPENAI_API_KEY`, are rejected.19- `skills`, `plugins`, `capability_directories`: Add [skills](https://developers.openai.com/api/docs/guides/tools-skills#agents-api) and [plugins](https://developers.openai.com/api/docs/guides/agents-api/tools/plugins).20- `environment_template_id`: [Reuse saved configuration](https://developers.openai.com/api/docs/guides/agents-api/tools/plugins#reuse-a-hosted-plugin-setup) across sessions. Omitted settings inherit the template; network overrides cannot broaden its policy.2122Packages and input files are prepared before setup commands run. A nonzero setup23exit status prevents the agent from starting. Use a setup command to check required24dependencies or files. Templates save configuration, not a running workspace.2526### Control network access2728| `network.access` | Behavior                                                                         |29| ---------------- | -------------------------------------------------------------------------------- |30| `enabled`        | Allow outbound access. This is the default unless you inherit a template policy. |31| `disabled`       | Block outbound access.                                                           |32| `restricted`     | Allow only the hosts listed in `allowed_domains`.                                |3334Restricted mode accepts 1–100 exact host names, such as `api.example.com`.35Do not include wildcards, protocols, paths, or ports. Subdomains and redirect36destinations need their own entries. Hosted stdio MCP servers currently require37`enabled` access; see [stdio MCP requirements](https://developers.openai.com/api/docs/guides/agents-api/tools/mcp#start-a-server-over-stdio).3839### Check that setup succeeded4041The create-session response means setup has started. Retrieve42`GET /v1/agents/environments/{environment_id}` using the session's `environment.id`:43`provisioning` means setup is running; `connected` means setup succeeded.44For `failed`, read `environment.error` in the `agent.session.environment.failed`45event. Wait for `connected` before adding or listing live files.4647## Files and lifetime4849Each session has a separate workspace. Files persist across turns while its50sandbox exists. Files under `/workspace/outputs` are published as immutable51artifacts when a turn completes; those copies remain downloadable after the52sandbox expires.5354Use [Files and artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files) for uploads,55path rules, live file operations, downloads, and limits. Save outputs you need56before deleting the session.5758### Sandbox expiry5960Connected sandboxes receive keep-alives, including between turns. If activity and61keep-alives stop for an hour, the sandbox can be deleted. This timeout isn’t62configurable.6364Delete the session when you're done to request sandbox cleanup. If deletion65returns `409` while setup or execution finishes, wait and retry with a limit on66the number of attempts. Closing an event stream does not cancel the task.6768## Pricing6970OpenAI-hosted sandboxes use standard [container rates](https://developers.openai.com/api/docs/pricing#built-in-tools).71Model usage is billed separately at the selected model's [API rates](https://developers.openai.com/api/docs/pricing).7273## Example: Create a report7475Give the agent a CSV containing `10`, `20`, and `30`. It runs Python to calculate76the sum and writes `/workspace/outputs/summary.json`.7778Set `OPENAI_API_KEY` in your application terminal using the79[quickstart prerequisites](https://developers.openai.com/api/docs/guides/agents-api/quickstart#prerequisites).80Keep this key outside the sandbox. Use a version of your81[OpenAI SDK](https://developers.openai.com/api/docs/libraries) that includes the beta Agents API.8283Create summary.json8485```javascript86import OpenAI from "openai";8788const client = new OpenAI();89const stream = await client.beta.agents.sessions.create({90  agent: { model: "gpt-6-astra" },91  environment: {92    type: "openai_hosted",93    network: { access: "disabled" },94    files: [95      {96        type: "inline",97        path: "/workspace/amounts.csv",98        data: "YW1vdW50CjEwCjIwCjMwCg==",99      },100    ],101  },102  input:103    "Use Python to sum the amount column in /workspace/amounts.csv. Write a JSON object with the total to /workspace/outputs/summary.json, then read it back to verify it.",104  stream: true,105});106107for await (const event of stream) {108  console.log(event);109}110```111112```python113from openai import OpenAI114115client = OpenAI()116stream = client.beta.agents.sessions.create(117    agent={"model": "gpt-6-astra"},118    environment={119        "type": "openai_hosted",120        "network": {"access": "disabled"},121        "files": [122            {123                "type": "inline",124                "path": "/workspace/amounts.csv",125                "data": "YW1vdW50CjEwCjIwCjMwCg==",126            }127        ],128    },129    input="Use Python to sum the amount column in /workspace/amounts.csv. Write a JSON object with the total to /workspace/outputs/summary.json, then read it back to verify it.",130    stream=True,131)132133with stream:134    for event in stream:135        print(event.model_dump_json())136```137138```go139package main140141import (142	"context"143	"fmt"144145	"github.com/openai/openai-go/v3"146)147148func main() {149	ctx := context.Background()150	client := openai.NewClient()151	stream := client.Beta.Agents.Sessions.NewStreaming(ctx, openai.BetaAgentSessionNewParams{152		Agent: openai.BetaAgentSessionNewParamsAgent{Model: openai.String("gpt-6-astra")},153		Environment: openai.EnvironmentParamUnion{OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{154			Network: openai.EnvironmentParamOpenAIHostedNetwork{Access: "disabled"},155			Files: []openai.HostedEnvironmentFileParamUnion{{OfParamInline: &openai.HostedEnvironmentFileParamInline{156				Path: "/workspace/amounts.csv",157				Data: "YW1vdW50CjEwCjIwCjMwCg==",158			}}},159		}},160		Input: openai.BetaAgentSessionNewParamsInputUnion{OfString: openai.String("Use Python to sum the amount column in /workspace/amounts.csv. Write a JSON object with the total to /workspace/outputs/summary.json, then read it back to verify it.")},161	})162	defer stream.Close()163164	for stream.Next() {165		fmt.Println(stream.Current().RawJSON())166	}167	if err := stream.Err(); err != nil {168		panic(err)169	}170}171```172173```java174import com.openai.client.okhttp.OpenAIOkHttpClient;175import com.openai.models.beta.agents.EnvironmentParam;176import com.openai.models.beta.agents.HostedEnvironmentFileParam;177import com.openai.models.beta.agents.sessions.SessionCreateParams;178179public class HostedReport {180  public static void main(String[] args) throws Exception {181    var client = OpenAIOkHttpClient.fromEnv();182    var params =183        SessionCreateParams.builder()184            .agent(SessionCreateParams.Agent.builder().model("gpt-6-astra").build())185            .environment(186                EnvironmentParam.OpenAIHosted.builder()187                    .network(188                        EnvironmentParam.OpenAIHosted.Network.builder()189                            .access(EnvironmentParam.OpenAIHosted.Network.Access.DISABLED)190                            .build())191                    .addFile(192                        HostedEnvironmentFileParam.Inline.builder()193                            .path("/workspace/amounts.csv")194                            .data("YW1vdW50CjEwCjIwCjMwCg==")195                            .build())196                    .build())197            .input(198                "Use Python to sum the amount column in /workspace/amounts.csv. Write a JSON object"199                    + " with the total to /workspace/outputs/summary.json, then read it back to"200                    + " verify it.")201            .build();202203    try (var stream = client.beta().agents().sessions().createStreaming(params)) {204      stream.stream().forEach(System.out::println);205    }206  }207}208```209210```ruby211require "openai"212require "json"213214client = OpenAI::Client.new215stream = client.beta.agents.sessions.create_streaming(216  agent: { model: "gpt-6-astra" },217  environment: {218    type: :openai_hosted,219    network: { access: :disabled },220    files: [221      {222        type: :inline,223        path: "/workspace/amounts.csv",224        data: "YW1vdW50CjEwCjIwCjMwCg=="225      }226    ]227  },228  input: "Use Python to sum the amount column in /workspace/amounts.csv. Write a JSON object with the total to /workspace/outputs/summary.json, then read it back to verify it."229)230231begin232  stream.each { |event| puts event.to_json }233ensure234  stream.close235end236```237238```bash239curl --no-buffer --fail-with-body https://api.openai.com/v1/agents/sessions \\\n  -H "OpenAI-Beta: agents=v1" \\\n  -H "Authorization: Bearer $OPENAI_API_KEY" \\\n  -H "Content-Type: application/json" \\\n  -d \'{\n  "agent": {\n    "model": "gpt-6-astra"\n  },\n  "environment": {\n    "type": "openai_hosted",\n    "network": {\n      "access": "disabled"\n    },\n    "files": [\n      {\n        "type": "inline",\n        "path": "/workspace/amounts.csv",\n        "data": "YW1vdW50CjEwCjIwCjMwCg=="\n      }\n    ]\n  },\n  "input": "Use Python to sum the amount column in /workspace/amounts.csv. Write a JSON object with the total to /workspace/outputs/summary.json, then read it back to verify it.",\n  "stream": true\n}\'240```241242243The base64 value in `files` contains the CSV input. The code prints session events.244Save `session.id` from `agent.session.created`. After `agent.session.turn.completed`,245[list the artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#list-artifacts), find `summary.json`,246and [download it](https://developers.openai.com/api/docs/guides/agents-api/environments/files#download-an-artifact). Its contents should be:247248```json249{ "total": 60 }250```251252A completed turn does not guarantee every tool succeeded. If the task fails or the253stream ends before completion, [inspect the saved session items](https://developers.openai.com/api/docs/guides/agents-api/sessions#retrieve-session-items).254[Delete the session](https://developers.openai.com/api/docs/guides/agents-api/quickstart#4-clean-up) when you're done.255256## Troubleshooting257258| Problem                                     | What to check                                                                                                                  |259| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |260| Setup fails                                 | Inspect the environment-failure event and fix the package, input-file, or setup-command error before creating another session. |261| A sandbox request is blocked                | Check `network` and any hosts reached through redirects.                                                                       |262| A live file operation fails                 | Confirm the sandbox is `connected`. If it expired, create a new session and supply the inputs again.                           |263| A status or file-list request returns `5xx` | Retry with increasing delays and a deadline. Keep the request ID if the error persists.                                        |
Files main
Menu

Theme