Code Interpreter
Execute Python, JavaScript, and TypeScript code with support for data visualizations, tables, and rich output formats. Contexts maintain state (variables, imports, functions) across executions.
Create a persistent execution context for running code.
const context = await sandbox.createCodeContext(options?: CreateContextOptions): Promise<CodeContext>Parameters:
options(optional):language-"python" | "javascript" | "typescript"(default:"python")cwd- Working directory (default:"/workspace")envVars- Environment variablestimeout- Request timeout in milliseconds (default: 30000)
Returns: Promise<CodeContext> with id, language, cwd, createdAt, lastUsed
const ctx = await sandbox.createCodeContext({ language: "python", envVars: { API_KEY: env.API_KEY },});const ctx = await sandbox.createCodeContext({ language: 'python', envVars: { API_KEY: env.API_KEY }});Execute code in a context and return the complete result.
const result = await sandbox.runCode(code: string, options?: RunCodeOptions): Promise<ExecutionResult>Parameters:
code- The code to execute (required)options(optional):context- Context to run in (recommended - see below)language-"python" | "javascript" | "typescript"(default:"python")timeout- Execution timeout in milliseconds (default: 60000)onStdout,onStderr,onResult,onError- Streaming callbacks
Returns: Promise<ExecutionResult> with:
code- The executed codelogs-stdoutandstderrarraysresults- Array of rich outputs (see Rich Output Formats)error- Execution error if anyexecutionCount- Execution counter
Recommended usage - create explicit context:
const ctx = await sandbox.createCodeContext({ language: "python" });
await sandbox.runCode("import math; radius = 5", { context: ctx });const result = await sandbox.runCode("math.pi * radius ** 2", { context: ctx });
console.log(result.results[0].text); // "78.53981633974483"const ctx = await sandbox.createCodeContext({ language: 'python' });
await sandbox.runCode('import math; radius = 5', { context: ctx });const result = await sandbox.runCode('math.pi * radius ** 2', { context: ctx });
console.log(result.results[0].text); // "78.53981633974483"Error handling:
const result = await sandbox.runCode("x = 1 / 0", { language: "python" });
if (result.error) { console.error(result.error.name); // "ZeroDivisionError" console.error(result.error.value); // "division by zero" console.error(result.error.traceback); // Stack trace array}const result = await sandbox.runCode('x = 1 / 0', { language: 'python' });
if (result.error) { console.error(result.error.name); // "ZeroDivisionError" console.error(result.error.value); // "division by zero" console.error(result.error.traceback); // Stack trace array}List all active code execution contexts.
const contexts = await sandbox.listCodeContexts(): Promise<CodeContext[]>const contexts = await sandbox.listCodeContexts();console.log(`Found ${contexts.length} contexts`);const contexts = await sandbox.listCodeContexts();console.log(`Found ${contexts.length} contexts`);Delete a code execution context and free its resources.
await sandbox.deleteCodeContext(contextId: string): Promise<void>const ctx = await sandbox.createCodeContext({ language: "python" });await sandbox.runCode('print("Hello")', { context: ctx });await sandbox.deleteCodeContext(ctx.id);const ctx = await sandbox.createCodeContext({ language: 'python' });await sandbox.runCode('print("Hello")', { context: ctx });await sandbox.deleteCodeContext(ctx.id);Results include: text, html, png, jpeg, svg, latex, markdown, json, chart, data
Charts (matplotlib):
const result = await sandbox.runCode( `import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(0, 10, 100)plt.plot(x, np.sin(x))plt.show()`, { language: "python" },);
if (result.results[0]?.png) { const imageBuffer = Buffer.from(result.results[0].png, "base64"); return new Response(imageBuffer, { headers: { "Content-Type": "image/png" }, });}const result = await sandbox.runCode(`import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(0, 10, 100)plt.plot(x, np.sin(x))plt.show()`, { language: 'python' });
if (result.results[0]?.png) { const imageBuffer = Buffer.from(result.results[0].png, 'base64'); return new Response(imageBuffer, { headers: { 'Content-Type': 'image/png' } });}Tables (pandas):
const result = await sandbox.runCode( `import pandas as pddf = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})df`, { language: "python" },);
if (result.results[0]?.html) { return new Response(result.results[0].html, { headers: { "Content-Type": "text/html" }, });}const result = await sandbox.runCode(`import pandas as pddf = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})df`, { language: 'python' });
if (result.results[0]?.html) { return new Response(result.results[0].html, { headers: { 'Content-Type': 'text/html' } });}- Build an AI Code Executor - Complete tutorial
- Commands API - Lower-level command execution
- Files API - File operations
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark