Foundational Compute

Give an agent a code tool

Give a model a run_code tool backed by a sandbox, so it can check its answer and fix errors.

Templatebase (2 vCPU, 512 MiB, $0.039 per hour)
Run timeModel time plus less than 1 second per tool call
Cost of a runSandbox: less than $0.001. Anthropic bills the model tokens.
CleanupThe finally block kills the sandbox. The 10-minute lifetime ends it if your process stops first.

1Before you start

  1. Install the Anthropic SDK: pip install anthropic or npm i @anthropic-ai/sdk.
  2. Set export ANTHROPIC_API_KEY=sk-ant-... on your computer. The sandbox never sees it.

2The code

While the model asks for a tool call, the loop runs the code and returns the result.

Python · TypeScript

agent_tool.py
import anthropic
from fdtn import Sandbox, CommandExitException, TimeoutException

client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY
sbx = Sandbox.create(
    "base",
    timeout=600,                        # the sandbox lives 10 minutes at most
    metadata={"example": "agent-tool"},
)

tools = [{
    "name": "run_code",
    "description": "Run a Python 3 program in an isolated Linux sandbox. "
                   "Returns stdout, stderr and the exit code. Files stay between calls.",
    "input_schema": {
        "type": "object",
        "properties": {"code": {"type": "string", "description": "The Python program"}},
        "required": ["code"],
        "additionalProperties": False,
    },
}]

def run_code(code: str) -> str:
    sbx.files.write("/home/user/main.py", code)
    try:
        r = sbx.commands.run("python3 /home/user/main.py", timeout=30)
        return f"exit 0\n{r.stdout}{r.stderr}"
    except CommandExitException as e:
        return f"exit {e.exit_code}\n{e.stdout}{e.stderr}"
    except TimeoutException:
        return "stopped after 30 seconds"

messages = [{"role": "user", "content": "What is the 30th Fibonacci number? Use run_code to check."}]
try:
    while True:
        response = client.messages.create(
            model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})
        if response.stop_reason != "tool_use":
            break
        results = []
        for block in response.content:
            if block.type == "tool_use" and block.name == "run_code":
                output = run_code(block.input["code"])
                print("run_code ->", output.strip())
                results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
        messages.append({"role": "user", "content": results})
    print("".join(b.text for b in response.content if b.type == "text"))
finally:
    sbx.kill()

3Run it

The model writes its own code and text, so your output can differ:

$ python agent_tool.py      # or: node agent_tool.mjs
run_code -> exit 0
832040
The 30th Fibonacci number is 832040.

Notes

  • run_code never raises. It returns the exit code and stderr as text, so the model can fix its code.
  • The 30-second command timeout stops code that never ends.
  • One sandbox serves the whole conversation, so files stay between calls. For a long chat, call sbx.set_timeout() after each turn.
  • The model can pip install packages. It cannot reach your computer or private networks.

Other tools

ToolSDK call
run_shellsbx.commands.run(command, timeout=60)
write_filesbx.files.write(path, text)
read_filesbx.files.read(path)
list_filessbx.files.list(path)

Next