JavaScript/TypeScript SDK for E2B's code interpreter service with secure sandbox execution
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive result handling with support for multiple output formats, data types, and execution metadata.
The main execution result containing all outputs from code execution.
/**
* Represents the result of a code execution
*/
class Execution {
/**
* List of results from the execution (main result, display calls, etc.)
*/
results: Result[];
/**
* Logs printed to stdout and stderr during execution
*/
logs: Logs;
/**
* Execution error if one occurred, undefined otherwise
*/
error?: ExecutionError;
/**
* Execution count of the cell/code block
*/
executionCount?: number;
/**
* Returns the text representation of the main result
*/
get text(): string | undefined;
/**
* Returns the serializable representation of the execution result
*/
toJSON(): object;
}Each result represents a single output from the execution.
/**
* Represents data to be displayed as a result of executing code
* Similar to Jupyter notebook result structure
*/
class Result {
/**
* Text representation of the result
*/
readonly text?: string;
/**
* HTML representation of the data
*/
readonly html?: string;
/**
* Markdown representation of the data
*/
readonly markdown?: string;
/**
* SVG representation of the data
*/
readonly svg?: string;
/**
* PNG representation of the data (base64 encoded)
*/
readonly png?: string;
/**
* JPEG representation of the data (base64 encoded)
*/
readonly jpeg?: string;
/**
* PDF representation of the data
*/
readonly pdf?: string;
/**
* LaTeX representation of the data
*/
readonly latex?: string;
/**
* JSON representation of the data
*/
readonly json?: string;
/**
* JavaScript representation of the data
*/
readonly javascript?: string;
/**
* Contains data from DataFrame or structured data
*/
readonly data?: Record<string, unknown>;
/**
* Contains chart data
*/
readonly chart?: ChartTypes;
/**
* Extra data that can be included (not part of standard types)
*/
readonly extra?: any;
/**
* Raw data object containing all formats
*/
readonly raw: RawData;
/**
* Whether this is the main result of the execution
*/
readonly isMainResult: boolean;
/**
* Returns all available formats for the result
* @returns Array of format names
*/
formats(): string[];
/**
* Returns the serializable representation of the result
*/
toJSON(): object;
}Real-time output messages from stdout and stderr.
/**
* Represents an output message from sandbox code execution
*/
class OutputMessage {
constructor(line: string, timestamp: number, error: boolean);
/**
* The output line content
*/
readonly line: string;
/**
* Unix epoch timestamp in nanoseconds
*/
readonly timestamp: number;
/**
* Whether the output is an error message
*/
readonly error: boolean;
/**
* String representation of the output message
*/
toString(): string;
}/**
* Data printed to stdout and stderr during execution
*/
type Logs = {
/**
* List of strings printed to stdout
*/
stdout: string[];
/**
* List of strings printed to stderr
*/
stderr: string[];
};/**
* Represents an error that occurred during code execution
*/
class ExecutionError {
constructor(name: string, value: string, traceback: string);
/**
* Name of the error (e.g., 'NameError', 'SyntaxError')
*/
name: string;
/**
* Value/message of the error
*/
value: string;
/**
* The raw traceback of the error
*/
traceback: string;
}/**
* MIME type string
*/
type MIMEType = string;
/**
* Dictionary mapping MIME types to their data representations
*/
type RawData = {
[key: MIMEType]: string;
} & E2BData;
type E2BData = {
data: Record<string, unknown>;
chart: ChartTypes;
};Usage Examples:
import { Sandbox } from "@e2b/code-interpreter";
const sandbox = await Sandbox.create();
// Basic text result
const textResult = await sandbox.runCode('2 + 2');
console.log(textResult.text); // "4"
console.log(textResult.results[0].text); // "4"
console.log(textResult.results[0].isMainResult); // true
// Multiple format result (e.g., matplotlib plot)
const plotResult = await sandbox.runCode(`
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.show()
`);
// Check available formats
console.log(plotResult.results[0].formats()); // ['png', 'text', ...]
// Access different formats
if (plotResult.results[0].png) {
console.log('PNG data available:', plotResult.results[0].png.substring(0, 50));
}
// Handle execution logs
const logResult = await sandbox.runCode(`
print("This goes to stdout")
import sys
print("This goes to stderr", file=sys.stderr)
`);
console.log('Stdout:', logResult.logs.stdout); // ['This goes to stdout\n']
console.log('Stderr:', logResult.logs.stderr); // ['This goes to stderr\n']
// Handle errors
const errorResult = await sandbox.runCode('undefined_variable');
if (errorResult.error) {
console.log('Error type:', errorResult.error.name); // 'NameError'
console.log('Error message:', errorResult.error.value);
console.log('Full traceback:', errorResult.error.traceback);
}
// DataFrame data
const dataResult = await sandbox.runCode(`
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df
`);
if (dataResult.results[0].data) {
console.log('DataFrame data:', dataResult.results[0].data);
}
// Streaming with callbacks
await sandbox.runCode(`
for i in range(3):
print(f"Processing item {i}")
import time
time.sleep(0.5)
`, {
onStdout: (output) => {
console.log(`[${new Date(output.timestamp / 1000000).toISOString()}] ${output.line}`);
},
onResult: (result) => {
console.log('New result available:', result.formats());
},
onError: (error) => {
console.error('Execution error:', error.name, error.value);
}
});
// JSON serialization
const result = await sandbox.runCode('{"key": "value"}');
const serialized = result.toJSON();
console.log('Serialized execution:', JSON.stringify(serialized, null, 2));// Check and handle different result formats
const result = await sandbox.runCode(`
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
`);
const firstResult = result.results[0];
// Check what formats are available
const availableFormats = firstResult.formats();
console.log('Available formats:', availableFormats);
// Handle different formats conditionally
if (firstResult.png) {
// Save or display PNG image
console.log('PNG image available');
}
if (firstResult.svg) {
// Handle SVG vector format
console.log('SVG format available');
}
if (firstResult.html) {
// Display HTML content
console.log('HTML representation available');
}
if (firstResult.data) {
// Process structured data
console.log('Structured data available:', firstResult.data);
}Install with Tessl CLI
npx tessl i tessl/npm-e2b--code-interpreter