# Your own agent with a “run code” tool

Language models are good at writing code but cannot run it. Give your model a tool called `run_python`: when it wants to compute something, it writes Python, your program runs it in a sandbox and sends the output back. The model's code never runs on your machine.

## What you'll build

A small command-line agent of about 50 lines. You ask it a question that needs real computation (“What is the 200th prime and how long does a naive search take?”), the model calls the tool as often as it needs, and it answers with numbers it actually measured. The example uses the Anthropic API; any model with tool calling (OpenAI, Gemini, local models) follows the same loop.

## What you need

- A WBX Sandbox **API key** (portal → *API keys*) in `WBXSANDBOX_API_KEY`.
- An **Anthropic API key** in `ANTHROPIC_API_KEY` (or adapt the model call to your provider).
- Python 3.9+ or Node.js 20+. About **15 minutes**.

## Steps

1. ### Install the packages

   **Python**

   ```
   pip install wbxsandbox anthropic
   export WBXSANDBOX_API_KEY=YOUR_WBX_KEY
   export ANTHROPIC_API_KEY=YOUR_ANTHROPIC_KEY
   ```

   **TypeScript**

   ```
   npm install wbxsandbox @anthropic-ai/sdk
   export WBXSANDBOX_API_KEY=YOUR_WBX_KEY
   export ANTHROPIC_API_KEY=YOUR_ANTHROPIC_KEY
   ```
2. ### Write the agent

   The loop: send the conversation and the tool definition to the model; if it asks for `run_python`, run the code in the sandbox and send back the output; repeat until the model answers in text. One sandbox serves the whole conversation, so files and variables the model saves to disk are there for the next call. The sandbox is deleted at the end – also when something fails.

   **Python**

   ```
   # agent.py
   import sys
   import anthropic
   from wbxsandbox import Sandbox

   MODEL = "claude-sonnet-5-5"   # replace with a current model

   TOOLS = [{
       "name": "run_python",
       "description": "Run Python 3 code in an isolated Linux sandbox and return what it prints. "
                      "Files under /home/user are kept between calls in this conversation.",
       "input_schema": {"type": "object",
                        "properties": {"code": {"type": "string", "description": "Python code to run"}},
                        "required": ["code"]},
   }]

   def run_python(sb, code):
       r = sb.run_code(code, timeout=120)                 # seconds; the code is killed after that
       out = f"exit code {r.exit_code}" + (" (timed out after 120 s)" if r.timed_out else "")
       if r.stdout:
           out += "\nstdout:\n" + r.stdout[-8000:]
       if r.stderr:
           out += "\nstderr:\n" + r.stderr[-4000:]
       return out

   def main(question):
       client = anthropic.Anthropic()
       messages = [{"role": "user", "content": question}]
       # 15 minutes of lifetime; leaving the block deletes the sandbox
       with Sandbox.create(template="code-interpreter", timeout=900) as sb:
           for _ in range(10):                            # at most 10 model turns
               resp = client.messages.create(model=MODEL, max_tokens=2048, tools=TOOLS, messages=messages)
               messages.append({"role": "assistant", "content": resp.content})
               if resp.stop_reason != "tool_use":
                   print("".join(b.text for b in resp.content if b.type == "text"))
                   return
               results = []
               for block in resp.content:
                   if block.type == "tool_use":
                       print(f"[run_python]\n{block.input['code']}\n", file=sys.stderr)
                       results.append({"type": "tool_result", "tool_use_id": block.id,
                                       "content": run_python(sb, block.input["code"])})
               messages.append({"role": "user", "content": results})
           print("Stopped after 10 turns.")

   if __name__ == "__main__":
       main(" ".join(sys.argv[1:]) or "What is the 200th prime number? Compute it and time the search.")
   ```

   **TypeScript**

   ```
   // agent.mts (an ES module – top-level await)
   import Anthropic from "@anthropic-ai/sdk";
   import { WBX, type Sandbox } from "wbxsandbox";

   const MODEL = "claude-sonnet-5-5"; // replace with a current model

   const tools: Anthropic.Tool[] = [{
     name: "run_python",
     description: "Run Python 3 code in an isolated Linux sandbox and return what it prints. " +
       "Files under /home/user are kept between calls in this conversation.",
     input_schema: {
       type: "object",
       properties: { code: { type: "string", description: "Python code to run" } },
       required: ["code"],
     },
   }];

   async function runPython(sb: Sandbox, code: string): Promise<string> {
     const r = await sb.runCode(code, { timeoutMs: 120_000 }); // the code is killed after 120 s
     let out = `exit code ${r.exitCode}` + (r.timedOut ? " (timed out after 120 s)" : "");
     if (r.stdout) out += "\nstdout:\n" + r.stdout.slice(-8000);
     if (r.stderr) out += "\nstderr:\n" + r.stderr.slice(-4000);
     return out;
   }

   const question = process.argv.slice(2).join(" ") || "What is the 200th prime number? Compute it and time the search.";
   const client = new Anthropic();
   const wbx = new WBX();
   const messages: Anthropic.MessageParam[] = [{ role: "user", content: question }];
   // 15 minutes of lifetime; deleted in finally
   const sb = await wbx.sandboxes.create({ template: "code-interpreter", timeoutSeconds: 900 });
   try {
     let answered = false;
     for (let turn = 0; turn < 10 && !answered; turn++) {      // at most 10 model turns
       const resp = await client.messages.create({ model: MODEL, max_tokens: 2048, tools, messages });
       messages.push({ role: "assistant", content: resp.content });
       if (resp.stop_reason !== "tool_use") {
         for (const b of resp.content) if (b.type === "text") console.log(b.text);
         answered = true;
         break;
       }
       const results: Anthropic.ToolResultBlockParam[] = [];
       for (const block of resp.content) {
         if (block.type !== "tool_use") continue;
         const code = (block.input as { code: string }).code;
         console.error(`[run_python]\n${code}\n`);
         results.push({ type: "tool_result", tool_use_id: block.id, content: await runPython(sb, code) });
       }
       messages.push({ role: "user", content: results });
     }
     if (!answered) console.log("Stopped after 10 turns.");
   } finally {
     await sb.kill();
   }
   ```
