Skip to content

Commit f9886d8

Browse files
committed
Propagate the envs
1 parent c302e7a commit f9886d8

File tree

4 files changed

+88
-55
lines changed

4 files changed

+88
-55
lines changed

js/src/sandbox.ts

Lines changed: 79 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
11
import { Sandbox as BaseSandbox, InvalidArgumentError } from 'e2b'
22

3-
import { Result, Execution, OutputMessage, parseOutput, extractError, ExecutionError } from './messaging'
4-
import { formatExecutionTimeoutError, formatRequestTimeoutError, readLines } from "./utils";
3+
import {
4+
Result,
5+
Execution,
6+
OutputMessage,
7+
parseOutput,
8+
extractError,
9+
ExecutionError,
10+
} from './messaging'
11+
import {
12+
formatExecutionTimeoutError,
13+
formatRequestTimeoutError,
14+
readLines,
15+
} from './utils'
516
import { JUPYTER_PORT, DEFAULT_TIMEOUT_MS } from './consts'
617

718
/**
@@ -29,37 +40,37 @@ export interface RunCodeOpts {
2940
/**
3041
* Callback for handling stdout messages.
3142
*/
32-
onStdout?: (output: OutputMessage) => (Promise<any> | any),
43+
onStdout?: (output: OutputMessage) => Promise<any> | any
3344
/**
3445
* Callback for handling stderr messages.
3546
*/
36-
onStderr?: (output: OutputMessage) => (Promise<any> | any),
47+
onStderr?: (output: OutputMessage) => Promise<any> | any
3748
/**
3849
* Callback for handling the final execution result.
3950
*/
40-
onResult?: (data: Result) => (Promise<any> | any),
51+
onResult?: (data: Result) => Promise<any> | any
4152
/**
4253
* Callback for handling the `ExecutionError` object.
4354
*/
44-
onError?: (error: ExecutionError) => (Promise<any> | any),
55+
onError?: (error: ExecutionError) => Promise<any> | any
4556
/**
4657
* Custom environment variables for code execution.
47-
*
58+
*
4859
* @default {}
4960
*/
50-
envs?: Record<string, string>,
61+
envs?: Record<string, string>
5162
/**
5263
* Timeout for the code execution in **milliseconds**.
53-
*
64+
*
5465
* @default 60_000 // 60 seconds
5566
*/
56-
timeoutMs?: number,
67+
timeoutMs?: number
5768
/**
5869
* Timeout for the request in **milliseconds**.
59-
*
70+
*
6071
* @default 30_000 // 30 seconds
6172
*/
62-
requestTimeoutMs?: number,
73+
requestTimeoutMs?: number
6374
}
6475

6576
/**
@@ -68,22 +79,22 @@ export interface RunCodeOpts {
6879
export interface CreateCodeContextOpts {
6980
/**
7081
* Working directory for the context.
71-
*
82+
*
7283
* @default /home/user
7384
*/
74-
cwd?: string,
85+
cwd?: string
7586
/**
7687
* Language for the context.
77-
*
88+
*
7889
* @default python
7990
*/
80-
language?: string,
91+
language?: string
8192
/**
8293
* Timeout for the request in **milliseconds**.
83-
*
94+
*
8495
* @default 30_000 // 30 seconds
8596
*/
86-
requestTimeoutMs?: number,
97+
requestTimeoutMs?: number
8798
}
8899

