### Install E2B SDK Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Install the necessary E2B SDK packages using pip. Ensure you have Python and pip installed. ```bash pip install e2b dotenv ``` -------------------------------- ### Install E2B Python SDK Source: https://github.com/e2b-dev/code-interpreter/blob/main/python/README.md Install the E2B Python SDK using pip. Ensure you have Python and pip installed. ```bash pip install e2b-code-interpreter ``` -------------------------------- ### Install E2B Code Interpreter SDK Source: https://github.com/e2b-dev/code-interpreter/blob/main/js/README.md Install the JavaScript SDK using npm. This is the first step to interact with E2B sandboxes. ```bash npm i @e2b/code-interpreter ``` -------------------------------- ### Sandbox Context Management Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Demonstrates how to create and manage code execution contexts within the E2B sandbox. Includes examples for creating contexts with default and custom settings, running code in isolated contexts, and verifying context isolation. ```APIDOC ## Sandbox Context Creation and Execution ### Description This section covers the creation and management of code execution contexts within the E2B sandbox. It illustrates how to create contexts with default or custom configurations (like language and working directory) and how code execution is isolated between these contexts. ### Method `Sandbox.create_code_context()` (Python) `sandbox.createCodeContext()` (TypeScript) ### Parameters #### Request Body - **language** (string) - Optional - The programming language for the context (e.g., "python", "javascript"). Defaults to "python". - **cwd** (string) - Optional - The current working directory for the context. Defaults to "/app". ### Request Example ```python # Python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: context1 = sandbox.create_code_context() context2 = sandbox.create_code_context(language="javascript", cwd="/root") sandbox.run_code("x = 100", context=context1) result1 = sandbox.run_code("x", context=context1) print(result1.text) # "100" ``` ```typescript // JavaScript/TypeScript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() const context1 = await sandbox.createCodeContext() const context2 = await sandbox.createCodeContext({ language: "javascript", cwd: "/root" }) await sandbox.runCode('x = 100', { context: context1 }) const result1 = await sandbox.runCode('x', { context: context1 }) console.log(result1.text) // "100" ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the code context. - **language** (string) - The programming language of the context. - **cwd** (string) - The current working directory of the context. #### Response Example ```json { "id": "ctx_abc123", "language": "python", "cwd": "/app" } ``` ``` -------------------------------- ### Execute Code in E2B Sandbox Source: https://github.com/e2b-dev/code-interpreter/blob/main/python/README.md Run Python code within an E2B sandbox. This example demonstrates creating a sandbox, running a simple assignment, and then executing code that modifies and prints the variable's value. ```python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: sandbox.run_code("x = 1") execution = sandbox.run_code("x+=1; x") print(execution.text) # outputs 2 ``` -------------------------------- ### Create and Use a Sandbox Instance Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Demonstrates creating a sandbox, running code, and cleaning up. Use the `Sandbox.create()` method to initialize a new sandbox environment. Ensure to call `sandbox.kill()` when done, or use a context manager for automatic cleanup. ```typescript import { Sandbox } from '@e2b/code-interpreter' // Create a new sandbox const sandbox = await Sandbox.create() console.log('Sandbox ID:', sandbox.sandboxId) // Execute code and get results const execution = await sandbox.runCode('x = 1') const result = await sandbox.runCode('x += 1; x') console.log(result.text) // Output: "2" // Clean up when done await sandbox.kill() ``` -------------------------------- ### Python Sandbox Creation and Execution (Async) Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Illustrates asynchronous Python sandbox creation and code execution. Use `AsyncSandbox.create()` for async operations and remember to call `await sandbox.kill()` to release resources. ```python # Python (async) from e2b_code_interpreter import AsyncSandbox sandbox = await AsyncSandbox.create() execution = await sandbox.run_code("x = 1; x") print(execution.text) # Output: "1" await sandbox.kill() ``` -------------------------------- ### Build Custom Sandbox Template Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Build the custom sandbox template with specified resources and logging. Load environment variables for configuration. ```python from dotenv import load_dotenv from .template import template from e2b import Template, default_build_logger load_dotenv() Template.build( template, alias="code-interpreter-custom", cpu_count=2, memory_mb=2048, on_build_logs=default_build_logger(), ) ``` -------------------------------- ### Execute Code with Callbacks and Options Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Demonstrates executing code with various options, including specifying the language, streaming output via callbacks, setting environment variables, and applying timeouts. The `runCode` method handles different execution scenarios. ```typescript // JavaScript/TypeScript - Basic execution import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() // Simple code execution const result = await sandbox.runCode('print("Hello, World!")') console.log(result.logs.stdout) // ["Hello, World!\n"] console.log(result.text) // undefined (print doesn't return a value) // Return value captured const calc = await sandbox.runCode('2 + 2') console.log(calc.text) // "4" // Execute with specific language const jsResult = await sandbox.runCode( 'console.log("From JS"); 42', { language: 'javascript' } ) console.log(jsResult.text) // "42" // Execute with callbacks for streaming output const execution = await sandbox.runCode('for i in range(3): print(i)', { onStdout: (msg) => console.log('stdout:', msg.line), onStderr: (msg) => console.log('stderr:', msg.line), onResult: (result) => console.log('result:', result.text), onError: (error) => console.log('error:', error.name, error.value) }) // Execute with custom environment variables const envResult = await sandbox.runCode( 'import os; print(os.environ["MY_VAR"])', { envs: { MY_VAR: 'custom_value' } } ) // Execute with timeout (milliseconds) const timedResult = await sandbox.runCode('import time; time.sleep(1); "done"', { timeoutMs: 5000 // 5 second timeout }) await sandbox.kill() ``` ```python # Python - Basic execution from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: # Simple execution result = sandbox.run_code("x = 1; x") print(result.text) # "1" # Access stdout/stderr logs result = sandbox.run_code('print("Hello")') print(result.logs.stdout) # ["Hello\n"] print(result.logs.stderr) # [] # Execute with different language js_result = sandbox.run_code( 'console.log("Hello from JS"); 100', language='javascript' ) print(js_result.text) # "100" # With callbacks def on_stdout(msg): print(f"Output: {msg.line}") sandbox.run_code( 'for i in range(3): print(i)', on_stdout=on_stdout ) # With custom environment variables result = sandbox.run_code( 'import os; os.environ["API_KEY"]', envs={"API_KEY": "secret123"} ) # With timeout (seconds) result = sandbox.run_code( 'import time; time.sleep(1); "done"', timeout=10 # 10 seconds ) ``` -------------------------------- ### Create and Manage Code Contexts in Python Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Demonstrates creating isolated code contexts with default or custom settings and running code within them. Contexts are isolated from each other and the default context. ```python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: # Create context with default settings context1 = sandbox.create_code_context() print(f"Context: {context1.id}, {context1.language}, {context1.cwd}") # Create context with specific options context2 = sandbox.create_code_context( language="javascript", cwd="/root" ) # Contexts are isolated from each other sandbox.run_code("x = 100", context=context1) sandbox.run_code("let x = 200", context=context2) result1 = sandbox.run_code("x", context=context1) print(result1.text) # "100" result2 = sandbox.run_code("x", context=context2) print(result2.text) # "200" # Contexts are isolated from the default context sandbox.run_code("y = 50") # Default context result = sandbox.run_code("y", context=context1) print(result.error.name) # "NameError" - y not defined in context1 ``` -------------------------------- ### Python Sandbox Creation and Execution (Sync) Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Shows synchronous Python sandbox creation and code execution using a context manager for automatic resource management. Alternatively, manually manage the sandbox lifecycle with `Sandbox.create()` and `sandbox.kill()`. ```python # Python (sync) from e2b_code_interpreter import Sandbox # Using context manager for automatic cleanup with Sandbox.create() as sandbox: sandbox.run_code("x = 1") execution = sandbox.run_code("x += 1; x") print(execution.text) # Output: "2" # Or manually manage lifecycle sandbox = Sandbox.create() sandbox.run_code("print('Hello')") sandbox.kill() ``` -------------------------------- ### Create Custom Sandbox Template Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Initialize a custom sandbox template by inheriting from a base template. This script defines the template configuration. ```python from e2b import Template template = Template().from_template("code-interpreter-v1") ``` -------------------------------- ### Build Custom Sandbox Script Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Execute the build script to compile the custom sandbox template. This command initiates the sandbox build process. ```bash python build.py ``` -------------------------------- ### Use Custom Sandbox for Code Execution Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Create an instance of the custom sandbox and run Python code within it. Prints the standard output of the execution. ```python from e2b import Sandbox sbx = Sandbox.create(template="code-interpreter-custom") execution = sbx.run_code("print('Hello, World!')") print(execution.logs.stdout) ``` -------------------------------- ### Create and Access DataFrame in Python Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Demonstrates creating a Pandas DataFrame in a Python sandbox and accessing its data and HTML representation. ```python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: result = sandbox.run_code(""" import pandas as pd df = pd.DataFrame({ 'product': ['Laptop', 'Phone', 'Tablet'], 'price': [999, 699, 449], 'stock': [50, 150, 75] }) df """) data = result.results[0] # Access as dictionary if data.data: print("Products:", data.data['product']) print("Prices:", data.data['price']) print("Stock:", data.data['stock']) # HTML representation if data.html: print("HTML table available") # Text representation print("Text repr:", data.text) ``` -------------------------------- ### List Active Code Contexts in Python Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Demonstrates listing all active execution contexts in a sandbox, including default Python and JavaScript contexts. New contexts can be added and verified in the list. ```python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: # List all contexts contexts = sandbox.list_code_contexts() print(f"Total contexts: {len(contexts)}") for ctx in contexts: print(f"ID: {ctx.id}, Language: {ctx.language}, CWD: {ctx.cwd}") # Check default languages languages = [ctx.language for ctx in contexts] assert "python" in languages assert "javascript" in languages # Add a new context new_ctx = sandbox.create_code_context(language="bash") # Verify it's in the list contexts = sandbox.list_code_contexts() assert new_ctx.id in [ctx.id for ctx in contexts] ``` -------------------------------- ### Sandbox.create Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Creates a new sandbox instance for code execution. The sandbox provides an isolated cloud environment with a full Linux OS where you can execute code securely. The sandbox persists state between executions, allowing variables and imports to be referenced across multiple `runCode` calls. ```APIDOC ## Sandbox.create ### Description Creates a new sandbox instance for code execution. The sandbox provides an isolated cloud environment with a full Linux OS where you can execute code securely. The sandbox persists state between executions, allowing variables and imports to be referenced across multiple `runCode` calls. ### Method `Sandbox.create()` (JavaScript/TypeScript), `Sandbox.create()` (Python sync), `AsyncSandbox.create()` (Python async) ### Endpoint N/A (SDK method) ### Request Example ```typescript // JavaScript/TypeScript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() ``` ```python # Python (sync) from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: pass ``` ```python # Python (async) from e2b_code_interpreter import AsyncSandbox sandbox = await AsyncSandbox.create() ``` ### Response - **sandbox** (Sandbox instance) - An instance of the Sandbox class ready for code execution. ``` -------------------------------- ### Access DataFrame Data in JavaScript Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Shows how to create a Pandas DataFrame in a sandbox and access its data and HTML representation using JavaScript. ```javascript // Access DataFrame data const dataResult = result.results[0] if (dataResult.data) { console.log('DataFrame columns:', Object.keys(dataResult.data)) console.log('Names:', dataResult.data.name) // ['Alice', 'Bob', 'Charlie', 'Diana'] console.log('Ages:', dataResult.data.age) // [25, 30, 35, 28] console.log('Cities:', dataResult.data.city) // ['NYC', 'LA', 'Chicago', 'Houston'] } // HTML representation also available if (dataResult.html) { console.log('HTML table available for rendering') } await sandbox.kill() ``` -------------------------------- ### Reconnect to Existing Sandbox in Python Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Shows how to reconnect to an existing sandbox using its ID in Python, allowing for resuming work or managing sandbox lifecycle. ```python # Python from e2b_code_interpreter import Sandbox # Create and configure sandbox sandbox1 = Sandbox.create() sandbox_id = sandbox1.sandbox_id sandbox1.run_code("data = [1, 2, 3, 4, 5]") # Reconnect to the same sandbox sandbox2 = Sandbox.connect(sandbox_id) result = sandbox2.run_code("sum(data)") print(result.text) # "15" sandbox2.kill() ``` -------------------------------- ### Execute Code in E2B Sandbox Source: https://github.com/e2b-dev/code-interpreter/blob/main/js/README.md Create a sandbox instance and run code within it. The `runCode` method executes a string of code and returns the execution result. ```typescript import { Sandbox } from '@e2b/code-interpreter' const sbx = await Sandbox.create() await sbx.runCode('x = 1') const execution = await sbx.runCode('x+=1; x') console.log(execution.text) // outputs 2 ``` -------------------------------- ### List Code Contexts Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Retrieves a list of all currently active execution contexts within the sandbox. Includes default Python and JavaScript contexts. ```APIDOC ## sandbox.listCodeContexts ### Description Returns a list of all active execution contexts in the sandbox. By default, sandboxes include pre-created Python and JavaScript contexts. This method allows you to inspect and manage the available execution environments. ### Method `sandbox.list_code_contexts()` (Python) `sandbox.listCodeContexts()` (TypeScript) ### Endpoint N/A (This is a client-side method call) ### Parameters None ### Request Example ```typescript // JavaScript/TypeScript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() const contexts = await sandbox.listCodeContexts() console.log('Number of contexts:', contexts.length) for (const ctx of contexts) { console.log(`Context: ${ctx.id}`) console.log(` Language: ${ctx.language}`) console.log(` Working directory: ${ctx.cwd}`) } await sandbox.kill() ``` ```python # Python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: contexts = sandbox.list_code_contexts() print(f"Total contexts: {len(contexts)}") for ctx in contexts: print(f"ID: {ctx.id}, Language: {ctx.language}, CWD: {ctx.cwd}") ``` ### Response #### Success Response (200) - **contexts** (array) - A list of context objects. - **id** (string) - Unique identifier for the code context. - **language** (string) - The programming language of the context. - **cwd** (string) - The current working directory of the context. #### Response Example ```json [ { "id": "ctx_default_python", "language": "python", "cwd": "/app" }, { "id": "ctx_default_javascript", "language": "javascript", "cwd": "/app" } ] ``` ``` -------------------------------- ### List Active Code Contexts in TypeScript Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Shows how to list all active execution contexts in a sandbox, including default Python and JavaScript contexts. New contexts can be added and verified in the list. ```typescript // JavaScript/TypeScript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() // List default contexts const contexts = await sandbox.listCodeContexts() console.log('Number of contexts:', contexts.length) for (const ctx of contexts) { console.log(`Context: ${ctx.id}`) console.log(` Language: ${ctx.language}`) console.log(` Working directory: ${ctx.cwd}`) } // Default contexts include Python and JavaScript const languages = contexts.map(c => c.language) console.log('Has Python:', languages.includes('python')) // true console.log('Has JavaScript:', languages.includes('javascript')) // true // Create additional context and verify it appears in list const newContext = await sandbox.createCodeContext({ language: 'r' }) const updatedContexts = await sandbox.listCodeContexts() console.log('Updated count:', updatedContexts.length) await sandbox.kill() ``` -------------------------------- ### Handle Code Execution Errors in Python Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Illustrates how to handle code execution errors, including syntax errors, runtime errors, and timeouts, when using the Python SDK. ```python # Python from e2b_code_interpreter import Sandbox from e2b import TimeoutException, SandboxException, NotFoundException with Sandbox.create() as sandbox: # Code execution errors (captured in result.error) result = sandbox.run_code("1 / 0") if result.error: print(f"Error: {result.error.name}") # "ZeroDivisionError" print(f"Message: {result.error.value}") # "division by zero" print(f"Traceback: {result.error.traceback}") # Type errors result = sandbox.run_code("'string' + 5") if result.error: print(f"TypeError: {result.error.value}") # Handle timeouts (raises exception) try: sandbox.run_code("import time; time.sleep(100)", timeout=1) except TimeoutException as e: print(f"Timeout: {e}") # Handle sandbox errors try: bad_sandbox = Sandbox.connect("invalid-sandbox-id") except NotFoundException as e: print(f"Sandbox not found: {e}") except SandboxException as e: print(f"Sandbox error: {e}") ``` -------------------------------- ### sandbox.runCode Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Executes code in the sandbox and returns an `Execution` object containing results, logs, and any errors. By default, code runs in a Python context, but you can specify other languages. The method supports streaming output through callbacks and maintains state between executions. ```APIDOC ## sandbox.runCode ### Description Executes code in the sandbox and returns an `Execution` object containing results, logs, and any errors. By default, code runs in a Python context, but you can specify other languages. The method supports streaming output through callbacks and maintains state between executions. ### Method `sandbox.runCode(code, options)` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **code** (string) - Required - The code to execute. - **options** (object) - Optional - Configuration for the code execution. - **language** (string) - Optional - The programming language of the code (e.g., 'python', 'javascript'). Defaults to 'python'. - **envs** (object) - Optional - Environment variables to set for the execution. - **timeoutMs** (number) - Optional - Timeout for the execution in milliseconds (JavaScript/TypeScript). - **timeout** (number) - Optional - Timeout for the execution in seconds (Python). - **onStdout** (function) - Optional - Callback for standard output streams. - **onStderr** (function) - Optional - Callback for standard error streams. - **onResult** (function) - Optional - Callback for the final result of the execution. - **onError** (function) - Optional - Callback for execution errors. ### Request Example ```typescript // JavaScript/TypeScript const result = await sandbox.runCode('2 + 2') console.log(result.text) // "4" const jsResult = await sandbox.runCode('console.log("From JS"); 42', { language: 'javascript' }) console.log(jsResult.text) // "42" ``` ```python # Python result = sandbox.run_code("x = 1; x") print(result.text) # "1" js_result = sandbox.run_code("console.log('Hello from JS'); 100", language='javascript') print(js_result.text) # "100" ``` ### Response - **Execution object** - Contains results, logs, and errors from the code execution. - **text** (string) - The return value of the code execution. - **logs** (object) - Contains stdout and stderr. - **stdout** (array) - Array of strings from standard output. - **stderr** (array) - Array of strings from standard error. - **error** (object) - Information about any execution errors. #### Response Example ```json { "text": "4", "logs": { "stdout": [], "stderr": [] }, "error": null } ``` ``` -------------------------------- ### Handle Code Execution Errors in JavaScript Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Demonstrates how to handle various errors during code execution in a JavaScript sandbox, including syntax errors, runtime errors, and timeouts. ```javascript // JavaScript/TypeScript import { Sandbox, TimeoutError, SandboxError } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() // Handle code execution errors (errors in user code) const result = await sandbox.runCode('undefined_variable + 1') if (result.error) { console.log('Error type:', result.error.name) // "NameError" console.log('Error message:', result.error.value) // "name 'undefined_variable' is not defined" console.log('Traceback:', result.error.traceback) } // Syntax errors const syntaxResult = await sandbox.runCode('def broken(') if (syntaxResult.error) { console.log('Syntax error:', syntaxResult.error.name) // "SyntaxError" } // Handle timeouts try { await sandbox.runCode('import time; time.sleep(100)', { timeoutMs: 1000 // 1 second timeout }) } catch (error) { if (error instanceof TimeoutError) { console.log('Execution timed out') } } // Handle SDK/infrastructure errors try { const badSandbox = await Sandbox.connect('invalid-id') } catch (error) { if (error instanceof SandboxError) { console.log('Sandbox error:', error.message) } } await sandbox.kill() ``` -------------------------------- ### Restart Code Context in Python Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Shows how to restart a code context in Python to clear its state, including variables and imports, while keeping the same context ID. This effectively resets the execution environment. ```python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: # Create context and set up state context = sandbox.create_code_context() sandbox.run_code("x = 42", context=context) sandbox.run_code("import pandas as pd", context=context) # Verify state result = sandbox.run_code("x", context=context) print(result.text) # "42" # Restart context (can use context object or ID string) sandbox.restart_code_context(context) # or context.id # State is cleared result = sandbox.run_code("x", context=context) assert result.error is not None print(result.error.name) # "NameError" print(result.error.value) # "name 'x' is not defined" ``` -------------------------------- ### sandbox.kill Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Terminates the sandbox instance, releasing associated resources. ```APIDOC ## sandbox.kill ### Description Terminates the sandbox instance, releasing associated resources. ### Method `sandbox.kill()` ### Endpoint N/A (SDK method) ### Request Example ```typescript // JavaScript/TypeScript await sandbox.kill() ``` ```python # Python sandbox.kill() ``` ### Response None ``` -------------------------------- ### Set E2B API Key Environment Variable Source: https://github.com/e2b-dev/code-interpreter/blob/main/js/README.md Set your E2B API key as an environment variable. This key is required for authentication when using the SDK. ```bash E2B_API_KEY=e2b_*** ``` -------------------------------- ### Restart Code Context Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Restarts a specified code context, clearing its state (variables, imports) while retaining the context ID. Useful for resetting execution environments. ```APIDOC ## sandbox.restartCodeContext ### Description Restarts a context, clearing all its state (variables, imports, etc.) while keeping the same context ID. This is useful for resetting the execution state of a context without the overhead of creating a new one. ### Method `sandbox.restart_code_context(context_id_or_object)` (Python) `sandbox.restartCodeContext(contextIdOrObject)` (TypeScript) ### Parameters #### Path Parameters - **context_id_or_object** (string | object) - Required - The ID of the context to restart, or the context object itself. ### Request Example ```typescript // JavaScript/TypeScript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() const context = await sandbox.createCodeContext() await sandbox.runCode('x = 42', { context }) // Verify state exists let result1 = await sandbox.runCode('x', { context }) console.log(result1.text) // "42" // Restart the context await sandbox.restartCodeContext(context.id) // State is cleared let result2 = await sandbox.runCode('x', { context }) console.log(result2.error?.name) // "NameError" await sandbox.kill() ``` ```python # Python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: context = sandbox.create_code_context() sandbox.run_code("x = 42", context=context) # Verify state result = sandbox.run_code("x", context=context) print(result.text) # "42" # Restart context sandbox.restart_code_context(context) # or context.id # State is cleared result = sandbox.run_code("x", context=context) assert result.error is not None print(result.error.name) # "NameError" ``` ### Response #### Success Response (200) Indicates that the context was successfully restarted. No specific data is returned. #### Response Example (No response body for success) ``` -------------------------------- ### Reconnect to Existing Sandbox in TypeScript Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Demonstrates reconnecting to a previously created sandbox using its ID in TypeScript. This is useful for managing sandbox lifecycle across different parts of an application. ```typescript // JavaScript/TypeScript import { Sandbox } from '@e2b/code-interpreter' // Create initial sandbox and do some work const sandbox1 = await Sandbox.create() const sandboxId = sandbox1.sandboxId console.log('Created sandbox:', sandboxId) await sandbox1.runCode('x = 42') // Later, reconnect to the same sandbox const sandbox2 = await Sandbox.connect(sandboxId) const result = await sandbox2.runCode('x') console.log('Retrieved value:', result.text) // "42" // Both references point to the same sandbox await sandbox2.kill() ``` -------------------------------- ### Restart Code Context in TypeScript Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Illustrates restarting a specific code context to clear its state, including variables and imports, while retaining the same context ID. This is useful for resetting execution environments. ```typescript // JavaScript/TypeScript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() // Create and populate a context const context = await sandbox.createCodeContext() await sandbox.runCode('x = 42', { context }) await sandbox.runCode('import numpy as np', { context }) // Verify state exists const result1 = await sandbox.runCode('x', { context }) console.log(result1.text) // "42" // Restart the context await sandbox.restartCodeContext(context.id) // State is cleared - variable no longer exists const result2 = await sandbox.runCode('x', { context }) console.log(result2.error?.name) // "NameError" console.log(result2.error?.value) // "name 'x' is not defined" // Imports are also cleared const result3 = await sandbox.runCode('np.array([1,2,3])', { context }) console.log(result3.error?.name) // "NameError" await sandbox.kill() ``` -------------------------------- ### Execute Python Code in TypeScript Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Executes Python code within the sandbox. The default language is Python. Results are returned as text. ```typescript // JavaScript/TypeScript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() // Python (default) const pyResult = await sandbox.runCode(` def greet(name): return f"Hello, {name}!" greet("World") `) console.log('Python:', pyResult.text) // "Hello, World!" // JavaScript const jsResult = await sandbox.runCode(` const numbers = [1, 2, 3, 4, 5]; numbers.map(n => n * 2).reduce((a, b) => a + b); `, { language: 'javascript' }) console.log('JavaScript:', jsResult.text) // "30" // TypeScript const tsResult = await sandbox.runCode(` interface User { name: string; age: number } const user: User = { name: "Alice", age: 30 }; JSON.stringify(user); `, { language: 'typescript' }) console.log('TypeScript:', tsResult.text) // Bash const bashResult = await sandbox.runCode(` echo "Current directory: $(pwd)" ls -la | head -5 `, { language: 'bash' }) console.log('Bash stdout:', bashResult.logs.stdout) // R const rResult = await sandbox.runCode(` x <- c(1, 2, 3, 4, 5) mean(x) `, { language: 'r' }) console.log('R:', rResult.text) // "[1] 3" // Java const javaResult = await sandbox.runCode(` public class Main { public static void main(String[] args) { System.out.println("Hello from Java!"); } } `, { language: 'java' }) console.log('Java stdout:', javaResult.logs.stdout) await sandbox.kill() ``` -------------------------------- ### Create and Use Isolated Code Contexts in TypeScript Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Manage independent code execution environments using `createCodeContext`. Each context maintains its own state, preventing variable leakage between sessions. Supports Python and JavaScript. ```typescript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() // Create a new context with default settings (Python, /home/user) const context1 = await sandbox.createCodeContext() console.log('Context ID:', context1.id) console.log('Language:', context1.language) // "python" console.log('Working dir:', context1.cwd) // "/home/user" // Create context with specific options const context2 = await sandbox.createCodeContext({ language: 'javascript', cwd: '/root' }) // Use contexts independently - variables don't leak between contexts await sandbox.runCode('x = 100', { context: context1 }) await sandbox.runCode('let x = 200', { context: context2 }) const result1 = await sandbox.runCode('x', { context: context1 }) console.log(result1.text) // "100" (Python context) const result2 = await sandbox.runCode('x', { context: context2 }) console.log(result2.text) // "200" (JavaScript context) // Default context is separate from custom contexts await sandbox.runCode('y = 50') // Uses default Python context const defaultResult = await sandbox.runCode('y') console.log(defaultResult.text) // "50" // y doesn't exist in context1 const isolatedResult = await sandbox.runCode('y', { context: context1 }) console.log(isolatedResult.error?.name) // "NameError" await sandbox.kill() ``` -------------------------------- ### Handle Code Execution Results in TypeScript Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Access return values, display outputs (like plots and DataFrames), logs, and errors from code execution. Use the `execution` object to inspect results in various formats. ```typescript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() // Execution object structure const execution = await sandbox.runCode( ` import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y) plt.title("Sine Wave") plt.show() "computation complete" ` ) // Access the main result (last expression value) console.log(execution.text) // "computation complete" // Access all results (including display outputs) for (const result of execution.results) { console.log('Is main result:', result.isMainResult) console.log('Available formats:', result.formats()) if (result.png) { console.log('PNG image available (base64)') } if (result.text) { console.log('Text:', result.text) } if (result.chart) { console.log('Chart type:', result.chart.type) console.log('Chart title:', result.chart.title) } } // Access logs console.log('stdout:', execution.logs.stdout) console.log('stderr:', execution.logs.stderr) // Check for errors if (execution.error) { console.log('Error name:', execution.error.name) console.log('Error value:', execution.error.value) console.log('Traceback:', execution.error.traceback) } // Execution count console.log('Execution count:', execution.executionCount) await sandbox.kill() ``` -------------------------------- ### Handle Code Execution Results in Python Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Process execution results including logs, various data formats (images, DataFrames, charts), and errors. The `execution` object provides access to `stdout`, `stderr`, and detailed result objects. ```python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: # Execute code with multiple outputs execution = sandbox.run_code(""" import matplotlib.pyplot as plt import pandas as pd import numpy as np # Create a DataFrame df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) print("DataFrame created") # Create a plot plt.figure(figsize=(8, 6)) plt.plot([1, 2, 3], [1, 4, 9]) plt.title("Sample Plot") plt.show() # Return the DataFrame df """) # Access logs print("stdout:", execution.logs.stdout) # ["DataFrame created\n"] print("stderr:", execution.logs.stderr) # [] # Access results for result in execution.results: print("Formats available:", list(result.formats())) # Check for image data if result.png: print("PNG image available") # Check for DataFrame data if result.data: print("DataFrame data:", result.data) # Check for chart data if result.chart: print("Chart type:", result.chart.type) # Access the main result (last expression) print("Main result text:", execution.text) # Error handling error_execution = sandbox.run_code("undefined_variable") if error_execution.error: print("Error:", error_execution.error.name) # "NameError" print("Message:", error_execution.error.value) # "name 'undefined_variable' is not defined" print("Traceback:", error_execution.error.traceback) ``` -------------------------------- ### Execute Python Code in Python Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Executes Python code using the default Python interpreter. Supports specifying other languages like JavaScript and Bash. ```python # Python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: # Python (default) py_result = sandbox.run_code(""" def factorial(n): return 1 if n <= 1 else n * factorial(n-1) factorial(5) """ ) print("Python:", py_result.text) # "120" # JavaScript js_result = sandbox.run_code(""" const arr = [1, 2, 3]; arr.map(x => x ** 2).join(', '); """, language="javascript") print("JavaScript:", js_result.text) # "1, 4, 9" # Bash bash_result = sandbox.run_code(""" echo "Files in home:" ls ~ """, language="bash") print("Bash:", bash_result.logs.stdout) # R r_result = sandbox.run_code(""" v <- c(10, 20, 30, 40, 50) summary(v) """, language="r") print("R:", r_result.text) ``` -------------------------------- ### Extract Data from Matplotlib Charts (Python) Source: https://context7.com/e2b-dev/code-interpreter/llms.txt This Python snippet demonstrates extracting data from matplotlib charts using the E2B Code Interpreter SDK. It covers line, bar, and scatter charts, showing how to access chart titles, labels, scales, and data points. ```python from e2b_code_interpreter import Sandbox from e2b_code_interpreter.charts import LineChart, BarChart, PieChart, ChartType with Sandbox.create() as sandbox: # Line chart result = sandbox.run_code(""" import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) plt.plot(x, np.exp(-x/5) * np.cos(2*x), label='Damped oscillation') plt.xlabel("Time (s)") plt.ylabel("Amplitude") plt.title("Damped Oscillation") plt.show() """ ) chart = result.results[0].chart if isinstance(chart, LineChart): print(f"Title: {chart.title}") print(f"X Label: {chart.x_label}, Y Label: {chart.y_label}") print(f"X Scale: {chart.x_scale}, Y Scale: {chart.y_scale}") for line in chart.elements: print(f"Line '{line.label}': {len(line.points)} points") # Access individual points for x, y in line.points[:3]: # First 3 points print(f" ({x}, {y})") # Bar chart result = sandbox.run_code(""" import matplotlib.pyplot as plt plt.bar(['Q1', 'Q2', 'Q3', 'Q4'], [100, 150, 120, 180]) plt.title("Quarterly Sales") plt.show() """ ) bar_chart = result.results[0].chart if isinstance(bar_chart, BarChart): for bar in bar_chart.elements: print(f"{bar.label}: {bar.value} (group: {bar.group})") # Scatter chart result = sandbox.run_code(""" import matplotlib.pyplot as plt import numpy as np x = np.random.randn(50) y = x + np.random.randn(50) * 0.5 plt.scatter(x, y) plt.title("Correlation Plot") plt.show() """ ) scatter_chart = result.results[0].chart print(f"Scatter chart type: {scatter_chart.type}") ``` -------------------------------- ### Extract Data from Matplotlib Charts (TypeScript) Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Use this snippet to extract structured data from various matplotlib chart types like line, bar, and pie charts. Ensure the sandbox is created and the code interpreter is used to run the plotting code. ```typescript import { Sandbox, ChartType } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() // Create a line chart const lineResult = await sandbox.runCode(` import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2*np.pi, 50) plt.figure(figsize=(10, 6)) plt.plot(x, np.sin(x), label='sin(x)') plt.plot(x, np.cos(x), label='cos(x)') plt.xlabel("Angle (radians)") plt.ylabel("Value") plt.title("Trigonometric Functions") plt.legend() plt.show() `) const chart = lineResult.results[0].chart if (chart && chart.type === ChartType.LINE) { console.log('Title:', chart.title) // "Trigonometric Functions" console.log('X Label:', chart.x_label) // "Angle (radians)" console.log('Y Label:', chart.y_label) // "Value" console.log('X Scale:', chart.x_scale) // "linear" console.log('Y Scale:', chart.y_scale) // "linear" // Access data points for each line for (const line of chart.elements) { console.log(`Line: ${line.label}`) console.log(` Points: ${line.points.length}`) console.log(` First point: (${line.points[0][0]}, ${line.points[0][1]})`) } } // Create a bar chart const barResult = await sandbox.runCode(` import matplotlib.pyplot as plt categories = ['A', 'B', 'C', 'D'] values = [23, 45, 56, 78] plt.bar(categories, values) plt.title("Category Values") plt.xlabel("Category") plt.ylabel("Value") plt.show() `) const barChart = barResult.results[0].chart if (barChart && barChart.type === ChartType.BAR) { console.log('Bar chart elements:') for (const bar of barChart.elements) { console.log(` ${bar.label}: ${bar.value}`) } } // Create a pie chart const pieResult = await sandbox.runCode(` import matplotlib.pyplot as plt sizes = [30, 25, 20, 15, 10] labels = ['Python', 'JavaScript', 'Java', 'C++', 'Other'] plt.pie(sizes, labels=labels) plt.title("Language Usage") plt.show() `) const pieChart = pieResult.results[0].chart if (pieChart && pieChart.type === ChartType.PIE) { for (const slice of pieChart.elements) { console.log(`${slice.label}: angle=${slice.angle}, radius=${slice.radius}`) } } await sandbox.kill() ``` -------------------------------- ### Remove Code Context in Python Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Removes a code context from the sandbox using its ID or context object. The context becomes unusable after removal. ```python # Python from e2b_code_interpreter import Sandbox with Sandbox.create() as sandbox: # Create a context context = sandbox.create_code_context() context_id = context.id # Verify it exists contexts = sandbox.list_code_contexts() assert context_id in [c.id for c in contexts] # Remove the context sandbox.remove_code_context(context) # or context_id # Verify removal contexts = sandbox.list_code_contexts() assert context_id not in [c.id for c in contexts] ``` -------------------------------- ### Extract Data from Pandas DataFrames (TypeScript) Source: https://context7.com/e2b-dev/code-interpreter/llms.txt This TypeScript snippet shows how to extract data from pandas DataFrames using the E2B Code Interpreter SDK. It's useful for processing tabular data programmatically after it has been generated or loaded within the sandbox. ```typescript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() const result = await sandbox.runCode(` import pandas as pd import numpy as np ``` -------------------------------- ### Remove Code Context in TypeScript Source: https://context7.com/e2b-dev/code-interpreter/llms.txt Removes a code context from the sandbox. The context ID can no longer be used after removal. Accepts either a context object or its ID string. ```typescript // JavaScript/TypeScript import { Sandbox } from '@e2b/code-interpreter' const sandbox = await Sandbox.create() // Create a context const context = await sandbox.createCodeContext() const contextId = context.id // Verify it exists let contexts = await sandbox.listCodeContexts() console.log('Context exists:', contexts.some(c => c.id === contextId)) // true // Remove the context (accepts context object or ID string) await sandbox.removeCodeContext(context) // or context.id // Verify it's removed contexts = await sandbox.listCodeContexts() console.log('Context exists:', contexts.some(c => c.id === contextId)) // false await sandbox.kill() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.