@e2b/code-interpreter
Advanced tools
Comparing version 1.0.0 to 1.0.1
@@ -1,5 +0,131 @@ | ||
import { Sandbox, SandboxOpts, ProcessMessage } from 'e2b'; | ||
import { Sandbox as Sandbox$1 } from 'e2b'; | ||
export * from 'e2b'; | ||
/** | ||
* Chart types | ||
*/ | ||
declare enum ChartType { | ||
LINE = "line", | ||
SCATTER = "scatter", | ||
BAR = "bar", | ||
PIE = "pie", | ||
BOX_AND_WHISKER = "box_and_whisker", | ||
SUPERCHART = "superchart", | ||
UNKNOWN = "unknown" | ||
} | ||
/** | ||
* Ax scale types | ||
*/ | ||
declare enum ScaleType { | ||
LINEAR = "linear", | ||
DATETIME = "datetime", | ||
CATEGORICAL = "categorical", | ||
LOG = "log", | ||
SYMLOG = "symlog", | ||
LOGIT = "logit", | ||
FUNCTION = "function", | ||
FUNCTIONLOG = "functionlog", | ||
ASINH = "asinh" | ||
} | ||
/** | ||
* Represents a chart. | ||
*/ | ||
type Chart = { | ||
type: ChartType; | ||
title: string; | ||
elements: any[]; | ||
}; | ||
type Chart2D = Chart & { | ||
x_label?: string; | ||
y_label?: string; | ||
x_unit?: string; | ||
y_unit?: string; | ||
}; | ||
type PointData = { | ||
label: string; | ||
points: [number | string, number | string][]; | ||
}; | ||
type PointChart = Chart2D & { | ||
x_ticks: (number | string)[]; | ||
x_scale: ScaleType; | ||
x_tick_labels: string[]; | ||
y_ticks: (number | string)[]; | ||
y_scale: ScaleType; | ||
y_tick_labels: string[]; | ||
elements: PointData[]; | ||
}; | ||
type LineChart = PointChart & { | ||
type: ChartType.LINE; | ||
}; | ||
type ScatterChart = PointChart & { | ||
type: ChartType.SCATTER; | ||
}; | ||
type BarData = { | ||
label: string; | ||
value: string; | ||
group: string; | ||
}; | ||
type BarChart = Chart2D & { | ||
type: ChartType.BAR; | ||
elements: BarData[]; | ||
}; | ||
type PieData = { | ||
label: string; | ||
angle: number; | ||
radius: number; | ||
}; | ||
type PieChart = Chart & { | ||
type: ChartType.PIE; | ||
elements: PieData[]; | ||
}; | ||
type BoxAndWhiskerData = { | ||
label: string; | ||
min: number; | ||
first_quartile: number; | ||
median: number; | ||
third_quartile: number; | ||
max: number; | ||
}; | ||
type BoxAndWhiskerChart = Chart2D & { | ||
type: ChartType.BOX_AND_WHISKER; | ||
elements: BoxAndWhiskerData[]; | ||
}; | ||
type SuperChart = Chart & { | ||
type: ChartType.SUPERCHART; | ||
elements: Chart[]; | ||
}; | ||
type ChartTypes = LineChart | ScatterChart | BarChart | PieChart | BoxAndWhiskerChart | SuperChart; | ||
/** | ||
* Represents an output message from the sandbox code execution. | ||
*/ | ||
declare class OutputMessage { | ||
/** | ||
* The output line. | ||
*/ | ||
readonly line: string; | ||
/** | ||
* Unix epoch in nanoseconds. | ||
*/ | ||
readonly timestamp: number; | ||
/** | ||
* Whether the output is an error. | ||
*/ | ||
readonly error: boolean; | ||
constructor( | ||
/** | ||
* The output line. | ||
*/ | ||
line: string, | ||
/** | ||
* Unix epoch in nanoseconds. | ||
*/ | ||
timestamp: number, | ||
/** | ||
* Whether the output is an error. | ||
*/ | ||
error: boolean); | ||
toString(): string; | ||
} | ||
/** | ||
* Represents an error that occurred during the execution of a cell. | ||
@@ -20,3 +146,3 @@ * The error contains the name of the error, the value of the error, and the traceback. | ||
**/ | ||
tracebackRaw: string[]; | ||
traceback: string; | ||
constructor( | ||
@@ -34,7 +160,3 @@ /** | ||
**/ | ||
tracebackRaw: string[]); | ||
/** | ||
* Returns the traceback of the error as a string. | ||
*/ | ||
get traceback(): string; | ||
traceback: string); | ||
} | ||
@@ -45,8 +167,12 @@ /** | ||
type MIMEType = string; | ||
type E2BData = { | ||
data: Record<string, unknown>; | ||
chart: ChartTypes; | ||
}; | ||
/** | ||
* Dictionary that maps MIME types to their corresponding string representations of the data. | ||
* Dictionary that maps MIME types to their corresponding representations of the data. | ||
*/ | ||
type RawData = { | ||
[key: MIMEType]: string; | ||
}; | ||
} & E2BData; | ||
/** | ||
@@ -104,2 +230,10 @@ * Represents the data to be displayed as a result of executing a cell in a Jupyter notebook. | ||
/** | ||
* Contains the data from DataFrame. | ||
*/ | ||
readonly data?: Record<string, unknown>; | ||
/** | ||
* Contains the chart data. | ||
*/ | ||
readonly chart?: ChartTypes; | ||
/** | ||
* Extra data that can be included. Not part of the standard types. | ||
@@ -109,3 +243,3 @@ */ | ||
readonly raw: RawData; | ||
constructor(data: RawData, isMainResult: boolean); | ||
constructor(rawData: RawData, isMainResult: boolean); | ||
/** | ||
@@ -163,2 +297,6 @@ * Returns all the formats available for the result. | ||
error?: ExecutionError | undefined; | ||
/** | ||
* Execution count of the cell. | ||
*/ | ||
executionCount?: number | undefined; | ||
constructor( | ||
@@ -168,12 +306,16 @@ /** | ||
*/ | ||
results: Result[], | ||
results?: Result[], | ||
/** | ||
* Logs printed to stdout and stderr during execution. | ||
*/ | ||
logs: Logs, | ||
logs?: Logs, | ||
/** | ||
* An Error object if an error occurred, null otherwise. | ||
*/ | ||
error?: ExecutionError | undefined); | ||
error?: ExecutionError | undefined, | ||
/** | ||
* Execution count of the cell. | ||
*/ | ||
executionCount?: number | undefined); | ||
/** | ||
* Returns the text representation of the main result of the cell. | ||
@@ -192,103 +334,174 @@ */ | ||
interface CreateKernelProps { | ||
/** | ||
* Represents a context for code execution. | ||
*/ | ||
type Context = { | ||
/** | ||
* The ID of the context. | ||
*/ | ||
id: string; | ||
/** | ||
* The language of the context. | ||
*/ | ||
language: string; | ||
/** | ||
* The working directory of the context. | ||
*/ | ||
cwd: string; | ||
kernelName?: string; | ||
} | ||
}; | ||
/** | ||
* E2B code interpreter sandbox extension. | ||
* Options for running code. | ||
*/ | ||
declare class CodeInterpreter extends Sandbox { | ||
private static template; | ||
readonly notebook: JupyterExtension; | ||
constructor(opts?: SandboxOpts, createCalled?: boolean); | ||
_open(opts?: { | ||
timeout?: number; | ||
}): Promise<this>; | ||
close(): Promise<void>; | ||
} | ||
declare class JupyterExtension { | ||
private sandbox; | ||
private readonly connectedKernels; | ||
private readonly kernelIDPromise; | ||
private readonly setDefaultKernelID; | ||
private get defaultKernelID(); | ||
constructor(sandbox: CodeInterpreter); | ||
connect(timeout?: number): Promise<void>; | ||
interface RunCodeOpts { | ||
/** | ||
* Executes a code cell in a notebool cell. | ||
* Callback for handling stdout messages. | ||
*/ | ||
onStdout?: (output: OutputMessage) => (Promise<any> | any); | ||
/** | ||
* Callback for handling stderr messages. | ||
*/ | ||
onStderr?: (output: OutputMessage) => (Promise<any> | any); | ||
/** | ||
* Callback for handling the final execution result. | ||
*/ | ||
onResult?: (data: Result) => (Promise<any> | any); | ||
/** | ||
* Callback for handling the `ExecutionError` object. | ||
*/ | ||
onError?: (error: ExecutionError) => (Promise<any> | any); | ||
/** | ||
* Custom environment variables for code execution. | ||
* | ||
* This method sends the provided code to a specified kernel in a remote notebook for execution. | ||
* @param code The code to be executed in the notebook cell. | ||
* @param kernelID The ID of the kernel to execute the code on. If not provided, the default kernel is used. | ||
* @param onStdout A callback function to handle standard output messages from the code execution. | ||
* @param onStderr A callback function to handle standard error messages from the code execution. | ||
* @param onResult A callback function to handle display data messages from the code execution. | ||
* @param timeout The maximum time to wait for the code execution to complete, in milliseconds. | ||
* @returns A promise that resolves with the result of the code execution. | ||
* @default {} | ||
*/ | ||
execCell(code: string, { kernelID, onStdout, onStderr, onResult, timeout }?: { | ||
kernelID?: string; | ||
onStdout?: (msg: ProcessMessage) => any; | ||
onStderr?: (msg: ProcessMessage) => any; | ||
onResult?: (data: Result) => any; | ||
timeout?: number; | ||
}): Promise<Execution>; | ||
private startConnectingToDefaultKernel; | ||
envs?: Record<string, string>; | ||
/** | ||
* Connects to a kernel's WebSocket. | ||
* Timeout for the code execution in **milliseconds**. | ||
* | ||
* This method establishes a WebSocket connection to the specified kernel. It is used internally | ||
* to facilitate real-time communication with the kernel, enabling operations such as executing | ||
* code and receiving output. The connection details are managed within the method, including | ||
* the retrieval of the necessary WebSocket URL from the kernel's information. | ||
* @default 60_000 // 60 seconds | ||
*/ | ||
timeoutMs?: number; | ||
/** | ||
* Timeout for the request in **milliseconds**. | ||
* | ||
* @param kernelID The unique identifier of the kernel to connect to. | ||
* @throws {Error} Throws an error if the connection to the kernel's WebSocket cannot be established. | ||
* @default 30_000 // 30 seconds | ||
*/ | ||
private connectToKernelWS; | ||
requestTimeoutMs?: number; | ||
} | ||
/** | ||
* Options for creating a code context. | ||
*/ | ||
interface CreateCodeContextOpts { | ||
/** | ||
* Creates a new Jupyter kernel. It can be useful if you want to have multiple independent code execution environments. | ||
* Working directory for the context. | ||
* | ||
* The kernel can be optionally configured to start in a specific working directory and/or | ||
* with a specific kernel name. If no kernel name is provided, the default kernel will be used. | ||
* Once the kernel is created, this method establishes a WebSocket connection to the new kernel for | ||
* real-time communication. | ||
* @default /home/user | ||
*/ | ||
cwd?: string; | ||
/** | ||
* Language for the context. | ||
* | ||
* @param cwd Sets the current working directory where the kernel should start. Defaults to "/home/user". | ||
* @param kernelName The name of the kernel to create, useful if you have multiple kernel types. If not provided, the default kernel will be used. | ||
* @returns A promise that resolves with the ID of the newly created kernel. | ||
* @throws {Error} Throws an error if the kernel creation fails. | ||
* @default python | ||
*/ | ||
createKernel(cwd?: string, kernelName?: string): Promise<string>; | ||
language?: string; | ||
/** | ||
* Restarts an existing Jupyter kernel. This can be useful to reset the kernel's state or to recover from errors. | ||
* Timeout for the request in **milliseconds**. | ||
* | ||
* @param kernelID The unique identifier of the kernel to restart. If not provided, the default kernel is restarted. | ||
* @throws {Error} Throws an error if the kernel restart fails or if the operation times out. | ||
* @default 30_000 // 30 seconds | ||
*/ | ||
restartKernel(kernelID?: string): Promise<void>; | ||
requestTimeoutMs?: number; | ||
} | ||
/** | ||
* E2B cloud sandbox is a secure and isolated cloud environment. | ||
* | ||
* The sandbox allows you to: | ||
* - Access Linux OS | ||
* - Create, list, and delete files and directories | ||
* - Run commands | ||
* - Run isolated code | ||
* - Access the internet | ||
* | ||
* Check docs [here](https://e2b.dev/docs). | ||
* | ||
* Use {@link Sandbox.create} to create a new sandbox. | ||
* | ||
* @example | ||
* ```ts | ||
* import { Sandbox } from '@e2b/code-interpreter' | ||
* | ||
* const sandbox = await Sandbox.create() | ||
* ``` | ||
*/ | ||
declare class Sandbox extends Sandbox$1 { | ||
protected static readonly defaultTemplate: string; | ||
/** | ||
* Shuts down an existing Jupyter kernel. This method is used to gracefully terminate a kernel's process. | ||
* @param kernelID The unique identifier of the kernel to shutdown. If not provided, the default kernel is shutdown. | ||
* @throws {Error} Throws an error if the kernel shutdown fails or if the operation times out. | ||
* Run the code as Python. | ||
* | ||
* Specify the `language` or `context` option to run the code as a different language or in a different `Context`. | ||
* | ||
* You can reference previously defined variables, imports, and functions in the code. | ||
* | ||
* @param code code to execute. | ||
* @param opts options for executing the code. | ||
* | ||
* @returns `Execution` result object. | ||
*/ | ||
shutdownKernel(kernelID?: string): Promise<void>; | ||
runCode(code: string, opts?: RunCodeOpts & { | ||
/** | ||
* Language to use for code execution. | ||
* | ||
* If not defined, the default Python context is used. | ||
*/ | ||
language?: 'python'; | ||
}): Promise<Execution>; | ||
/** | ||
* Lists all available Jupyter kernels. | ||
* Run the code for the specified language. | ||
* | ||
* This method fetches a list of all currently available Jupyter kernels from the server. It can be used | ||
* to retrieve the IDs of all kernels that are currently running or available for connection. | ||
* Specify the `language` or `context` option to run the code as a different language or in a different `Context`. | ||
* If no language is specified, Python is used. | ||
* | ||
* @returns A promise that resolves to an array of kernel IDs. | ||
* @throws {Error} Throws an error if the request to list kernels fails. | ||
* You can reference previously defined variables, imports, and functions in the code. | ||
* | ||
* @param code code to execute. | ||
* @param opts options for executing the code. | ||
* | ||
* @returns `Execution` result object. | ||
*/ | ||
listKernels(): Promise<string[]>; | ||
runCode(code: string, opts?: RunCodeOpts & { | ||
/** | ||
* Language to use for code execution. | ||
* | ||
* If not defined, the default Python context is used. | ||
*/ | ||
language?: string; | ||
}): Promise<Execution>; | ||
/** | ||
* Close all the websocket connections to the kernels. It doesn't shutdown the kernels. | ||
* Runs the code in the specified context, if not specified, the default context is used. | ||
* | ||
* Specify the `language` or `context` option to run the code as a different language or in a different `Context`. | ||
* | ||
* You can reference previously defined variables, imports, and functions in the code. | ||
* | ||
* @param code code to execute. | ||
* @param opts options for executing the code | ||
* | ||
* @returns `Execution` result object | ||
*/ | ||
close(): Promise<void>; | ||
runCode(code: string, opts?: RunCodeOpts & { | ||
/** | ||
* Context to run the code in. | ||
*/ | ||
context?: Context; | ||
}): Promise<Execution>; | ||
/** | ||
* Creates a new context to run code in. | ||
* | ||
* @param opts options for creating the context. | ||
* | ||
* @returns context object. | ||
*/ | ||
createCodeContext(opts?: CreateCodeContextOpts): Promise<Context>; | ||
protected get jupyterUrl(): string; | ||
} | ||
export { CodeInterpreter, CreateKernelProps, Execution, ExecutionError, JupyterExtension, Logs, MIMEType, RawData, Result, CodeInterpreter as default }; | ||
export { type BarChart, type BarData, type BoxAndWhiskerChart, type BoxAndWhiskerData, type Chart, ChartType, type ChartTypes, type Context, type CreateCodeContextOpts, Execution, ExecutionError, type LineChart, type Logs, type MIMEType, OutputMessage, type PieChart, type PieData, type PointData, type RawData, Result, type RunCodeOpts, Sandbox, ScaleType, type ScatterChart, type SuperChart, Sandbox as default }; |
"use strict"; | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __defProps = Object.defineProperties; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropDescs = Object.getOwnPropertyDescriptors; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getOwnPropSymbols = Object.getOwnPropertySymbols; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __propIsEnum = Object.prototype.propertyIsEnumerable; | ||
var __reflectGet = Reflect.get; | ||
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name); | ||
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; | ||
@@ -23,2 +23,3 @@ var __spreadValues = (a, b) => { | ||
}; | ||
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); | ||
var __export = (target, all) => { | ||
@@ -37,12 +38,3 @@ for (var name in all) | ||
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); | ||
var __async = (__this, __arguments, generator) => { | ||
@@ -68,2 +60,18 @@ return new Promise((resolve, reject) => { | ||
}; | ||
var __await = function(promise, isYieldStar) { | ||
this[0] = promise; | ||
this[1] = isYieldStar; | ||
}; | ||
var __asyncGenerator = (__this, __arguments, generator) => { | ||
var resume = (k, v, yes, no) => { | ||
try { | ||
var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done; | ||
Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no)); | ||
} catch (e) { | ||
no(e); | ||
} | ||
}, method = (k) => it[k] = (x) => new Promise((yes, no) => resume(k, x, yes, no)), it = {}; | ||
return generator = generator.apply(__this, __arguments), it[__knownSymbol("asyncIterator")] = () => it, method("next"), method("throw"), method("return"), it; | ||
}; | ||
var __forAwait = (obj, it, method) => (it = obj[__knownSymbol("asyncIterator")]) ? it.call(obj) : (obj = obj[__knownSymbol("iterator")](), it = {}, method = (key, fn) => (fn = obj[key]) && (it[key] = (arg) => new Promise((yes, no, done) => (arg = fn.call(obj, arg), done = arg.done, Promise.resolve(arg.value).then((value) => yes({ value, done }), no)))), method("next"), method("return"), it); | ||
@@ -73,83 +81,72 @@ // src/index.ts | ||
__export(src_exports, { | ||
CodeInterpreter: () => CodeInterpreter, | ||
JupyterExtension: () => JupyterExtension, | ||
Sandbox: () => Sandbox, | ||
default: () => src_default | ||
}); | ||
module.exports = __toCommonJS(src_exports); | ||
__reExport(src_exports, require("e2b"), module.exports); | ||
// src/code-interpreter.ts | ||
var import_e2b2 = require("e2b"); | ||
// src/sandbox.ts | ||
var import_e2b3 = require("e2b"); | ||
// src/messaging.ts | ||
var import_isomorphic_ws = __toESM(require("isomorphic-ws")); | ||
var import_e2b = require("e2b"); | ||
// src/utils.ts | ||
function createDeferredPromise() { | ||
let resolve; | ||
let reject; | ||
const promise = new Promise((res, rej) => { | ||
resolve = res; | ||
reject = rej; | ||
function extractError(res) { | ||
return __async(this, null, function* () { | ||
if (res.ok) { | ||
return; | ||
} | ||
switch (res.status) { | ||
case 502: | ||
return new import_e2b.TimeoutError( | ||
`${yield res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.` | ||
); | ||
case 404: | ||
return new import_e2b.NotFoundError(yield res.text()); | ||
default: | ||
return new import_e2b.SandboxError(`${res.status} ${res.statusText}`); | ||
} | ||
}); | ||
return { | ||
promise, | ||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | ||
reject, | ||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | ||
resolve | ||
}; | ||
} | ||
function id(length) { | ||
let result = ""; | ||
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | ||
const charactersLength = characters.length; | ||
for (let i = 0; i < length; i++) { | ||
result += characters.charAt(Math.floor(Math.random() * charactersLength)); | ||
} | ||
return result; | ||
} | ||
// src/messaging.ts | ||
var ExecutionError = class { | ||
constructor(name, value, tracebackRaw) { | ||
constructor(name, value, traceback) { | ||
this.name = name; | ||
this.value = value; | ||
this.tracebackRaw = tracebackRaw; | ||
this.traceback = traceback; | ||
} | ||
/** | ||
* Returns the traceback of the error as a string. | ||
*/ | ||
get traceback() { | ||
return this.tracebackRaw.join("\n"); | ||
} | ||
}; | ||
var Result = class { | ||
constructor(data, isMainResult) { | ||
constructor(rawData, isMainResult) { | ||
this.isMainResult = isMainResult; | ||
this.text = data["text/plain"]; | ||
this.html = data["text/html"]; | ||
this.markdown = data["text/markdown"]; | ||
this.svg = data["image/svg+xml"]; | ||
this.png = data["image/png"]; | ||
this.jpeg = data["image/jpeg"]; | ||
this.pdf = data["application/pdf"]; | ||
this.latex = data["text/latex"]; | ||
this.json = data["application/json"]; | ||
this.javascript = data["application/javascript"]; | ||
const data = __spreadValues({}, rawData); | ||
delete data["type"]; | ||
delete data["is_main_result"]; | ||
this.text = data["text"]; | ||
this.html = data["html"]; | ||
this.markdown = data["markdown"]; | ||
this.svg = data["svg"]; | ||
this.png = data["png"]; | ||
this.jpeg = data["jpeg"]; | ||
this.pdf = data["pdf"]; | ||
this.latex = data["latex"]; | ||
this.json = data["json"]; | ||
this.javascript = data["javascript"]; | ||
this.isMainResult = isMainResult; | ||
this.raw = data; | ||
this.data = data["data"]; | ||
this.chart = data["chart"]; | ||
this.extra = {}; | ||
for (const key of Object.keys(data)) { | ||
if (![ | ||
"text/plain", | ||
"text/html", | ||
"text/markdown", | ||
"image/svg+xml", | ||
"image/png", | ||
"image/jpeg", | ||
"application/pdf", | ||
"text/latex", | ||
"application/json", | ||
"application/javascript" | ||
"plain", | ||
"html", | ||
"markdown", | ||
"svg", | ||
"png", | ||
"jpeg", | ||
"pdf", | ||
"latex", | ||
"json", | ||
"javascript", | ||
"data", | ||
"extra" | ||
].includes(key)) { | ||
@@ -194,2 +191,5 @@ this.extra[key] = data[key]; | ||
} | ||
if (this.data) { | ||
formats.push("data"); | ||
} | ||
for (const key of Object.keys(this.extra)) { | ||
@@ -219,6 +219,7 @@ formats.push(key); | ||
var Execution = class { | ||
constructor(results, logs, error) { | ||
constructor(results = [], logs = { stdout: [], stderr: [] }, error, executionCount) { | ||
this.results = results; | ||
this.logs = logs; | ||
this.error = error; | ||
this.executionCount = executionCount; | ||
} | ||
@@ -246,397 +247,163 @@ /** | ||
}; | ||
var CellExecution = class { | ||
constructor(onStdout, onStderr, onResult) { | ||
this.inputAccepted = false; | ||
this.execution = new Execution([], { stdout: [], stderr: [] }); | ||
this.onStdout = onStdout; | ||
this.onStderr = onStderr; | ||
this.onResult = onResult; | ||
} | ||
}; | ||
var JupyterKernelWebSocket = class { | ||
// constructor | ||
/** | ||
* Does not start WebSocket connection! | ||
* You need to call connect() method first. | ||
*/ | ||
constructor(url) { | ||
this.url = url; | ||
this.idAwaiter = {}; | ||
this.cells = {}; | ||
} | ||
set ws(ws) { | ||
this._ws = ws; | ||
} | ||
get ws() { | ||
if (!this._ws) { | ||
throw new Error("WebSocket is not connected."); | ||
} | ||
return this._ws; | ||
} | ||
// public | ||
/** | ||
* Starts WebSocket connection. | ||
*/ | ||
connect() { | ||
this._ws = new import_isomorphic_ws.default(this.url); | ||
return this.listen(); | ||
} | ||
// events | ||
/** | ||
* Listens for messages from WebSocket server. | ||
* | ||
* Message types: | ||
* https://jupyter-client.readthedocs.io/en/stable/messaging.html | ||
* | ||
*/ | ||
listenMessages() { | ||
this.ws.onmessage = (e) => { | ||
const message = JSON.parse(e.data.toString()); | ||
const parentMsgId = message.parent_header.msg_id; | ||
const cell = this.cells[parentMsgId]; | ||
if (!cell) { | ||
return; | ||
} | ||
const execution = cell.execution; | ||
if (message.msg_type == "error") { | ||
execution.error = new ExecutionError( | ||
message.content.ename, | ||
message.content.evalue, | ||
message.content.traceback | ||
function parseOutput(execution, line, onStdout, onStderr, onResult, onError) { | ||
return __async(this, null, function* () { | ||
const msg = JSON.parse(line); | ||
switch (msg.type) { | ||
case "result": | ||
const result = new Result( | ||
__spreadProps(__spreadValues({}, msg), { type: void 0, is_main_result: void 0 }), | ||
msg.is_main_result | ||
); | ||
} else if (message.msg_type == "stream") { | ||
if (message.content.name == "stdout") { | ||
execution.logs.stdout.push(message.content.text); | ||
if (cell == null ? void 0 : cell.onStdout) { | ||
cell.onStdout( | ||
new import_e2b.ProcessMessage( | ||
message.content.text, | ||
(/* @__PURE__ */ new Date()).getTime() * 1e6, | ||
false | ||
) | ||
); | ||
} | ||
} else if (message.content.name == "stderr") { | ||
execution.logs.stderr.push(message.content.text); | ||
if (cell == null ? void 0 : cell.onStderr) { | ||
cell.onStderr( | ||
new import_e2b.ProcessMessage( | ||
message.content.text, | ||
(/* @__PURE__ */ new Date()).getTime() * 1e6, | ||
true | ||
) | ||
); | ||
} | ||
} | ||
} else if (message.msg_type == "display_data") { | ||
const result = new Result(message.content.data, false); | ||
execution.results.push(result); | ||
if (cell.onResult) { | ||
cell.onResult(result); | ||
if (onResult) { | ||
yield onResult(result); | ||
} | ||
} else if (message.msg_type == "execute_result") { | ||
const result = new Result(message.content.data, true); | ||
execution.results.push(result); | ||
if (cell.onResult) { | ||
cell.onResult(result); | ||
break; | ||
case "stdout": | ||
execution.logs.stdout.push(msg.text); | ||
if (onStdout) { | ||
yield onStdout({ | ||
error: false, | ||
line: msg.text, | ||
timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3 | ||
}); | ||
} | ||
} else if (message.msg_type == "status") { | ||
if (message.content.execution_state == "idle") { | ||
if (cell.inputAccepted) { | ||
this.idAwaiter[parentMsgId](execution); | ||
} | ||
} else if (message.content.execution_state == "error") { | ||
execution.error = new ExecutionError( | ||
message.content.ename, | ||
message.content.evalue, | ||
message.content.traceback | ||
); | ||
this.idAwaiter[parentMsgId](execution); | ||
break; | ||
case "stderr": | ||
execution.logs.stderr.push(msg.text); | ||
if (onStderr) { | ||
yield onStderr({ | ||
error: true, | ||
line: msg.text, | ||
timestamp: (/* @__PURE__ */ new Date()).getTime() * 1e3 | ||
}); | ||
} | ||
} else if (message.msg_type == "execute_reply") { | ||
if (message.content.status == "error") { | ||
execution.error = new ExecutionError( | ||
message.content.ename, | ||
message.content.evalue, | ||
message.content.traceback | ||
); | ||
} else if (message.content.status == "ok") { | ||
return; | ||
break; | ||
case "error": | ||
execution.error = new ExecutionError(msg.name, msg.value, msg.traceback); | ||
if (onError) { | ||
yield onError(execution.error); | ||
} | ||
} else if (message.msg_type == "execute_input") { | ||
cell.inputAccepted = true; | ||
} else { | ||
console.warn("[UNHANDLED MESSAGE TYPE]:", message.msg_type); | ||
} | ||
}; | ||
break; | ||
case "number_of_executions": | ||
execution.executionCount = msg.execution_count; | ||
break; | ||
} | ||
}); | ||
} | ||
// src/utils.ts | ||
var import_e2b2 = require("e2b"); | ||
function formatRequestTimeoutError(error) { | ||
if (error instanceof Error && error.name === "AbortError") { | ||
return new import_e2b2.TimeoutError("Request timed out \u2014 the 'requestTimeoutMs' option can be used to increase this timeout"); | ||
} | ||
// communication | ||
/** | ||
* Sends code to be executed by Jupyter kernel. | ||
* @param code Code to be executed. | ||
* @param onStdout Callback for stdout messages. | ||
* @param onStderr Callback for stderr messages. | ||
* @param onResult Callback function to handle the result and display calls of the code execution. | ||
* @param timeout Time in milliseconds to wait for response. | ||
* @returns Promise with execution result. | ||
*/ | ||
sendExecutionMessage(code, onStdout, onStderr, onResult, timeout) { | ||
return new Promise((resolve, reject) => { | ||
const msg_id = id(16); | ||
const data = this.sendExecuteRequest(msg_id, code); | ||
let timeoutSet; | ||
if (timeout) { | ||
timeoutSet = setTimeout(() => { | ||
delete this.idAwaiter[msg_id]; | ||
reject( | ||
new Error( | ||
`Awaiting response to "${code}" with id: ${msg_id} timed out.` | ||
) | ||
); | ||
}, timeout); | ||
} | ||
this.cells[msg_id] = new CellExecution(onStdout, onStderr, onResult); | ||
this.idAwaiter[msg_id] = (responseData) => { | ||
clearInterval(timeoutSet); | ||
delete this.idAwaiter[msg_id]; | ||
resolve(responseData); | ||
}; | ||
const json = JSON.stringify(data); | ||
this.ws.send(json); | ||
}); | ||
return error; | ||
} | ||
function formatExecutionTimeoutError(error) { | ||
if (error instanceof Error && error.name === "AbortError") { | ||
return new import_e2b2.TimeoutError("Execution timed out \u2014 the 'timeoutMs' option can be used to increase this timeout"); | ||
} | ||
/** | ||
* Listens for messages from WebSocket server. | ||
*/ | ||
listen() { | ||
return new Promise((resolve, reject) => { | ||
this.ws.onopen = (e) => { | ||
resolve(e); | ||
}; | ||
this.listenMessages(); | ||
this.ws.onclose = (e) => { | ||
reject( | ||
new Error( | ||
`WebSocket closed with code: ${e.code} and reason: ${e.reason}` | ||
) | ||
); | ||
}; | ||
}); | ||
} | ||
/** | ||
* Creates a websocket message for code execution. | ||
* @param msg_id Unique message id. | ||
* @param code Code to be executed. | ||
*/ | ||
sendExecuteRequest(msg_id, code) { | ||
const session = id(16); | ||
return { | ||
header: { | ||
msg_id, | ||
username: "e2b", | ||
session, | ||
msg_type: "execute_request", | ||
version: "5.3" | ||
}, | ||
parent_header: {}, | ||
metadata: {}, | ||
content: { | ||
code, | ||
silent: false, | ||
store_history: false, | ||
user_expressions: {}, | ||
allow_stdin: false | ||
return error; | ||
} | ||
function readLines(stream) { | ||
return __asyncGenerator(this, null, function* () { | ||
const reader = stream.getReader(); | ||
let buffer = ""; | ||
try { | ||
while (true) { | ||
const { done, value } = yield new __await(reader.read()); | ||
if (value !== void 0) { | ||
buffer += new TextDecoder().decode(value); | ||
} | ||
if (done) { | ||
if (buffer.length > 0) { | ||
yield buffer; | ||
} | ||
break; | ||
} | ||
let newlineIdx = -1; | ||
do { | ||
newlineIdx = buffer.indexOf("\n"); | ||
if (newlineIdx !== -1) { | ||
yield buffer.slice(0, newlineIdx); | ||
buffer = buffer.slice(newlineIdx + 1); | ||
} | ||
} while (newlineIdx !== -1); | ||
} | ||
}; | ||
} | ||
/** | ||
* Closes WebSocket connection. | ||
*/ | ||
close() { | ||
this.ws.close(); | ||
} | ||
}; | ||
} finally { | ||
reader.releaseLock(); | ||
} | ||
}); | ||
} | ||
// src/code-interpreter.ts | ||
var _CodeInterpreter = class extends import_e2b2.Sandbox { | ||
constructor(opts, createCalled = false) { | ||
super(__spreadValues({ template: (opts == null ? void 0 : opts.template) || _CodeInterpreter.template }, opts), createCalled); | ||
this.notebook = new JupyterExtension(this); | ||
} | ||
_open(opts) { | ||
// src/consts.ts | ||
var DEFAULT_TIMEOUT_MS = 6e4; | ||
var JUPYTER_PORT = 49999; | ||
// src/sandbox.ts | ||
var Sandbox = class extends import_e2b3.Sandbox { | ||
runCode(code, opts) { | ||
return __async(this, null, function* () { | ||
yield __superGet(_CodeInterpreter.prototype, this, "_open").call(this, { timeout: opts == null ? void 0 : opts.timeout }); | ||
yield this.notebook.connect(opts == null ? void 0 : opts.timeout); | ||
return this; | ||
}); | ||
} | ||
close() { | ||
return __async(this, null, function* () { | ||
yield this.notebook.close(); | ||
yield __superGet(_CodeInterpreter.prototype, this, "close").call(this); | ||
}); | ||
} | ||
}; | ||
var CodeInterpreter = _CodeInterpreter; | ||
CodeInterpreter.template = "code-interpreter-stateful"; | ||
var JupyterExtension = class { | ||
constructor(sandbox) { | ||
this.sandbox = sandbox; | ||
this.connectedKernels = {}; | ||
this.kernelIDPromise = createDeferredPromise(); | ||
this.setDefaultKernelID = this.kernelIDPromise.resolve; | ||
} | ||
get defaultKernelID() { | ||
return this.kernelIDPromise.promise; | ||
} | ||
connect(timeout) { | ||
return __async(this, null, function* () { | ||
return this.startConnectingToDefaultKernel(this.setDefaultKernelID, { | ||
timeout | ||
}); | ||
}); | ||
} | ||
/** | ||
* Executes a code cell in a notebool cell. | ||
* | ||
* This method sends the provided code to a specified kernel in a remote notebook for execution. | ||
* @param code The code to be executed in the notebook cell. | ||
* @param kernelID The ID of the kernel to execute the code on. If not provided, the default kernel is used. | ||
* @param onStdout A callback function to handle standard output messages from the code execution. | ||
* @param onStderr A callback function to handle standard error messages from the code execution. | ||
* @param onResult A callback function to handle display data messages from the code execution. | ||
* @param timeout The maximum time to wait for the code execution to complete, in milliseconds. | ||
* @returns A promise that resolves with the result of the code execution. | ||
*/ | ||
execCell(_0) { | ||
return __async(this, arguments, function* (code, { | ||
kernelID, | ||
onStdout, | ||
onStderr, | ||
onResult, | ||
timeout | ||
} = {}) { | ||
kernelID = kernelID || (yield this.defaultKernelID); | ||
const ws = this.connectedKernels[kernelID] || (yield this.connectToKernelWS(kernelID)); | ||
return yield ws.sendExecutionMessage( | ||
code, | ||
onStdout, | ||
onStderr, | ||
onResult, | ||
timeout | ||
); | ||
}); | ||
} | ||
startConnectingToDefaultKernel(resolve, opts) { | ||
return __async(this, null, function* () { | ||
const kernelID = (yield this.sandbox.filesystem.read("/root/.jupyter/kernel_id", opts)).trim(); | ||
yield this.connectToKernelWS(kernelID); | ||
resolve(kernelID); | ||
}); | ||
} | ||
/** | ||
* Connects to a kernel's WebSocket. | ||
* | ||
* This method establishes a WebSocket connection to the specified kernel. It is used internally | ||
* to facilitate real-time communication with the kernel, enabling operations such as executing | ||
* code and receiving output. The connection details are managed within the method, including | ||
* the retrieval of the necessary WebSocket URL from the kernel's information. | ||
* | ||
* @param kernelID The unique identifier of the kernel to connect to. | ||
* @throws {Error} Throws an error if the connection to the kernel's WebSocket cannot be established. | ||
*/ | ||
connectToKernelWS(kernelID) { | ||
return __async(this, null, function* () { | ||
const url = `${this.sandbox.getProtocol("ws")}://${this.sandbox.getHostname( | ||
8888 | ||
)}/api/kernels/${kernelID}/channels`; | ||
const ws = new JupyterKernelWebSocket(url); | ||
yield ws.connect(); | ||
this.connectedKernels[kernelID] = ws; | ||
return ws; | ||
}); | ||
} | ||
/** | ||
* Creates a new Jupyter kernel. It can be useful if you want to have multiple independent code execution environments. | ||
* | ||
* The kernel can be optionally configured to start in a specific working directory and/or | ||
* with a specific kernel name. If no kernel name is provided, the default kernel will be used. | ||
* Once the kernel is created, this method establishes a WebSocket connection to the new kernel for | ||
* real-time communication. | ||
* | ||
* @param cwd Sets the current working directory where the kernel should start. Defaults to "/home/user". | ||
* @param kernelName The name of the kernel to create, useful if you have multiple kernel types. If not provided, the default kernel will be used. | ||
* @returns A promise that resolves with the ID of the newly created kernel. | ||
* @throws {Error} Throws an error if the kernel creation fails. | ||
*/ | ||
createKernel(cwd = "/home/user", kernelName) { | ||
return __async(this, null, function* () { | ||
const data = { cwd }; | ||
if (kernelName) { | ||
data.kernelName = kernelName; | ||
var _a, _b, _c; | ||
if ((opts == null ? void 0 : opts.context) && (opts == null ? void 0 : opts.language)) { | ||
throw new import_e2b3.InvalidArgumentError("You can provide context or language, but not both at the same time."); | ||
} | ||
const response = yield fetch( | ||
`${this.sandbox.getProtocol()}://${this.sandbox.getHostname( | ||
8888 | ||
)}/api/kernels`, | ||
{ | ||
const controller = new AbortController(); | ||
const requestTimeout = (_a = opts == null ? void 0 : opts.requestTimeoutMs) != null ? _a : this.connectionConfig.requestTimeoutMs; | ||
const reqTimer = requestTimeout ? setTimeout(() => { | ||
controller.abort(); | ||
}, requestTimeout) : void 0; | ||
try { | ||
const res = yield fetch(`${this.jupyterUrl}/execute`, { | ||
method: "POST", | ||
body: JSON.stringify(data) | ||
headers: { | ||
"Content-Type": "application/json" | ||
}, | ||
body: JSON.stringify({ | ||
code, | ||
context_id: (_b = opts == null ? void 0 : opts.context) == null ? void 0 : _b.id, | ||
language: opts == null ? void 0 : opts.language, | ||
env_vars: opts == null ? void 0 : opts.envs | ||
}), | ||
signal: controller.signal, | ||
keepalive: true | ||
}); | ||
const error2 = yield extractError(res); | ||
if (error2) { | ||
throw error2; | ||
} | ||
); | ||
if (!response.ok) { | ||
throw new Error(`Failed to create kernel: ${response.statusText}`); | ||
} | ||
const kernelID = (yield response.json()).id; | ||
yield this.connectToKernelWS(kernelID); | ||
return kernelID; | ||
}); | ||
} | ||
/** | ||
* Restarts an existing Jupyter kernel. This can be useful to reset the kernel's state or to recover from errors. | ||
* | ||
* @param kernelID The unique identifier of the kernel to restart. If not provided, the default kernel is restarted. | ||
* @throws {Error} Throws an error if the kernel restart fails or if the operation times out. | ||
*/ | ||
restartKernel(kernelID) { | ||
return __async(this, null, function* () { | ||
kernelID = kernelID || (yield this.defaultKernelID); | ||
this.connectedKernels[kernelID].close(); | ||
delete this.connectedKernels[kernelID]; | ||
const response = yield fetch( | ||
`${this.sandbox.getProtocol()}://${this.sandbox.getHostname( | ||
8888 | ||
)}/api/kernels/${kernelID}/restart`, | ||
{ | ||
method: "POST" | ||
if (!res.body) { | ||
throw new Error(`Not response body: ${res.statusText} ${yield res == null ? void 0 : res.text()}`); | ||
} | ||
); | ||
if (!response.ok) { | ||
throw new Error(`Failed to restart kernel ${kernelID}`); | ||
} | ||
yield this.connectToKernelWS(kernelID); | ||
}); | ||
} | ||
/** | ||
* Shuts down an existing Jupyter kernel. This method is used to gracefully terminate a kernel's process. | ||
* @param kernelID The unique identifier of the kernel to shutdown. If not provided, the default kernel is shutdown. | ||
* @throws {Error} Throws an error if the kernel shutdown fails or if the operation times out. | ||
*/ | ||
shutdownKernel(kernelID) { | ||
return __async(this, null, function* () { | ||
kernelID = kernelID || (yield this.defaultKernelID); | ||
this.connectedKernels[kernelID].close(); | ||
delete this.connectedKernels[kernelID]; | ||
const response = yield fetch( | ||
`${this.sandbox.getProtocol()}://${this.sandbox.getHostname( | ||
8888 | ||
)}/api/kernels/${kernelID}`, | ||
{ | ||
method: "DELETE" | ||
clearTimeout(reqTimer); | ||
const bodyTimeout = (_c = opts == null ? void 0 : opts.timeoutMs) != null ? _c : DEFAULT_TIMEOUT_MS; | ||
const bodyTimer = bodyTimeout ? setTimeout(() => { | ||
controller.abort(); | ||
}, bodyTimeout) : void 0; | ||
const execution = new Execution(); | ||
try { | ||
try { | ||
for (var iter = __forAwait(readLines(res.body)), more, temp, error; more = !(temp = yield iter.next()).done; more = false) { | ||
const chunk = temp.value; | ||
yield parseOutput(execution, chunk, opts == null ? void 0 : opts.onStdout, opts == null ? void 0 : opts.onStderr, opts == null ? void 0 : opts.onResult, opts == null ? void 0 : opts.onError); | ||
} | ||
} catch (temp) { | ||
error = [temp]; | ||
} finally { | ||
try { | ||
more && (temp = iter.return) && (yield temp.call(iter)); | ||
} finally { | ||
if (error) | ||
throw error[0]; | ||
} | ||
} | ||
} catch (error3) { | ||
throw formatExecutionTimeoutError(error3); | ||
} finally { | ||
clearTimeout(bodyTimer); | ||
} | ||
); | ||
if (!response.ok) { | ||
throw new Error(`Failed to shutdown kernel ${kernelID}`); | ||
return execution; | ||
} catch (error2) { | ||
throw formatRequestTimeoutError(error2); | ||
} | ||
@@ -646,47 +413,46 @@ }); | ||
/** | ||
* Lists all available Jupyter kernels. | ||
* Creates a new context to run code in. | ||
* | ||
* This method fetches a list of all currently available Jupyter kernels from the server. It can be used | ||
* to retrieve the IDs of all kernels that are currently running or available for connection. | ||
* | ||
* @returns A promise that resolves to an array of kernel IDs. | ||
* @throws {Error} Throws an error if the request to list kernels fails. | ||
* @param opts options for creating the context. | ||
* | ||
* @returns context object. | ||
*/ | ||
listKernels() { | ||
createCodeContext(opts) { | ||
return __async(this, null, function* () { | ||
const response = yield fetch( | ||
`${this.sandbox.getProtocol()}://${this.sandbox.getHostname( | ||
8888 | ||
)}/api/kernels`, | ||
{ | ||
method: "GET" | ||
try { | ||
const res = yield fetch(`${this.jupyterUrl}/contexts`, { | ||
method: "POST", | ||
headers: { | ||
"Content-Type": "application/json" | ||
}, | ||
body: JSON.stringify({ | ||
language: opts == null ? void 0 : opts.language, | ||
cwd: opts == null ? void 0 : opts.cwd | ||
}), | ||
keepalive: true, | ||
signal: this.connectionConfig.getSignal(opts == null ? void 0 : opts.requestTimeoutMs) | ||
}); | ||
const error = yield extractError(res); | ||
if (error) { | ||
throw error; | ||
} | ||
); | ||
if (!response.ok) { | ||
throw new Error(`Failed to list kernels: ${response.statusText}`); | ||
return yield res.json(); | ||
} catch (error) { | ||
throw formatRequestTimeoutError(error); | ||
} | ||
return (yield response.json()).map((kernel) => kernel.id); | ||
}); | ||
} | ||
/** | ||
* Close all the websocket connections to the kernels. It doesn't shutdown the kernels. | ||
*/ | ||
close() { | ||
return __async(this, null, function* () { | ||
for (const kernelID of Object.keys(this.connectedKernels)) { | ||
this.connectedKernels[kernelID].close(); | ||
} | ||
}); | ||
get jupyterUrl() { | ||
return `${this.connectionConfig.debug ? "http" : "https"}://${this.getHost(JUPYTER_PORT)}`; | ||
} | ||
}; | ||
Sandbox.defaultTemplate = "code-interpreter-v1"; | ||
// src/index.ts | ||
__reExport(src_exports, require("e2b"), module.exports); | ||
var src_default = CodeInterpreter; | ||
var src_default = Sandbox; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = { | ||
CodeInterpreter, | ||
JupyterExtension, | ||
Sandbox, | ||
...require("e2b") | ||
}); | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@e2b/code-interpreter", | ||
"version": "1.0.0", | ||
"version": "1.0.1", | ||
"description": "E2B Code Interpreter - Stateful code execution", | ||
@@ -29,7 +29,7 @@ "homepage": "https://e2b.dev", | ||
"dotenv": "^16.4.5", | ||
"knip": "^2.34.0", | ||
"npm-check-updates": "^16.14.6", | ||
"tsup": "^6.7.0", | ||
"typescript": "^5.2.2", | ||
"vitest": "^0.34.6" | ||
"knip": "^5.25.1", | ||
"npm-check-updates": "^16.14.20", | ||
"tsup": "^8.1.0", | ||
"typescript": "^5.5.3", | ||
"vitest": "^2.0.1" | ||
}, | ||
@@ -55,5 +55,3 @@ "files": [ | ||
"dependencies": { | ||
"e2b": "^0.16.1", | ||
"isomorphic-ws": "^5.0.0", | ||
"ws": "^8.15.1" | ||
"e2b": "^1.0.0" | ||
}, | ||
@@ -72,4 +70,7 @@ "engines": { | ||
"check-deps": "knip", | ||
"update-deps": "ncu -u && pnpm i" | ||
"update-deps": "ncu -u && pnpm i", | ||
"example": "npx tsx example.mts", | ||
"test:bun": "bun test tests/runtimes/bun --env-file=.env", | ||
"test:deno": "deno test tests/runtimes/deno/ --allow-net --allow-read --allow-env --unstable-sloppy-imports --trace-leaks" | ||
} | ||
} |
@@ -1,3 +0,22 @@ | ||
# Code interpreter extension for JavaScript | ||
<p align="center"> | ||
<img width="100" src="/readme-assets/logo-circle.png" alt="e2b logo"> | ||
</p> | ||
<h1 align="center"> | ||
Code interpreter extension for JavaScript | ||
</h1> | ||
<h4 align="center"> | ||
<a href="https://pypi.org/project/e2b/"> | ||
<img alt="Last 1 month downloads for the Python SDK" loading="lazy" width="200" height="20" decoding="async" data-nimg="1" | ||
style="color:transparent;width:auto;height:100%" src="https://img.shields.io/pypi/dm/e2b?label=PyPI%20Downloads"> | ||
</a> | ||
<a href="https://www.npmjs.com/package/e2b"> | ||
<img alt="Last 1 month downloads for the Python SDK" loading="lazy" width="200" height="20" decoding="async" data-nimg="1" | ||
style="color:transparent;width:auto;height:100%" src="https://img.shields.io/npm/dm/e2b?label=NPM%20Downloads"> | ||
</a> | ||
</h4> | ||
The repository contains a template and modules for the code interpreter sandbox. It is based on the Jupyter server and implements the Jupyter Kernel messaging protocol. This allows for sharing context between code executions and improves support for plotting charts and other display-able data. | ||
@@ -8,3 +27,3 @@ | ||
- **Stateful Execution**: Unlike traditional sandboxes that treat each code execution independently, this package maintains context across executions. | ||
- **Displaying Graph & Data**: Implements parts of the [Jupyter Kernel messaging protocol](https://jupyter-client.readthedocs.io/en/latest/messaging.html), which support for interactive features like plotting charts, rendering DataFrames, etc. | ||
- **Displaying Charts & Data**: Implements parts of the [Jupyter Kernel messaging protocol](https://jupyter-client.readthedocs.io/en/latest/messaging.html), which support for interactive features like plotting charts, rendering DataFrames, etc. | ||
@@ -22,8 +41,8 @@ ## Installation | ||
```js | ||
import { CodeInterpreter } from '@e2b/code-interpreter' | ||
import { Sandbox } from '@e2b/code-interpreter' | ||
const sandbox = await CodeInterpreter.create() | ||
await sandbox.notebook.execCell('x = 1') | ||
const sandbox = await Sandbox.create() | ||
await sbx.runCode()('x = 1') | ||
const execution = await sandbox.notebook.execCell('x+=1; x') | ||
const execution = await sbx.runCode()('x+=1; x') | ||
console.log(execution.text) // outputs 2 | ||
@@ -37,5 +56,5 @@ | ||
```js | ||
import { CodeInterpreter } from '@e2b/code-interpreter' | ||
import { Sandbox } from '@e2b/code-interpreter' | ||
const sandbox = await CodeInterpreter.create() | ||
const sandbox = await Sandbox.create() | ||
@@ -54,5 +73,5 @@ const code = ` | ||
// you can install dependencies in "jupyter notebook style" | ||
await sandbox.notebook.execCell("!pip install matplotlib") | ||
await sandbox.runCode('!pip install matplotlib') | ||
const execution = await sandbox.notebook.execCell(code) | ||
const execution = await sandbox.runCode(code) | ||
@@ -62,3 +81,3 @@ // this contains the image data, you can e.g. save it to file or send to frontend | ||
await sandbox.close() | ||
await sandbox.kill() | ||
``` | ||
@@ -69,3 +88,3 @@ | ||
```js | ||
import { CodeInterpreter } from '@e2b/code-interpreter' | ||
import { Sandbox } from '@e2b/code-interpreter' | ||
@@ -84,11 +103,32 @@ const code = ` | ||
const sandbox = await CodeInterpreter.create() | ||
const sandbox = await Sandbox.create() | ||
await sandbox.notebook.execCell(code, { | ||
await sandbox.runCode(code, { | ||
onStdout: (out) => console.log(out), | ||
onStderr: (outErr) => console.error(outErr), | ||
onResult: (result) => console.log(result.text) | ||
onResult: (result) => console.log(result.text), | ||
}) | ||
await sandbox.close() | ||
await sandbox.kill() | ||
``` | ||
### More resources | ||
- Check out the [JavaScript/TypeScript](https://e2b.dev/docs/hello-world/js) and [Python](https://e2b.dev/docs/hello-world/py) "Hello World" guides to learn how to use our SDK. | ||
- See [E2B documentation](https://e2b.dev/docs) to get started. | ||
- Visit our [Cookbook](https://github.com/e2b-dev/e2b-cookbook/tree/main) to get inspired by examples with different LLMs and AI frameworks. | ||
___ | ||
<div align='center'> | ||
<!-- <a href="https://e2b.dev/docs" target="_blank"> | ||
<img src="https://img.shields.io/badge/docs-%2300acee.svg?color=143D52&style=for-the-badge&logo=x&logoColor=white" alt=docs style="margin-bottom: 5px;"/></a> --> | ||
<a href="https://twitter.com/e2b_dev" target="_blank"> | ||
<img src="https://img.shields.io/badge/x (twitter)-%2300acee.svg?color=000000&style=for-the-badge&logo=x&logoColor=white" alt=linkedin style="margin-bottom: 5px;"/></a> | ||
<a href="https://discord.com/invite/U7KEcGErtQ" target="_blank"> | ||
<img src="https://img.shields.io/badge/discord -%2300acee.svg?color=143D52&style=for-the-badge&logo=discord&logoColor=white" alt=discord style="margin-bottom: 5px;"/></a> | ||
<a href="https://www.linkedin.com/company/e2b-dev/" target="_blank"> | ||
<img src="https://img.shields.io/badge/linkedin-%2300acee.svg?color=000000&style=for-the-badge&logo=linkedin&logoColor=white" alt=linkedin style="margin-bottom: 5px;"/></a> | ||
</div align='center'> |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
1
9
0
127
4
121156
1358
+ Added@bufbuild/protobuf@2.2.3(transitive)
+ Added@connectrpc/connect@2.0.0-rc.3(transitive)
+ Added@connectrpc/connect-web@2.0.0-rc.3(transitive)
+ Addedcompare-versions@6.1.1(transitive)
+ Addede2b@1.0.5(transitive)
+ Addedopenapi-fetch@0.9.8(transitive)
+ Addedopenapi-typescript-helpers@0.0.8(transitive)
- Removedisomorphic-ws@^5.0.0
- Removedws@^8.15.1
- Removedbufferutil@4.0.8(transitive)
- Removede2b@0.16.2(transitive)
- Removedisomorphic-ws@5.0.0(transitive)
- Removednode-gyp-build@4.8.4(transitive)
- Removednormalize-path@3.0.0(transitive)
- Removedopenapi-typescript-fetch@1.1.3(transitive)
- Removedpath-browserify@1.0.1(transitive)
- Removedutf-8-validate@6.0.5(transitive)
- Removedws@8.18.0(transitive)
Updatede2b@^1.0.0