Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Remove old code interpreter

Jakub Novak6e09c76aeb56
diff --git a/packages/js-sdk/testground/basic.cjs b/packages/example.cjs/basic.cjs
similarity index 91%
rename from packages/js-sdk/testground/basic.cjs
rename to packages/example.cjs/basic.cjs
index 23d477d01..794b596b4 100644
--- a/packages/js-sdk/testground/basic.cjs
+++ b/packages/example.cjs/basic.cjs
@@ -1,4 +1,4 @@
-const e2b = require('../dist')
+const e2b = require('../js-sdk')
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
diff --git a/packages/js-sdk/package.json b/packages/js-sdk/package.json
index a64f16b82..c7a8f290e 100644
--- a/packages/js-sdk/package.json
+++ b/packages/js-sdk/package.json
@@ -35,9 +35,6 @@
"update-deps": "ncu -u && pnpm i",
"postPublish": "./scripts/post-publish.sh || true"
},
- "peerDependencies": {
- "openai": "^4.17.4"
- },
"devDependencies": {
"@types/node": "^18.18.6",
"@types/normalize-path": "^3.0.0",
@@ -47,7 +44,6 @@
"@typescript-eslint/eslint-plugin": "^6.8.0",
"@typescript-eslint/parser": "^6.8.0",
"knip": "^2.34.0",
- "markdown-it": "^13.0.2",
"npm-check-updates": "^16.14.6",
"openapi-typescript": "^5.4.1",
"tsup": "^6.7.0",
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 882d1eddb..e3c5cf9ba 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -21,15 +21,9 @@ export { Process, ProcessMessage, ProcessOutput } from './sandbox/process'
export type { ProcessManager } from './sandbox/process'
export type { EnvVars } from './sandbox/envVars'
export { runCode, CodeRuntime } from './runCode' // Export CodeRuntime enum as value, not as type, so it can be actually used in consumer code
-import { Sandbox } from './sandbox/index'
+import { Sandbox } from './sandbox'
-import { DataAnalysis } from './templates/dataAnalysis'
-export { DataAnalysis as CodeInterpreter }
-
-export { Artifact, DataAnalysis } from './templates/dataAnalysis'
-export type { RunPythonOpts } from './templates/dataAnalysis'
export type { SandboxMetadata, RunningSandbox } from './sandbox/sandboxConnection'
-export type { Action } from './sandbox/index'
export { Sandbox }
export default Sandbox
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index c0c946c92..87f8af81e 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -10,7 +10,6 @@ import { Process, ProcessManager, ProcessMessage, ProcessOpts, ProcessOutput, pr
import { CallOpts, SandboxConnection, SandboxConnectionOpts } from './sandboxConnection'
import { Terminal, TerminalManager, TerminalOpts, TerminalOutput, terminalService } from './terminal'
import { resolvePath } from '../utils/filesystem'
-import { Actions } from '../templates/openai'
import { CurrentWorkingDirectoryDoesntExistError } from '../error'
export type DownloadFileFormat =
@@ -29,11 +28,6 @@ export interface SandboxOpts extends SandboxConnectionOpts {
onExit?: (() => Promise<void> | void) | ((exitCode: number) => Promise<void> | void);
}
-export interface Action<S extends Sandbox = Sandbox, T = {
- [key: string]: any;
-}> {
- (sandbox: S, args: T): string | Promise<string>;
-}
/**
* E2B cloud sandbox gives your agent a full cloud development environment that's sandboxed.
@@ -74,9 +68,6 @@ export class Sandbox extends SandboxConnection {
*/
readonly process: ProcessManager
- // We use any here because we cannot properly reference the type of the Sandbox subclass
- readonly _actions: Map<string, Action<any, any>> = new Map()
-
private readonly onScanPorts?: ScanOpenPortsHandler
/**
@@ -433,26 +424,6 @@ export class Sandbox extends SandboxConnection {
return `${protocol}://${hostname}${FILE_ROUTE}`
}
- /**
- * Returns a map of added actions.
- *
- * @returns Map of added actions
- */
- get actions() {
- return new Map(this._actions)
- }
-
- /**
- * OpenAI integration that can be used to get output for the actions added in the sandbox.
- *
- * @returns OpenAI integration
- */
- get openai() {
- return {
- actions: new Actions(this),
- } as const
- }
-
/**
* Creates a new Sandbox from the default `base` sandbox template.
* @returns New Sandbox
@@ -555,79 +526,6 @@ export class Sandbox extends SandboxConnection {
return sandbox
}
- /**
- * Add a new action. The name of the action is automatically extracted from the function name.
- *
- * You can use this action with specific integrations like OpenAI to interact with the sandbox and get output for the action.
- *
- * @param action Action handler
- * @returns Sandbox
- *
- * @example
- * ```ts
- * const sandbox = await Sandbox.create()
- * sandbox.addAction('readFile', (sandbox, args) => sandbox.filesystem.read(args.path))
- * ```
- */
- addAction<T = { [name: string]: any }>(action: Action<this, T>): this
- /**
- * Add a new action with a specified name.
- *
- * You can use this action with specific integrations like OpenAI to interact with the sandbox and get output for the action.
- *
- * @param name Action name
- * @param action Action handler
- * @returns Sandbox
- *
- * @example
- * ```ts
- * async function readFile(sandbox: Sandbox, args: any) {
- * return sandbox.filesystem.read(args.path)
- * }
- *
- * const sandbox = await Sandbox.create()
- * sandbox.addAction(readFile)
- * ```
- */
- addAction<T = { [name: string]: any }>(name: string, action: Action<this, T>): this
- addAction<T = { [name: string]: any }>(actionOrName: string | Action<this, T>, action?: Action<this, T>): this {
- if (typeof actionOrName === 'string') {
- if (!action) throw new Error('Action is required')
- this._actions.set(actionOrName, action)
- return this
- } else if (typeof actionOrName === 'function') {
- action = actionOrName
-
- if (!action.name) {
- throw new Error('Action name is required')
- }
-
- this._actions.set(action.name, action)
- } else {
- throw new Error('Action or action name and action is required')
- }
-
- return this
- }
-
- /**
- * Remove an action.
- * @param name Action name
- * @returns Sandbox
- *
- * @example
- * ```ts
- * const sandbox = await Sandbox.create()
- * sandbox.addAction('hello', (sandbox, args) => 'Hello World')
- * sandbox.removeAction('hello')
- * ```
- */
- removeAction(name: string) {
- this._actions.delete(name)
-
- return this
- }
-
/**
* Uploads a file to the sandbox.
* The file will be uploaded to the user's home directory with the same name.
diff --git a/packages/js-sdk/src/templates/dataAnalysis.ts b/packages/js-sdk/src/templates/dataAnalysis.ts
deleted file mode 100644
index 0f95df2f2..000000000
--- a/packages/js-sdk/src/templates/dataAnalysis.ts
+++ /dev/null
@@ -1,116 +0,0 @@
-import { Sandbox, SandboxOpts } from '../sandbox'
-import type { ProcessOpts } from '../sandbox/process'
-import { FilesystemEvent, FilesystemOperation } from '../sandbox/filesystemWatcher'
-
-export class Artifact<S extends DataAnalysis> {
- readonly path: string
- readonly _sandbox: S
-
- constructor(path: string, sandbox: S) {
- this.path = path
- this._sandbox = sandbox
- }
-
- async download() {
- return this._sandbox.downloadFile(this.path)
- }
-}
-
-export interface RunPythonOpts<S extends DataAnalysis> extends Omit<ProcessOpts, 'cmd'> {
- onArtifact?: (artifact: Artifact<S>) => Promise<void> | void;
-}
-
-export class DataAnalysis extends Sandbox {
- private static template = 'Python3-DataAnalysis'
-
- /**
- * Use `DataAnalysis.create()` instead.
- *
- * @hidden
- * @hide
- * @internal
- * @access protected
- */
- constructor(opts: SandboxOpts) {
- super({ template: opts.template || DataAnalysis.template, ...opts })
- }
-
- /**
- * Creates a new Sandbox from the template.
- * @returns New Sandbox
- */
- static override async create(): Promise<DataAnalysis>
- /**
- * Creates a new Sandbox from the specified options.
- * @param opts Sandbox options
- * @returns New Sandbox
- */
- static override async create(opts: SandboxOpts): Promise<DataAnalysis>
- static override async create(opts?: SandboxOpts) {
- const sandbox = new DataAnalysis({ ...opts ? opts : {} })
- await sandbox._open({ timeout: opts?.timeout })
-
- return sandbox
- }
-
- async runPython(code: string, opts: RunPythonOpts<this> = {}): Promise<{
- stdout: string;
- stderr: string;
- artifacts: Artifact<DataAnalysis>[];
- }> {
- const artifacts: string[] = []
-
- const registerArtifacts = async (event: FilesystemEvent) => {
- if (event.operation === FilesystemOperation.Create) {
- const artifact = new Artifact<this>(event.path, this)
- artifacts.push(event.path)
- await opts.onArtifact?.(artifact)
- }
- }
-
- const watcher = this.filesystem.watchDir('/home/user/artifacts')
- watcher.addEventListener(registerArtifacts)
- await watcher.start()
-
- const currentEpoch = new Date().getTime()
- const codefilePath = `/tmp/main-${currentEpoch}.py`
- await this.filesystem.write(codefilePath, code)
- const output = await this.process.startAndWait({
- cmd: `python ${codefilePath}`,
- ...opts,
- })
-
- await watcher.stop()
-
- return {
- stdout: output.stdout,
- stderr: output.stderr,
- artifacts: artifacts.map((artifact) => new Artifact<this>(artifact, this)),
- }
- }
-
- async installPythonPackages(packageNames: string | string[]) {
- await this.installPackages('pip install', packageNames)
- }
-
- async installSystemPackages(packageNames: string | string[]) {
- await this.installPackages('sudo apt-get install -y', packageNames)
- }
-
- private async installPackages(command: string, packageNames: string | string[]) {
- if (Array.isArray(packageNames)) {
- packageNames = packageNames.join(' ')
- }
-
- packageNames = packageNames.trim()
- if (packageNames.length === 0) {
- return
- }
-
- const out = await this.process.startAndWait(`${command} ${packageNames}`)
-
- if (out.exitCode !== 0) {
- throw new Error(`Failed to install package ${packageNames}: ${out.stderr}`)
- }
- }
-}
diff --git a/packages/js-sdk/src/templates/openai.ts b/packages/js-sdk/src/templates/openai.ts
deleted file mode 100644
index aaf4ecb27..000000000
--- a/packages/js-sdk/src/templates/openai.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import type { Run, RunSubmitToolOutputsParams } from 'openai/resources/beta/threads/runs/runs'
-
-import type { Sandbox } from '../sandbox'
-
-
-export class Actions {
- constructor(private readonly sandbox: Sandbox) { }
-
- /**
- * Call the required actions for the provided run and return their outputs.
- *
- * @param run OpenAI run object from `openai.beta.threads.runs.retrieve` or `openai.beta.threads.runs.retrieve.create` call that contains the names of the required actions and their arguments.
- * @returns The outputs of the required actions in the run.
- */
- async run(run: Run): Promise<RunSubmitToolOutputsParams.ToolOutput[]> {
- if (run.status !== 'requires_action') {
- return []
- }
-
- if (!run.required_action) {
- return []
- }
-
- const outputs: RunSubmitToolOutputsParams.ToolOutput[] = []
-
- for (const toolCall of run.required_action.submit_tool_outputs.tool_calls) {
- const action = this.sandbox._actions.get(toolCall.function.name)
- if (!action) {
- console.warn(`Action ${toolCall.function.name} not found`)
- continue
- }
-
- const args = JSON.parse(toolCall.function.arguments)
- const output = await action(this.sandbox, args)
-
- outputs.push({
- tool_call_id: toolCall.id,
- output,
- })
- }
-
- return outputs
- }
-}
diff --git a/packages/js-sdk/test/action.test.mjs b/packages/js-sdk/test/action.test.mjs
deleted file mode 100644
index 5ba4038d8..000000000
--- a/packages/js-sdk/test/action.test.mjs
+++ /dev/null
@@ -1,16 +0,0 @@
-import { Sandbox } from '../src'
-import { test, expect } from 'vitest'
-
-import { id } from './setup.mjs'
-
-test('add action', async () => {
- const sandbox = await Sandbox.create({ id })
-
- sandbox.addAction('test', () => {
- return 'test'
- })
-
- expect([sandbox.actions.values()].length).toEqual(1)
-
- await sandbox.close()
-})
diff --git a/packages/js-sdk/testground/enhance-sdk.js b/packages/js-sdk/testground/enhance-sdk.js
deleted file mode 100644
index 6317ee1d9..000000000
--- a/packages/js-sdk/testground/enhance-sdk.js
+++ /dev/null
@@ -1,84 +0,0 @@
-// eslint-disable-next-line @typescript-eslint/no-var-requires
-const e2b = require("../dist/index");
-
-function enhance(sandbox) {
- sandbox.fs = sandbox.filesystem; // alias, for convenience & consistency with stdlib
-
- sandbox.process._run = async function (cmd, opts) {
- const cmdSlug = cmd.substring(0, 20); // keep it short for nicer logs
- const proc = await this.start({
- cmd,
- ...opts,
- onStdout: ({ line }) => console.log(`[🔹 ${cmdSlug}]`, line),
- onStderr: ({ line }) => console.log(`[🔸 ${cmdSlug}]`, line)
- });
- await proc.finished;
- return proc.output.stdout.trim();
- };
-
- sandbox.process._cloneRepo = async function (repo, dir = "") {
- const cmd = `git clone --depth 1 ${repo} ${dir}`;
- await this._run(cmd);
- };
-
- sandbox._keepAlive = async function () {
- const interval = setInterval(async () => {
- try {
- await this.process._run('echo "♥"');
- } catch (err) {
- console.error("Keepalive failed:", err);
- clearInterval(interval);
- }
- }, 1000 * 10);
- };
-}
-
-const printedPorts = [];
-
-function printNewPortAndURL(openPorts, sandbox) {
- openPorts.forEach((port) => {
- if (!printedPorts.includes(port.port)) {
- printedPorts.push(port.port);
- console.log(port, `https://${sandbox.getHostname(port.port)}`);
- }
- });
-}
-
-async function main() {
- const sandbox = await e2b.Sandbox.create({
- id: "Nodejs",
- apiKey: process.env.E2B_API_KEY
- // onScanPorts: openPorts => printNewPortAndURL(openPorts, sandbox),
- });
- enhance(sandbox);
-
- sandbox._keepAlive();
-
- console.log("Cloning repo...");
- await sandbox.process._cloneRepo("https://github.com/Strajk/demo-todos");
- console.log("Repo cloned.");
-
- // install deps
- console.log("Installing deps...");
- await sandbox.process._run("npm i");
- console.log("Deps installed.");
-
- // log deps
- console.log("Listing deps...");
- const deps = await sandbox.process._run("npm ls --depth=0");
- console.log("Deps:", deps);
-
- // run tests
- console.log("Running tests...");
- await sandbox.process._run("npm test");
- console.log("Tests finished.");
-
- // wait for 5m
- console.log("Waiting for 5m...");
-
- await new Promise((resolve) => setTimeout(resolve, 1000 * 60 * 5));
-
- await sandbox.close();
-}
-
-main().catch(console.error);
diff --git a/packages/js-sdk/testground/next-js/.env.sample b/packages/js-sdk/testground/next-js/.env.sample
deleted file mode 100644
index 39ab05e16..000000000
--- a/packages/js-sdk/testground/next-js/.env.sample
+++ /dev/null
@@ -1 +0,0 @@
-NEXT_PUBLIC_E2B_API_KEY=e2b_...
diff --git a/packages/js-sdk/testground/next-js/.gitignore b/packages/js-sdk/testground/next-js/.gitignore
deleted file mode 100644
index 8f322f0d8..000000000
--- a/packages/js-sdk/testground/next-js/.gitignore
+++ /dev/null
@@ -1,35 +0,0 @@
-# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
-
-# dependencies
-/node_modules
-/.pnp
-.pnp.js
-
-# testing
-/coverage
-
-# next.js
-/.next/
-/out/
-
-# production
-/build
-
-# misc
-.DS_Store
-*.pem
-
-# debug
-npm-debug.log*
-yarn-debug.log*
-yarn-error.log*
-
-# local env files
-.env*.local
-
-# vercel
-.vercel
-
-# typescript
-*.tsbuildinfo
-next-env.d.ts
diff --git a/packages/js-sdk/testground/next-js/jsconfig.json b/packages/js-sdk/testground/next-js/jsconfig.json
deleted file mode 100644
index 928135118..000000000
--- a/packages/js-sdk/testground/next-js/jsconfig.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "compilerOptions": {
- "paths": {
- "@/*": [
- "./src/*"
- ]
- }
- }
-}
diff --git a/packages/js-sdk/testground/next-js/next.config.js b/packages/js-sdk/testground/next-js/next.config.js
deleted file mode 100644
index bddbae938..000000000
--- a/packages/js-sdk/testground/next-js/next.config.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/** @type {import('next').NextConfig} */
-const nextConfig = {
- eslint: {
- ignoreDuringBuilds: true
- }
-}
-
-module.exports = nextConfig
diff --git a/packages/js-sdk/testground/next-js/package.json b/packages/js-sdk/testground/next-js/package.json
deleted file mode 100644
index 93e799135..000000000
--- a/packages/js-sdk/testground/next-js/package.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "name": "next-js",
- "version": "0.1.0",
- "private": true,
- "scripts": {
- "dev": "next dev",
- "build": "next build",
- "start": "next start",
- "build-and-start": "next build && next start"
- },
- "dependencies": {
- "@e2b/sdk": "^0.2.5",
- "encoding": "^0.1.13",
- "next": "13.4.19",
- "react": "18.2.0",
- "react-dom": "18.2.0"
- }
-}
diff --git a/packages/js-sdk/testground/next-js/src/app/layout.js b/packages/js-sdk/testground/next-js/src/app/layout.js
deleted file mode 100644
index b1a468366..000000000
--- a/packages/js-sdk/testground/next-js/src/app/layout.js
+++ /dev/null
@@ -1,16 +0,0 @@
-import { Inter } from "next/font/google";
-
-const inter = Inter({ subsets: ["latin"] });
-
-export const metadata = {
- title: "Create Next App",
- description: "Generated by create next app"
-};
-
-export default function RootLayout({ children }) {
- return (
- <html lang="en">
- <body className={inter.className}>{children}</body>
- </html>
- );
-}
diff --git a/packages/js-sdk/testground/next-js/src/app/page.js b/packages/js-sdk/testground/next-js/src/app/page.js
deleted file mode 100644
index 133775b1c..000000000
--- a/packages/js-sdk/testground/next-js/src/app/page.js
+++ /dev/null
@@ -1,10 +0,0 @@
-import Playground from "@/components/playground";
-
-export default function Home() {
- return (
- <>
- <h1>Home</h1>
- <Playground/>
- </>
- );
-}
diff --git a/packages/js-sdk/testground/next-js/src/components/playground.jsx b/packages/js-sdk/testground/next-js/src/components/playground.jsx
deleted file mode 100644
index c35a3b159..000000000
--- a/packages/js-sdk/testground/next-js/src/components/playground.jsx
+++ /dev/null
@@ -1,33 +0,0 @@
-"use client";
-
-import { Sandbox } from "@e2b/sdk";
-import { useEffect, useState } from "react";
-
-function Playground() {
- const [playground, setPlayground] = useState(null);
- const [url, setURL] = useState("");
-
- console.log("process.env", process.env);
-
- async function initPlayground() {
- const sandbox = await Sandbox.create({
- id: "Nodejs",
- apiKey: process.env.NEXT_PUBLIC_E2B_API_KEY
- });
- setURL("https://" + sandbox.getHostname(3000));
- setPlayground(sandbox);
- }
-
- useEffect(function init() {
- void initPlayground();
- }, []);
-
- return (
- <div>
- <h2>Playground</h2>
- {url && <iframe style={{ width: "100%", height: "400px" }} src={url}/>}
- </div>
- );
-}
-
-export default Playground;
diff --git a/packages/js-sdk/testground/playwright.mjs b/packages/js-sdk/testground/playwright.mjs
deleted file mode 100644
index 30b6011f6..000000000
--- a/packages/js-sdk/testground/playwright.mjs
+++ /dev/null
@@ -1,29 +0,0 @@
-import { Sandbox } from '../dist/index.js' // should be /esm/, but getting "The requested module '../dist/esm/index.js' is a CommonJS module"
-
-const commonProcessOpts = {
- onStdout: ({ line }) => console.log('🟢', line),
- onStderr: ({ line }) => console.log('🔴', line)
-}
-
-const sandbox = await Sandbox.create({
- id: 'Nodejs',
- apiKey: process.env.E2B_API_KEY
-})
-
-console.log('🟣 Creating package.json')
-await (
- await sandbox.process.start({
- cmd: 'npx playwright install',
- ...commonProcessOpts
- })
-).finished
-
-console.log('🟣 Running playwright --version')
-await (
- await sandbox.process.start({
- cmd: 'npx playwright --version',
- ...commonProcessOpts
- })
-).finished
-
-await sandbox.close()
diff --git a/packages/js-sdk/testground/testDataAnalysis.cjs b/packages/js-sdk/testground/testDataAnalysis.cjs
deleted file mode 100644
index 780671df0..000000000
--- a/packages/js-sdk/testground/testDataAnalysis.cjs
+++ /dev/null
@@ -1,45 +0,0 @@
-const e2b = require('../dist/cjs/index')
-const fs = require('fs')
-
-async function main() {
- const s = await e2b.DataAnalysis.create({
- apiKey: process.env.E2B_API_KEY
- })
- const response = await fetch('https://storage.googleapis.com/e2b-examples/netflix.csv')
- const buffer = await response.buffer()
-
- const path = await s.uploadFile(buffer, 'netflix.csv')
-
- const result = await s.runPython(`
-print(1)
-import pandas as pd
-import seaborn as sns
-import matplotlib.pyplot as plt
-
-data = pd.read_csv('${path}')
-top_countries = data['country'].value_counts().head(10)
-
-plt.figure(figsize=(10, 6))
-top_countries.plot(kind='bar', color='skyblue')
-plt.title('Number of content')
-plt.xlabel('Country')
-plt.ylabel('Count')
-plt.xticks(rotation=45)
-plt.show()`, {
- onArtifact: async (artifact) => {
- await artifact.download()
- }
- })
-
- console.log(result)
- for (const artifact of result.artifacts) {
- const data = await s.downloadFile(artifact.path, 'buffer')
- fs.writeFileSync(artifact.path, data)
- }
-
- await s.close()
-
-
-}
-
-main().catch(console.error)
diff --git a/packages/js-sdk/testground/testDataAnalysis.mjs b/packages/js-sdk/testground/testDataAnalysis.mjs
deleted file mode 100644
index ec80e190a..000000000
--- a/packages/js-sdk/testground/testDataAnalysis.mjs
+++ /dev/null
@@ -1,207 +0,0 @@
-import OpenAI from 'openai'
-import * as e2b from '../dist/cjs/index.js'
-import readline from 'node:readline'
-import fs from 'node:fs'
-import MarkdownIt from 'markdown-it'
-import { JSDOM } from 'jsdom'
-
-const md = new MarkdownIt()
-
-let codeSnippets = []
-
-function askUserQuestion(query) {
- const rl = readline.createInterface({
- input: process.stdin,
- output: process.stdout
- })
-
- return new Promise(resolve =>
- rl.question(query, ans => {
- rl.close()
- resolve(ans)
- })
- )
-}
-
-const systemPrompt = `You're a helpful Python data analyst. Always make sure all libraries are properly imported. Users ask you to solve data analysis problems and you solve them with running Python code. ALWAYS PRINT THE VARIABLES YOU WANT SHOW TO USER. The following Python packages are installed:
-NumPy
-Pandas
-Matplotlib
-SciPy
-Scikit-learn
-NLTK
-Requests
-Beautiful Soup
-SQLAlchemy`
-
-const exampleCodeInMarkdown = fs.readFileSync(
- '/Users/mlejva/Developer/e2b/packages/js-sdk/testground/code.md',
- 'utf8'
-)
-const history = [
- {
- role: 'system',
- content: systemPrompt
- },
- {
- role: 'user',
- content:
- 'I uploaded a CSV file here "/home/user/data.csv". What can you tell me about the data in this csv file?'
- },
- {
- role: 'assistant',
- content: `Let's start by loading the data and then we can explore its general characteristics such as the number of rows and columns, column names and types, missing values, and basic statistics. ${exampleCodeInMarkdown}`
- }
- // {
- // role: 'assistant',
- // content: ``,
- // },
-]
-
-const desc =
- 'Run Python code from file. You have access to the internet and can load and save files from the "/home/user" directory. ALWASY WRITE CORRECT PYTHON CODE'
-
-const functions = [
- {
- name: 'run_python_code',
- description: desc,
- parameters: {
- type: 'object',
- properties: {
- code: {
- type: 'string',
- description: 'The Python code to run in Markdown format.'
- }
- }
- },
- required: ['code']
- }
-]
-
-let s
-const openai = new OpenAI()
-
-async function chat() {
- const response = await openai.chat.completions.create({
- model: 'gpt-4',
- messages: history
- // functions,
- })
- return response
-}
-
-function respond(msg) {
- history.push({
- role: 'user',
- content: msg
- })
- return chat()
-}
-
-async function handleArtifact(artifact) {
- const path = '/Users/mlejva/Developer/e2b/packages/js-sdk/testground/chart.png'
- const file = await artifact.download('buffer')
- fs.writeFileSync(path, file)
- console.log('Chart saved to ', `file://${path}`)
-}
-
-async function startSandbox() {
- s = await e2b.DataAnalysis.create()
-
- const localFile = fs.readFileSync('/Users/mlejva/Downloads/netflix.csv')
- const remotePath = await s.uploadFile(localFile, 'netflix.csv')
- return remotePath
-}
-
-async function runPython(code) {
- const { stdout, stderr } = await s.runPython(code, {
- onStdout: out => console.log(out.line),
- onStderr: out => console.error(out.line),
- onArtifact: handleArtifact
- })
-
- if (stderr) {
- // fs.writeFileSync(
- // '/Users/mlejva/Developer/e2b/packages/js-sdk/testground/code.txt',
- // code,
- // )
- // codeSnippets.pop()
- console.log('Got an error in code, fixing mysekf...')
- const response = await respond(
- `I ran your code and got the following error: ${stderr}`
- )
-
- await parseResponse(response)
- } else if (stdout) {
- const response = await respond(`I ran your code and this is the output: ${stdout}`)
- await parseResponse(response)
- }
-}
-
-function getPythonCodeSnippets(content) {
- const html = md.render(content)
- const dom = new JSDOM(html)
- const snippets = []
- dom.window.document.querySelectorAll('pre').forEach(pre => {
- if (pre.textContent) {
- // console.log('SNIPPET')
- // console.log(pre.textContent)
- snippets.push(pre.textContent)
- }
- })
- return snippets
-}
-
-async function parseResponse(response) {
- const choice = response.choices[0]
- // console.log('==== CHOICE')
- // console.log(choice)
- // console.log('====')
-
- if (choice.finish_reason === 'stop') {
- const content = choice.message.content
- const snippets = getPythonCodeSnippets(content)
-
- if (snippets.length > 0) {
- const newCode = snippets[0]
- // codeSnippets.push(newCode)
- // await runFunction('run_python_code', { code: codeSnippets.join('\n') })
- await runFunction('run_python_code', { code: newCode })
- } else {
- console.log(content)
- const ans = await askUserQuestion('> ')
- const response = await respond(ans)
- await parseResponse(response)
- }
- } else if (choice.finish_reason === 'function_call') {
- // const functionName = choice.message.function_call.name
- // const functionsArgsStr = choice.message.function_call.arguments
- // console.log(functionsArgsStr)
- // process.exit()
- // const functionArgs = JSON.parse(functionsArgsStr)
- // await runFunction(functionName, functionArgs)
- } else {
- console.log('unexpected finish reason', choice.finish_reason)
- }
-}
-
-async function runFunction(name, args) {
- if (name === 'run_python_code') {
- await runPython(args.code)
- }
-}
-
-const remoteCSVFilePath = await startSandbox()
-
-const response = await respond(
- `I uploaded a CSV file here "${remoteCSVFilePath}". What can you tell me about the data in this csv file?`
-)
-await parseResponse(response)
-
-// const response = await openai.chat.completions.create({
-// model: 'gpt-4',
-// messages: history,
-// functions,
-// })
-
-await s.close()
diff --git a/packages/js-sdk/testground/testDataAnalysis.ts b/packages/js-sdk/testground/testDataAnalysis.ts
deleted file mode 100644
index 41086d444..000000000
--- a/packages/js-sdk/testground/testDataAnalysis.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { DataAnalysis } from "../src"
-import { writeFileSync } from "fs"
-
-async function main() {
- const s = await DataAnalysis.create({
- apiKey: process.env.E2B_API_KEY
- })
- const response = await fetch('https://storage.googleapis.com/e2b-examples/netflix.csv')
- const buffer = await response.blob()
-
- const path = await s.uploadFile(buffer, 'netflix.csv')
-
- const result = await s.runPython(`
-print(1)
-import pandas as pd
-import seaborn as sns
-import matplotlib.pyplot as plt
-
-data = pd.read_csv('${path}')
-top_countries = data['country'].value_counts().head(10)
-
-plt.figure(figsize=(10, 6))
-top_countries.plot(kind='bar', color='skyblue')
-plt.title('Number of content')
-plt.xlabel('Country')
-plt.ylabel('Count')
-plt.xticks(rotation=45)
-plt.show()`, {
- onArtifact: async (artifact) => {
- await artifact.download()
- }
- })
-
- console.log(result)
- for (const artifact of result.artifacts) {
- const data = await s.downloadFile(artifact.path, 'buffer')
- if (typeof data === 'string') {
- writeFileSync(artifact.path, data)
- }
- }
-
- await s.close()
-
-
-}
-
-main().catch(console.error)
diff --git a/packages/js-sdk/testground/zameest.js b/packages/js-sdk/testground/zameest.js
deleted file mode 100644
index 6317ee1d9..000000000
--- a/packages/js-sdk/testground/zameest.js
+++ /dev/null
@@ -1,84 +0,0 @@
-// eslint-disable-next-line @typescript-eslint/no-var-requires
-const e2b = require("../dist/index");
-
-function enhance(sandbox) {
- sandbox.fs = sandbox.filesystem; // alias, for convenience & consistency with stdlib
-
- sandbox.process._run = async function (cmd, opts) {
- const cmdSlug = cmd.substring(0, 20); // keep it short for nicer logs
- const proc = await this.start({
- cmd,
- ...opts,
- onStdout: ({ line }) => console.log(`[🔹 ${cmdSlug}]`, line),
- onStderr: ({ line }) => console.log(`[🔸 ${cmdSlug}]`, line)
- });
- await proc.finished;
- return proc.output.stdout.trim();
- };
-
- sandbox.process._cloneRepo = async function (repo, dir = "") {
- const cmd = `git clone --depth 1 ${repo} ${dir}`;
- await this._run(cmd);
- };
-
- sandbox._keepAlive = async function () {
- const interval = setInterval(async () => {
- try {
- await this.process._run('echo "♥"');
- } catch (err) {
- console.error("Keepalive failed:", err);
- clearInterval(interval);
- }
- }, 1000 * 10);
- };
-}
-
-const printedPorts = [];
-
-function printNewPortAndURL(openPorts, sandbox) {
- openPorts.forEach((port) => {
- if (!printedPorts.includes(port.port)) {
- printedPorts.push(port.port);
- console.log(port, `https://${sandbox.getHostname(port.port)}`);
- }
- });
-}
-
-async function main() {
- const sandbox = await e2b.Sandbox.create({
- id: "Nodejs",
- apiKey: process.env.E2B_API_KEY
- // onScanPorts: openPorts => printNewPortAndURL(openPorts, sandbox),
- });
- enhance(sandbox);
-
- sandbox._keepAlive();
-
- console.log("Cloning repo...");
- await sandbox.process._cloneRepo("https://github.com/Strajk/demo-todos");
- console.log("Repo cloned.");
-
- // install deps
- console.log("Installing deps...");
- await sandbox.process._run("npm i");
- console.log("Deps installed.");
-
- // log deps
- console.log("Listing deps...");
- const deps = await sandbox.process._run("npm ls --depth=0");
- console.log("Deps:", deps);
-
- // run tests
- console.log("Running tests...");
- await sandbox.process._run("npm test");
- console.log("Tests finished.");
-
- // wait for 5m
- console.log("Waiting for 5m...");
-
- await new Promise((resolve) => setTimeout(resolve, 1000 * 60 * 5));
-
- await sandbox.close();
-}
-
-main().catch(console.error);
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 897347e50..9c668778e 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -42,7 +42,6 @@ from .sandbox import (
ProcessManager,
Process,
OpenPort,
- Action,
EnvVars,
SandboxException,
TerminalException,
@@ -56,7 +55,3 @@ from .sandbox import (
run_code,
RunningSandbox,
)
-from .templates import (
- DataAnalysis,
- CodeInterpreter,
-)
diff --git a/packages/python-sdk/e2b/sandbox/__init__.py b/packages/python-sdk/e2b/sandbox/__init__.py
index 0e4aba9d1..4e8a09820 100644
--- a/packages/python-sdk/e2b/sandbox/__init__.py
+++ b/packages/python-sdk/e2b/sandbox/__init__.py
@@ -19,7 +19,7 @@ from .filesystem_watcher import (
FilesystemOperation,
FilesystemWatcher,
)
-from .main import Sandbox, Action
+from .main import Sandbox
from .process import (
Process,
ProcessManager,
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index ba1432475..7d98c8353 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -4,8 +4,7 @@ import requests
import threading
from os import path
-from typing import Any, Callable, Dict, List, Literal, Optional, IO, TypeVar, Union
-from typing_extensions import Self
+from typing import Any, Callable, Dict, List, Literal, Optional, IO, Union
from e2b.api import models
from e2b.constants import TIMEOUT, ENVD_PORT, FILE_ROUTE
@@ -19,14 +18,6 @@ from e2b.sandbox.terminal import TerminalManager
logger = logging.getLogger(__name__)
-S = TypeVar(
- "S",
- bound="Sandbox",
-)
-
-Action = Callable[[S, Dict[str, Any]], str]
-
-
class Sandbox(SandboxConnection):
"""
E2B cloud sandbox gives your agent a full cloud development environment that's sandboxed.
@@ -147,89 +138,6 @@ class Sandbox(SandboxConnection):
_debug_dev_env=_debug_dev_env,
timeout=timeout,
)
- self._actions: Dict[str, Action[Self]] = {}
-
- def add_action(self, action: Action[Self], name: Optional[str] = None) -> "Sandbox":
- """
- Add a new action. If the name is not specified, it is automatically extracted from the function name.
- An action is a function that takes a sandbox and a dictionary of arguments and returns a string.
-
- You can use this action with specific integrations like OpenAI to interact with the sandbox and get output for the action.
- :param action: The action to add
- :param name: The name of the action, if not provided, the name of the function will be used
-
- Example:
-
- ```python
- from e2b import Sandbox
-
- def read_file(sandbox, args):
- with open(args["path"], "r") as f:
- return sandbox.filesystem.read(args.path)
-
- s = Sandbox()
- s.add_action(read_file)
- s.add_action(name="hello", action=lambda s, args: f"Hello {args['name']}!")
- ```
- """
-
- if not name:
- name = action.__name__
-
- self._actions[name] = action
-
- return self
-
- def remove_action(self, name: str) -> "Sandbox":
- """
- Remove an action.
-
- :param name: The name of the action
- """
- del self._actions[name]
-
- return self
-
- @property
- def actions(self) -> Dict[str, Action[Self]]:
- """
- Return a dict of added actions.
- """
-
- return self._actions.copy()
-
- def action(self, name: Optional[str] = None):
- """
- Decorator to add an action.
-
- :param name: The name of the action, if not provided, the name of the function will be used
- """
-
- def _action(action: Action[Self]):
- self.add_action(action=action, name=name or action.__name__)
-
- return action
-
- return _action
-
- @property
- def openai(self):
- """
- OpenAI integration that can be used to get output for the actions added in the sandbox.
-
- Example:
-
- ```python
- from e2b import Sandbox
-
- s = Sandbox()
- s.openai.actions.run(run)
- ```
- """
-
- from e2b.templates.openai import OpenAI, Actions
-
- return OpenAI[Self](Actions[Self](self))
def _handle_start_cmd_logs(self):
def run_in_thread():
diff --git a/packages/python-sdk/e2b/templates/__init__.py b/packages/python-sdk/e2b/templates/__init__.py
deleted file mode 100644
index 7c752c6fc..000000000
--- a/packages/python-sdk/e2b/templates/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from .data_analysis import Artifact, DataAnalysis, CodeInterpreter
diff --git a/packages/python-sdk/e2b/templates/data_analysis.py b/packages/python-sdk/e2b/templates/data_analysis.py
deleted file mode 100644
index d3b8c6d3b..000000000
--- a/packages/python-sdk/e2b/templates/data_analysis.py
+++ /dev/null
@@ -1,141 +0,0 @@
-import logging
-import time
-from typing import Optional, Callable, Any, Tuple, List, Union
-from e2b.sandbox.process import ProcessMessage
-
-from pydantic import BaseModel, PrivateAttr
-
-from e2b import EnvVars, Sandbox
-from e2b.constants import TIMEOUT
-
-logger = logging.getLogger(__name__)
-
-
-class Artifact(BaseModel):
- name: str
- _sandbox: Sandbox = PrivateAttr()
-
- def __init__(self, sandbox: Sandbox, **data: Any):
- super().__init__(**data)
- self._sandbox = sandbox
-
- def __hash__(self):
- return hash(self.name)
-
- def download(self) -> bytes:
- return self._sandbox.download_file(self.name)
-
-
-class DataAnalysis(Sandbox):
- template = "Python3-DataAnalysis"
-
- def __init__(
- self,
- template: Optional[str] = None,
- api_key: Optional[str] = None,
- cwd: Optional[str] = None,
- env_vars: Optional[EnvVars] = None,
- timeout: Optional[float] = TIMEOUT,
- on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
- on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
- on_artifact: Optional[Callable[[Artifact], Any]] = None,
- on_exit: Optional[Callable[[int], Any]] = None,
- **kwargs,
- ):
- self.on_artifact = on_artifact
- super().__init__(
- template=template or self.template,
- api_key=api_key,
- cwd=cwd,
- env_vars=env_vars,
- timeout=timeout,
- on_stdout=on_stdout,
- on_stderr=on_stderr,
- on_exit=on_exit,
- **kwargs,
- )
-
- def run_python(
- self,
- code: str,
- on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,
- on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,
- on_artifact: Optional[Callable[[Artifact], Any]] = None,
- on_exit: Optional[Callable[[int], Any]] = None,
- env_vars: Optional[EnvVars] = None,
- cwd: str = "",
- process_id: Optional[str] = None,
- timeout: Optional[float] = TIMEOUT,
- ) -> Tuple[str, str, List[Artifact]]:
- artifacts = set()
-
- def register_artifacts(event: Any) -> None:
- on_artifact_func = on_artifact or self.on_artifact
- if event.operation == "Create":
- artifact = Artifact(name=event.path, sandbox=self)
- artifacts.add(artifact)
- if on_artifact_func:
- try:
- on_artifact_func(artifact)
- except Exception as e:
- logger.error("Failed to process artifact", exc_info=e)
-
- watcher = self.filesystem.watch_dir("/home/user/artifacts")
- watcher.add_event_listener(register_artifacts)
- watcher.start()
-
- epoch_time = time.time()
- codefile_path = f"/tmp/main-{epoch_time}.py"
- self.filesystem.write(codefile_path, code)
-
- output = self.process.start_and_wait(
- f"python {codefile_path}",
- on_stdout=on_stdout,
- on_stderr=on_stderr,
- on_exit=on_exit,
- env_vars=env_vars,
- cwd=cwd,
- process_id=process_id,
- timeout=timeout,
- )
-
- watcher.stop()
-
- return output.stdout, output.stderr, list(artifacts)
-
- def _install_packages(
- self,
- command: str,
- package_names: Union[str, List[str]],
- timeout: Optional[float] = TIMEOUT,
- ) -> None:
- if isinstance(package_names, list):
- package_names = " ".join(package_names)
-
- package_names = package_names.strip()
- if not package_names:
- return
-
- output = self.process.start_and_wait(
- f"{command} {package_names}", timeout=timeout
- )
-
- if output.exit_code != 0:
- raise Exception(
- f"Failed to install package {package_names}: {output.stderr}"
- )
-
- def install_python_packages(
- self, package_names: Union[str, List[str]], timeout: Optional[float] = TIMEOUT
- ) -> None:
- self._install_packages("pip install", package_names, timeout=timeout)
-
- def install_system_packages(
- self, package_names: Union[str, List[str]], timeout: Optional[float] = TIMEOUT
- ) -> None:
- self._install_packages(
- "sudo apt-get install -y", package_names, timeout=timeout
- )
-
-
-CodeInterpreter = DataAnalysis
diff --git a/packages/python-sdk/e2b/templates/openai.py b/packages/python-sdk/e2b/templates/openai.py
deleted file mode 100644
index 105ec8aba..000000000
--- a/packages/python-sdk/e2b/templates/openai.py
+++ /dev/null
@@ -1,71 +0,0 @@
-import json
-import logging
-
-from typing import (
- Generic,
- List,
- TYPE_CHECKING,
- TypeVar,
-)
-
-from e2b.sandbox.main import Sandbox
-
-logger = logging.getLogger(__name__)
-
-if TYPE_CHECKING:
- from openai.types.beta.threads.run_submit_tool_outputs_params import ToolOutput
- from openai.types.beta.threads.run import Run
-
-
-S = TypeVar(
- "S",
- bound=Sandbox,
-)
-
-
-class Actions(Generic[S]):
- def __init__(self, sandbox: S):
- self._sandbox = sandbox
-
- def run(self, run: "Run") -> List["ToolOutput"]:
- """
- Call the required actions for the provided run and return their outputs.
-
- :param run: OpenAI run object from `openai.beta.threads.runs.retrieve` or `openai.beta.threads.runs.retrieve.create` call that contains the names of the required actions and their arguments.
-
- :return: The outputs of the required actions in the run.
- """
- if run.status != "requires_action":
- return []
-
- if not run.required_action:
- return []
-
- outputs = []
-
- for tool_call in run.required_action.submit_tool_outputs.tool_calls:
- action = self._sandbox._actions.get(tool_call.function.name)
- if not action:
- logger.warning(f"Action {tool_call.function.name} not found.")
- continue
-
- args = json.loads(tool_call.function.arguments)
- output = action(self._sandbox, args)
-
- outputs.append(
- {
- "tool_call_id": tool_call.id,
- "output": output,
- }
- )
-
- return outputs
-
-
-class OpenAI(Generic[S]):
- def __init__(self, actions: Actions[S]):
- self._actions = actions
-
- @property
- def actions(self):
- return self._actions
diff --git a/packages/python-sdk/poetry.lock b/packages/python-sdk/poetry.lock
index 7f9c7e2f6..05c9e911a 100644
--- a/packages/python-sdk/poetry.lock
+++ b/packages/python-sdk/poetry.lock
@@ -1,4 +1,4 @@
-# This file is automatically @generated by Poetry 1.6.1 and should not be changed by hand.
+# This file is automatically @generated by Poetry 1.8.1 and should not be changed by hand.
[[package]]
name = "aenum"
@@ -148,27 +148,6 @@ files = [
[package.dependencies]
typing-extensions = {version = ">=4.0.0", markers = "python_version < \"3.9\""}
-[[package]]
-name = "anyio"
-version = "3.7.1"
-description = "High level compatibility layer for multiple asynchronous event loop implementations"
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "anyio-3.7.1-py3-none-any.whl", hash = "sha256:91dee416e570e92c64041bd18b900d1d6fa78dff7048769ce5ac5ddad004fbb5"},
- {file = "anyio-3.7.1.tar.gz", hash = "sha256:44a3c9aba0f5defa43261a8b3efb97891f2bd7d804e0e1f56419befa1adfc780"},
-]
-
-[package.dependencies]
-exceptiongroup = {version = "*", markers = "python_version < \"3.11\""}
-idna = ">=2.8"
-sniffio = ">=1.1"
-
-[package.extras]
-doc = ["Sphinx", "packaging", "sphinx-autodoc-typehints (>=1.2.0)", "sphinx-rtd-theme (>=1.2.2)", "sphinxcontrib-jquery"]
-test = ["anyio[trio]", "coverage[toml] (>=4.5)", "hypothesis (>=4.0)", "mock (>=4)", "psutil (>=5.9)", "pytest (>=7.0)", "pytest-mock (>=3.6.1)", "trustme", "uvloop (>=0.17)"]
-trio = ["trio (<0.22)"]
-
[[package]]
name = "async-timeout"
version = "4.0.3"
@@ -379,17 +358,6 @@ files = [
{file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
]
-[[package]]
-name = "distro"
-version = "1.8.0"
-description = "Distro - an OS platform information API"
-optional = false
-python-versions = ">=3.6"
-files = [
- {file = "distro-1.8.0-py3-none-any.whl", hash = "sha256:99522ca3e365cac527b44bde033f64c6945d90eb9f769703caaec52b09bbd3ff"},
- {file = "distro-1.8.0.tar.gz", hash = "sha256:02e111d1dc6a50abb8eed6bf31c3e48ed8b0830d1ea2a1b78c61765c2513fdd8"},
-]
-
[[package]]
name = "exceptiongroup"
version = "1.1.3"
@@ -488,62 +456,6 @@ files = [
{file = "frozenlist-1.4.0.tar.gz", hash = "sha256:09163bdf0b2907454042edb19f887c6d33806adc71fbd54afc14908bfdc22251"},
]
-[[package]]
-name = "h11"
-version = "0.14.0"
-description = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1"
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "h11-0.14.0-py3-none-any.whl", hash = "sha256:e3fe4ac4b851c468cc8363d500db52c2ead036020723024a109d37346efaa761"},
- {file = "h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d"},
-]
-
-[[package]]
-name = "httpcore"
-version = "1.0.2"
-description = "A minimal low-level HTTP client."
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "httpcore-1.0.2-py3-none-any.whl", hash = "sha256:096cc05bca73b8e459a1fc3dcf585148f63e534eae4339559c9b8a8d6399acc7"},
- {file = "httpcore-1.0.2.tar.gz", hash = "sha256:9fc092e4799b26174648e54b74ed5f683132a464e95643b226e00c2ed2fa6535"},
-]
-
-[package.dependencies]
-certifi = "*"
-h11 = ">=0.13,<0.15"
-
-[package.extras]
-asyncio = ["anyio (>=4.0,<5.0)"]
-http2 = ["h2 (>=3,<5)"]
-socks = ["socksio (==1.*)"]
-trio = ["trio (>=0.22.0,<0.23.0)"]
-
-[[package]]
-name = "httpx"
-version = "0.25.1"
-description = "The next generation HTTP client."
-optional = false
-python-versions = ">=3.8"
-files = [
- {file = "httpx-0.25.1-py3-none-any.whl", hash = "sha256:fec7d6cc5c27c578a391f7e87b9aa7d3d8fbcd034f6399f9f79b45bcc12a866a"},
- {file = "httpx-0.25.1.tar.gz", hash = "sha256:ffd96d5cf901e63863d9f1b4b6807861dbea4d301613415d9e6e57ead15fc5d0"},
-]
-
-[package.dependencies]
-anyio = "*"
-certifi = "*"
-httpcore = "*"
-idna = "*"
-sniffio = "*"
-
-[package.extras]
-brotli = ["brotli", "brotlicffi"]
-cli = ["click (==8.*)", "pygments (==2.*)", "rich (>=10,<14)"]
-http2 = ["h2 (>=3,<5)"]
-socks = ["socksio (==1.*)"]
-
[[package]]
name = "idna"
version = "3.4"
@@ -673,28 +585,6 @@ files = [
{file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"},
]
-[[package]]
-name = "openai"
-version = "1.2.3"
-description = "The official Python library for the openai API"
-optional = false
-python-versions = ">=3.7.1"
-files = [
- {file = "openai-1.2.3-py3-none-any.whl", hash = "sha256:d8d1221d777c3b2d12468f17410bf929ca0cb06e9556586e61f5a4255f0cf2b4"},
- {file = "openai-1.2.3.tar.gz", hash = "sha256:800d206ec02c8310400f07b3bb52e158751f3a419e75d080117d913f358bf0d5"},
-]
-
-[package.dependencies]
-anyio = ">=3.5.0,<4"
-distro = ">=1.7.0,<2"
-httpx = ">=0.23.0,<1"
-pydantic = ">=1.9.0,<3"
-tqdm = ">4"
-typing-extensions = ">=4.5,<5"
-
-[package.extras]
-datalib = ["numpy (>=1)", "pandas (>=1.2.3)", "pandas-stubs (>=1.1.0.11)"]
-
[[package]]
name = "packaging"
version = "23.2"
@@ -1001,17 +891,6 @@ files = [
{file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"},
]
-[[package]]
-name = "sniffio"
-version = "1.3.0"
-description = "Sniff out which async library your code is running under"
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "sniffio-1.3.0-py3-none-any.whl", hash = "sha256:eecefdce1e5bbfb7ad2eeaabf7c1eeb404d7757c379bd1f7e5cce9d8bf425384"},
- {file = "sniffio-1.3.0.tar.gz", hash = "sha256:e60305c5e5d314f5389259b7f22aaa33d8f7dee49763119234af3755c55b9101"},
-]
-
[[package]]
name = "tomli"
version = "2.0.1"
@@ -1023,26 +902,6 @@ files = [
{file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"},
]
-[[package]]
-name = "tqdm"
-version = "4.66.1"
-description = "Fast, Extensible Progress Meter"
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "tqdm-4.66.1-py3-none-any.whl", hash = "sha256:d302b3c5b53d47bce91fea46679d9c3c6508cf6332229aa1e7d8653723793386"},
- {file = "tqdm-4.66.1.tar.gz", hash = "sha256:d88e651f9db8d8551a62556d3cff9e3034274ca5d66e93197cf2490e2dcb69c7"},
-]
-
-[package.dependencies]
-colorama = {version = "*", markers = "platform_system == \"Windows\""}
-
-[package.extras]
-dev = ["pytest (>=6)", "pytest-cov", "pytest-timeout", "pytest-xdist"]
-notebook = ["ipywidgets (>=6)"]
-slack = ["slack-sdk"]
-telegram = ["requests"]
-
[[package]]
name = "typing-extensions"
version = "4.9.0"
@@ -1242,4 +1101,4 @@ multidict = ">=4.0"
[metadata]
lock-version = "2.0"
python-versions = "^3.8"
-content-hash = "dd06162caf65ee5493c6a0c66fdee779f97b209bf0c47f1a6a5e10e2c703604f"
+content-hash = "d2487ac309e5f09bf24584fb2c938a3fbe8835b404d766cefec9c7235df6e7cc"
diff --git a/packages/python-sdk/pyproject.toml b/packages/python-sdk/pyproject.toml
index d92b20c02..ca21b9888 100644
--- a/packages/python-sdk/pyproject.toml
+++ b/packages/python-sdk/pyproject.toml
@@ -28,7 +28,6 @@ pytest = "^7.4.0"
pytest-xdist = "^3.3.1"
python-dotenv = "^1.0.0"
pytest-dotenv = "^0.5.2"
-openai = "^1.2.3"
[build-system]
requires = ["poetry-core"]
diff --git a/packages/python-sdk/scripts/upload_test_results.py b/packages/python-sdk/scripts/upload_test_results.py
deleted file mode 100644
index 856f4ab5c..000000000
--- a/packages/python-sdk/scripts/upload_test_results.py
+++ /dev/null
@@ -1,49 +0,0 @@
-import csv
-import os
-from urllib.parse import urlparse
-
-import psycopg2
-from psycopg2.extras import execute_values
-
-database_url = urlparse(os.getenv("SUPABASE_POSTGRES_URL"))
-
-user = database_url.username
-password = database_url.password
-database = database_url.path[1:]
-host = database_url.hostname
-
-
-# Read the results.csv file
-with open("results.csv", "r") as f:
- reader = csv.DictReader(f)
- results = list(reader)
-
-# Connect to the database
-conn = psycopg2.connect(
- host=host,
- database=database,
- user=user,
- password=password,
-)
-
-# Create a cursor
-cur = conn.cursor()
-
-# Get values to insert
-result_values = [
- [result["test_name"], result["duration"], result["outcome"]] for result in results
-]
-
-# Insert all results into the database
-execute_values(
- cur,
- "INSERT INTO tests.test_results (test_name, duration, outcome) VALUES %s",
- result_values,
-)
-
-# Commit the changes
-conn.commit()
-
-# Close the cursor and connection
-cur.close()
-conn.close()
diff --git a/packages/python-sdk/tests/conftest.py b/packages/python-sdk/tests/conftest.py
deleted file mode 100644
index 091039f3e..000000000
--- a/packages/python-sdk/tests/conftest.py
+++ /dev/null
@@ -1,22 +0,0 @@
-import csv
-import pytest
-
-
[email protected](tryfirst=True)
-def pytest_configure():
- with open("results.csv", "w") as f:
- writer = csv.DictWriter(f, ["test_name", "duration", "outcome"])
- writer.writeheader()
-
-
-def pytest_report_teststatus(report):
- if report.when == "call": # <-- Added this line
- with open("results.csv", "a") as f:
- writer = csv.DictWriter(f, ["test_name", "duration", "outcome"])
- writer.writerow(
- {
- "test_name": report.nodeid,
- "duration": round(report.duration, 4),
- "outcome": report.outcome,
- }
- )
diff --git a/packages/python-sdk/tests/templates/test_data_analysis.py b/packages/python-sdk/tests/templates/test_data_analysis.py
deleted file mode 100644
index 1277ce400..000000000
--- a/packages/python-sdk/tests/templates/test_data_analysis.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from e2b.templates.data_analysis import DataAnalysis
-
-
-def test_create_graph():
- s = DataAnalysis()
- a, b, artifacts = s.run_python(
- """
-import matplotlib.pyplot as plt
-
-plt.plot([1, 2, 3, 4])
-plt.ylabel('some numbers')
-plt.show()
- """
- )
- s.close()
- assert len(artifacts) == 1
-
-
-def test_install_packages():
- s = DataAnalysis()
-
- s.install_python_packages("pandas")
- s.install_python_packages(["pandas"])
- s.install_python_packages(" ")
- s.install_python_packages([])
-
- s.install_system_packages("curl")
- s.install_system_packages(["curl"])
- s.install_system_packages("")
- s.install_system_packages([])
- s.close()
diff --git a/packages/python-sdk/tests/test_action.py b/packages/python-sdk/tests/test_action.py
deleted file mode 100644
index 2927e3c52..000000000
--- a/packages/python-sdk/tests/test_action.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from e2b import Sandbox
-
-
-def test_add_action():
- sandbox = Sandbox()
-
- sandbox.add_action(name="test", action=lambda sbx, args: "test")
- assert len(sandbox.actions.values()) == 1
-
- sandbox.remove_action(name="test")
- assert len(sandbox.actions.values()) == 0
-
- sandbox.close()
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index dd3acc102..087a0ec85 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -17,10 +17,10 @@ importers:
devDependencies:
'@typescript-eslint/eslint-plugin':
specifier: ^6.7.2
- version: 6.7.2(@typescript-eslint/[email protected])([email protected])([email protected])
+ version: 6.7.2(@typescript-eslint/[email protected])([email protected])([email protected])
'@typescript-eslint/parser':
specifier: ^6.7.2
changeset:
specifier: ^0.2.6
version: 0.2.6
@@ -321,9 +321,6 @@ importers:
normalize-path:
specifier: ^3.0.0
version: 3.0.0
- openai:
- specifier: ^4.17.4
- version: 4.17.4
openapi-typescript-fetch:
specifier: ^1.1.3
version: 1.1.3
@@ -368,9 +365,6 @@ importers:
knip:
specifier: ^2.34.0
version: 2.35.0
- markdown-it:
- specifier: ^13.0.2
- version: 13.0.2
npm-check-updates:
specifier: ^16.14.6
version: 16.14.6
@@ -3031,7 +3025,7 @@ packages:
'@types/node': 18.18.6
dev: true
- /@typescript-eslint/[email protected](@typescript-eslint/[email protected])([email protected])([email protected]):
+ /@typescript-eslint/[email protected](@typescript-eslint/[email protected])([email protected])([email protected]):
resolution: {integrity: sha512-ooaHxlmSgZTM6CHYAFRlifqh1OAr3PAQEwi7lhYhaegbnXrnh7CDcHmc3+ihhbQC7H0i4JF0psI5ehzkF6Yl6Q==}
engines: {node: ^16.0.0 || >=18.0.0}
peerDependencies:
@@ -3043,10 +3037,10 @@ packages:
optional: true
dependencies:
'@eslint-community/regexpp': 4.8.1
- '@typescript-eslint/parser': 6.7.2([email protected])([email protected])
+ '@typescript-eslint/parser': 6.7.2([email protected])([email protected])
'@typescript-eslint/scope-manager': 6.7.2
- '@typescript-eslint/type-utils': 6.7.2([email protected])([email protected])
- '@typescript-eslint/utils': 6.7.2([email protected])([email protected])
+ '@typescript-eslint/type-utils': 6.7.2([email protected])([email protected])
+ '@typescript-eslint/utils': 6.7.2([email protected])([email protected])
'@typescript-eslint/visitor-keys': 6.7.2
debug: 4.3.4
eslint: 8.49.0
@@ -3054,8 +3048,8 @@ packages:
ignore: 5.2.4
natural-compare: 1.4.0
semver: 7.5.4
- ts-api-utils: 1.0.3([email protected])
- typescript: 5.4.3
+ ts-api-utils: 1.0.3([email protected])
+ typescript: 5.4.4
transitivePeerDependencies:
- supports-color
dev: true
@@ -3110,7 +3104,7 @@ packages:
- supports-color
dev: true
resolution: {integrity: sha512-KA3E4ox0ws+SPyxQf9iSI25R6b4Ne78ORhNHeVKrPQnoYsb9UhieoiRoJgrzgEeKGOXhcY1i8YtOeCHHTDa6Fw==}
engines: {node: ^16.0.0 || >=18.0.0}
peerDependencies:
@@ -3122,11 +3116,11 @@ packages:
dependencies:
'@typescript-eslint/scope-manager': 6.7.2
'@typescript-eslint/types': 6.7.2
- '@typescript-eslint/typescript-estree': 6.7.2([email protected])
+ '@typescript-eslint/typescript-estree': 6.7.2([email protected])
'@typescript-eslint/visitor-keys': 6.7.2
debug: 4.3.4
eslint: 8.49.0
- typescript: 5.4.3
+ typescript: 5.4.4
transitivePeerDependencies:
- supports-color
dev: true
@@ -3176,7 +3170,7 @@ packages:
'@typescript-eslint/visitor-keys': 6.8.0
dev: true
resolution: {integrity: sha512-36F4fOYIROYRl0qj95dYKx6kybddLtsbmPIYNK0OBeXv2j9L5nZ17j9jmfy+bIDHKQgn2EZX+cofsqi8NPATBQ==}
engines: {node: ^16.0.0 || >=18.0.0}
peerDependencies:
@@ -3186,12 +3180,12 @@ packages:
typescript:
optional: true
dependencies:
- '@typescript-eslint/typescript-estree': 6.7.2([email protected])
- '@typescript-eslint/utils': 6.7.2([email protected])([email protected])
+ '@typescript-eslint/typescript-estree': 6.7.2([email protected])
+ '@typescript-eslint/utils': 6.7.2([email protected])([email protected])
debug: 4.3.4
eslint: 8.49.0
- ts-api-utils: 1.0.3([email protected])
- typescript: 5.4.3
+ ts-api-utils: 1.0.3([email protected])
+ typescript: 5.4.4
transitivePeerDependencies:
- supports-color
dev: true
@@ -3274,7 +3268,7 @@ packages:
- supports-color
dev: true
- /@typescript-eslint/[email protected]([email protected]):
+ /@typescript-eslint/[email protected]([email protected]):
resolution: {integrity: sha512-kiJKVMLkoSciGyFU0TOY0fRxnp9qq1AzVOHNeN1+B9erKFCJ4Z8WdjAkKQPP+b1pWStGFqezMLltxO+308dJTQ==}
engines: {node: ^16.0.0 || >=18.0.0}
peerDependencies:
@@ -3289,8 +3283,8 @@ packages:
globby: 11.1.0
is-glob: 4.0.3
semver: 7.5.4
- ts-api-utils: 1.0.3([email protected])
- typescript: 5.4.3
+ ts-api-utils: 1.0.3([email protected])
+ typescript: 5.4.4
transitivePeerDependencies:
- supports-color
dev: true
@@ -3335,7 +3329,7 @@ packages:
- typescript
dev: true
resolution: {integrity: sha512-ZCcBJug/TS6fXRTsoTkgnsvyWSiXwMNiPzBUani7hDidBdj1779qwM1FIAmpH4lvlOZNF3EScsxxuGifjpLSWQ==}
engines: {node: ^16.0.0 || >=18.0.0}
peerDependencies:
@@ -3346,7 +3340,7 @@ packages:
'@types/semver': 7.5.2
'@typescript-eslint/scope-manager': 6.7.2
'@typescript-eslint/types': 6.7.2
- '@typescript-eslint/typescript-estree': 6.7.2([email protected])
+ '@typescript-eslint/typescript-estree': 6.7.2([email protected])
eslint: 8.49.0
semver: 7.5.4
transitivePeerDependencies:
@@ -3590,6 +3584,15 @@ packages:
acorn: ^6.0.0 || ^7.0.0 || ^8.0.0
dependencies:
acorn: 8.10.0
+ dev: false
+
+ resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}
+ peerDependencies:
+ acorn: ^6.0.0 || ^7.0.0 || ^8.0.0
+ dependencies:
+ acorn: 8.11.3
+ dev: true
resolution: {integrity: sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==}
@@ -4932,11 +4935,6 @@ packages:
strip-ansi: 6.0.1
dev: false
- resolution: {integrity: sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q==}
- engines: {node: '>=0.12'}
- dev: true
-
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'}
@@ -5262,7 +5260,7 @@ packages:
eslint-import-resolver-webpack:
optional: true
dependencies:
- '@typescript-eslint/parser': 6.7.2([email protected])([email protected])
+ '@typescript-eslint/parser': 6.7.2([email protected])([email protected])
debug: 3.2.7
eslint: 8.49.0
eslint-import-resolver-node: 0.3.9
@@ -5280,7 +5278,7 @@ packages:
'@typescript-eslint/parser':
optional: true
dependencies:
- '@typescript-eslint/parser': 6.7.2([email protected])([email protected])
+ '@typescript-eslint/parser': 6.7.2([email protected])([email protected])
array-includes: 3.1.7
array.prototype.findlastindex: 1.2.3
array.prototype.flat: 1.3.2
@@ -5374,7 +5372,7 @@ packages:
'@typescript-eslint/eslint-plugin':
optional: true
dependencies:
- '@typescript-eslint/eslint-plugin': 6.7.2(@typescript-eslint/[email protected])([email protected])([email protected])
+ '@typescript-eslint/eslint-plugin': 6.7.2(@typescript-eslint/[email protected])([email protected])([email protected])
eslint: 8.49.0
eslint-rule-composer: 0.3.0
dev: true
@@ -5455,8 +5453,8 @@ packages:
resolution: {integrity: sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
dependencies:
- acorn: 8.10.0
- acorn-jsx: 5.3.2([email protected])
+ acorn: 8.11.3
+ acorn-jsx: 5.3.2([email protected])
eslint-visitor-keys: 3.4.3
dev: true
@@ -7057,12 +7055,6 @@ packages:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
- resolution: {integrity: sha512-C7bfi1UZmoj8+PQx22XyeXCuBlokoyWQL5pWSP+EI6nzRylyThouddufc2c1NDIcP9k5agmN9fLpA7VNJfIiqw==}
- dependencies:
- uc.micro: 1.0.6
- dev: true
-
resolution: {integrity: sha512-gUD/epcRms75Cw8RT1pUdHugZYM5ce64ucs2GEISABwkRsOQr0q2wm/MV2TKThycIe5e0ytRweW2RZxclogCdQ==}
engines: {node: '>=8'}
@@ -7312,17 +7304,6 @@ packages:
engines: {node: '>=0.10.0'}
dev: false
- resolution: {integrity: sha512-FtwnEuuK+2yVU7goGn/MJ0WBZMM9ZPgU9spqlFs7/A/pDIUNSOQZhUgOqYCficIuR2QaFnrt8LHqBWsbTAoI5w==}
- hasBin: true
- dependencies:
- argparse: 2.0.1
- entities: 3.0.1
- linkify-it: 4.0.1
- mdurl: 1.0.1
- uc.micro: 1.0.6
- dev: true
-
resolution: {integrity: sha512-Z1NL3Tb1M9wH4XESsCDEksWoKTdlUafKc4pt0GRwjUyXaCFZ+dc3g2erqB6zm3szA2IUSi7VnPI+o/9jnxh9hw==}
dev: false
@@ -7521,10 +7502,6 @@ packages:
'@types/mdast': 3.0.12
dev: false
- resolution: {integrity: sha512-/sKlQJCBYVY9Ers9hqzKou4H6V5UWc/M59TH2dvkt+84itfnq7uFOMLpOiOS4ujvHP4etln18fmIxA5R5fll0g==}
- dev: true
-
resolution: {integrity: sha512-2XrOlQeBDUa8GirNHy/Y7BR1h/P+vzk+1G2rzAfqJ+lg6JcEOKMCqsVkpVFSw0hdzpVuj9BnoNeA+aU1XPTkoA==}
dependencies:
@@ -8303,6 +8280,7 @@ packages:
resolution: {integrity: sha512-24vnklJmyRS8ViBNI8KbtK/r/DmXQMRiOMXTNz2nrTnAYUwjmEEbnnpB/+kt+yWRv73bPsSPRFddrcIbAxSiMQ==}
hasBin: true
+ requiresBuild: true
dev: false
@@ -10543,13 +10521,13 @@ packages:
typescript: 5.2.2
dev: true
resolution: {integrity: sha512-wNMeqtMz5NtwpT/UZGY5alT+VoKdSsOOP/kqHFcUW1P/VRhH2wJ48+DN2WwUliNbQ976ETwDL0Ifd2VVvgonvg==}
engines: {node: '>=16.13.0'}
peerDependencies:
typescript: '>=4.2.0'
dependencies:
- typescript: 5.4.3
+ typescript: 5.4.4
dev: true
@@ -10793,8 +10771,10 @@ packages:
hasBin: true
dev: true
- resolution: {integrity: sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA==}
+ resolution: {integrity: sha512-dGE2Vv8cpVvw28v8HCPqyb08EzbBURxDpuhJvTrusShUfGnhHBafDsLdS1EhhxyL6BJQE+2cT3dDPAv+MQ6oLw==}
+ engines: {node: '>=14.17'}
+ hasBin: true
dev: true