### Install Dependencies and Run Example Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/playwright-in-e2b/README.md Installs project dependencies and starts the Playwright execution within the E2B sandbox. ```bash npm install npm run start ``` -------------------------------- ### Run the Example with npm Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/firecrawl-scrape-and-analyze-airbnb-data/README.md Execute this command to start the main script of the example after setting up your environment variables. ```bash npm run start ``` -------------------------------- ### Start Vite Dev Server and Get Preview URL Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/homepage_vite_basic_updated.ipynb Starts a Vite development server in the sandbox, installs dependencies, and returns the public preview URL. Includes a readiness check for the server. ```python async def start_preview(session, version_name: str) -> str: print(f"[preview:{version_name}] starting Vite dev server") result = await session.exec( "sh", "-lc", ( "npm install >/tmp/e2b-example-npm-install.log 2>&1 && " "nohup npm run dev -- --host 0.0.0.0 --port 4173 " ">/tmp/e2b-example-vite.log 2>&1 &" ), shell=False, timeout=120, ) if not result.ok(): raise RuntimeError(f"Failed to start preview server: {result.stderr}") endpoint = await session.resolve_exposed_port(PREVIEW_PORT) preview_url = endpoint.url_for("http") for _ in range(30): probe = await session.exec( "sh", "-lc", f"curl -fsS http://127.0.0.1:{PREVIEW_PORT}/ >/dev/null", shell=False, timeout=5, ) if probe.ok(): break await __import__("asyncio").sleep(1) else: raise RuntimeError("Preview server did not become ready in time") print(f"[preview:{version_name}] {preview_url}") return preview_url ``` -------------------------------- ### Setup Environment and Install Dependencies Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/forecast_model_bakeoff.ipynb Configures the project root, adds necessary paths to sys.path, loads environment variables from a .env file if present, and installs required E2B-related modules using pip. ```python import importlib import os import subprocess import sys from pathlib import Path repo_root = Path.cwd() if not (repo_root / "src" / "agents").exists(): for candidate in [Path.cwd(), *Path.cwd().parents]: if (candidate / "src" / "agents").exists(): repo_root = candidate break if (candidate / "openai-agents-python-preview" / "src" / "agents").exists(): repo_root = candidate / "openai-agents-python-preview" break src_root = repo_root / "src" if str(repo_root) not in sys.path: sys.path.insert(0, str(repo_root)) if str(src_root) not in sys.path: sys.path.insert(0, str(src_root)) env_path = None for candidate in [Path.cwd(), *Path.cwd().parents, repo_root, *repo_root.parents]: maybe_env = candidate / ".env" if maybe_env.exists(): env_path = maybe_env break if env_path is not None: try: from dotenv import load_dotenv load_dotenv(env_path, override=False) except Exception: for raw_line in env_path.read_text().splitlines(): line = raw_line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'")) required_modules = ["agents", "openai", "e2b", "e2b_code_interpreter"] missing_modules = [ module_name for module_name in required_modules if importlib.util.find_spec(module_name) is None ] if missing_modules: subprocess.check_call( [sys.executable, "-m", "pip", "install", "-q", "-e", str(repo_root) + "[e2b]"] ) ``` -------------------------------- ### Start Development Server Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/watsonx-ai-code-interpreter-js/README.md Start the development server to run the application. This command is used after dependencies are installed and environment variables are set. ```bash npm run dev ``` -------------------------------- ### Setup and Environment Configuration Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/data_science_parallel_workbench.ipynb Configures the repository root, adds necessary paths to sys.path, loads environment variables from a .env file if present, and installs required modules using pip. ```python import importlib import json import os import subprocess import sys from pathlib import Path repo_root = Path.cwd() if not (repo_root / "src" / "agents").exists(): for candidate in [Path.cwd(), *Path.cwd().parents]: if (candidate / "src" / "agents").exists(): repo_root = candidate break if (candidate / "openai-agents-python-preview" / "src" / "agents").exists(): repo_root = candidate / "openai-agents-python-preview" break src_root = repo_root / "src" if str(repo_root) not in sys.path: sys.path.insert(0, str(repo_root)) if str(src_root) not in sys.path: sys.path.insert(0, str(src_root)) env_path = None for candidate in [Path.cwd(), *Path.cwd().parents, repo_root, *repo_root.parents]: maybe_env = candidate / ".env" if maybe_env.exists(): env_path = maybe_env break if env_path is not None: try: from dotenv import load_dotenv load_dotenv(env_path, override=False) except Exception: for raw_line in env_path.read_text().splitlines(): line = raw_line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'")) required_modules = ["agents", "openai", "e2b", "e2b_code_interpreter"] missing_modules = [] for module_name in required_modules: try: importlib.import_module(module_name) except Exception: missing_modules.append(module_name) if missing_modules: subprocess.check_call([sys.executable, "-m", "pip", "install", "-e", f"{repo_root}[e2b]"]) print(f"Using repo root: {repo_root}") ``` -------------------------------- ### Connect MCP Client with Custom Filesystem Server Source: https://context7.com/e2b-dev/e2b-cookbook/llms.txt Enable the MCP gateway and install a custom filesystem server from GitHub. This example demonstrates calling a tool on the custom server to list directory contents. ```typescript // TypeScript — MCP with custom filesystem server from GitHub import Sandbox from 'e2b' import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' const sandbox = await Sandbox.create({ mcp: { 'github/modelcontextprotocol/servers': { installCmd: 'npm install', runCmd: 'npx -y @modelcontextprotocol/server-filesystem /root', }, }, timeoutMs: 600_000, }) const client = new Client({ name: 'fs-client', version: '1.0.0' }) const transport = new StreamableHTTPClientTransport( new URL(sandbox.getMcpUrl()), { requestInit: { headers: { Authorization: `Bearer ${await sandbox.getMcpToken()}` } } }, ) await client.connect(transport) const result = await client.callTool({ name: 'list_directory', arguments: { path: '/' } }) console.log('Root directory:', result.content) await sandbox.kill() ``` -------------------------------- ### Setup E2B Environment and Dependencies Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/ci_cd_parallel_runner.ipynb Initializes the project environment, loads environment variables, checks for required Python modules, and installs them if missing. This script ensures the kernel has the necessary dependencies to run E2B agents. ```python import importlib import json import os import subprocess import sys from pathlib import Path repo_root = Path.cwd() if not (repo_root / "src" / "agents").exists(): for candidate in [Path.cwd(), *Path.cwd().parents]: if (candidate / "src" / "agents").exists(): repo_root = candidate break if (candidate / "openai-agents-python-preview" / "src" / "agents").exists(): repo_root = candidate / "openai-agents-python-preview" break src_root = repo_root / "src" if str(repo_root) not in sys.path: sys.path.insert(0, str(repo_root)) if str(src_root) not in sys.path: sys.path.insert(0, str(src_root)) env_path = None for candidate in [Path.cwd(), *Path.cwd().parents, repo_root, *repo_root.parents]: maybe_env = candidate / ".env" if maybe_env.exists(): env_path = maybe_env break if env_path is not None: try: from dotenv import load_dotenv load_dotenv(env_path, override=False) except Exception: for raw_line in env_path.read_text().splitlines(): line = raw_line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'")) required_modules = ["agents", "openai", "e2b", "e2b_code_interpreter"] missing_modules = [] for module_name in required_modules: try: importlib.import_module(module_name) except Exception: missing_modules.append(module_name) if missing_modules: print(f"Installing missing modules into kernel env {sys.executable}: {missing_modules}") subprocess.check_call([sys.executable, "-m", "pip", "install", "-e", f"{repo_root}[e2b]"]) importlib.invalidate_caches() print("Install complete. If imports still fail, restart the kernel and rerun from the top.") else: print(f"Kernel env already has required modules: {required_modules}") print(f"Using repo root: {repo_root}") print(f"OPENAI_API_KEY set: {bool(os.getenv('OPENAI_API_KEY'))}") print(f"E2B_API_KEY set: {bool(os.getenv('E2B_API_KEY'))}") ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/stirrup-python/README.md Use 'uv sync' to install project dependencies. Ensure you have uv installed and configured for your project. ```bash uv sync ``` -------------------------------- ### Run Example with UV Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-codex-in-sandbox-python/README.md Executes the Python example script using the 'uv run' command after activating the virtual environment. ```bash uv run src/openai_codex_in_sandbox_python/main.py ``` -------------------------------- ### Install Dependencies Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/homepage_vite_basic_updated.ipynb Installs the editable package and dotenv support. Run this notebook from the repo root. ```python # Install the editable package and dotenv support. Run this notebook from the repo root. %pip install -U -e ".[e2b]" python-dotenv ``` -------------------------------- ### Install Dependencies Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/anthropic-claude-code-in-sandbox-python/README.md Installs the project dependencies in the activated virtual environment. ```bash pip install -e . ``` -------------------------------- ### Run Example with Poetry Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/langgraph-python/README.md Execute the main example script using Poetry. This command assumes your entry point is configured correctly in `pyproject.toml`. ```bash poetry run start ``` -------------------------------- ### Clone Repository Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/watsonx-ai-code-interpreter-js/README.md Clone the e2b-cookbook repository to access the example code. Navigate into the specific example directory. ```bash git clone https://github.com/e2b-dev/e2b-cookbook/ cd e2b-cookbook/examples/watsonx-ai-code-interpreter-js/ ``` -------------------------------- ### Setup E2B Environment and Dependencies Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/preview_environment_builder.ipynb This code block handles repository root detection, path manipulation for imports, and environment variable loading (using python-dotenv or a manual fallback). It also ensures necessary E2B packages are installed. ```python import importlib import os import subprocess import sys from pathlib import Path repo_root = Path.cwd() if not (repo_root / "src" / "agents").exists(): for candidate in [Path.cwd(), *Path.cwd().parents]: if (candidate / "src" / "agents").exists(): repo_root = candidate break if (candidate / "openai-agents-python-preview" / "src" / "agents").exists(): repo_root = candidate / "openai-agents-python-preview" break src_root = repo_root / "src" if str(repo_root) not in sys.path: sys.path.insert(0, str(repo_root)) if str(src_root) not in sys.path: sys.path.insert(0, str(src_root)) env_path = None for candidate in [Path.cwd(), *Path.cwd().parents, repo_root, *repo_root.parents]: maybe_env = candidate / ".env" if maybe_env.exists(): env_path = maybe_env break if env_path is not None: try: from dotenv import load_dotenv load_dotenv(env_path, override=False) env_loader = "python-dotenv" except Exception: for raw_line in env_path.read_text().splitlines(): line = raw_line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'")) env_loader = "manual-fallback" else: env_loader = "not-found" for module_name in ["agents", "openai", "e2b", "e2b_code_interpreter"]: try: importlib.import_module(module_name) except Exception: subprocess.check_call([sys.executable, "-m", "pip", "install", "-e", f"{repo_root}[e2b]"]) break print(f"Using repo root: {repo_root}") print(f".env loader: {env_loader} ({env_path})") print(f"OPENAI_API_KEY set: {bool(os.getenv('OPENAI_API_KEY'))}") print(f"E2B_API_KEY set: {bool(os.getenv('E2B_API_KEY'))}") ``` -------------------------------- ### Install Dependencies for Code Interpreter and Groq SDK Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/upload-dataset-code-interpreter/llama_3_code_interpreter_upload_dataset.ipynb Install the E2B code interpreter SDK and Groq's Python SDK using pip. This step is crucial for setting up the environment to run code in the sandbox. ```python %pip install groq e2b_code_interpreter==1.0.0 python-dotenv==1.0.1 ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/firecrawl-scrape-and-analyze-airbnb-data/README.md Run this command in your terminal to install the necessary Node.js dependencies for the project. ```bash npm install ``` -------------------------------- ### Install and Import Libraries Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/o1-and-gpt-4-python/o1.ipynb Installs necessary Python packages and imports essential libraries for data manipulation, machine learning, and visualization. ```python !pip install pandas scikit-learn matplotlib seaborn import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import learning_curve, train_test_split from sklearn.metrics import accuracy_score ``` -------------------------------- ### Install OpenAI Agents SDK with E2B extra Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/README.md Install the SDK using pip, including the E2B extra for sandbox integration. Ensure you have your OpenAI and E2B API keys set as environment variables. ```bash pip install openai-agents[e2b] ``` ```bash export OPENAI_API_KEY="..." export E2B_API_KEY="..." ``` -------------------------------- ### Create and Start E2B Sandbox Session Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/data_science_parallel_workbench.ipynb Initializes an E2B sandbox client and creates a dashboard session with specified options. The session is then started to prepare the environment. ```python preview_client = E2BSandboxClient() dashboard_session = await preview_client.create( manifest=manifest, options=E2BSandboxClientOptions( sandbox_type=SANDBOX_TYPE, template=TEMPLATE, timeout=300, exposed_ports=(8765,), ), ) await dashboard_session.start() ``` -------------------------------- ### Install E2B Code Interpreter and Groq SDK Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/groq-code-interpreter-python/llama_3_code_interpreter.ipynb Install the E2B code interpreter SDK and Groq's Python SDK using pip. Ensure you are using the specified version for compatibility. ```python %pip install groq e2b_code_interpreter==1.0.0 ``` -------------------------------- ### Run the Example Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/anthropic-claude-code-in-sandbox-python/README.md Executes the main Python script to run the Anthropic Claude Code example in the E2B Sandbox. ```bash python anthropic_claude_code_in_sandbox/main.py ``` -------------------------------- ### Start Inngest Dev Server Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/agentkit-coding-agent/README.md Initiate the Inngest development server to manage and monitor your Inngest functions. ```bash npx inngest-cli@latest dev ``` -------------------------------- ### Install E2B SDK and Dependencies Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/webpage_designer_example.ipynb Installs the E2B SDK and its dependencies in editable mode. This cell must run inside an IPython kernel. ```python from pathlib import Path from IPython import get_ipython def find_sdk_root(start: Path) -> Path: candidates = [] for base in (start, *start.parents): candidates.append(base) candidates.append(base / "SDK") for candidate in candidates: if (candidate / "pyproject.toml").exists() and (candidate / "src" / "agents").exists(): return candidate.resolve() raise RuntimeError( "Could not find the local SDK root from the current notebook working directory" ) sdk_root = find_sdk_root(Path.cwd().resolve()) ip = get_ipython() assert ip is not None, "This install cell must run inside an IPython kernel" ip.run_line_magic("pip", f'install python-dotenv -e "{sdk_root}[e2b]"') ``` -------------------------------- ### Python Example: Using Claude with E2B Code Interpreter Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/claude-code-interpreter-python/claude_code_interpreter.ipynb This example demonstrates a full workflow: initializing the E2B Code Interpreter sandbox, sending a prompt to Claude via `chat_with_claude` to perform a calculation and visualization, and then printing the results. Ensure `E2B_API_KEY` is set. ```python from e2b_code_interpreter import Sandbox with Sandbox(api_key=E2B_API_KEY) as code_interpreter: code_interpreter_results = chat_with_claude( code_interpreter, "Calculate value of pi using monte carlo method. Use 1000 iterations. Visualize all point of all iterations on a single plot, a point inside the unit circle should be green, other points should be gray.", ) result = code_interpreter_results[0] print(result) # This will render the image # You can also access the data directly # result.png # result.jpg # result.pdf ``` -------------------------------- ### Create and Start E2B Sandbox Session Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/webpage_designer_example.ipynb Initializes and starts a new E2B sandbox session with specified configurations, including exposed ports and internet access. Prints the sandbox ID upon successful creation. ```python client = E2BSandboxClient() async def new_session(manifest: Manifest | None = None) -> object: session = await client.create( manifest=base_manifest() if manifest is None else manifest, options=E2BSandboxClientOptions( sandbox_type=E2BSandboxType.E2B, exposed_ports=(PORT,), allow_internet_access=True, pause_on_exit=True, ), ) await session.start() print(f"sandbox id: {session.state.sandbox_id}") return session ``` -------------------------------- ### Copy Environment Template Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/mcp-browserbase-js/README.md Copy the environment template file to start configuring your API keys. ```bash cp env.template .env ``` -------------------------------- ### Copy Environment Variables File Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/playwright-in-e2b/README.md Copies the example environment variables file to be edited with your API keys. ```bash cp example.env .env ``` -------------------------------- ### Basic Plotting with Matplotlib Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/gpt-4o-python/gpt_4o.ipynb This snippet shows a fundamental example of creating a plot using Matplotlib. Ensure Matplotlib is installed. ```python import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 100) y = np.sin(x) plt.plot(x, y) plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("Simple Sine Wave Plot") plt.show() ``` -------------------------------- ### Basic GPT-4o Text Generation Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/gpt-4o-python/gpt_4o.ipynb A simple example of generating text using the GPT-4o model. Ensure you have the necessary API keys and libraries installed. ```python from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ] ) print(response.choices[0].message.content) ``` -------------------------------- ### Basic GPT-4o Text Generation Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/gpt-4o-python/gpt_4o.ipynb A fundamental example of using GPT-4o to generate text based on a prompt. Ensure you have the necessary API keys and libraries installed. ```python from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"} ] ) print(response.choices[0].message.content) ``` -------------------------------- ### Initialize Virtual Environment Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/anthropic-claude-code-in-sandbox-python/README.md Sets up a Python virtual environment for managing project dependencies. ```bash python -m venv .venv ``` -------------------------------- ### Configure and Run Parallel Homepage Demo Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/homepage_prototype_parallel.ipynb Sets up configuration variables for the homepage prototyping demo, including the OpenAI model, sandbox type, template, and timeout. It then requires credentials and initiates the parallel demo. ```python from agents.extensions.sandbox import E2BSandboxType from examples.sandbox.extensions.e2b.homepage_prototype_parallel import ( DEFAULT_BRIEF, require_credentials, run_homepage_parallel_demo, ) MODEL = os.getenv("OPENAI_MODEL", "gpt-5.4-mini") SANDBOX_TYPE = E2BSandboxType(os.getenv("E2B_SANDBOX_TYPE", E2BSandboxType.E2B.value)) TEMPLATE = os.getenv("E2B_TEMPLATE") or None TIMEOUT_SECONDS = int(os.getenv("E2B_TIMEOUT", "900")) HOMEPAGE_BRIEF = DEFAULT_BRIEF require_credentials() ``` ```python payload = await run_homepage_parallel_demo( # type: ignore[top-level-await] # noqa: F704 model=MODEL, sandbox_type=SANDBOX_TYPE, template=TEMPLATE, timeout_seconds=TIMEOUT_SECONDS, homepage_brief=HOMEPAGE_BRIEF, ) payload["selection"] ``` -------------------------------- ### Configure API Keys Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/mcp-groq-exa-js/README.md Fill in your E2B, Groq, and Exa API keys in the .env file. ```bash E2B_API_KEY=your_e2b_api_key GROQ_API_KEY=your_groq_api_key EXA_API_KEY=your_exa_api_key ``` -------------------------------- ### LLM Tool-Calling with OpenAI and Code Interpreter Source: https://context7.com/e2b-dev/e2b-cookbook/llms.txt Uses OpenAI's chat completions with function/tool calling and the E2B code interpreter. This example demonstrates uploading a dataset before running analysis and generating a chart. Ensure you have the OpenAI SDK and E2B code interpreter installed. ```typescript // TypeScript — OpenAI o3-mini + E2B code interpreter import OpenAI from 'openai' import fs from 'node:fs' import { Sandbox, Result } from '@e2b/code-interpreter' const client = new OpenAI() const codeInterpreter = await Sandbox.create() // Upload a dataset before running analysis const csvBuffer = fs.readFileSync('./city_temperature.csv') await codeInterpreter.files.write('/home/user/city_temperature.csv', csvBuffer) const tools = [{ type: 'function' as const, function: { name: 'execute_python', description: 'Execute Python in a Jupyter notebook cell.', parameters: { type: 'object', properties: { code: { type: 'string' } }, required: ['code'], }, }, }] const completion = await client.chat.completions.create({ model: 'o3-mini', messages: [ { role: 'system', content: 'You are a Python data scientist. Dataset is at /home/user/city_temperature.csv.' }, { role: 'user', content: 'Analyze the top 5 hottest cities and create a temperature trend chart.' }, ], tools, tool_choice: 'auto', }) const toolCall = completion.choices[0].message.tool_calls?.[0] if (toolCall?.function.name === 'execute_python') { const { code } = JSON.parse(toolCall.function.arguments) const exec = await codeInterpreter.runCode(code) if (exec.error) console.error('Error:', exec.error.value) if (exec.results[0]?.png) { fs.writeFileSync('temperature_analysis.png', Buffer.from(exec.results[0].png, 'base64')) console.log('Chart saved') } } await codeInterpreter.kill() ``` -------------------------------- ### Install Dependencies with Poetry Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/autogen-python/README.md Install project dependencies using Poetry. Ensure you have Poetry installed and configured. ```sh poetry install ``` -------------------------------- ### Initialize E2B Environment Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/o1-and-gpt-4-python/o1.ipynb Sets up the E2B environment by importing necessary libraries and initializing the E2B client. Ensure you have your API key configured. ```python from e2b import Env # Ensure your E2B API key is set as an environment variable E2B_API_KEY # or pass it directly: Env(api_key="YOUR_API_KEY") env = Env() ``` -------------------------------- ### Install Dependencies Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/watsonx-ai-code-interpreter-python/granite_code_interpreter_py.ipynb Installs the necessary Python packages for E2B Code Interpreter, python-dotenv, and IBM WatsonX AI. Note that you may need to restart the kernel after installation. ```python %pip install -q e2b_code_interpreter==1.0.5 python-dotenv==1.0.1 ibm_watsonx_ai==1.2.9 ``` -------------------------------- ### Install Libraries for Code Interpreter Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/o1-and-gpt-4-python/o1.ipynb Installs the necessary libraries, including openai and e2b_code_interpreter, for using the Code Interpreter with OpenAI models. It's recommended to restart the kernel after installation if required. ```python %pip install openai e2b_code_interpreter==1.0.0 python-dotenv ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/sandbox-agent-sdk-js/README.md Create a .env file and add your E2B API key and at least one provider API key (e.g., OpenAI, Anthropic). Refer to the Sandbox Agent credentials documentation for other provider options. ```bash E2B_API_KEY=your_e2b_api_key # At least one provider key OPENAI_API_KEY=your_openai_api_key # ANTHROPIC_API_KEY=your_anthropic_api_key ``` -------------------------------- ### Install Fireworks AI, OpenAI, and E2B Code Interpreter Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/fireworks-code-interpreter-python/qwen_code_interpreter.ipynb Installs or upgrades the Fireworks AI, OpenAI, and E2B Code Interpreter SDK packages. Ensure you have Python and pip installed. ```python %pip install --upgrade fireworks-ai openai e2b_code_interpreter==1.0.0 python-dotenv==1.0.1 ``` -------------------------------- ### Initialize Virtual Environment Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-codex-in-sandbox-python/README.md Sets up a Python virtual environment using 'uv venv'. This isolates project dependencies. ```bash uv venv ``` -------------------------------- ### Install and Configure Playwright in Review Sandbox Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/webpage_designer_example.ipynb Ensures Playwright is installed and ready for use within the review sandbox. This involves running npm commands to install Playwright and its dependencies, and setting up a script to capture webpage screenshots. ```python async def ensure_reviewer_browser(session) -> None: ready_marker = "review/.playwright-ready" if await file_exists(session, ready_marker): print("review sandbox browser ready") return print("installing playwright once in the review sandbox...") npm_install_command = ( "mkdir -p review/playwright review/logs review/screenshots && " "cd review/playwright && " "if [ ! -x node_modules/.bin/playwright ]; then " "npm init -y >/dev/null 2>&1 && " "npm install playwright@latest >../logs/playwright-npm-install.log 2>&1; " "fi" ) npm_install_result = await session.exec( "bash", "-lc", npm_install_command, shell=False, timeout=900 ) assert npm_install_result.ok(), await tail_file( session, "review/logs/playwright-npm-install.log" ) deps_command = ( "cd review/playwright && " "sudo -n ./node_modules/.bin/playwright install-deps chromium " ">../logs/playwright-install-deps.log 2>&1" ) deps_result = await session.exec("bash", "-lc", deps_command, shell=False, timeout=900) assert deps_result.ok(), await tail_file(session, "review/logs/playwright-install-deps.log") install_command = ( "cd review/playwright && " "PLAYWRIGHT_BROWSERS_PATH=0 ./node_modules/.bin/playwright install chromium " ">../logs/playwright-install.log 2>&1" ) install_result = await session.exec("bash", "-lc", install_command, shell=False, timeout=900) assert install_result.ok(), await tail_file(session, "review/logs/playwright-install.log") capture_script = ( dedent( """ const { chromium } = require("playwright"); const fs = require("fs"); const path = require("path"); const [url, outputPath] = process.argv.slice(2); if (!url || !outputPath) { console.error("usage: node capture.js "); process.exit(2); } (async () => { const browser = await chromium.launch({ headless: true, args: [ "--disable-dev-shm-usage", "--single-process", "--no-zygote", "--js-flags=--jitless" ] }); ``` -------------------------------- ### Configure API Keys Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/mcp-browserbase-js/README.md Fill in your E2B, Browserbase, Gemini, and OpenAI API keys in the .env file. ```bash E2B_API_KEY=your_e2b_api_key BROWSERBASE_API_KEY=your_browserbase_api_key BROWSERBASE_PROJECT_ID=your_browserbase_project_id GEMINI_API_KEY=your_gemini_api_key OPENAI_API_KEY=your_openai_api_key ``` -------------------------------- ### Environment Variables Setup Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/agentkit-coding-agent/README.md Create a .env file with your E2B and Anthropic API keys. Optionally, specify the Anthropic model to use. ```bash E2B_API_KEY=your_e2b_api_key ANTHROPIC_API_KEY=your_anthropic_api_key # Optional: Specify which Claude model to use (defaults to claude-haiku-4-5) # All models: https://console.anthropic.com/docs/en/about-claude/models/overview ANTHROPIC_MODEL=claude-sonnet-4-5-20250929 ``` -------------------------------- ### Install E2B CLI Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/playwright-in-e2b/README.md Installs the latest version of the E2B CLI globally, which is required for building custom sandboxes. ```bash npm i -g @e2b/cli@latest ``` -------------------------------- ### Setup and Utility Functions for Webpage Review Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/webpage_designer_example.ipynb Defines constants, instructions, and utility functions for interacting with the E2B environment, including file operations and path manipulation. These are essential for setting up the review sandbox and managing files. ```python import asyncio import io import shlex from pathlib import Path from textwrap import dedent WORKSPACE_ROOT = Path("/workspace") review_instructions = ( "Review the provided landing-page screenshot, improve the page based " "on what you see, and return a short structured summary." ) review_notes = ( "First read review/history.md, brief.md, site/index.html, and site/styles.css. " "Then call view_image on review/screenshots/current.png. " "Use apply_patch for focused edits only. " "Keep the current structure, but improve any obvious visual issues " "you can see in the screenshot, especially spacing, hierarchy, " "balance, and CTA clarity. " "Before finishing, append a short note to review/history.md " "describing what you noticed and what you changed this round. " "Make sure site/ is still being served on port 8765 and verify it with curl. " "served_port must be 8765." ) review_prompt = ( "Review review/history.md and the provided screenshot in " "review/screenshots/current.png, then make one visual refinement pass." ) def workspace_path(path: str) -> str: return str(WORKSPACE_ROOT / path) async def read_text_file(session, path: str) -> str: handle = await session.read(Path(path)) return handle.read().decode() async def write_file(session, path: str, payload: bytes | str) -> None: parent = Path(path).parent await session.exec( "bash", "-lc", f"mkdir -p {shlex.quote(str(parent))}", shell=False, timeout=5 ) if isinstance(payload, str): payload = payload.encode() await session.write(Path(path), io.BytesIO(payload)) async def file_exists(session, path: str) -> bool: result = await session.exec( "bash", "-lc", f"test -f {shlex.quote(path)}", shell=False, timeout=5 ) return result.ok() async def tail_file(session, path: str, lines: int = 40) -> str: result = await session.exec( "bash", "-lc", f"tail -n {lines} {shlex.quote(path)}", shell=False, timeout=5, ) stdout = result.stdout.decode() if isinstance(result.stdout, bytes) else result.stdout stderr = result.stderr.decode() if isinstance(result.stderr, bytes) else result.stderr if result.ok(): return stdout or "(empty file)" return stdout or stderr or f"{path} does not exist" ``` -------------------------------- ### Initialize E2B Sandbox Template Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/playwright-in-e2b/README.md Initializes a new E2B sandbox template in the current project directory. ```bash e2b template init ``` -------------------------------- ### Initialize OpenAI Client and E2B Sandbox Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-python/openai.ipynb Sets up the OpenAI client and E2B Sandbox using API keys loaded from environment variables. This code is a prerequisite for interacting with both services. ```python import os from dotenv import load_dotenv from openai import OpenAI import json from e2b_code_interpreter import Sandbox load_dotenv() OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") E2B_API_KEY = os.getenv("E2B_API_KEY") SYSTEM_PROMPT = """ ``` -------------------------------- ### Run Example with uv Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/stirrup-python/README.md Execute the main Python script using 'uv run'. This command ensures the script runs within the correct environment managed by uv. ```bash uv run python main.py ``` -------------------------------- ### Install Grit CLI Source: https://context7.com/e2b-dev/e2b-cookbook/llms.txt Install the Grit CLI globally using npm to manage codemod scripts for migrating E2B SDK versions. ```bash # Install Grit CLI npm install -g @getgrit/cli ``` -------------------------------- ### Install Dependencies Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/claude-visualize-website-topics/claude-visualize-website-topics.ipynb Installs the necessary Python libraries for the project, including E2B Code Interpreter, Anthropic's SDK, Firecrawl, and python-dotenv. ```python %pip install e2b_code_interpreter==1.0.0 anthropic==0.35.0 firecrawl-py==0.0.16 python-dotenv==1.0.1 ``` -------------------------------- ### Screenshot-Guided Warm-Up Pass Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/webpage_designer_example.ipynb Sets up a session for a screenshot reviewer agent, captures a preview screenshot, verifies file existence, and reads review history. Use this to initialize and perform an initial review pass with screenshot capabilities. ```python session=screenshot_warmup_session, agent=build_agent( "Screenshot Reviewer Warm-Up", instructions=review_instructions, developer_notes=review_notes, ), prompt=review_prompt, max_turns=30, ) await capture_preview_screenshot( review_session, screenshot_warmup["preview_url"], warmup_after_path ) assert await file_exists(review_session, warmup_before_path) assert await file_exists(review_session, warmup_after_path) screenshot_warmup["review_sandbox_id"] = review_session.state.sandbox_id screenshot_warmup["before_screenshot"] = warmup_before_path screenshot_warmup["after_screenshot"] = warmup_after_path warmup_notes = await read_text_file(screenshot_warmup_session, "review/history.md") current_html, current_css = await read_site(screenshot_warmup_session) current_preview_url = screenshot_warmup["preview_url"] review_history = extend_review_history("warm-up", screenshot_warmup, warmup_notes) ``` ```python print("screenshot-guided warm-up") print(screenshot_warmup["result"]["summary"]) print(f"preview url: {screenshot_warmup['preview_url']}") print(f"elapsed: {screenshot_warmup['elapsed_seconds']}s") print(f"review sandbox id: {screenshot_warmup['review_sandbox_id']}") print(f"before screenshot: {screenshot_warmup['before_screenshot']}") print(f"after screenshot: {screenshot_warmup['after_screenshot']}") ``` -------------------------------- ### Write Initial Screenshot and Prepare for Review Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-agents-sdk/notebooks/webpage_designer_example.ipynb Writes the captured initial screenshot to a file and sets up a new E2B session specifically for the screenshot review process, including the initial review history. ```python screenshot_warmup_session = await new_session( base_manifest( html=current_html, css=current_css, review_history=review_history, ) ) await write_file(screenshot_warmup_session, "review/screenshots/current.png", warmup_before_bytes) screenshot_warmup = await run_builder( ``` -------------------------------- ### Install E2B Code Interpreter SDK Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/openai-python/openai.ipynb Installs the necessary libraries for using the E2B Code Interpreter with OpenAI. Ensure you have pip available and restart your kernel if prompted. ```python %pip install openai e2b_code_interpreter==1.0.0 ``` -------------------------------- ### Install E2B Code Interpreter and Mistral AI SDKs Source: https://github.com/e2b-dev/e2b-cookbook/blob/main/examples/codestral-code-interpreter-python/codestral_code_interpreter.ipynb Install the necessary Python packages for E2B code interpreter and Mistral AI. Ensure you have the correct versions specified. ```python %pip install mistralai==0.4.2 e2b_code_interpreter==1.0.0 ```