Run code with the code interpreter
This guide runs code in a sandbox made from the built-in code-interpreter
template. State lives between calls, as in a notebook, and results can be
text, HTML, or images. You need the Python or TypeScript SDK. See
Use the SDKs and the MCP server.
The code_interpreter feature gate is on by default.
Step 1: Create the sandbox
from triton_sandbox import Sandbox
sbx = Sandbox.create(template="code-interpreter")
Step 2: Run code
ex = sbx.run_code("import pandas as pd; pd.DataFrame({'a': [1, 2]}).sum()")
print(ex.text)
ex.text is the text form of the last expression's result.
Step 3: Get a chart
ex = sbx.run_code("import matplotlib.pyplot as plt; plt.plot([1, 3, 2]); plt.show()")
png_base64 = ex.results[0].png
Each item in ex.results is a bundle of the result in one or more formats,
such as text, HTML, and PNG.
Step 4: Keep state apart
Variables you set in one call are there in the next. For a separate set of variables, make a new context:
ctx = sbx.create_code_context()
sbx.run_code("x = 1", context=ctx)
The interpreter carries a Python kernel only. run_code takes language=,
but javascript, typescript, bash, and r return 501 with "the code
interpreter carries a Python kernel only". A value outside that list, or a
language that does not match the context, returns 400 BadRequest. The default context is made on first use.
A sandbox holds at most 16 contexts and runs at most 8 calls at once. A tenant
runs at most 64 calls at once across its sandboxes. Past any of these limits a
call returns 429 TooManyRequests, and a sandbox at 16 contexts takes no new
one until you delete one.
Step 5: Delete the sandbox
sbx.kill()
In TypeScript
import { Sandbox } from '@triton/sandbox'
const sbx = await Sandbox.create({ template: 'code-interpreter' })
console.log((await sbx.runCode('1 + 1')).text)
await sbx.kill()