Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Load API key from env variable (#172)

Jakub Novák8aaca0d1db02
diff --git a/.changeset/moody-peas-provide.md b/.changeset/moody-peas-provide.md
new file mode 100644
index 000000000..a1660eb55
--- /dev/null
+++ b/.changeset/moody-peas-provide.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': patch
+'@e2b/sdk': patch
+---
+
+Load api key from env variable
diff --git a/packages/js-sdk/src/session/sessionConnection.ts b/packages/js-sdk/src/session/sessionConnection.ts
index 1a6c9f975..d7a7dee77 100644
--- a/packages/js-sdk/src/session/sessionConnection.ts
+++ b/packages/js-sdk/src/session/sessionConnection.ts
@@ -40,7 +40,7 @@ interface Logger {
export interface SessionConnectionOpts {
id: string
- apiKey: string
+ apiKey?: string
cwd?: string
logger?: Logger
__debug_hostname?: string
@@ -63,16 +63,19 @@ export class SessionConnection {
protected session?: components['schemas']['Session']
protected isOpen = false
+ private readonly apiKey: string
private readonly rpc = new RpcWebSocketClient()
private subscribers: Subscriber[] = []
// let's keep opts readonly, but public – for convenience, mainly when debugging
constructor(readonly opts: SessionConnectionOpts) {
- if (!opts.apiKey) {
+ const apiKey = opts.apiKey || process.env.E2B_API_KEY
+ if (!apiKey) {
throw new AuthenticationError(
'API key is required, please visit https://e2b.dev/docs to get your API key',
)
}
+ this.apiKey = apiKey
this.logger = opts.logger ?? {
// by default, we log to the console
// we don't log debug messages by default
@@ -162,7 +165,7 @@ export class SessionConnection {
if (!this.opts.__debug_hostname) {
try {
const res = await createSession({
- api_key: this.opts.apiKey,
+ api_key: this.apiKey,
codeSnippetID: this.opts.id,
editEnabled: false,
})
@@ -390,7 +393,7 @@ export class SessionConnection {
try {
this.logger.debug?.(`Refreshed session "${sessionID}"`)
await refreshSession({
- api_key: this.opts.apiKey,
+ api_key: this.apiKey,
sessionID,
})
} catch (e) {
diff --git a/packages/js-sdk/test/_smoke.test.mjs b/packages/js-sdk/test/_smoke.test.mjs
index 55d0f6ad7..a419948be 100644
--- a/packages/js-sdk/test/_smoke.test.mjs
+++ b/packages/js-sdk/test/_smoke.test.mjs
@@ -1,15 +1,13 @@
-import { Session } from '../src'
-import { expect, test } from 'vitest'
-
-const E2B_API_KEY = process.env.E2B_API_KEY
+import {Session} from '../src'
+import {expect, test} from 'vitest'
// Smoke test = quick, high-level, basic functionality test
test('Smoke test', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
- await session.filesystem.makeDir('/test/new')
+ const session = await Session.create({id: 'Nodejs'})
+ await session.filesystem.makeDir('/test/new')
- const ls = await session.filesystem.list('/test')
- expect(ls.map(x => x.name)).toEqual(['new'])
+ const ls = await session.filesystem.list('/test')
+ expect(ls.map(x => x.name)).toEqual(['new'])
- await session.close()
+ await session.close()
})
diff --git a/packages/js-sdk/test/filesystem.test.mjs b/packages/js-sdk/test/filesystem.test.mjs
index ca5a8e50b..223d7a741 100644
--- a/packages/js-sdk/test/filesystem.test.mjs
+++ b/packages/js-sdk/test/filesystem.test.mjs
@@ -1,12 +1,10 @@
-import { Session } from '../src'
-import { expect, test } from 'vitest'
+import {Session} from '../src'
+import {expect, test} from 'vitest'
import * as fs from 'node:fs'
import * as path from 'node:path'
-const E2B_API_KEY = process.env.E2B_API_KEY
-
test('list files', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
await session.filesystem.makeDir('/test/new')
const ls = await session.filesystem.list('/test')
@@ -15,8 +13,9 @@ test('list files', async () => {
await session.close()
})
+
test('create file', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
await session.filesystem.makeDir('/test')
await session.filesystem.write('/test/test.txt', 'Hello World!')
@@ -27,7 +26,7 @@ test('create file', async () => {
})
test('read and write', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
// String
await session.filesystem.write('/tmp/test.txt', 'Hello World!')
@@ -44,7 +43,7 @@ test('read and write', async () => {
})
test('list delete files', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
await session.filesystem.makeDir('/test/new')
let ls = await session.filesystem.list('/test')
@@ -59,7 +58,7 @@ test('list delete files', async () => {
})
test('watch dir', async () => {
- const session = new Session({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = new Session({id: 'Nodejs'})
await session.open()
await session.filesystem.write('/tmp/test.txt', 'Hello')
diff --git a/packages/js-sdk/test/logging.test.mjs b/packages/js-sdk/test/logging.test.mjs
index 6e8b28f1e..d0afa6209 100644
--- a/packages/js-sdk/test/logging.test.mjs
+++ b/packages/js-sdk/test/logging.test.mjs
@@ -1,5 +1,5 @@
-import { Session } from '../src'
-import { expect, test, vi } from 'vitest'
+import {Session} from '../src'
+import {expect, test, vi} from 'vitest'
test('no logs in console during very basic scenario', async () => {
const consoleSpy = {
@@ -9,7 +9,7 @@ test('no logs in console during very basic scenario', async () => {
error: vi.spyOn(console, 'error'),
}
- const session = await Session.create({ id: 'Nodejs', apiKey: process.env.E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
await session.filesystem.write('test.txt', 'Hello World')
await session.close()
@@ -18,6 +18,7 @@ test('no logs in console during very basic scenario', async () => {
expect(consoleSpy.error).toHaveBeenCalledTimes(0)
})
+
// TODO: Re-enable https://e2b-team.slack.com/archives/C05AGT4UFMJ/p1694697558738799?thread_ts=1694697479.308769&cid=C05AGT4UFMJ
test.skip('warn logs in console during convoluted scenario', async () => {
const consoleSpy = {
@@ -27,7 +28,7 @@ test.skip('warn logs in console during convoluted scenario', async () => {
error: vi.spyOn(console, 'error'),
}
- const session = await Session.create({ id: 'Nodejs', apiKey: process.env.E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
await session.close() // Note that we are intentionally closing and then trying to write
const warnsAmount = consoleSpy.warn.mock.calls.length
@@ -53,7 +54,6 @@ test('verbose & info logs in console when opted-in', async () => {
const session = await Session.create({
id: 'Nodejs',
- apiKey: process.env.E2B_API_KEY,
logger,
})
await session.filesystem.write('test.txt', 'Hello World')
diff --git a/packages/js-sdk/test/performance.mjs b/packages/js-sdk/test/performance.mjs
index 17d75fdfe..3ed23f7fd 100644
--- a/packages/js-sdk/test/performance.mjs
+++ b/packages/js-sdk/test/performance.mjs
@@ -1,15 +1,15 @@
-import { writeFileSync } from 'fs'
+import {writeFileSync} from 'fs'
-import { Session } from '../dist/cjs/index.js'
+import {Session} from '../dist/cjs/index.js'
-const apiKey = process.env.API_KEY
const reportSummaryFile = process.env.SUMMARY_FILE || './test.md'
const codeSnippetIDs = ['5udkAFHBVrGz']
const samplePerID = 15
const upperBoundary = 1000 // 1s
-async function spinSession(id, isEditSession) {
+
+async function spinSession(id) {
console.log('Creating session...')
let session
try {
@@ -17,8 +17,6 @@ async function spinSession(id, isEditSession) {
session = new Session({
id,
// debug: true,
- editEnabled: isEditSession,
- ...(isEditSession && { apiKey }),
})
session.open()
@@ -26,7 +24,7 @@ async function spinSession(id, isEditSession) {
return endTime - startTime
} catch (e) {
console.error(
- `Measuring ${id}${isEditSession ? ' (persistent session)' : ''} failed`,
+ `Measuring ${id} failed`,
e,
)
} finally {
@@ -68,18 +66,13 @@ function writeMeasurements(data) {
writeFileSync(reportSummaryFile, report)
}
-async function sample(id, size, isEditSession) {
- if (isEditSession && !apiKey) {
- console.log('No API key, skipping measuring persistent sessions')
- return {}
- }
-
+async function sample(id, size) {
let totalTime = 0
- const entryName = `${isEditSession ? 'Persistent' : 'Public'} session (${id})`
+ const entryName = `Public session (${id})`
try {
for (let i = 0; i < size; i++) {
- const timeToSession = await spinSession(id, isEditSession)
+ const timeToSession = await spinSession(id)
totalTime += timeToSession
}
@@ -108,7 +101,7 @@ async function main() {
for (const id of codeSnippetIDs) {
const entry = await sample(id, samplePerID)
- entries = { ...entries, ...entry }
+ entries = {...entries, ...entry}
}
// for (const id of codeSnippetIDs) {
diff --git a/packages/js-sdk/test/process.test.mjs b/packages/js-sdk/test/process.test.mjs
index 3f7fb666e..a2233fcad 100644
--- a/packages/js-sdk/test/process.test.mjs
+++ b/packages/js-sdk/test/process.test.mjs
@@ -1,10 +1,9 @@
-import { Session } from '../src'
-import { expect, test, vi } from 'vitest'
+import {Session} from '../src'
+import {expect, test, vi} from 'vitest'
-const E2B_API_KEY = process.env.E2B_API_KEY
test('process on stdout/stderr', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
const stdout = []
const stderr = []
@@ -35,9 +34,10 @@ test('process expected stderr', async () => {
})
test('process on exit', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
- const onExit = vi.fn(() => {})
+ const onExit = vi.fn(() => {
+ })
const process = await session.process.start({
cmd: 'pwd',
@@ -51,7 +51,7 @@ test('process on exit', async () => {
})
test('process send stdin', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
const process = await session.process.start({
cmd: 'read -r line; echo "$line"',
diff --git a/packages/js-sdk/test/session.test.mjs b/packages/js-sdk/test/session.test.mjs
index a87ca67e1..18c45bfe1 100644
--- a/packages/js-sdk/test/session.test.mjs
+++ b/packages/js-sdk/test/session.test.mjs
@@ -1,16 +1,16 @@
import { Session } from '../src'
import { test, expect } from 'vitest'
-const E2B_API_KEY = process.env.E2B_API_KEY
test('create session', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
await session.close()
})
+
test('create multiple sessions', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
- const session2 = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
+ const session2 = await Session.create({id: 'Nodejs'})
await session.close()
await session2.close()
}, 10000)
@@ -20,7 +20,6 @@ test(
async () => {
const session = await Session.create({
id: 'Nodejs',
- apiKey: E2B_API_KEY,
cwd: '/code/app',
})
diff --git a/packages/js-sdk/test/timeout.test.mjs b/packages/js-sdk/test/timeout.test.mjs
index 41be4ab0d..dab4833b4 100644
--- a/packages/js-sdk/test/timeout.test.mjs
+++ b/packages/js-sdk/test/timeout.test.mjs
@@ -1,14 +1,13 @@
-import { expect, test } from 'vitest'
+import {expect, test} from 'vitest'
-import { Session } from '../src'
-import { TimeoutError } from '../src/error.ts'
+import {Session} from '../src'
+import {TimeoutError} from '../src/error.ts'
-const E2B_API_KEY = process.env.E2B_API_KEY
// TODO: Make it work on CI and re-enable!
test.skip('timeout session', async () => {
await expect(
- Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY, timeout: 10 }),
+ Session.create({id: 'Nodejs', timeout: 10}),
).rejects.toThrow()
})
@@ -16,7 +15,6 @@ test.skip('timeout session', async () => {
test.skip('dont timeout session', async () => {
const session = await Session.create({
id: 'Nodejs',
- apiKey: E2B_API_KEY,
timeout: 10000,
})
await session.close()
@@ -24,35 +22,35 @@ test.skip('dont timeout session', async () => {
// TODO: Make it work on CI and re-enable!
test.skip('timeout filesystem', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
await expect(
- session.filesystem.write('/home/test.txt', 'Hello World', { timeout: 10 }),
+ session.filesystem.write('/home/test.txt', 'Hello World', {timeout: 10}),
).rejects.toThrow(TimeoutError)
await expect(
- session.filesystem.read('/home/test.txt', { timeout: 10 }),
+ session.filesystem.read('/home/test.txt', {timeout: 10}),
).rejects.toThrow(TimeoutError)
- await expect(session.filesystem.list('/home', { timeout: 10 })).rejects.toThrow(
+ await expect(session.filesystem.list('/home', {timeout: 10})).rejects.toThrow(
TimeoutError,
)
await expect(
- session.filesystem.makeDir('/home/test/', { timeout: 10 }),
+ session.filesystem.makeDir('/home/test/', {timeout: 10}),
).rejects.toThrow(TimeoutError)
await session.filesystem.write('/home/test.txt', 'Hello World')
await expect(
- session.filesystem.remove('/home/test.txt', { timeout: 10 }),
+ session.filesystem.remove('/home/test.txt', {timeout: 10}),
).rejects.toThrow(TimeoutError)
})
// TODO: Make it work on CI and re-enable!
test.skip('timeout process', async () => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const session = await Session.create({id: 'Nodejs'})
await expect(
- session.process.start({ cmd: "node -e 'setTimeout(() => {}, 10000)'", timeout: 10 }),
+ session.process.start({cmd: "node -e 'setTimeout(() => {}, 10000)'", timeout: 10}),
).rejects.toThrow(TimeoutError)
const process = await session.process.start({
cmd: "while true; do echo 'Hello World'; sleep 1; done",
})
- await expect(process.sendStdin('Hello World', { timeout: 10 })).rejects.toThrow(
+ await expect(process.sendStdin('Hello World', {timeout: 10})).rejects.toThrow(
TimeoutError,
)
})
@@ -62,8 +60,7 @@ test.skip(
'timeout longer than cmd should not leak',
() =>
new Promise(async resolve => {
- const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
- const start = Date.now()
+ const session = await Session.create({id: 'Nodejs'})
const proc = await session.process.start({
cmd: "node -e 'setTimeout(() => {}, 1000)'", // should take around 1 second
onExit: () => {
@@ -74,5 +71,5 @@ test.skip(
})
await proc.finished
}),
- { timeout: 12_000 },
+ {timeout: 12_000},
)
diff --git a/packages/python-sdk/e2b/session/__init__.py b/packages/python-sdk/e2b/session/__init__.py
index e47fedcdd..1ffb154c5 100644
--- a/packages/python-sdk/e2b/session/__init__.py
+++ b/packages/python-sdk/e2b/session/__init__.py
@@ -12,4 +12,4 @@ from .filesystem_watcher import FilesystemEvent, FilesystemOperation, Filesystem
from .main import Session
from .process import Process, ProcessManager, ProcessMessage, ProcessOutput
from .terminal import Terminal, TerminalManager, TerminalOutput
-from .run_code import run_code
\ No newline at end of file
+from .run_code import run_code
diff --git a/packages/python-sdk/e2b/session/code_snippet.py b/packages/python-sdk/e2b/session/code_snippet.py
index 53ace931d..8bd8f85f9 100644
--- a/packages/python-sdk/e2b/session/code_snippet.py
+++ b/packages/python-sdk/e2b/session/code_snippet.py
@@ -1,8 +1,9 @@
from typing import Any, Callable, ClassVar, List, Optional
+from pydantic import BaseModel, ConfigDict
+
from e2b.session.exception import MultipleExceptions, RpcException, SessionException
from e2b.session.session_connection import SessionConnection
-from pydantic import BaseModel
class OpenPort(BaseModel):
@@ -15,14 +16,13 @@ ScanOpenedPortsHandler = Callable[[List[OpenPort]], Any]
class CodeSnippetManager(BaseModel):
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
service_name: ClassVar[str] = "codeSnippet"
session: SessionConnection
on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None
- class Config:
- arbitrary_types_allowed = True
-
async def _subscribe(self):
try:
await self.session._handle_subscriptions(
diff --git a/packages/python-sdk/e2b/session/exception.py b/packages/python-sdk/e2b/session/exception.py
index fd916f39f..6af521e96 100644
--- a/packages/python-sdk/e2b/session/exception.py
+++ b/packages/python-sdk/e2b/session/exception.py
@@ -7,11 +7,11 @@ class SessionException(Exception):
class RpcException(SessionException):
def __init__(
- self,
- message: str,
- code: int,
- id: str,
- data: Optional[Dict] = None,
+ self,
+ message: str,
+ code: int,
+ id: str,
+ data: Optional[Dict] = None,
):
super().__init__(message)
self.data = data
@@ -40,3 +40,7 @@ class TerminalException(SessionException):
class AuthenticationException(SessionException):
pass
+
+
+class UnsupportedRuntimeException(SessionException):
+ pass
diff --git a/packages/python-sdk/e2b/session/main.py b/packages/python-sdk/e2b/session/main.py
index 66f1d530e..6b8948a13 100644
--- a/packages/python-sdk/e2b/session/main.py
+++ b/packages/python-sdk/e2b/session/main.py
@@ -2,6 +2,7 @@ import logging
from typing import Any, Callable, List, Literal, Optional, Union
from async_timeout import timeout as async_timeout
+
from e2b.constants import TIMEOUT
from e2b.session.code_snippet import CodeSnippetManager, OpenPort
from e2b.session.filesystem import FilesystemManager
@@ -59,14 +60,14 @@ class Session(SessionConnection):
return self._filesystem
def __init__(
- self,
- id: Union[Environment, str],
- api_key: str,
- cwd: Optional[str] = None,
- on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
- _debug_hostname: Optional[str] = None,
- _debug_port: Optional[int] = None,
- _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ self,
+ id: Union[Environment, str],
+ api_key: Optional[str],
+ cwd: Optional[str] = None,
+ on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
+ _debug_hostname: Optional[str] = None,
+ _debug_port: Optional[int] = None,
+ _debug_dev_env: Optional[Literal["remote", "local"]] = None,
):
"""
Creates a new cloud environment session.
@@ -83,9 +84,8 @@ class Session(SessionConnection):
- `Perl`
- `DotNET`
- :param api_key: The API key to use
+ :param api_key: The API key to use, if not provided, the `E2B_API_KEY` environment variable is used
:param cwd: The current working directory to use
- :param edit_enabled: Whether the session state will be saved after exit
:param on_scan_ports: A callback to handle opened ports
"""
@@ -136,15 +136,15 @@ class Session(SessionConnection):
@classmethod
async def create(
- cls,
- id: Union[Environment, str],
- api_key: Optional[str] = None,
- cwd: Optional[str] = None,
- on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
- timeout: Optional[float] = TIMEOUT,
- _debug_hostname: Optional[str] = None,
- _debug_port: Optional[int] = None,
- _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ cls,
+ id: Union[Environment, str],
+ api_key: Optional[str] = None,
+ cwd: Optional[str] = None,
+ on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,
+ timeout: Optional[float] = TIMEOUT,
+ _debug_hostname: Optional[str] = None,
+ _debug_port: Optional[int] = None,
+ _debug_dev_env: Optional[Literal["remote", "local"]] = None,
):
"""
Creates a new cloud environment session.
diff --git a/packages/python-sdk/e2b/session/run_code.py b/packages/python-sdk/e2b/session/run_code.py
index b08d8126a..a2e675507 100644
--- a/packages/python-sdk/e2b/session/run_code.py
+++ b/packages/python-sdk/e2b/session/run_code.py
@@ -1,54 +1,60 @@
-from typing import Literal, Union, Optional
from os import getenv
+from typing import Literal, Union, Optional
from . import Session
+from .exception import UnsupportedRuntimeException
CodeRuntime = Literal[
- "Node16",
- "Python3",
+ "Node16",
+ "Python3",
]
+
async def run_code(
- runtime: Union[CodeRuntime, str],
- code: str,
- api_key: Optional[str] = getenv("E2B_API_KEY"),
+ runtime: Union[CodeRuntime, str],
+ code: str,
+ api_key: Optional[str] = None,
):
- """
- Runs code in a sandboxed cloud playground and return the stdout and stderr
- `run_ode` wraps the `Session` class and provides a simple interface for running code in a sandboxed environment
- without any need to manage lifecycle of the session.
- `run_code` automatically loads the E2B API key from the `E2B_API_KEY` environment variable.
-
- :param runtime: The runtime to run the code in. One of "Node16" or "Python3".
- :param code: The code to run
-
- :return: A string touple of stdout and stderr
- """
- binary = ""
- filepath = ""
- env_id = ""
- if runtime == "Node16":
- env_id = "Nodejs"
- binary = "node"
- filepath = "/index.js"
- elif runtime == "Python3":
- env_id = "Python3"
- binary = "python3"
- filepath = "/index.py"
- else:
- raise Exception(f'Invalid runtime "{runtime}". Please contact us ([email protected]) if you need support for this runtime')
-
- session = await Session.create(
- id=env_id,
- api_key=api_key,
- )
- await session.filesystem.write(filepath, code)
-
- proc = await session.process.start(
- cmd=f'{binary} {filepath}',
- )
- await proc
-
- await session.close()
-
- return proc.output.stdout, proc.output.stderr
+ """
+ Runs code in a sandboxed cloud playground and return the stdout and stderr
+ `run_ode` wraps the `Session` class and provides a simple interface for running code in a sandboxed environment
+ without any need to manage lifecycle of the session.
+ `run_code` automatically loads the E2B API key from the `E2B_API_KEY` environment variable.
+
+ :param runtime: The runtime to run the code in. One of "Node16" or "Python3".
+ :param code: The code to run
+ :param api_key: The E2B API key to use. If not provided, the `E2B_API_KEY` environment variable is used.
+
+ :return: A string touple of stdout and stderr
+ """
+
+ if api_key is None:
+ api_key = getenv("E2B_API_KEY")
+
+ if runtime == "Node16":
+ env_id = "Nodejs"
+ binary = "node"
+ filepath = "/index.js"
+ elif runtime == "Python3":
+ env_id = "Python3"
+ binary = "python3"
+ filepath = "/index.py"
+ else:
+ raise UnsupportedRuntimeException(
+ f'Invalid runtime "{runtime}". Please contact us ([email protected]) if you need support for this runtime'
+ )
+
+ session = await Session.create(
+ id=env_id,
+ api_key=api_key,
+ )
+ await session.filesystem.write(filepath, code)
+
+ proc = await session.process.start(
+ cmd=f"{binary} {filepath}",
+ )
+ await proc
+
+ await session.close()
+
+ return proc.output.stdout, proc.output.stderr
diff --git a/packages/python-sdk/e2b/session/session_connection.py b/packages/python-sdk/e2b/session/session_connection.py
index 137ecb0e4..519dd215a 100644
--- a/packages/python-sdk/e2b/session/session_connection.py
+++ b/packages/python-sdk/e2b/session/session_connection.py
@@ -2,9 +2,12 @@ import asyncio
import logging
import traceback
from concurrent.futures import ThreadPoolExecutor
+from os import getenv
from typing import Any, Awaitable, Callable, List, Literal, Optional, Union
import async_timeout
+from pydantic import BaseModel
+
from e2b.api.client import NewSession
from e2b.api.client import Session as SessionInfo
from e2b.api.client.rest import ApiException
@@ -26,7 +29,6 @@ from e2b.utils.future import DeferredFuture, run_async_func_in_new_loop
from e2b.utils.noop import noop
from e2b.utils.str import camel_case_to_snake_case
from e2b.utils.threads import shutdown_executor
-from pydantic import BaseModel
logger = logging.getLogger(__name__)
@@ -62,15 +64,17 @@ class SessionConnection:
return self._finished.__await__()
def __init__(
- self,
- id: str,
- api_key: str,
- cwd: Optional[str] = None,
- _debug_hostname: Optional[str] = None,
- _debug_port: Optional[int] = None,
- _debug_dev_env: Optional[Literal["remote", "local"]] = None,
- on_close: Optional[Callable[[], Any]] = None,
+ self,
+ id: str,
+ api_key: Optional[str],
+ cwd: Optional[str] = None,
+ _debug_hostname: Optional[str] = None,
+ _debug_port: Optional[int] = None,
+ _debug_dev_env: Optional[Literal["remote", "local"]] = None,
+ on_close: Optional[Callable[[], Any]] = None,
):
+ api_key = api_key or getenv("E2B_API_KEY")
+
if api_key is None:
raise AuthenticationException(
"API key is required, please visit https://e2b.dev/docs to get your API key",
@@ -220,11 +224,11 @@ class SessionConnection:
raise e
async def _call(
- self,
- service: str,
- method: str,
- params: List[Any] = None,
- timeout: Optional[float] = TIMEOUT,
+ self,
+ service: str,
+ method: str,
+ params: List[Any] = None,
+ timeout: Optional[float] = TIMEOUT,
):
if not params:
params = []
@@ -236,8 +240,8 @@ class SessionConnection:
return await self._rpc.send_message(f"{service}_{method}", params)
async def _handle_subscriptions(
- self,
- *subs: Optional[Awaitable[Callable[[], Awaitable[None]]]],
+ self,
+ *subs: Optional[Awaitable[Callable[[], Awaitable[None]]]],
):
results: List[
Union[Callable[[], Awaitable[None]], None, Exception]
@@ -285,12 +289,12 @@ class SessionConnection:
logger.debug(f"Unsubscribed (sub_id: {sub_id})")
async def _subscribe(
- self,
- service: str,
- handler: Callable[[Any], Any],
- method: str,
- *params,
- timeout: Optional[float] = TIMEOUT,
+ self,
+ service: str,
+ handler: Callable[[Any], Any],
+ method: str,
+ *params,
+ timeout: Optional[float] = TIMEOUT,
):
sub_id = await self._call(
service, "subscribe", [method, *params], timeout=timeout
diff --git a/packages/python-sdk/e2b/session/session_rpc.py b/packages/python-sdk/e2b/session/session_rpc.py
index 87852ed95..ef13cc7f8 100644
--- a/packages/python-sdk/e2b/session/session_rpc.py
+++ b/packages/python-sdk/e2b/session/session_rpc.py
@@ -8,17 +8,18 @@ from queue import Queue
from threading import Event
from typing import Any, Callable, Dict, Iterator, List, Union
-from e2b.session.exception import RpcException
-from e2b.session.websocket_client import WebSocket
-from e2b.utils.future import DeferredFuture, run_async_func_in_new_loop
-from e2b.utils.threads import shutdown_executor
from janus import Queue as JanusQueue
from jsonrpcclient import Error, Ok, request_json
from jsonrpcclient.id_generators import decimal as decimal_id_generator
from jsonrpcclient.responses import Response
-from pydantic import BaseModel, PrivateAttr
+from pydantic import BaseModel, PrivateAttr, ConfigDict
from websockets.typing import Data
+from e2b.session.exception import RpcException
+from e2b.session.websocket_client import WebSocket
+from e2b.utils.future import DeferredFuture, run_async_func_in_new_loop
+from e2b.utils.threads import shutdown_executor
+
logger = logging.getLogger(__name__)
@@ -51,6 +52,8 @@ def to_response_or_notification(response: Dict[str, Any]) -> Message:
class SessionRpc(BaseModel):
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
url: str
on_message: Callable[[Notification], None]
@@ -60,9 +63,6 @@ class SessionRpc(BaseModel):
_queue_out: JanusQueue = PrivateAttr(default_factory=JanusQueue)
_process_cleanup: List[Callable[[], Any]] = PrivateAttr(default_factory=list)
- class Config:
- arbitrary_types_allowed = True
-
async def process_messages(self):
while True:
data = await self._queue_out.async_q.get()
@@ -123,15 +123,15 @@ class SessionRpc(BaseModel):
)
if isinstance(message, Ok):
if (
- message.id in self._waiting_for_replies
- and self._waiting_for_replies[message.id]
+ message.id in self._waiting_for_replies
+ and self._waiting_for_replies[message.id]
):
self._waiting_for_replies[message.id](message.result)
return
elif isinstance(message, Error):
if (
- message.id in self._waiting_for_replies
- and self._waiting_for_replies[message.id]
+ message.id in self._waiting_for_replies
+ and self._waiting_for_replies[message.id]
):
self._waiting_for_replies[message.id].reject(
RpcException(
diff --git a/packages/python-sdk/tests/test_filesystem.py b/packages/python-sdk/tests/test_filesystem.py
index b952a303d..46a8328db 100644
--- a/packages/python-sdk/tests/test_filesystem.py
+++ b/packages/python-sdk/tests/test_filesystem.py
@@ -1,13 +1,12 @@
import filecmp
from asyncio import sleep
-from os import getenv, path
+from os import path
from e2b import Session
-E2B_API_KEY = getenv("E2B_API_KEY")
async def test_list_files():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
await session.filesystem.make_dir("/test/new")
ls = await session.filesystem.list("/test")
@@ -17,7 +16,7 @@ async def test_list_files():
async def test_create_file():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
await session.filesystem.make_dir("/test")
await session.filesystem.write("/test/test.txt", "Hello World!")
@@ -28,7 +27,7 @@ async def test_create_file():
async def test_read_and_write():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
await session.filesystem.write("/tmp/test.txt", "Hello World!")
@@ -39,7 +38,7 @@ async def test_read_and_write():
async def test_list_delete_files():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
await session.filesystem.make_dir("/test/new")
ls = await session.filesystem.list("/test")
@@ -54,7 +53,7 @@ async def test_list_delete_files():
async def test_watch_dir():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
await session.filesystem.write("/tmp/test.txt", "Hello")
watcher = await session.filesystem.watch_dir("/tmp")
@@ -87,7 +86,7 @@ async def test_write_bytes():
# TODO: This test isn't complete since we can't verify the size of the file inside session.
# We don't have any SDK function to get the size of a file inside session.
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
# Upload the file
with open(local_path, "rb") as f:
@@ -112,7 +111,7 @@ async def test_read_bytes():
# TODO: This test isn't complete since we can't verify the size of the file inside session.
# We don't have any SDK function to get the size of a file inside session.
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
# Upload the file first
with open(local_path, "rb") as f:
diff --git a/packages/python-sdk/tests/test_process.py b/packages/python-sdk/tests/test_process.py
index dd3625eb1..fc45e1e71 100644
--- a/packages/python-sdk/tests/test_process.py
+++ b/packages/python-sdk/tests/test_process.py
@@ -1,20 +1,20 @@
-from os import getenv
from unittest.mock import MagicMock
from e2b import Session
-E2B_API_KEY = getenv("E2B_API_KEY")
async def test_process_expected_stdout():
# TODO: Implement this once we fix envd stdout/stderr race condition
pass
+
async def test_process_expected_stderr():
# TODO: Implement this once we fix envd stdout/stderr race condition
pass
+
async def test_process_on_stdout_stderr():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
stdout = []
stderr = []
@@ -38,7 +38,7 @@ async def test_process_on_stdout_stderr():
async def test_process_on_exit():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
on_exit = MagicMock()
@@ -54,7 +54,7 @@ async def test_process_on_exit():
async def test_process_send_stdin():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
proc = await session.process.start(
'read -r line; echo "$line"',
diff --git a/packages/python-sdk/tests/test_run_code.py b/packages/python-sdk/tests/test_run_code.py
index 984876520..cd2f4574d 100644
--- a/packages/python-sdk/tests/test_run_code.py
+++ b/packages/python-sdk/tests/test_run_code.py
@@ -1,20 +1,18 @@
import pytest
-from os import getenv
from e2b import run_code
+from e2b.session.exception import UnsupportedRuntimeException
-E2B_API_KEY = getenv("E2B_API_KEY")
async def test_run_code():
- code = "console.log('hello'); throw new Error('error')"
- stdout, stderr = await run_code("Node16", code)
+ code = "console.log('hello'); throw new Error('error')"
+ stdout, stderr = await run_code("Node16", code)
- assert stdout == "hello"
- assert "Error: error" in stderr
+ assert stdout == "hello"
+ assert "Error: error" in stderr
async def test_unsupported_runtime():
- code = "console.log('hello'); throw new Error('error')"
- with pytest.raises(Exception) as e:
- await run_code("unsupported", code)
-
+ code = "console.log('hello'); throw new Error('error')"
+ with pytest.raises(UnsupportedRuntimeException) as e:
+ await run_code("unsupported", code)
diff --git a/packages/python-sdk/tests/test_session.py b/packages/python-sdk/tests/test_session.py
index b2998d75f..e227bb927 100644
--- a/packages/python-sdk/tests/test_session.py
+++ b/packages/python-sdk/tests/test_session.py
@@ -1,24 +1,20 @@
-from os import getenv
-
from e2b import Session
-E2B_API_KEY = getenv("E2B_API_KEY")
-
async def test_create_session():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
await session.close()
async def test_create_multiple_sessions():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
- session2 = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
+ session2 = await Session.create("Nodejs")
await session.close()
await session2.close()
async def test_custom_cwd():
- session = await Session.create("Nodejs", api_key=E2B_API_KEY, cwd="/code/app")
+ session = await Session.create("Nodejs", cwd="/code/app")
proc = await session.process.start("pwd")
output = await proc
diff --git a/packages/python-sdk/tests/test_timeout.py b/packages/python-sdk/tests/test_timeout.py
index 79dc1e9dd..0b728d102 100644
--- a/packages/python-sdk/tests/test_timeout.py
+++ b/packages/python-sdk/tests/test_timeout.py
@@ -1,20 +1,18 @@
import asyncio
-from os import getenv
import pytest
-from e2b import Session
-E2B_API_KEY = getenv("E2B_API_KEY")
+from e2b import Session
async def test_create_session_timeout():
with pytest.raises(asyncio.TimeoutError):
- await Session.create("Nodejs", api_key=E2B_API_KEY, timeout=0.01)
+ await Session.create("Nodejs", timeout=0.01)
async def test_process_timeout():
with pytest.raises(asyncio.TimeoutError):
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
await session.process.start(
"sleep 1",
timeout=0.01,
@@ -24,7 +22,7 @@ async def test_process_timeout():
async def test_filesystem_timeout():
with pytest.raises(asyncio.TimeoutError):
- session = await Session.create("Nodejs", api_key=E2B_API_KEY)
+ session = await Session.create("Nodejs")
await session.filesystem.write(
"test.txt",
"Hello World",