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

# Give your agent a Cloud code interpreter

> Let a model generate Python, execute it in a temporary Cloud box, return the result to the model, and clean up.

**Give a model a calculation task and let it use a Cloud box as its tool.** The model generates Python, your application runs it in an isolated box, and the execution result goes back to the model for its answer.

Use this pattern when an agent needs to calculate an answer or transform data with code. This first task has a known result so you can verify the entire tool loop before substituting your own data.

Ask it to calculate the sum of the squares of integers 1 through 100. Your terminal will show **338350**, and the temporary box will be removed automatically.

![Five-step loop from model tool call through Cloud execution and cleanup to the final answer](https://mintcdn.com/boxliteai/T55zNyy-RmFxjFGm/assets/diagrams/cloud-code-interpreter.svg?fit=max\&auto=format\&n=T55zNyy-RmFxjFGm\&q=85\&s=e6eb5802b67526a63ab42d758b5cf174)

This is **box as an agent's tool**: the model and orchestration run outside the box. For an agent that lives inside a persistent workspace, see [Host an agent runtime](https://docs.boxlite.ai/cloud/agent-runtime.md).

## 1. Configure your credentials

You need a [BoxLite Cloud account](https://app.boxlite.ai) with available capacity and a model provider supporting the **Anthropic Messages API and tool calls**.

Create a Cloud key under **API Keys** in the console. In your local Bash or Zsh terminal, set the Cloud endpoint and read the key:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export BOXLITE_REST_URL="https://api.boxlite.ai"
printf 'BoxLite Cloud API key: '
read -rs BOXLITE_API_KEY
printf '\n'
export BOXLITE_API_KEY
```

Set your model provider's base URL and model ID, then read its key. The URL below is Anthropic's endpoint; replace it with your provider's Anthropic-compatible base URL when using another provider. Use the base URL, without `/v1/messages`.

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export ANTHROPIC_BASE_URL="https://api.anthropic.com"
export ANTHROPIC_MODEL="<YOUR_TOOL_CAPABLE_MODEL_ID>"
printf 'Model provider API key: '
read -rs ANTHROPIC_API_KEY
printf '\n'
export ANTHROPIC_API_KEY
```

Both keys stay in your local application. **Only the generated Python code enters the box.** No model credentials, Cloud credentials, host directories, or Secrets are supplied to the guest.

## 2. Run the complete tool loop

Choose one client. Each example makes a real model request, handles its `run_python` tool call, returns the result, and prints the model's answer.

The box uses the `python:alpine` image with one CPU and 256 MiB memory. Guest networking is disabled; the generated code uses Python's standard library. The SDK examples set a 3-second execution timeout and stop waiting for its result after 15 seconds.

> [tab] Python
>
> Use Python 3.10 or later:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> python3 -m venv .venv
> source .venv/bin/activate
> python -m pip install --upgrade boxlite anthropic
> ```
>
> Save as `interpreter.py`:
>
> ```python interpreter.py theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import asyncio
> import os
>
> from anthropic import Anthropic
> import boxlite
>
> TASK = "Calculate the sum of the squares of integers 1 through 100 inclusive. Print only the number. Calculate it; do not hardcode the answer."
> TOOL = {
>     "name": "run_python",
>     "description": "Execute Python standard-library code in an isolated Cloud box with no network access.",
>     "input_schema": {
>         "type": "object",
>         "properties": {"code": {"type": "string"}},
>         "required": ["code"],
>     },
> }
>
>
> def generate_code():
>     with Anthropic(timeout=90, max_retries=0) as model:
>         response = model.messages.create(
>             model=os.environ["ANTHROPIC_MODEL"], max_tokens=2048,
>             messages=[{"role": "user", "content": TASK}],
>             tools=[TOOL], tool_choice={"type": "tool", "name": "run_python"},
>         )
>     for block in response.content:
>         if block.type == "tool_use" and block.name == "run_python":
>             code = block.input.get("code")
>             if isinstance(code, str) and code.strip():
>                 return code, response, block.id
>     raise RuntimeError("The model did not return a run_python call with code.")
>
>
> async def run_python(code):
>     runtime = boxlite.Boxlite.rest(boxlite.BoxliteRestOptions(
>         url=os.environ["BOXLITE_REST_URL"],
>         credential=boxlite.ApiKeyCredential(os.environ["BOXLITE_API_KEY"]),
>     ))
>     box = None
>     try:
>         box = await runtime.create(boxlite.BoxOptions(
>             image="python:alpine", cpus=1, memory_mib=256,
>             auto_stop=0, auto_delete=0,
>             network=boxlite.NetworkSpec(mode="disabled"),
>         ))
>         print(f"Created box: {box.id}")
>         await box.start()
>         execution = await box.exec("python", args=["-c", code], timeout_secs=3)
>
>         async def collect(stream):
>             return "".join([chunk async for chunk in stream])
>
>         stdout, stderr, result = await asyncio.wait_for(asyncio.gather(
>             collect(execution.stdout()), collect(execution.stderr()), execution.wait(),
>         ), timeout=15)
>         if result.exit_code != 0:
>             raise RuntimeError(f"Python exited with {result.exit_code}: {stderr.strip()}")
>         return stdout.strip()
>     finally:
>         try:
>             if box is not None:
>                 for attempt in range(5):
>                     try:
>                         await runtime.remove(box.id, force=True)
>                         break
>                     except RuntimeError as error:
>                         if "Box state change in progress" not in str(error) or attempt == 4:
>                             raise
>                         await asyncio.sleep(2)
>                 print(f"Removed box: {box.id}")
>         finally:
>             runtime.close()
>
>
> if __name__ == "__main__":
>     code, response, call_id = generate_code()
>     print("Model requested run_python")
>     result = asyncio.run(run_python(code))
>     print(f"Result: {result}")
>     with Anthropic(timeout=90, max_retries=0) as model:
>         answer = model.messages.create(
>             model=os.environ["ANTHROPIC_MODEL"], max_tokens=2048,
>             tools=[TOOL], tool_choice={"type": "none"},
>             messages=[
>                 {"role": "user", "content": TASK},
>                 {"role": "assistant", "content": response.content},
>                 {"role": "user", "content": [{
>                     "type": "tool_result", "tool_use_id": call_id, "content": result,
>                 }]},
>             ],
>         )
>     print("Answer:", "".join(b.text for b in answer.content if b.type == "text"))
> ```
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> python interpreter.py
> ```

> [tab] TypeScript
>
> Use Node.js 20 or later:
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> npm install @boxlite-ai/boxlite @anthropic-ai/sdk tsx
> ```
>
> Save as `interpreter.ts`:
>
> ```typescript interpreter.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import Anthropic from "@anthropic-ai/sdk";
> import { ApiKeyCredential, BoxliteRestOptions, JsBoxlite } from "@boxlite-ai/boxlite";
>
> const task = "Calculate the sum of the squares of integers 1 through 100 inclusive. Print only the number. Calculate it; do not hardcode the answer.";
>
> const tool = {
>       name: "run_python",
>       description: "Execute Python standard-library code in an isolated Cloud box with no network access.",
>       input_schema: {
>         type: "object" as const,
>         properties: { code: { type: "string" } }, required: ["code"],
>       },
>     };
>
> async function generateCode() {
>   const model = new Anthropic({ timeout: 90_000, maxRetries: 0 });
>   const response = await model.messages.create({
>     model: process.env.ANTHROPIC_MODEL!, max_tokens: 2048,
>     messages: [{ role: "user", content: task }],
>     tools: [tool],
>     tool_choice: { type: "tool", name: "run_python" },
>   });
>   for (const block of response.content) {
>     if (block.type === "tool_use" && block.name === "run_python") {
>       const code = (block.input as { code?: unknown }).code;
>       if (typeof code === "string" && code.trim()) return { code, response, callId: block.id };
>     }
>   }
>   throw new Error("The model did not return a run_python call with code.");
> }
>
> async function collect(stream: { next(): Promise<string | null> }) {
>   let output = "";
>   for (let chunk = await stream.next(); chunk !== null; chunk = await stream.next()) {
>     output += chunk;
>   }
>   return output;
> }
>
> async function runPython(code: string) {
>   const runtime = JsBoxlite.rest(new BoxliteRestOptions({
>     url: process.env.BOXLITE_REST_URL!,
>     credential: new ApiKeyCredential(process.env.BOXLITE_API_KEY!),
>   }));
>   let boxId: string | undefined;
>   try {
>     const box = await runtime.create({
>       image: "python:alpine", cpus: 1, memoryMib: 256,
>       autoStop: 0, autoDelete: 0, network: { mode: "disabled" },
>     });
>     boxId = box.id;
>     console.log(`Created box: ${boxId}`);
>     await box.start();
>     const execution = await box.exec("python", ["-c", code], null, false, null, 3);
>     let timer: ReturnType<typeof setTimeout> | undefined;
>     const resultPromise = Promise.all([
>       execution.stdout().then(collect), execution.stderr().then(collect), execution.wait(),
>     ]);
>     const [stdout, stderr, result] = await Promise.race([
>       resultPromise,
>       new Promise<never>((_, reject) => {
>         timer = setTimeout(() => reject(new Error("Execution result timed out")), 15_000);
>       }),
>     ]).finally(() => clearTimeout(timer));
>     if (result.exitCode !== 0) {
>       throw new Error(`Python exited with ${result.exitCode}: ${stderr.trim()}`);
>     }
>     return stdout.trim();
>   } finally {
>     try {
>       if (boxId) {
>         for (let attempt = 0; attempt < 5; attempt++) {
>           try {
>             await runtime.remove(boxId, true);
>             break;
>           } catch (error) {
>             if (!String(error).includes("Box state change in progress") || attempt === 4) throw error;
>             await new Promise(resolve => setTimeout(resolve, 2000));
>           }
>         }
>         console.log(`Removed box: ${boxId}`);
>       }
>     } finally {
>       runtime.close();
>     }
>   }
> }
>
> async function main() {
>   const { code, response, callId } = await generateCode();
>   console.log("Model requested run_python");
>   const result = await runPython(code);
>   console.log(`Result: ${result}`);
>   const model = new Anthropic({ timeout: 90_000, maxRetries: 0 });
>   const answer = await model.messages.create({
>     model: process.env.ANTHROPIC_MODEL!, max_tokens: 2048,
>     tools: [tool], tool_choice: { type: "none" },
>     messages: [
>       { role: "user", content: task },
>       { role: "assistant", content: response.content },
>       { role: "user", content: [{
>         type: "tool_result", tool_use_id: callId, content: result,
>       }] },
>     ],
>   });
>   console.log("Answer:", answer.content.map(b => b.type === "text" ? b.text : "").join(""));
> }
>
> main().catch((error) => {
>   console.error(error);
>   process.exitCode = 1;
> });
> ```
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> npx tsx interpreter.ts
> ```

> [tab] CLI
>
> Install the latest CLI on macOS or Linux. This example also uses `curl`, `jq`, and Bash. Use the SDK examples when your tool handler needs a per-execution timeout; the CLI example runs this finite calculation without one.
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> curl -fsSL https://sh.boxlite.ai | sh
> export PATH="$HOME/.local/bin:$PATH"
> boxlite --version
> jq --version
> ```
>
> Save as `interpreter.sh`. Run it as a script so its cleanup trap belongs to this task, rather than your interactive shell.
>
> ```bash interpreter.sh theme={"theme":{"light":"github-light","dark":"github-dark"}}
> #!/usr/bin/env bash
> set -euo pipefail
> : "${BOXLITE_REST_URL:?Set BOXLITE_REST_URL}"
> : "${BOXLITE_API_KEY:?Set BOXLITE_API_KEY}"
> : "${ANTHROPIC_BASE_URL:?Set ANTHROPIC_BASE_URL}"
> : "${ANTHROPIC_API_KEY:?Set ANTHROPIC_API_KEY}"
> : "${ANTHROPIC_MODEL:?Set ANTHROPIC_MODEL}"
>
> # The request is sent from your workstation, not from a box.
> request="$(jq -n --arg model "$ANTHROPIC_MODEL" '{
>   model: $model, max_tokens: 2048,
>   messages: [{role: "user", content: "Calculate the sum of the squares of integers 1 through 100 inclusive. Print only the number. Calculate it; do not hardcode the answer."}],
>   tools: [{name: "run_python",
>     description: "Execute Python standard-library code in an isolated Cloud box with no network access.",
>     input_schema: {type: "object", properties: {code: {type: "string"}}, required: ["code"]}}],
>   tool_choice: {type: "tool", name: "run_python"}
> }')"
> response="$(printf '%s' "$request" | curl --fail-with-body --silent --show-error --max-time 90 \
>   "${ANTHROPIC_BASE_URL%/}/v1/messages" \
>   -H "x-api-key: $ANTHROPIC_API_KEY" \
>   -H 'anthropic-version: 2023-06-01' \
>   -H 'Content-Type: application/json' --data-binary @-)"
> code="$(printf '%s' "$response" | jq -er '
>   [.content[] | select(.type == "tool_use" and .name == "run_python")][0].input.code
>   | select(type == "string" and length > 0)
> ')"
> printf 'Model requested run_python\n'
>
> box_id=''
> cleanup() {
>   if [ -n "$box_id" ]; then
>     for attempt in 1 2 3 4 5; do
>       if error="$(boxlite rm -f "$box_id" 2>&1)"; then
>         printf 'Removed box: %s\n' "$box_id"
>         return 0
>       fi
>       case "$error" in
>         *"Box state change in progress"*) sleep 2 ;;
>         *) printf '%s\n' "$error" >&2; return 1 ;;
>       esac
>     done
>     printf '%s\n' "$error" >&2
>     return 1
>   fi
> }
> trap cleanup EXIT
> box_id="$(boxlite create --cpus 1 --memory 256 --network disabled \
>   --auto-stop 0 --auto-delete 0 python:alpine)"
> printf 'Created box: %s\n' "$box_id"
> boxlite start "$box_id" >/dev/null
> result="$(boxlite exec "$box_id" -- python -c "$code")"
> cleanup
> box_id=''
> printf 'Result: %s\n' "$result"
>
> # Return the execution result to the model after the temporary box is gone.
> call_id="$(printf '%s' "$response" | jq -er '
>   [.content[] | select(.type == "tool_use" and .name == "run_python")][0].id
> ')"
> answer="$(printf '%s' "$request" | jq \
>   --argjson response "$response" --arg result "$result" --arg call_id "$call_id" '
>   .tool_choice = {type: "none"} |
>   .messages += [
>     {role: "assistant", content: $response.content},
>     {role: "user", content: [{type: "tool_result", tool_use_id: $call_id, content: $result}]}
>   ]
> ' | curl --fail-with-body --silent --show-error --max-time 90 \
>   "${ANTHROPIC_BASE_URL%/}/v1/messages" \
>   -H "x-api-key: $ANTHROPIC_API_KEY" \
>   -H 'anthropic-version: 2023-06-01' \
>   -H 'Content-Type: application/json' --data-binary @-)"
> printf 'Answer: '
> printf '%s' "$answer" | jq -er '[.content[] | select(.type == "text") | .text] | join("")'
> ```
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> bash interpreter.sh
> ```

