Skip to content

Integrations

Anthropic tool use

No framework: a Messages API loop that runs each tool_use block in the sandbox and returns a tool_result.

Install

Terminal
pip install sandboxplease anthropic

Code

Copy it as anthropic_tool_loop.py. The model is the only part you would change.

anthropic_tool_loop.py
"""Plain Anthropic tool use, no framework: Claude asks for commands, the loop runs them in a sandbox.

Run: SANDBOXPLEASE_API_KEY=... ANTHROPIC_API_KEY=... uv run python anthropic_tool_loop.py
"""

import json

from anthropic import Anthropic
from anthropic.types import MessageParam, ToolParam, ToolResultBlockParam
from sandboxplease import SandboxPlease

TOOLS: list[ToolParam] = [
    {
        "name": "run_command",
        "description": "Run a shell command in a Linux sandbox with Python 3 and Node. Returns exit code and output.",
        "input_schema": {
            "type": "object",
            "properties": {"command": {"type": "string", "description": "e.g. python3 -c 'print(1+1)'"}},
            "required": ["command"],
        },
    }
]


def solve(client: Anthropic, prompt: str, model: str = "claude-sonnet-4-5") -> str:
    with SandboxPlease() as sp, sp.sandboxes.create(timeout=600) as sandbox:
        messages: list[MessageParam] = [{"role": "user", "content": prompt}]
        for _ in range(10):
            reply = client.messages.create(model=model, max_tokens=1024, tools=TOOLS, messages=messages)
            messages.append({"role": "assistant", "content": reply.content})
            if reply.stop_reason != "tool_use":
                return "".join(block.text for block in reply.content if block.type == "text")
            results: list[ToolResultBlockParam] = []
            for block in reply.content:
                if block.type == "tool_use":
                    command = str(block.input["command"])
                    out = sandbox.exec(command)
                    content = json.dumps({"exit_code": out.exit_code, "stdout": out.stdout, "stderr": out.stderr})
                    results.append({"type": "tool_result", "tool_use_id": block.id, "content": content})
            messages.append({"role": "user", "content": results})
        raise RuntimeError("No answer after 10 steps")


if __name__ == "__main__":
    print(solve(Anthropic(), "Compute 6*7 with Python in the sandbox."))

Run it

Terminal
export SANDBOXPLEASE_API_KEY=sp-v1-…
export ANTHROPIC_API_KEY=…
python anthropic_tool_loop.py

The agent runs Python in the sandbox and answers 42. Each sandbox shows up in Logs with its provider and cost.