> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Sandboxes에서 OpenAI Agents API 실행하기

> OpenAI 관리형 에이전트를 CoreWeave 샌드박스에 연결하여 도구를 실행하고 공유 워크스페이스에서 분석을 수행하세요.

Use CoreWeave Sandboxes as the execution environment for an OpenAI-managed agent.
Your application creates an Agents API session and a CoreWeave sandbox. A Codex
executor inside that sandbox connects to OpenAI and runs the agent's commands.
This page explains the execution model, the credentials each component requires,
and the resource lifetimes you manage. With that context, you can run the
companion recipe and adapt the same pattern in your own application.

The companion recipe investigates a synthetic inference-service
incident. Three specialist subagents analyze latency, errors, and capacity. Their
coordinator combines the results into an incident report and answers a follow-up.
The application downloads the results, and a separate local verifier checks the
calculations and recorded agent activity.

## Execution model

OpenAI runs the agent loop, manages conversation context, and supplies delegation
tools. CoreWeave runs the executor and the programs the agents write. Your
application manages sandbox provisioning, file transfer, and cleanup.

The coordinator and its subagents share one sandbox and one filesystem.
Creating a subagent doesn't create a separate CoreWeave sandbox. Give each
specialist its own output files and let the coordinator own the final report.
These file assignments are conventions for avoiding write conflicts, not access
controls.
See OpenAI's [multi-agent guide](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).

## Requirements

Before you run the example, meet these requirements:

