> ## 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.

# サンドボックスで Pi を実行する

> アタッチしたターミナルから Pi を実行し（W&B Serverless Inference の利用も可能）、作業内容を取得します。

Run [Pi](https://github.com/earendil-works/pi) inside a CoreWeave sandbox to work on a repository from your terminal. Pi's agent process, files, and shell commands run in the sandbox. Model requests go to your chosen provider. This guide covers creating the workspace, connecting to Pi, checking its work, and stopping compute.

## Prerequisites

Before you begin, you need the following:

* macOS または Linux のターミナル、Python 3.12 以降、および [`uv`](https://docs.astral.sh/uv/getting-started/installation/)。
* サンドボックスへのアクセスに使用する [W\&B APIキー](https://forge.coreweave.com/settings#apikeys)。サンプルでは、認証方式として W\&B 認証を明示的に指定しています。
* [Pi がサポートするモデルプロバイダー](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/providers.md)の認証情報。このガイドでは W\&B Serverless Inference を使用するため、[推論クレジット](/ja/products/inference/serverless/api-reference#prerequisites)が必要です。
* 公開 Git リポジトリの URL。プライベートリポジトリを使用する場合は、サンドボックス内で別途 Git の認証を設定する必要があります。

## Prepare your local environment

Create a local project and install the Sandbox software development kit (SDK):

```bash theme={"system"}
uv init --bare pi-sandbox
cd pi-sandbox
uv venv --python 3.12
source .venv/bin/activate
uv pip install 'cwsandbox[wandb]==1.14.2'
```

同じターミナルで、`[WANDB-API-KEY]` をお使いの W\&B APIキーに置き換えます：

```bash theme={"system"}
export WANDB_API_KEY="[WANDB-API-KEY]"
```

The SDK uses this local credential to manage the sandbox. The creation script doesn't copy it into the sandbox. You configure model authentication separately.

## Create the sandbox

Save the following script as `create_pi_sandbox.py`. It creates a CPU sandbox, installs Pi `0.87.1`, and clones the repository. The Node.js image supplies the runtime and Git. If setup fails, the script stops the sandbox before raising the error.

```python title="create_pi_sandbox.py" theme={"system"}
import sys

from cwsandbox import AuthStrategy, Sandbox

if len(sys.argv) != 2:
    raise SystemExit("Pass a repository URL.")

sandbox = Sandbox.run(
    auth=AuthStrategy.WANDB,
    placement_mode="serverless",
    container_image="node:22-bookworm",
    resources={"cpu": "2", "memory": "4Gi"},
    max_lifetime_seconds=4 * 3600,
    tags=["pi-cli"],
)
print(f"Sandbox ID: {sandbox.sandbox_id}", flush=True)
try:
    sandbox.wait()
    commands = [
        ["npm", "install", "--global", "--ignore-scripts", "@earendil-works/pi-coding-agent@0.87.1"],
        ["mkdir", "-p", "/workspace"],
        ["git", "clone", "--", sys.argv[1], "/workspace/project"],
        ["pi", "--version"],
    ]
    for command in commands:
        result = sandbox.exec(command, timeout_seconds=900, check=True).result()
        print(result.stdout, end="")
except BaseException:
    sandbox.stop().result()
    raise
```

Replace `[REPOSITORY-URL]` with your repository URL, then run:

```bash theme={"system"}
python create_pi_sandbox.py [REPOSITORY-URL]
```

Keep the printed sandbox ID. Successful setup prints Pi's version, `0.87.1`. The sandbox remains running after the script exits, until you stop it or its 4-hour lifetime expires. The lifetime includes startup time.

## Attach your terminal

Save the following as `attach_sandbox.py`. It forwards your terminal input to a Bash shell in the sandbox and restores your local terminal settings when the shell exits.

```python title="attach_sandbox.py" theme={"system"}
import os
import shutil
import sys
import termios
import threading
import tty

from cwsandbox import AuthStrategy, Sandbox

if not sys.stdin.isatty() or not sys.stdout.isatty():
    raise SystemExit("Run this script in an interactive terminal.")

sandbox = Sandbox.from_id(sys.argv[1], auth=AuthStrategy.WANDB).result()
size = shutil.get_terminal_size()
terminal = sandbox.shell(["/bin/bash"], width=size.columns, height=size.lines)
fd = sys.stdin.fileno()
saved = termios.tcgetattr(fd)


def forward_input():
    while data := os.read(fd, 1024):
        terminal.stdin.write(data).result()
    terminal.stdin.close().result()


try:
    tty.setraw(fd)
    threading.Thread(target=forward_input, daemon=True).start()
    for chunk in terminal.output:
        sys.stdout.buffer.write(chunk)
        sys.stdout.buffer.flush()
    result = terminal.result()
finally:
    termios.tcsetattr(fd, termios.TCSADRAIN, saved)
    terminal.stdin.close().result()

raise SystemExit(result.returncode)
```

Replace `[SANDBOX-ID]` with your sandbox ID:

```bash theme={"system"}
python attach_sandbox.py [SANDBOX-ID]
```

At the sandbox's Bash prompt, enter the cloned repository:

```bash theme={"system"}
cd /workspace/project
```

Inside this shell, run the provider setup and Pi commands in the following sections.

## Choose a model provider

次のいずれかのオプションを選択してください。サンドボックスの認証とモデルの認証は、どちらにも W\&B キーを使用する場合でも別々に扱われます。Pi は自身のプロセスに渡された認証情報にアクセスでき、ワークスペース内のコンテンツを選択したモデルプロバイダーに送信する可能性があります。

### Use Serverless Inference

We recommend [W\&B Serverless Inference](/products/inference/serverless) for this walkthrough. The example uses `zai-org/GLM-5.2`. Choose another model from the [model catalog](/products/inference/serverless/models) if it better fits your task.

サンドボックスのシェルで、入力内容が表示されないプロンプトに W\&B の推論キーを入力します。アカウントに推論クレジットがある場合は、サンドボックスへのアクセスに使用したものと同じ W\&B キーを使用できます。

```bash theme={"system"}
read -r -s -p 'W&B inference API key: ' WANDB_INFERENCE_API_KEY
export WANDB_INFERENCE_API_KEY
printf '\n'
```

In the sandbox shell, configure Pi's OpenAI-compatible provider. The following commands create the `~/.pi/agent/models.json` file. The quoted heredoc preserves the environment-variable reference so the file doesn't contain the key:

```bash theme={"system"}
mkdir -p ~/.pi/agent
cat > ~/.pi/agent/models.json <<'JSON'
{
  "providers": {
    "wandb": {
      "baseUrl": "https://api.inference.wandb.ai/v1",
      "api": "openai-completions",
      "apiKey": "${WANDB_INFERENCE_API_KEY}",
      "models": [
        {
          "id": "zai-org/GLM-5.2",
          "name": "GLM 5.2 (W&B)",
          "reasoning": true,
          "input": ["text"],
          "contextWindow": 1048576,
          "maxTokens": 8192
        }
      ]
    }
  }
}
JSON
pi --provider wandb --model zai-org/GLM-5.2
```

Pi opens its terminal interface with `/workspace/project` and `zai-org/GLM-5.2` in the status area. Submit a task in [Run Pi and check its work](#run-pi-and-check-its-work) to verify model access.

The configuration limits each response to 8,192 tokens. If you change models, update the model ID and capabilities to match the provider. For more configuration options, see [Pi model configuration](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/models.md).

### Use another provider

To use Anthropic or OpenAI directly, choose the corresponding API key and start Pi in the same sandbox shell:

<Tabs>
  <Tab title="Anthropic">
    ```bash theme={"system"}
    read -r -s -p 'Anthropic API key: ' ANTHROPIC_API_KEY
    export ANTHROPIC_API_KEY
    printf '\n'
    pi --provider anthropic
    ```
  </Tab>

  <Tab title="OpenAI">
    ```bash theme={"system"}
    read -r -s -p 'OpenAI API key: ' OPENAI_API_KEY
    export OPENAI_API_KEY
    printf '\n'
    pi --provider openai
    ```
  </Tab>
</Tabs>

Use `/model` inside Pi to choose a model available to your provider. The Pi provider documentation linked in the prerequisites covers other providers and account sign-in options.

## Run Pi and check its work

If Pi displays a project trust prompt, follow it. To check that Pi can create and read a file in the cloned repository, submit this task in Pi:

```text theme={"system"}
Create sandbox-proof.txt in the current directory containing exactly "Hello from CoreWeave", then read it back.
```

Pi can read, write, and edit files and run shell commands. Its tools operate with the permissions of the sandbox process. Review the repository and any Pi extensions you load. See [Pi security](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/security.md).

After Pi finishes, enter `/quit` to return to the sandbox shell. Pi prints a `To resume this session:` line with a `pi --session` command. Keep that command to reopen this conversation.

Verify the file independently:

```bash theme={"system"}
cat /workspace/project/sandbox-proof.txt
```

The output should contain `Hello from CoreWeave`.

For an unattended task with the W\&B setup, run Pi in print mode from the same shell:

```bash theme={"system"}
pi --provider wandb --model zai-org/GLM-5.2 --print 'Read sandbox-proof.txt and report its contents.'
```

Print mode processes the prompt, prints Pi's response, and exits. For another provider, replace the provider and model arguments with your selection.

## Reconnect to a conversation

To reconnect while the sandbox is running, run the `attach_sandbox.py` script again. Re-enter any API keys supplied through the previous shell and return to the `/workspace/project` directory before starting Pi. To reopen your interactive conversation, replace `[SESSION-ID]` with the ID from the `To resume this session:` line Pi printed when you exited:

```bash theme={"system"}
pi --session [SESSION-ID]
```

Alternatively, `pi --continue` resumes the most recent session for the project. If you ran the print-mode example after your interactive conversation, it resumes the print-mode session. Use `--session` to return to a specific conversation.

## Retrieve the result and stop

Enter `exit` to leave the sandbox shell. In your local terminal, save the following as `collect_pi_result.py`:

```python title="collect_pi_result.py" theme={"system"}
import sys
from pathlib import Path

from cwsandbox import AuthStrategy, Sandbox

if len(sys.argv) != 2:
    raise SystemExit("Pass a sandbox ID.")

sandbox = Sandbox.from_id(sys.argv[1], auth=AuthStrategy.WANDB).result()
content = sandbox.read_file("/workspace/project/sandbox-proof.txt").result()
Path("sandbox-proof.txt").write_bytes(content)
print(content.decode(), end="")
sandbox.stop().result()
```

To save the file locally and stop compute, replace `[SANDBOX-ID]` with your sandbox ID and run the script:

```bash theme={"system"}
python collect_pi_result.py [SANDBOX-ID]
```

This script stops the sandbox only after it retrieves the file. If retrieval fails, fix the error and retry. To stop the sandbox separately when you no longer need its files, save the following as `stop_pi_sandbox.py`:

```python title="stop_pi_sandbox.py" theme={"system"}
import sys

from cwsandbox import AuthStrategy, Sandbox

if len(sys.argv) != 2:
    raise SystemExit("Pass a sandbox ID.")

sandbox = Sandbox.from_id(sys.argv[1], auth=AuthStrategy.WANDB).result()
sandbox.stop().result()
```

Run the script with your sandbox ID:

```bash theme={"system"}
python stop_pi_sandbox.py [SANDBOX-ID]
```

Pi やシェルを終了しても、サンドボックスは停止しません。この例では永続マウントを使用していないため、サンドボックスの停止または有効期限切れの前に、必要なファイルを取得しておいてください。新しいサンドボックスにリストアできるワークスペースが必要な場合は、作成時に[ファイルシステムスナップショット](/products/sandboxes/serverless/file-system-snapshots)を設定してください。

## Troubleshoot

Use these checks to resolve common issues:

* If sandbox creation fails, check your sandbox credential and the sandbox authentication requirements linked in the prerequisites.
* If Pi can't authenticate, check that the model credential is exported in the shell that starts Pi. With W\&B, also check inference credits and the model ID.
* If Pi can't reach its provider, check outbound access to the provider endpoint. Installation and cloning also require access to npm and your Git host.
* If your connection drops, attach again while the sandbox runs. If you need a process to survive terminal disconnections, use a terminal multiplexer such as `tmux`.

## Next steps

For more information, see the following resources:

* [Interactive shells](../client/guides/interactive-shells) covers terminal access through the SDK.
* [File operations](../client/guides/file-operations) covers uploading and retrieving workspace files.
* [Pi documentation](https://github.com/earendil-works/pi/tree/main/packages/coding-agent/docs) covers sessions, model selection, and extensions.