89100
/**
@@ -108,65 +119,66 @@ export interface CreateCodeContextOpts {
108119
* ```
109120
*/
110121
export class Sandbox extends BaseSandbox {
111-
protected static override readonly defaultTemplate: string = 'code-interpreter-v1'
122+
protected static override readonly defaultTemplate: string =
123+
'code-interpreter-v1'
112124

113125
/**
114126
* Run the code as Python.
115-
*
127+
*
116128
* Specify the `language` or `context` option to run the code as a different language or in a different `Context`.
117-
*
129+
*
118130
* You can reference previously defined variables, imports, and functions in the code.
119131
*
120132
* @param code code to execute.
121133
* @param opts options for executing the code.
122-
*
134+
*
123135
* @returns `Execution` result object.
124136
*/
125137
async runCode(
126138
code: string,
127139
opts?: RunCodeOpts & {
128140
/**
129141
* Language to use for code execution.
130-
*
142+
*
131143
* If not defined, the default Python context is used.
132144
*/
133-
language?: 'python',
134-
},
145+
language?: 'python'
146+
}
135147
): Promise<Execution>
136148
/**
137149
* Run the code for the specified language.
138-
*
150+
*
139151
* Specify the `language` or `context` option to run the code as a different language or in a different `Context`.
140152
* If no language is specified, Python is used.
141-
*
153+
*
142154
* You can reference previously defined variables, imports, and functions in the code.
143155
*
144156
* @param code code to execute.
145157
* @param opts options for executing the code.
146-
*
158+
*
147159
* @returns `Execution` result object.
148160
*/
149161
async runCode(
150162
code: string,
151163
opts?: RunCodeOpts & {
152164
/**
153165
* Language to use for code execution.
154-
*
166+
*
155167
* If not defined, the default Python context is used.
156168
*/
157-
language?: string,
158-
},
169+
language?: string
170+
}
159171
): Promise<Execution>
160172
/**
161173
* Runs the code in the specified context, if not specified, the default context is used.
162-
*
174+
*
163175
* Specify the `language` or `context` option to run the code as a different language or in a different `Context`.
164-
*
176+
*
165177
* You can reference previously defined variables, imports, and functions in the code.
166178
*
167179
* @param code code to execute.
168180
* @param opts options for executing the code
169-
*
181+
*
170182
* @returns `Execution` result object
171183
*/
172184
async runCode(
@@ -175,34 +187,39 @@ export class Sandbox extends BaseSandbox {
175187
/**
176188
* Context to run the code in.
177189
*/
178-
context?: Context,
179-
},
190+
context?: Context
191+
}
180192
): Promise<Execution>
181193
async runCode(
182194
code: string,
183195
opts?: RunCodeOpts & {
184-
language?: string,
185-
context?: Context,
186-
},
196+
language?: string
197+
context?: Context
198+
}
187199
): Promise<Execution> {
188200
if (opts?.context && opts?.language) {
189-
throw new InvalidArgumentError("You can provide context or language, but not both at the same time.")
201+
throw new InvalidArgumentError(
202+
'You can provide context or language, but not both at the same time.'
203+
)
190204
}
191205

192206
const controller = new AbortController()
193207

194-
const requestTimeout = opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
208+
const requestTimeout =
209+
opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
195210

196-
const reqTimer = requestTimeout ? setTimeout(() => {
197-
controller.abort()
198-
}, requestTimeout)
211+
const reqTimer = requestTimeout
212+
? setTimeout(() => {
213+
controller.abort()
214+
}, requestTimeout)
199215
: undefined
200216

201217
try {
202218
const res = await fetch(`${this.jupyterUrl}/execute`, {
203219
method: 'POST',
204220
headers: {
205221
'Content-Type': 'application/json',
222+
...this.connectionConfig.headers,
206223
},
207224
body: JSON.stringify({
208225
code,
@@ -220,7 +237,9 @@ export class Sandbox extends BaseSandbox {
220237
}
221238

222239
if (!res.body) {
223-
throw new Error(`Not response body: ${res.statusText} ${await res?.text()}`)
240+
throw new Error(
241+
`Not response body: ${res.statusText} ${await res?.text()}`
242+
)
224243
}
225244

226245
clearTimeout(reqTimer)
@@ -229,16 +248,22 @@ export class Sandbox extends BaseSandbox {
229248

230249
const bodyTimer = bodyTimeout
231250
? setTimeout(() => {
232-
controller.abort()
233-
}, bodyTimeout)
251+
controller.abort()
252+
}, bodyTimeout)
234253
: undefined
235254

236255
const execution = new Execution()
237256

238-
239257
try {
240258
for await (const chunk of readLines(res.body)) {
241-
await parseOutput(execution, chunk, opts?.onStdout, opts?.onStderr, opts?.onResult, opts?.onError)
259+
await parseOutput(
260+
execution,
261+
chunk,
262+
opts?.onStdout,
263+
opts?.onStderr,
264+
opts?.onResult,
265+
opts?.onError
266+
)
242267
}
243268
} catch (error) {
244269
throw formatExecutionTimeoutError(error)
@@ -256,7 +281,7 @@ export class Sandbox extends BaseSandbox {
256281
* Creates a new context to run code in.
257282
*
258283
* @param opts options for creating the context.
259-
*
284+
*
260285
* @returns context object.
261286
*/
262287
async createCodeContext(opts?: CreateCodeContextOpts): Promise<Context> {
@@ -265,6 +290,7 @@ export class Sandbox extends BaseSandbox {
265290
method: 'POST',
266291
headers: {
267292
'Content-Type': 'application/json',
293+
...this.connectionConfig.headers,
268294
},
269295
body: JSON.stringify({
270296
language: opts?.language,
@@ -286,6 +312,8 @@ export class Sandbox extends BaseSandbox {
286312
}
287313

288314
protected get jupyterUrl(): string {
289-
return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(JUPYTER_PORT)}`
315+
return `${this.connectionConfig.debug ? 'http' : 'https'}://${this.getHost(
316+
JUPYTER_PORT
317+
)}`
290318
}
291319
}

python/e2b_code_interpreter/code_interpreter_async.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@ async def run_code(
201201
"language": language,
202202
"env_vars": envs,
203203
},
204+
headers={"X-Access-Token": self._envd_access_token},
204205
timeout=(request_timeout, timeout, request_timeout, request_timeout),
205206
) as response:
206207

@@ -252,6 +253,7 @@ async def create_code_context(
252253
try:
253254
response = await self._client.post(
254255
f"{self._jupyter_url}/contexts",
256+
headers={"X-Access-Token": self._envd_access_token},
255257
json=data,
256258
timeout=request_timeout or self.connection_config.request_timeout,
257259
)

python/e2b_code_interpreter/code_interpreter_sync.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ def run_code(
198198
"language": language,
199199
"env_vars": envs,
200200
},
201+
headers={"X-Access-Token": self._envd_access_token},
201202
timeout=(request_timeout, timeout, request_timeout, request_timeout),
202203
) as response:
203204
err = extract_exception(response)
@@ -249,6 +250,7 @@ def create_code_context(
249250
response = self._client.post(
250251
f"{self._jupyter_url}/contexts",
251252
json=data,
253+
headers={"X-Access-Token": self._envd_access_token},
252254
timeout=request_timeout or self.connection_config.request_timeout,
253255
)
254256

template/server/envs.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
import os
2+
from typing import Optional
23

34
import httpx
45

56
LOCAL = os.getenv("E2B_LOCAL", False)
67
ENVD_PORT = 49983
78

89

9-
async def get_envs() -> dict:
10+
async def get_envs(access_token: Optional[str]) -> dict:
1011
if LOCAL:
11-
return {
12-
"E2B_TEST_VARIABLE": "true"
13-
}
12+
return {"E2B_TEST_VARIABLE": "true"}
1413
async with httpx.AsyncClient() as client:
14+
if access_token:
15+
client.headers["X-Access-Token"] = f"{access_token}"
1516
response = await client.get(f"http://localhost:{ENVD_PORT}/envs")
1617
return response.json()

0 commit comments

Comments
 (0)