Skip to content

Commit 273edcf

Browse files
committed
Rename result type
1 parent 5f4e094 commit 273edcf

File tree

11 files changed

+101
-81
lines changed

11 files changed

+101
-81
lines changed

README.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ with CodeInterpreter() as sandbox:
8989
result = sandbox.notebook.exec_cell(code)
9090

9191
# there's your image
92-
image = result.data[0].png
92+
image = result.results[0].png
9393

9494
# example how to show the image / prove it works
9595
i = base64.b64decode(image)
@@ -150,7 +150,7 @@ with CodeInterpreter() as sandbox:
150150
#### JavaScript
151151

152152
```js
153-
import { CodeInterpreter } from "@e2b/code-interpreter"
153+
import { CodeInterpreter } from '@e2b/code-interpreter'
154154

155155
code = `
156156
import time
@@ -162,11 +162,12 @@ print("world")
162162

163163
const sandbox = await CodeInterpreter.create()
164164

165-
await sandbox.notebook.execCell(
166-
code,
167-
(out) => console.log(out),
168-
(outErr) => console.error(outErr),
169-
)
165+
await sandbox.notebook.execCell(code, {
166+
onStdout: (out) => console.log(out),
167+
onStderr: (outErr) => console.error(outErr)
168+
onDisplayData: (outData) => console.log(data.text)
169+
})
170+
170171
```
171172

172173
### Pre-installed Python packages inside the sandbox

js/example.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
const { CodeInterpreter } = require('./dist')
22
const dotenv = require('dotenv')
3-
dotenv.config();
3+
dotenv.config()
44

55
async function main() {
6-
const sandbox = await CodeInterpreter.create()
7-
const r =await sandbox.notebook.execCell('x = 1; x')
8-
console.log(r)
6+
const sandbox = await CodeInterpreter.create()
7+
const r = await sandbox.notebook.execCell('x = 1; x')
8+
console.log(r)
99
}
1010

1111
main().catch(console.error)
12-

js/src/code-interpreter.ts

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { ProcessMessage, Sandbox, SandboxOpts } from 'e2b'
2-
import {Data, JupyterKernelWebSocket, Result} from './messaging'
2+
import { Result, JupyterKernelWebSocket, Execution } from './messaging'
33
import { createDeferredPromise } from './utils'
44

55
interface Kernels {
@@ -46,10 +46,12 @@ export class JupyterExtension {
4646
return this.kernelIDPromise.promise
4747
}
4848

49-
constructor(private sandbox: CodeInterpreter) { }
49+
constructor(private sandbox: CodeInterpreter) {}
5050

5151
async connect(timeout?: number) {
52-
return this.startConnectingToDefaultKernel(this.setDefaultKernelID, { timeout })
52+
return this.startConnectingToDefaultKernel(this.setDefaultKernelID, {
53+
timeout
54+
})
5355
}
5456

5557
/**
@@ -62,6 +64,7 @@ export class JupyterExtension {
6264
* @param onStdout A callback function to handle standard output messages from the code execution.
6365
* @param onStderr A callback function to handle standard error messages from the code execution.
6466
* @param onDisplayData A callback function to handle display data messages from the code execution.
67+
* @param timeout The maximum time to wait for the code execution to complete, in milliseconds.
6568
* @returns A promise that resolves with the result of the code execution.
6669
*/
6770
async execCell(
@@ -71,23 +74,32 @@ export class JupyterExtension {
7174
onStdout,
7275
onStderr,
7376
onDisplayData,
77+
timeout
7478
}: {
7579
kernelID?: string
7680
onStdout?: (msg: ProcessMessage) => Promise<void> | void
7781
onStderr?: (msg: ProcessMessage) => Promise<void> | void
78-
onDisplayData?: (data: Data) => Promise<void> | void
82+
onDisplayData?: (data: Result) => Promise<void> | void
83+
timeout?: number
7984
}
85+
): Promise<Execution> {
86+
kernelID = kernelID || (await this.defaultKernelID)
87+
const ws =
88+
this.connectedKernels[kernelID] ||
89+
(await this.connectToKernelWS(kernelID))
8090

81-
): Promise<Result> {
82-
kernelID = kernelID || await this.defaultKernelID
83-
const ws = this.connectedKernels[kernelID] || await this.connectToKernelWS(kernelID)
84-
85-
return await ws.sendExecutionMessage(code, onStdout, onStderr, onDisplayData)
91+
return await ws.sendExecutionMessage(
92+
code,
93+
onStdout,
94+
onStderr,
95+
onDisplayData,
96+
timeout
97+
)
8698
}
8799

88100
private async startConnectingToDefaultKernel(
89101
resolve: (value: string) => void,
90-
opts?: { timeout?: number },
102+
opts?: { timeout?: number }
91103
) {
92104
const kernelID = (
93105
await this.sandbox.filesystem.read('/root/.jupyter/kernel_id', opts)

js/src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
export { CodeInterpreter, JupyterExtension } from './code-interpreter'
22
export type { CreateKernelProps } from './code-interpreter'
33

4-
export type { ExecutionError, Data, Result, MIMEType } from './messaging'
4+
export type { ExecutionError, Result, Execution, MIMEType } from './messaging'
55

66
import { CodeInterpreter } from './code-interpreter'
77
export default CodeInterpreter

js/src/messaging.ts

Lines changed: 39 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ export class ExecutionError {
1818
/**
1919
* The raw traceback of the error.
2020
**/
21-
public tracebackRaw: string[],
22-
) { }
21+
public tracebackRaw: string[]
22+
) {}
2323

2424
/**
2525
* Returns the traceback of the error as a string.
@@ -50,9 +50,9 @@ export type RawData = {
5050
* as a string, and the result can contain multiple types of data. The text representation is always present, and
5151
* the other representations are optional.
5252
*/
53-
export class Data {
53+
export class Result {
5454
/**
55-
* Text representation of the data. Always present.
55+
* Text representation of the result. Always present.
5656
*/
5757
readonly text: string
5858
/**
@@ -114,18 +114,20 @@ export class Data {
114114

115115
this.extra = {}
116116
for (const key of Object.keys(data)) {
117-
if (![
118-
'text/plain',
119-
'text/html',
120-
'text/markdown',
121-
'image/svg+xml',
122-
'image/png',
123-
'image/jpeg',
124-
'application/pdf',
125-
'text/latex',
126-
'application/json',
127-
'application/javascript'
128-
].includes(key)) {
117+
if (
118+
![
119+
'text/plain',
120+
'text/html',
121+
'text/markdown',
122+
'image/svg+xml',
123+
'image/png',
124+
'image/jpeg',
125+
'application/pdf',
126+
'text/latex',
127+
'application/json',
128+
'application/javascript'
129+
].includes(key)
130+
) {
129131
this.extra[key] = data[key]
130132
}
131133
}
@@ -149,27 +151,27 @@ export type Logs = {
149151
/**
150152
* Represents the result of a cell execution.
151153
*/
152-
export class Result {
154+
export class Execution {
153155
constructor(
154156
/**
155-
* List of result of the cell (interactively interpreted last line), display calls, e.g. matplotlib plots.
157+
* List of result of the cell (interactively interpreted last line), display calls (e.g. matplotlib plots).
156158
*/
157-
public data: Data[],
159+
public results: Result[],
158160
/**
159161
* Logs printed to stdout and stderr during execution.
160162
*/
161163
public logs: Logs,
162164
/**
163165
* An Error object if an error occurred, null otherwise.
164166
*/
165-
public error?: ExecutionError,
166-
) { }
167+
public error?: ExecutionError
168+
) {}
167169

168170
/**
169171
* Returns the text representation of the main result of the cell.
170172
*/
171173
get text(): string | undefined {
172-
for (const data of this.data) {
174+
for (const data of this.results) {
173175
if (data.isMainResult) {
174176
return data.text
175177
}
@@ -182,18 +184,18 @@ export class Result {
182184
* It's an internal class used by JupyterKernelWebSocket.
183185
*/
184186
class CellExecution {
185-
result: Result
187+
result: Execution
186188
onStdout?: (out: ProcessMessage) => Promise<void> | void
187189
onStderr?: (out: ProcessMessage) => Promise<void> | void
188-
onDisplayData?: (data: Data) => Promise<void> | void
190+
onDisplayData?: (data: Result) => Promise<void> | void
189191
inputAccepted: boolean = false
190192

191193
constructor(
192194
onStdout?: (out: ProcessMessage) => Promise<void> | void,
193195
onStderr?: (out: ProcessMessage) => Promise<void> | void,
194-
onDisplayData?: (data: Data) => Promise<void> | void
196+
onDisplayData?: (data: Result) => Promise<void> | void
195197
) {
196-
this.result = new Result([], { stdout: [], stderr: [] })
198+
this.result = new Execution([], { stdout: [], stderr: [] })
197199
this.onStdout = onStdout
198200
this.onStderr = onStderr
199201
this.onDisplayData = onDisplayData
@@ -230,7 +232,7 @@ export class JupyterKernelWebSocket {
230232
* Does not start WebSocket connection!
231233
* You need to call connect() method first.
232234
*/
233-
constructor(private readonly url: string) { }
235+
constructor(private readonly url: string) {}
234236

235237
// public
236238
/**
@@ -263,7 +265,7 @@ export class JupyterKernelWebSocket {
263265
result.error = new ExecutionError(
264266
message.content.ename,
265267
message.content.evalue,
266-
message.content.traceback,
268+
message.content.traceback
267269
)
268270
} else if (message.msg_type == 'stream') {
269271
if (message.content.name == 'stdout') {
@@ -290,12 +292,12 @@ export class JupyterKernelWebSocket {
290292
}
291293
}
292294
} else if (message.msg_type == 'display_data') {
293-
result.data.push(new Data(message.content.data, false))
295+
result.results.push(new Result(message.content.data, false))
294296
if (cell.onDisplayData) {
295-
cell.onDisplayData(new Data(message.content.data, false))
297+
cell.onDisplayData(new Result(message.content.data, false))
296298
}
297299
} else if (message.msg_type == 'execute_result') {
298-
result.data.push(new Data(message.content.data, true))
300+
result.results.push(new Result(message.content.data, true))
299301
} else if (message.msg_type == 'status') {
300302
if (message.content.execution_state == 'idle') {
301303
if (cell.inputAccepted) {
@@ -305,7 +307,7 @@ export class JupyterKernelWebSocket {
305307
result.error = new ExecutionError(
306308
message.content.ename,
307309
message.content.evalue,
308-
message.content.traceback,
310+
message.content.traceback
309311
)
310312
this.idAwaiter[parentMsgId](result)
311313
}
@@ -314,15 +316,15 @@ export class JupyterKernelWebSocket {
314316
result.error = new ExecutionError(
315317
message.content.ename,
316318
message.content.evalue,
317-
message.content.traceback,
319+
message.content.traceback
318320
)
319321
} else if (message.content.status == 'ok') {
320322
return
321323
}
322324
} else if (message.msg_type == 'execute_input') {
323325
cell.inputAccepted = true
324326
} else {
325-
console.log('[UNHANDLED MESSAGE TYPE]:', message.msg_type)
327+
console.warn('[UNHANDLED MESSAGE TYPE]:', message.msg_type)
326328
}
327329
}
328330
}
@@ -341,10 +343,10 @@ export class JupyterKernelWebSocket {
341343
code: string,
342344
onStdout?: (out: ProcessMessage) => Promise<void> | void,
343345
onStderr?: (out: ProcessMessage) => Promise<void> | void,
344-
onDisplayData?: (data: Data) => Promise<void> | void,
346+
onDisplayData?: (data: Result) => Promise<void> | void,
345347
timeout?: number
346348
) {
347-
return new Promise<Result>((resolve, reject) => {
349+
return new Promise<Execution>((resolve, reject) => {
348350
const msg_id = crypto.randomUUID()
349351
const data = this.sendExecuteRequest(msg_id, code)
350352

@@ -364,7 +366,7 @@ export class JupyterKernelWebSocket {
364366

365367
// expect response
366368
this.cells[msg_id] = new CellExecution(onStdout, onStderr, onDisplayData)
367-
this.idAwaiter[msg_id] = (responseData: Result) => {
369+
this.idAwaiter[msg_id] = (responseData: Execution) => {
368370
// stop timeout
369371
clearInterval(timeoutSet as number)
370372
// stop waiting for response
@@ -383,7 +385,6 @@ export class JupyterKernelWebSocket {
383385
*/
384386
private listen() {
385387
return new Promise((resolve, reject) => {
386-
387388
this.ws.onopen = (e: unknown) => {
388389
resolve(e)
389390
}

js/tests/displayData.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ test('display data', async () => {
1717
plt.show()
1818
`)
1919