* [W\&B API 키](https://forge.coreweave.com/settings#apikeys)와
  CPU 샌드박스 1개를 실행할 수 있는 용량이 필요합니다.
  [자격 증명 선택](/ko/products/sandboxes/serverless/get-started#choose-a-credential)을 참고하세요.
* Agents API 액세스 권한과 선택한 모델에 대한 액세스 권한이 있는 OpenAI 프로젝트가 필요합니다.
* Python과 `uv`가 필요합니다. 버전과 lockfile은 함께 제공되는 레시피에 지정된 것을 사용하세요.
* `api.openai.com`에 대한 아웃바운드 HTTPS 연결과
  `codex-cloud-environments.chatgpt.com`에 대한 보안 WebSocket 액세스가 필요합니다. 이미지를 설정할 때는
  executor와 런타임 의존성을 설치하는 데 사용하는 패키지 레지스트리에도 액세스할 수 있어야 합니다.

This example uses CPU compute to analyze supplied telemetry. It doesn't launch
an inference server or request a GPU. OpenAI model usage and CoreWeave sandbox
compute have separate billing terms.

## Keep application and executor credentials separate

This example uses three credentials: one sandbox credential and two OpenAI keys.
Each credential belongs to a single component, which keeps application access out
of the sandbox:

| 자격 증명 | 사용 주체 | 용도 |
| - | - | - |
| `WANDB_API_KEY` | 애플리케이션 | W\&B 인증으로 샌드박스 프로비저닝 및 운영 |
| `OPENAI_API_KEY` | 애플리케이션 | 세션 생성, 입력 제출, 결과 확인 |
| `OPENAI_EXECUTOR_API_KEY` | 샌드박스 executor(`CODEX_API_KEY`로 사용) | 이 실행 환경을 OpenAI에 연결 |

레시피는 기본적으로 CoreWeave 인증을 사용합니다. W\&B 키를 사용하려면
`--sandbox-auth wandb`를 전달하세요. 샌드박스 자격 증명은 선택한 것 하나만 있으면 되지만,
어느 모드를 사용하든 OpenAI 키는 두 개 모두 필요합니다. 애플리케이션이 선택한
모드를 기록해 두므로, 정리할 때도 동일한 공급자 자격 증명이 사용됩니다.

The OpenAI application key requires `api.agents.read`, `api.agents.write`, and
`api.responses.write`. Create the separate environment key in
[**Agents > Environments > Keys**](https://platform.openai.com/agents?tab=environments\&environment_view=keys).
It must have the same organization, project, and user or service-account ownership
as the session. Set unrelated permissions to **None**.

The recipe passes the restricted executor key through the `environment_variables`
argument in the SDK. It doesn't configure a secret store.

Upload only task inputs. Keep application credentials, local configuration, and
the verifier outside the sandbox. Follow the
[OpenAI authentication instructions](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted#authentication).

<Warning>
  Agent-generated code can read the executor key. Restrict its permissions to limit
  what that code can access through OpenAI.
</Warning>

## Connect an agent session

The runnable recipe implements these steps with the OpenAI and CoreWeave SDKs:

1. Create a self-hosted Agents API session and save its session ID and environment
   ID. Use the exact returned `remote_url` when starting the executor.
2. Create a CoreWeave sandbox with an explicit maximum lifetime and both Python
   and Node.
3. Start `codex exec-server` with the returned environment ID and unchanged
   remote URL. Inject only the restricted executor key as `CODEX_API_KEY`.
4. Upload the synthetic inputs and task instructions, then confirm the environment
   connection. Submit the task and observe its outcome.
5. Retrieve generated artifacts and API activity records before cleanup.

At the end of this sequence, the agent's output files and the session's activity
records are available locally for inspection.

The following configuration excerpt enables built-in delegation at session creation.
The recipe passes these dictionaries to `client.beta.agents.sessions.create()`:

```python theme={"system"}
agent = {
    "model": "gpt-6-astra",
    "instructions": "Follow TASK.md. Delegate the three independent analyses, then synthesize their findings.",
    "multi_agent": {"enabled": True, "max_concurrent_subagents": 3},
}
environment = {
    "type": "self_hosted",
    "workspace_directory": "/workspace/project",
}
```

This configuration permits up to three concurrent subagents, excluding the
coordinator. The instructions request delegation. Configuration alone doesn't
prove the model used it.

The recipe attributes API-completed script commands through turn and subagent IDs.
Commands with explicit nonzero exit codes don't count as successful execution
evidence. The verifier reports omitted exit codes as unknown.
The optional `--require-exit-codes` check requires numeric zero-exit evidence for
every specialist. Overlapping `started_at` and `completed_at` intervals show
concurrent subagent turns. These timestamps have whole-second precision, so they
don't prove simultaneous shell processes or a speedup over a sequential run.

## Run the example

Follow the [recipe setup and run steps](https://github.com/coreweave/cwsandbox-recipes/tree/main/recipes/openai-agents-api).
The recipe includes original synthetic data, a task specification, the
application, and an independent verifier.
Inspect the downloaded report alongside the verifier's findings.

You can also inspect session turns and tool calls in
[**OpenAI Logs > Agents**](https://platform.openai.com/logs?api=agents) while the session
exists. Select the matching organization and project. This example doesn't
provide a chat UI or establish ChatGPT or Codex app continuity.

For an existing command-line interface (CLI) workflow, see
[OpenAI Agents API in cws-agent](https://github.com/coreweave/cws-agent/blob/main/docs/openai-agents.md).
The recipe uses the SDKs directly and doesn't require that CLI.

## Session, sandbox, and file lifetimes

Manage the conversation, compute, and workspace files separately when choosing
what to preserve.

| Resource | What preserves it | What ends it |
| - | - | - |
| API conversation | Reusing the same OpenAI session ID | Explicit API session deletion, subject to provider retention policies |
| Running sandbox | Keeping CoreWeave compute alive | Explicit stop, maximum lifetime, or infrastructure failure |
| Workspace files | Keeping the sandbox or saving files or snapshots | Losing compute without a preserved copy |

Choose the compute lifetime explicitly. The recipe sets a 20-minute maximum
lifetime. A maximum lifetime is a cap, not an inactivity timer that each prompt
refreshes.

Reconnecting an executor to the same running sandbox retains its workspace. Starting
replacement compute with the same environment ID doesn't restore its files.
Download artifacts or use CoreWeave persistence features before stopping compute.
The recipe downloads artifacts and deletes its resources. It doesn't
implement automatic recovery or snapshot and restore.

Stopping a sandbox doesn't delete its API conversation. Deleting the conversation
doesn't stop the sandbox. Attempt both cleanup operations and report each failure.

## Handle failures

To investigate failures, use the following guidance:

* **The executor never connects:** check environment-key ownership, outbound network
  access, executor compatibility, and the exact remote URL returned by OpenAI.
* **OpenAI reports a usage or billing limit:** check the OpenAI organization and
  project billing limits before retrying. An executor connection alone doesn't
  establish that a model turn can run.
* **The stream disconnects or the client times out:** inspect session state and saved
  events before retrying input. A timeout doesn't itself cancel cloud work.
* **Delegation or overlap isn't observed:** read the saved activity evidence.
  A correct report alone is insufficient evidence of a parallel multi-agent run.
* **The OpenAI environment expires:** inspect its state before retrying. The recipe
  may wait until its work deadline rather than fail immediately.
* **The sandbox expires:** recover saved artifacts if available. A replacement
  sandbox requires an explicit file-restoration policy.
* **The application is interrupted:** use the recipe's saved resource journal and
  cleanup command. The maximum sandbox lifetime is a fallback, not a substitute
  for deleting the API session.

For applications that retain sessions, coordinate shutdown with incoming work.
An idle event alone isn't a safe shutdown signal. Webhook-driven provisioning is
a separate deployment pattern. See OpenAI's
[sandbox lifecycle guide](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle).
