Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/opensandbox-group/OpenSandbox/llms.txt

Use this file to discover all available pages before exploring further.

The Code Interpreter SDK lets you run multi-language code snippets inside an OpenSandbox sandbox without managing runtime installations yourself. A single prebuilt image ships Python, Java, Go, and TypeScript runtimes, and the CodeInterpreter client exposes a simple codes.run() API that returns structured stdout, a return value, and any error details.

Prerequisites

Pull the prebuilt code-interpreter image from the registry before starting the server:
docker pull sandbox-registry.cn-zhangjiakou.cr.aliyuncs.com/opensandbox/code-interpreter:v1.1.0

# Docker Hub mirror
# docker pull opensandbox/code-interpreter:v1.1.0

Start the OpenSandbox Server

1

Install and initialise the server

uv pip install opensandbox-server
opensandbox-server init-config ~/.sandbox.toml --example docker
opensandbox-server
2

Install the Python SDKs

uv pip install opensandbox opensandbox-code-interpreter

Environment Variables

VariableDefaultDescription
SANDBOX_DOMAINlocalhost:8080Sandbox service address
SANDBOX_API_KEY(optional)API key if your server requires authentication
SANDBOX_IMAGEsandbox-registry.cn-zhangjiakou.cr.aliyuncs.com/opensandbox/code-interpreter:v1.1.0Sandbox image to use

Full Example

The script below creates a sandbox, attaches a CodeInterpreter, runs code in four languages, prints stdout and the return value for each, and then terminates the sandbox.
import asyncio
import os
from datetime import timedelta

from code_interpreter import CodeInterpreter, SupportedLanguage
from opensandbox import Sandbox
from opensandbox.config import ConnectionConfig


async def main() -> None:
    domain = os.getenv("SANDBOX_DOMAIN", "localhost:8080")
    api_key = os.getenv("SANDBOX_API_KEY")
    image = os.getenv(
        "SANDBOX_IMAGE",
        "sandbox-registry.cn-zhangjiakou.cr.aliyuncs.com/opensandbox/code-interpreter:v1.1.0",
    )

    config = ConnectionConfig(
        domain=domain,
        api_key=api_key,
        request_timeout=timedelta(seconds=60),
    )

    sandbox = await Sandbox.create(
        image,
        connection_config=config,
        entrypoint=["/opt/code-interpreter/code-interpreter.sh"]
    )

    async with sandbox:
        interpreter = await CodeInterpreter.create(sandbox=sandbox)

        # Python example: show runtime info and return a simple calculation.
        py_exec = await interpreter.codes.run(
            "import platform\n"
            "print('Hello from Python!')\n"
            "result = {'py': platform.python_version(), 'sum': 2 + 2}\n"
            "result",
            language=SupportedLanguage.PYTHON,
        )
        print("\n=== Python example ===")
        for msg in py_exec.logs.stdout:
            print(f"[Python stdout] {msg.text}")
        if py_exec.result:
            for res in py_exec.result:
                print(f"[Python result] {res.text}")

        # Java example: print to stdout and return the final result line.
        java_exec = await interpreter.codes.run(
            "System.out.println(\"Hello from Java!\");\n"
            "int result = 2 + 3;\n"
            "System.out.println(\"2 + 3 = \" + result);\n"
            "result",
            language=SupportedLanguage.JAVA,
        )
        print("\n=== Java example ===")
        for msg in java_exec.logs.stdout:
            print(f"[Java stdout] {msg.text}")
        if java_exec.result:
            for res in java_exec.result:
                print(f"[Java result] {res.text}")
        if java_exec.error:
            print(f"[Java error] {java_exec.error.name}: {java_exec.error.value}")

        # Go example: print logs and demonstrate a main function structure.
        go_exec = await interpreter.codes.run(
            "package main\n"
            "import \"fmt\"\n"
            "func main() {\n"
            "    fmt.Println(\"Hello from Go!\")\n"
            "    sum := 3 + 4\n"
            "    fmt.Println(\"3 + 4 =\", sum)\n"
            "}",
            language=SupportedLanguage.GO,
        )
        print("\n=== Go example ===")
        for msg in go_exec.logs.stdout:
            print(f"[Go stdout] {msg.text}")
        if go_exec.error:
            print(f"[Go error] {go_exec.error.name}: {go_exec.error.value}")

        # TypeScript example: use typing and sum an array.
        ts_exec = await interpreter.codes.run(
            "console.log('Hello from TypeScript!');\n"
            "const nums: number[] = [1, 2, 3];\n"
            "console.log('sum =', nums.reduce((a, b) => a + b, 0));",
            language=SupportedLanguage.TYPESCRIPT,
        )
        print("\n=== TypeScript example ===")
        for msg in ts_exec.logs.stdout:
            print(f"[TypeScript stdout] {msg.text}")
        if ts_exec.error:
            print(f"[TypeScript error] {ts_exec.error.name}: {ts_exec.error.value}")

        await sandbox.kill()


