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.
| Template | base (2 vCPU, 512 MiB, $0.039 per hour) |
|---|---|
| Run time | Model time plus less than 1 second per tool call |
| Cost of a run | Sandbox: less than $0.001. Anthropic bills the model tokens. |
| Cleanup | The finally block kills the sandbox. The 10-minute lifetime ends it if your process stops first. |
1Before you start
- Install the Anthropic SDK:
pip install anthropicornpm i @anthropic-ai/sdk. - 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.
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()
import Anthropic from '@anthropic-ai/sdk' import { Sandbox, CommandExitError, TimeoutError } from '@fdtn/sdk' const client = new Anthropic() // reads ANTHROPIC_API_KEY const sbx = await Sandbox.create('base', { timeoutMs: 600_000, // the sandbox lives 10 minutes at most metadata: { example: 'agent-tool' }, }) const 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, }, }] async function runCode(code) { await sbx.files.write('/home/user/main.py', code) try { const r = await sbx.commands.run('python3 /home/user/main.py', { timeoutMs: 30_000 }) return `exit 0\n${r.stdout}${r.stderr}` } catch (e) { if (e instanceof CommandExitError) return `exit ${e.exitCode}\n${e.stdout}${e.stderr}` if (e instanceof TimeoutError) return 'stopped after 30 seconds' throw e } } const messages = [{ role: 'user', content: 'What is the 30th Fibonacci number? Use run_code to check.' }] try { let response while (true) { response = await client.messages.create({ model: 'claude-opus-5-5', max_tokens: 16000, tools, messages, }) messages.push({ role: 'assistant', content: response.content }) if (response.stop_reason !== 'tool_use') break const results = [] for (const block of response.content) { if (block.type === 'tool_use' && block.name === 'run_code') { const output = await runCode(block.input.code) console.log('run_code ->', output.trim()) results.push({ type: 'tool_result', tool_use_id: block.id, content: output }) } } messages.push({ role: 'user', content: results }) } console.log(response.content.filter((b) => b.type === 'text').map((b) => b.text).join('')) } finally { await 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_codenever 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 installpackages. It cannot reach your computer or private networks.
Other tools
| Tool | SDK call |
|---|---|
run_shell | sbx.commands.run(command, timeout=60) |
write_file | sbx.files.write(path, text) |
read_file | sbx.files.read(path) |
list_files | sbx.files.list(path) |