3. ### Run it

   **Python**

   ```
   python3 agent.py "Plot sin(x) and save it to /home/user/sin.png, then tell me the file size."
   ```

   **TypeScript**

   ```
   npx tsx agent.mts "Plot sin(x) and save it to /home/user/sin.png, then tell me the file size."
   ```

   The code the model runs is printed to standard error, the final answer to standard output.

## How to tell it works

- You see one or more `[run_python]` blocks with the model's code before the answer – the model really ran something.
- While the agent runs, the sandbox is listed on the *Sandboxes* page in the portal; after the program ends it disappears.
- When the code fails, the model gets the error in `stderr` and usually fixes it on the next turn – that is expected, not a bug.

## Before you ship it

- **Keep the sandbox for the conversation, not per call.** In a chat app, create it with a `name` (for example the conversation ID) and `on_timeout="pause"`: it is reused on the next message and sleeps while the user is away. See [A workspace that remembers](https://sandbox.wbx.cz/docs/guides/workspace.md).
- **Limit the network** if the model does not need the internet: `internet=False` (Python) or `network: { mode: "none" }` (TypeScript), or an allowlist such as `pypi.org`. See [Run untrusted code safely](https://sandbox.wbx.cz/docs/guides/untrusted-code.md).
- **Don't pass your secrets** into the sandbox through `env` unless the model's code needs them – the code can read and print them.
- **Long work** (minutes to hours) belongs in a [background job](https://sandbox.wbx.cz/docs/guides/long-job.md), not in a tool call the model waits for.

## Common problems

| Error | Meaning and fix |
| --- | --- |
| `401` | The WBX API key is missing or wrong – check `WBXSANDBOX_API_KEY`. (An Anthropic authentication error comes from the model call instead.) |
| `402` | No credit left on your WBX account – top up under *Billing*. |
| `429 quota` | “account limit reached (concurrent sandboxes, vCPU or memory)”: your plan's concurrent sandboxes are in use. Delete forgotten sandboxes or wait; `SandboxError.retry_after` / `RateLimitError.retryAfter` says how long when the server sends it. |
| The model loops | The turn limit (10) stops it. Return shorter output to the model (the example keeps the last 8,000 characters) and ask it to print only what it needs. |
| `timed out after 120 s` | The model's code ran too long and was killed. Raise the timeout for heavy work, or tell the model in the tool description that it has 120 seconds. |

## Next steps

- [Prepare once, run many agents](https://sandbox.wbx.cz/docs/guides/snapshot-clone.md): Install dependencies once, start copies in seconds.
- [Run untrusted code safely](https://sandbox.wbx.cz/docs/guides/untrusted-code.md): No network, short limits, an unprivileged user.
- [Python SDK](https://sandbox.wbx.cz/docs/sdk.md): All sandbox, command and file calls.
- [TypeScript SDK](https://sandbox.wbx.cz/docs/sdk/typescript.md): The same for Node.js, Deno and Bun.

Source: https://sandbox.wbx.cz/docs/guides/own-agent
