Code Execution Tokens
Let the model compute — safely
A code-execution tool lets the model run writes, math, manipulation or experiments. Powerful, and dangerous: it needs a sandbox, timeouts, resource caps, and a read-only bias. Done right it converts 'estimate' into 'compute'.
What you will learn
- Architect a sandboxed executor
- Cap runtime resources
- Bias toward read-only execution
What is this?
A code-execution tool runs model-written code (usually in a sandbox): Python in a container, timeout enforced, memory/CPU bounded, network and filesystem restricted, results returned as text/images. It makes computations exact and enables manipulation, analysis and iteration the model couldn't do by reasoning alone.
Why do you need it?
- Math by reasoning is unreliable; math by code is exact.
- Iterative experiments — clean, transform, plot — turn the model into an analyst.
- Deterministic computation fixes a whole class of arith hallucinations.
- Sandboxing turns the danger into a governed, bounded compute slot.
Mental model
A chemistry lab with fume hoods
Code executor
Students (models) may run experiments, but only in hooded, fume-containing benches: gloves (sandbox), timed sessions (timeout), capped reagents (memory), no contact with street (network off). The hood is why you're fine letting students cook.
How it works
- Pass code + optional input files to a sandboxed runtime.
- Enforce timeout, memory, CPU, disk limits.
- Restrict network where not needed; block sensitive mounts.
- Capture stdout/stderr + artifacts.
- Return the result (text/render) back to the model loop.
Execution envelope.
In production
- Data analysts query DBs then plot with Python.
- Finance tools compute exact forecasts and tables.
- Infrastructure copilots dry-run then apply approved changes.
Best practices
- Default sandbox: no network, tight time, modest memory.
- Persist nothing across runs unless intentional.
- Return structured stdout + artifacts, not raw dumps.
- Log every execution (code, limits, outcome) for audit.
Common mistakes
- Executing in the server's own container.
- No timeout — infinite loops bill forever.
- Giving the executor prod credentials.
Common issues
Model writes buggy code repeatedlyNo feedback loop
Return tracebacks; let the model fix and re-run (capped).
Sandbox lacks libsThin image
Curate the image for your use cases.
Debugging tips
- Execution reports missing deps → preload required libs in the image.
- Timeout hits commonly → lower expectations or split the task.
- Non-deterministic results → seed/bump environment drift in logs.
Interview checkpoint
Hands-on lab
- Execute model-provided code in a subprocess
- Enforce timeout and resource limits
- Return stdout/stderr to the calling loop
Sandbox a Python Executor with Cap
35 min · intermediate
Quick quiz
Sandbox prerequisites for a code tool:
Deterministic computation removes arithmetic hallucination.