What you build
The interpreter is made of a few simple pieces:The interpreter
1
A sandbox for the conversation
First, a function that returns the sandbox for a conversation, creating it the first time. The conversation’s ID
is stored as a label, so the next message finds the same sandbox again. The sandbox goes to sleep two minutes
after the last message, and wakes up with everything still in memory when the user writes again. Its network only
allows installing Python packages, so the code cannot send data anywhere else.
2
A Python process that keeps its variables
Next, the part that remembers variables between turns. If every piece of code ran as a separate program, a variable
created in one turn would be gone in the next. So instead we start one long-running Python process (a
kernel) and send it each piece of code, called a cell, as the conversation goes on.This kernel is deliberately tiny. It reads a cell from its standard input, runs it in the same namespace as every
earlier cell, and prints a marker when it has finished, so we know when to stop reading its output:
3
Run a cell, collect output and charts
4
Try it with what a model would write
Here are two cells like the ones a model would write. The first loads the data into a table called
df. The
second uses df without loading it again, because the kernel remembers it, and saves a chart to /work/out.Connect a model
To connect a model, give it one tool,run_python, and run whatever code it sends through runCell. The loop
keeps going until the model answers without asking to run more code. Here it is with the Anthropic SDK:
Clean up
What it costs
Take a conversation with 6 turns, each running for 5 seconds on thesmall size. The sandbox is awake for about
30 seconds in total, plus the time it takes to install packages once. At $0.015 an hour, that is a fraction of
a cent per conversation. If you start from a snapshot with pandas already installed, the
install time disappears too.
Make it production-ready
A few improvements take this from an example to a product:- Make the kernel a snapshot. Save a sandbox with the packages installed and the kernel already running. Each conversation then starts from it, ready in seconds.
- Upload the user’s files with the files API before the first turn.
- Limit how long each cell can run. If a cell takes too long, stop the kernel with
kill()and start a fresh one. - Send the charts back to the model as well as to the user, so the model can describe its own chart.
Related
Run commands
spawn, standard input and streaming output, all used above.Network access
How the sandbox is limited to installing packages, and nothing else.