> ## Documentation Index
> Fetch the complete documentation index at: https://blaxel-feat-keep-alive-timeout-clarification.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Run Codex in a sandbox

> Run OpenAI Codex inside a Blaxel sandbox to execute coding tasks on a hosted codebase, with persistent storage and secure network access.

This tutorial explains how to run [OpenAI Codex](https://openai.com/codex) inside a Blaxel sandbox and have it execute coding tasks on a codebase hosted in a different sandbox.

## Prerequisites

Before starting, ensure you have:

* a Python or TypeScript development environment;
* a Blaxel account and API key. If not, [sign up for a Blaxel account](https://blaxel.ai) and [create a Blaxel API key](../Security/Access-tokens#api-keys);
* an OpenAI API key with access to Codex. If not, [create an OpenAI API key](https://platform.openai.com/api-keys).

## Install the Blaxel CLI and SDK

1. [Download and install the Blaxel CLI](https://docs.blaxel.ai/cli-reference/introduction#install) and log in to your Blaxel account:

   ```shell theme={null}
   bl login
   ```

2. In a new directory, install the Blaxel SDK ([Python](https://github.com/blaxel-ai/sdk-python) and [TypeScript](https://github.com/blaxel-ai/sdk-typescript) are both supported):

   <CodeGroup>
     ```shell TypeScript (npm) theme={null}
     npm init # if new project
     npm install @blaxel/core
     ```

     ```shell TypeScript (pnpm) theme={null}
     pnpm init # if new project
     pnpm install @blaxel/core
     ```

     ```shell TypeScript (yarn) theme={null}
     yarn init # if new project
     yarn add @blaxel/core
     ```

     ```shell TypeScript (bun) theme={null}
     bun init -m --yes # if new project
     bun install @blaxel/core
     ```

     ```shell Python theme={null}
     python3 -m venv .venv
     source .venv/bin/activate
     pip install blaxel
     ```
   </CodeGroup>

## Create sandboxes

1. In the host environment, define the following variables:

   ```shell theme={null}
   export BLAXEL_API_KEY=YOUR-BLAXEL-API-KEY-HERE
   export OPENAI_API_KEY=YOUR-OPENAI-API-KEY-HERE
   ```

2. Create a script named `main.py` (Python) or `index.ts` (TypeScript) in the same directory.

   <CodeGroup>
     ```typescript TypeScript theme={null}
     import { SandboxInstance } from "@blaxel/core";

     async function main() {
       // Check for required variables
       const blaxelApiKey = process.env.BLAXEL_API_KEY;
       if (!blaxelApiKey) {
         throw new Error("BLAXEL_API_KEY environment variable is not set");
       }
       const openaiApiKey = process.env.OPENAI_API_KEY;
       if (!openaiApiKey) {
         throw new Error("OPENAI_API_KEY environment variable is not set");
       }

       // Create application sandbox
       const appSandbox = await SandboxInstance.createIfNotExists({
         name: "nextjs-sandbox",
         image: "blaxel/nextjs:latest",
         memory: 4096,
         region: "us-pdx-1",
       });
       console.log("Application sandbox created");

       // Start dev server in application sandbox
       await appSandbox.process.exec({
         workingDir: "/blaxel/app",
         command: "npm run dev -- --hostname 0.0.0.0 --port 3000"
       });
       console.log("Application server started");

       // Create preview URL
       const appPreview = await appSandbox.previews.createIfNotExists({
         metadata: { name: "app-preview" },
         spec: {
           port: 3000,
           public: false,
         }
       });
       console.log("Preview URL created");

       // Create preview token
       // Valid for 24 hours
       const expiresAt = new Date(Date.now() + 1440 * 60 * 1000);
       const token = await appPreview.tokens.create(expiresAt);

       // Get preview URL
       console.log(`Preview URL: ${appPreview.spec.url}?bl_preview_token=${token.value}`);
       console.log(`MCP URL: ${appSandbox.metadata.url}/mcp`);

       // Create Codex sandbox
       const codexSandbox = await SandboxInstance.createIfNotExists({
         name: "codex-sandbox",
         image: "blaxel/codex:latest",
         memory: 4096,
         region: "us-pdx-1",
         envs: [
           { name: "OPENAI_API_KEY", value: openaiApiKey },
           { name: "BLAXEL_API_KEY", value: blaxelApiKey }
         ]
       });
       console.log("Codex sandbox created");
     }

     main();

     ```

     ```python Python theme={null}
     import asyncio
     import os
     import sys
     from datetime import datetime, timedelta, UTC

     from blaxel.core import SandboxInstance

     async def main():

         # Check for required variables
         blaxel_api_key = os.getenv("BLAXEL_API_KEY")
         if not blaxel_api_key:
             raise ValueError("BLAXEL_API_KEY environment variable is not set")

         openai_api_key = os.getenv("OPENAI_API_KEY")
         if not openai_api_key:
             raise ValueError("OPENAI_API_KEY environment variable is not set")

         # Create application sandbox
         app_sandbox = await SandboxInstance.create_if_not_exists({
             "name": "nextjs-sandbox",
             "image": "blaxel/nextjs:latest",
             "memory": 4096,
             "region": "us-pdx-1",
         })
         print("Application sandbox created")

         # Start dev server in application sandbox
         await app_sandbox.process.exec({
           "working_dir": "/blaxel/app",
           "command": "npm run dev -- --hostname 0.0.0.0 --port 3000"
         })
         print("Application server started")

         # Create preview URL
         app_preview = await app_sandbox.previews.create_if_not_exists({
             "metadata": {"name": "app-preview"},
             "spec": {
                 "port": 3000,
                 "public": False,
             }
         })
         print("Preview URL created")

         # Create preview token
         # Valid for 24 hours
         expires_at = datetime.now(UTC) + timedelta(minutes=1440)
         token = await app_preview.tokens.create(expires_at)

         # Get preview URL
         print(f"Preview URL: {app_preview.spec.url}?bl_preview_token={token.value}")
         print(f"MCP URL: {app_sandbox.metadata.url}/mcp")

         # Create Codex sandbox
         codex_sandbox = await SandboxInstance.create_if_not_exists({
             "name": "codex-sandbox",
             "image": "blaxel/codex:latest",
             "memory": 4096,
             "region": "us-pdx-1",
             "envs": [
                 {"name": "OPENAI_API_KEY", "value": openai_api_key},
                 {"name": "BLAXEL_API_KEY", "value": blaxel_api_key}
             ]
         })
         print("Codex sandbox created")

     if __name__ == "__main__":
         asyncio.run(main())
     ```
   </CodeGroup>

   This script creates two Blaxel sandboxes:

   * `codex-sandbox` using Blaxel's pre-built Codex image, which includes the Codex CLI
   * `nextjs-sandbox` using Blaxel's Next.js base image

   In the Codex sandbox, it:

   * adds the Blaxel and OpenAI API keys to `codex-sandbox` as environment variables.

   In the application sandbox, it:

   * starts the Next.js dev server in `nextjs-sandbox` on port 3000;
   * creates a preview URL for the Next.js service running in `nextjs-sandbox` on port 3000;
   * creates an access token for the preview URL, valid for 24 hours;
   * returns the preview URL.

3. Run the script to create the sandboxes and preview URL:

   <CodeGroup>
     ```python Python theme={null}
     python main.py
     ```

     ```typescript TypeScript theme={null}
     bun index.ts
     ```
   </CodeGroup>

   Once complete, the script displays the generated preview URL for the Next.js application (for example, `https://b186....preview.bl.run?bl_preview_token=cbba622560db78e...`) and the MCP server URL (for example, `https://sbx-nextjs-sandbox....bl.run/mcp`) for the Next.js sandbox. Note these values, as you will require them in subsequent steps.

## Configure and test Codex

1. Connect to the Codex sandbox terminal:

   ```shell theme={null}
   bl connect sandbox codex-sandbox
   ```

2. Configure Codex to connect to the application sandbox's MCP server URL (obtained from the sandbox creation script in the previous section) with your Blaxel API key (set in the sandbox environment):

   ```shell theme={null}
   codex mcp add sandbox --url YOUR-SANDBOX-MCP-URL-HERE  --bearer-token-env-var  BLAXEL_API_KEY
   ```

3. Start Codex and confirm that it is connected to the sandbox MCP server with the `/mcp` command. This command should return the list of tools available in the sandbox.

## Test Codex

Once Codex starts, give it a coding task referencing the application sandbox, as in the example prompt below:

```shell theme={null}
You have access to a sandbox environment over MCP. The sandbox includes tools to read and write files and directories and run commands. The sandbox includes a skeleton Next.js application at /blaxel/app. Update the application codebase and complete the coding task below.

You must make all your changes only in the sandbox.
Do not make any changes in the local environment.

Your task is: create a website for a new board game of your own invention, including an interactive demo
```

Codex will connect to the application sandbox, inspect the Next.js codebase and make changes as per your request. Once complete, visit the application sandbox's preview URL (obtained from the sandbox creation script in the previous section) to see the result.

## Resources

Want more information on building and deploying with OpenAI on Blaxel? Check out the following resources:

<CardGroup>
  <Card title="Use OpenAI Agents SDK with Blaxel sandboxes" icon="thumbs-up" href="/Tutorials/OpenAI-Agents-SDK">
    Build compute-capable agents backed by Blaxel sandboxes using OpenAI Agents SDK.
  </Card>

  <Card title="Deploy on Blaxel" icon="star-christmas" href="/Tutorials/OpenAI-Agents-SDK-Deployment">
    Build and deploy agents with OpenAI Agents SDK to Blaxel.
  </Card>
</CardGroup>