## 3. Check the result and cleanup

A successful run looks like this:

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
Model requested run_python
Created box: <box-id>
Removed box: <box-id>
Result: 338350
Answer: 338350
```

The model's final wording can vary. **`Result` comes from executing its generated code in the box.** The application returns that output using the model's tool-call ID, so the final answer can use the computation.

Check the console's **Boxes** list: the printed box ID should no longer exist. The example removes it before requesting the final answer, so the box also stays deleted if that last model request fails.

The SDK examples use `finally`; the CLI uses an exit trap. A Python error also triggers cleanup and a nonzero local exit code. The SDK examples apply the same cleanup when execution or result collection times out. Cleanup briefly retries if Cloud reports a state transition in progress. If you forcibly terminate the local process, check the console for a leftover box and remove it there.

## Adapt it to your agent

Change the task prompt to another calculation or standard-library data-processing task. Keep the same tool interface: the model supplies `code`, and your application returns the execution output.

In an existing agent loop, register `run_python` as a tool handler. You can choose whether to return execution errors as tool results for the model to correct; this walkthrough stops on an execution error.

| Your next requirement | Where to go |
| - | - |
| Set CPU, memory, and execution capacity | [Choose a box size](https://docs.boxlite.ai/cloud/box-sizes.md) |
| Decide when to retain, stop, or delete the workspace | [Box lifecycle](https://docs.boxlite.ai/cloud/box-lifecycle.md) |
| Reuse a workspace across multiple tool calls | [Manage boxes from code](https://docs.boxlite.ai/cloud/box-from-code.md) |
| Run code with additional packages | [Choose an image](https://docs.boxlite.ai/cloud/images.md) or prepare a [checkpoint](https://docs.boxlite.ai/cloud/checkpoints.md) |
| Give an in-box tool access to an authenticated API | Configure [Secrets](https://docs.boxlite.ai/cloud/secrets.md) and the necessary [outbound access](https://docs.boxlite.ai/cloud/network-policy.md) |
| Keep an application running after a task finishes | [Cloud deployment quickstart](https://docs.boxlite.ai/cloud/quickstart.md) |

Keep model and Cloud credentials in the trusted caller. Use Secrets when code **inside** a box needs an external credential; this example's model calls happen outside it.

## Troubleshooting

| Symptom | What to check |
| - | - |
| Model request returns `401` or `404` | Check the provider key, model ID, and base URL; an OpenAI-compatible endpoint alone does not guarantee Anthropic Messages compatibility |
| No `run_python` call is returned | Confirm the model supports tools and the requested tool choice; the examples stop before creating a box |
| Box creation fails | Check your Cloud key, [plan limits](https://docs.boxlite.ai/cloud/plans.md), and [usage balance](https://docs.boxlite.ai/cloud/billing.md) |
| Python exits with a nonzero code | Read stderr; the model may have generated invalid code or used an unavailable package |
| Execution times out | Simplify the task or deliberately adjust the 3-second limit; cleanup still runs |
| A cleanup request fails | Use the printed box ID to inspect and delete that box in the console |
| Node reports `Cannot find native binding` | Check installation of the SDK's platform dependency; use the Python or CLI path if that package is unavailable |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.