if __name__ == "__main__":
    asyncio.run(main())
Run it with:
uv run python examples/code-interpreter/main.py

Expected Output

=== Python example ===
[Python stdout] Hello from Python!
[Python result] {'py': '3.14.2', 'sum': 4}

=== Java example ===
[Java stdout] Hello from Java!
[Java stdout] 2 + 3 = 5
[Java result] 5

=== Go example ===
[Go stdout] Hello from Go!
3 + 4 = 7

=== TypeScript example ===
[TypeScript stdout] Hello from TypeScript!
[TypeScript stdout] sum = 6

Using a Sandbox Pool (Kubernetes)

When running on Kubernetes, you can pre-warm a pool of code-interpreter sandboxes to eliminate cold-start latency. Create a Pool resource and pass extensions={"poolRef": "pool-sample"} when creating the sandbox.
sandbox = await Sandbox.create(
    image,
    connection_config=config,
    extensions={"poolRef": "pool-sample"},
    entrypoint=["/opt/code-interpreter/code-interpreter.sh"],
    env={"TEST_ENV": "test"},
)
The Kubernetes Pool manifest below configures a buffer of 1–3 warm sandboxes out of a maximum pool of 5:
apiVersion: sandbox.opensandbox.io/v1alpha1
kind: Pool
metadata:
  labels:
    app.kubernetes.io/name: sandbox-k8s
    app.kubernetes.io/managed-by: kustomize
  name: pool-sample
  namespace: opensandbox
spec:
  template:
    metadata:
      labels:
        app: example
    spec:
      volumes:
        - name: sandbox-storage
          emptyDir: { }
        - name: opensandbox-bin
          emptyDir: { }
      initContainers:
        - name: task-executor-installer
          image: sandbox-registry.cn-zhangjiakou.cr.aliyuncs.com/opensandbox/task-executor:v0.1.0
          command: ["/bin/sh", "-c"]
          args:
            - |
              cp /workspace/server /opt/opensandbox/task-executor &&
              chmod +x /opt/opensandbox/task-executor
          volumeMounts:
            - name: opensandbox-bin
              mountPath: /opt/opensandbox
        - name: execd-installer
          image: sandbox-registry.cn-zhangjiakou.cr.aliyuncs.com/opensandbox/execd:v1.0.19
          command: ["/bin/sh", "-c"]
          args:
            - |
              cp ./execd /opt/opensandbox/execd &&
              cp ./bootstrap.sh /opt/opensandbox/bootstrap.sh &&
              chmod +x /opt/opensandbox/execd &&
              chmod +x /opt/opensandbox/bootstrap.sh
          volumeMounts:
            - name: opensandbox-bin
              mountPath: /opt/opensandbox
      containers:
        - name: sandbox
          image: sandbox-registry.cn-zhangjiakou.cr.aliyuncs.com/opensandbox/code-interpreter:v1.1.0
          command:
            - "/bin/sh"
            - "-c"
            - |
              /opt/opensandbox/task-executor -listen-addr=0.0.0.0:5758 >/tmp/task-executor.log 2>&1
          env:
            - name: SANDBOX_MAIN_CONTAINER
              value: main
            - name: EXECD_ENVS
              value: /opt/opensandbox/.env
            - name: EXECD
              value: /opt/opensandbox/execd
          volumeMounts:
            - name: sandbox-storage
              mountPath: /var/lib/sandbox
            - name: opensandbox-bin
              mountPath: /opt/opensandbox
      tolerations:
        - operator: "Exists"
  capacitySpec:
    bufferMax: 3
    bufferMin: 1
    poolMax: 5
    poolMin: 0

Start the Kubernetes Server

After applying the Pool manifest, start the Kubernetes-mode OpenSandbox server:
uv pip install opensandbox-server

# replace with your k8s cluster config, kubeconfig etc.
opensandbox-server init-config ~/.sandbox.toml --example k8s
curl -o ~/batchsandbox-template.yaml https://raw.githubusercontent.com/opensandbox-group/OpenSandbox/main/server/opensandbox_server/examples/example.batchsandbox-template.yaml

opensandbox-server

Run the Pool Example

uv pip install opensandbox opensandbox-code-interpreter
uv run python examples/code-interpreter/main_use_pool.py

Pool Example Output

=== Verify Environment Variable ===
[ENV Check] TEST_ENV value: test

[ENV Result] 'test'

=== Java example ===
[Java stdout] Hello from Java!

[Java stdout] 2 + 3 = 5

[Java result] 5

=== Go example ===
[Go stdout] Hello from Go!
3 + 4 = 7


=== TypeScript example ===
[TypeScript stdout] Hello from TypeScript!

[TypeScript stdout] sum = 6
Run the pool example with uv run python examples/code-interpreter/main_use_pool.py after applying the Pool manifest to your cluster.

References

Build docs developers (and LLMs) love