20-
const image = result.data[0]
20+
const image = result.results[0]
2121
expect(image.png).toBeDefined()
2222
expect(image.text).toBeDefined()
2323

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
from .main import CodeInterpreter, JupyterExtension
2-
from .models import Result, Error, Data, KernelException
2+
from .models import Execution, Error, Result, KernelException

python/e2b_code_interpreter/main.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from e2b.constants import TIMEOUT
1111

1212
from e2b_code_interpreter.messaging import JupyterKernelWebSocket
13-
from e2b_code_interpreter.models import KernelException, Result
13+
from e2b_code_interpreter.models import KernelException, Execution
1414

1515

1616
logger = logging.getLogger(__name__)
@@ -68,7 +68,7 @@ def exec_cell(
6868
on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
6969
on_display_data: Optional[Callable[[Dict[str, Any]], Any]] = None,
7070
timeout: Optional[float] = TIMEOUT,
71-
) -> Result:
71+
) -> Execution:
7272
"""
7373
Execute code in a notebook cell.
7474
@@ -93,7 +93,9 @@ def exec_cell(
9393
logger.debug(f"Creating new websocket connection to kernel {kernel_id}")
9494
ws = self._connect_to_kernel_ws(kernel_id, timeout=timeout)
9595

96-
session_id = ws.send_execution_message(code, on_stdout, on_stderr, on_display_data)
96+
session_id = ws.send_execution_message(
97+
code, on_stdout, on_stderr, on_display_data
98+
)
9799
logger.debug(
98100
f"Sent execution message to kernel {kernel_id}, session_id: {session_id}"
99101
)

0 commit comments

Comments
 (0)