### Error handling Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-contexts.md Example showing how to handle both session creation exceptions and directory setup failures. ```python try: ctx = await create_context(client, {}, "python", "/home/user") if hasattr(ctx, "id"): print(ctx.id) else: print("cwd setup failed:", ctx.status_code) # 500 except Exception as e: print("session creation failed:", e) # "Failed to create context: ..." ``` -------------------------------- ### Install build dependencies Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Install the necessary packages for building the production template. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Install E2B SDK Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Install the E2B SDK and dotenv package for custom template development. ```bash pip install e2b dotenv ``` -------------------------------- ### Context JSON Response Example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-models.md Example JSON structure returned by POST /contexts or retrieved via GET /contexts. ```json {"id": "1f0b2c3d-...", "language": "python", "cwd": "/home/user"} ``` -------------------------------- ### Install Python SDK Source: https://github.com/e2b-dev/code-interpreter/blob/main/README.md Install the E2B code interpreter package for Python projects. ```bash pip install e2b-code-interpreter ``` -------------------------------- ### Install JavaScript SDK Source: https://github.com/e2b-dev/code-interpreter/blob/main/README.md Install the E2B code interpreter package for JavaScript or TypeScript projects. ```bash npm i @e2b/code-interpreter ``` -------------------------------- ### Embedding Server Modules Example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-messaging.md Demonstrates how to instantiate the ContextWebSocket, connect, execute code, and close the connection. ```python import asyncio from messaging import ContextWebSocket async def demo(): ws = ContextWebSocket("ctx-id", "sess-id", "python", "/home/user") await ws.connect() # issue an execution async for item in ws.execute("print('hi')", env_vars={}, access_token=None): print(item) await ws.close() asyncio.run(demo()) # {'type': 'number_of_executions', 'execution_count': 1} # {'type': 'stdout', 'text': 'hi', ...} # {'type': 'end_of_execution'} ``` -------------------------------- ### Usage as the server does Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-contexts.md Example demonstrating how to invoke create_context within an async client session. ```python import httpx from contexts import create_context from messaging import ContextWebSocket websockets = {} async def make(): async with httpx.AsyncClient() as client: ctx = await create_context(client, websockets, "r", "/home/user") print(ctx.id, ctx.language, ctx.cwd) # 3f2a… r /home/user # websockets[ctx.id] is now a connected ContextWebSocket ``` -------------------------------- ### CreateContext Example Payload Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-models.md Example JSON request body for creating a context with a custom language and working directory. ```json {"language": "bash", "cwd": "/tmp"} ``` -------------------------------- ### normalize_language usage examples Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-contexts.md Examples showing how normalize_language handles various inputs. ```python normalize_language(None) # "python" normalize_language("JS") # "javascript" normalize_language("Python") # "python" ``` -------------------------------- ### Create a Context via POST /contexts Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-main.md Example of creating a new execution context with a specified language and working directory. ```python resp = httpx.post("http://localhost:49999/contexts", json={"language": "r", "cwd": "/tmp"}) print(resp.json()) # {'id': '9f2c...', 'language': 'r', 'cwd': '/tmp'} ``` -------------------------------- ### Constructing an Execution instance Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-messaging.md Example of initializing an Execution instance for internal server use and queuing an end-of-execution signal. ```python execution = Execution(in_background=True) await execution.queue.put(EndOfExecution()) ``` -------------------------------- ### Configure custom kernels and debug mode Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/template-builder.md Example of creating a template with specific kernels and a custom readiness timeout for debugging. ```python from e2b import wait_for_timeout from template import make_template tpl = make_template( kernels=["python", "r"], ready=wait_for_timeout(60_000), debug=True, ) ``` -------------------------------- ### Build template with script usage Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/template-builder.md Example of using Template.build with the make_template function to define sandbox resources and logging. ```python from e2b import Template, default_build_logger from template import make_template Template.build( make_template(kernels=["python", "javascript"]), alias="code-interpreter-dev", cpu_count=2, memory_mb=2048, on_build_logs=default_build_logger(min_level="debug"), ) ``` -------------------------------- ### LineChart basic usage Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-planar.md Example of initializing a LineChart from a Matplotlib axis and dumping the model data. ```python from matplotlib.pyplot import subplots from e2b_charts.charts import LineChart fig, ax = subplots() ax.plot([1, 2, 3], [1, 4, 9], label="squares") chart = LineChart(ax=ax) print(chart.model_dump()) # {'type': 'line', 'x_scale': 'linear', 'elements': [ # {'label': 'squares', 'points': [[1.0, 1.0], [2.0, 4.0], [3.0, 9.0]]}]} ``` -------------------------------- ### Stdout log serialization example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-models.md An example of a serialized Stdout object, showing how it appears on the wire when exclude_none is set to True. ```json {"type": "stdout", "text": "hello\n", "timestamp": "2025-01-01T00:00:00Z"} ``` -------------------------------- ### NumberOfExecutions JSON Example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-models.md Example JSON payload for the NumberOfExecutions model. ```json {"type": "number_of_executions", "execution_count": 3} ``` -------------------------------- ### GET /contexts Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-main.md Lists all active execution contexts. ```APIDOC ## GET /contexts ### Description Returns a list of all active execution contexts, excluding the default alias. ### Method GET ### Endpoint /contexts ### Response #### Success Response (200) - **contexts** (List[Context]) - A list of active context objects. ``` -------------------------------- ### ExecutionRequest Example Payload Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-models.md Example JSON request body for executing a simple print statement with specified language and environment variables. ```json {"code": "print(1)", "language": "python", "env_vars": {"FOO": "bar"}} ``` -------------------------------- ### BarChart basic usage example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-bars.md Demonstrates initializing a BarChart from a matplotlib axes object and exporting the data model. ```python from matplotlib.pyplot import subplots from e2b_charts.charts import BarChart fig, ax = subplots() ax.bar(["a", "b", "c"], [1, 4, 2]) chart = BarChart(ax=ax) print(chart.model_dump()) # {'type': 'bar', 'elements': [{'label': 'a', 'group': 'Group 1', 'value': 1.0}, ...]} ``` -------------------------------- ### ScatterChart basic usage example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-planar.md Demonstrates initializing a ScatterChart from a Matplotlib axes object and dumping the model data. ```python import numpy as np from matplotlib.pyplot import subplots from e2b_charts.charts import ScatterChart fig, ax = subplots() ax.scatter(np.arange(5), np.random.rand(5), label="samples") chart = ScatterChart(ax=ax) print(chart.model_dump()) # {'type': 'scatter', 'elements': [ # {'label': 'samples', 'points': [[0.0, 0.37], ...]}]} ``` -------------------------------- ### PointChart._detect_scale usage Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-planar.md Examples demonstrating scale detection for different input data types. ```python from e2b_charts.charts import PointChart PointChart._detect_scale(None, "linear", [0, 1, 2], ["A", "B", "C"]) # "categorical" PointChart._detect_scale(None, "linear", [1, 2, 3], ["1", "2", "3"]) # "linear" PointChart._detect_scale(None, "log", [1, 10], ["1", "10"]) # "log" ``` -------------------------------- ### Print Dockerfile with build_docker.py Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/template-builder.md Generates and prints the Dockerfile for the template without building it. The bash command shows how to start the template server using the generated configuration. ```python from template import make_template from e2b import Template tmp = make_template(kernels=["python", "javascript"], is_docker=True) print(Template.to_dockerfile(tmp)) ``` ```bash make start-template-server # docker run -e E2B_LOCAL=true -p 49999:49999 ... ``` -------------------------------- ### Building a Chart Model Programmatically Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-base.md Example of instantiating a Chart model directly without an existing matplotlib figure. ```python from e2b_charts.charts import Chart, ChartType chart = Chart(type=ChartType.UNKNOWN, title="My plot") print(chart.type, chart.title) # ChartType.UNKNOWN My plot ``` -------------------------------- ### Constructing Result from execute_result Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-models.md Example of initializing a Result object with a standard Jupyter MIME bundle. ```python result = Result(is_main_result=True, data={ "text/plain": "3", "text/html": "3", "image/png": b"...", "e2b/chart": {"type": "line", "elements": []}, }) print(result.text) # "3" print(result.html) # "3" print(result.formats()) # ['text', 'html', 'png', 'chart'] ``` -------------------------------- ### make_template(kernels, is_docker, ready, debug) Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/template-builder.md Constructs an e2b.Template object defining the sandbox environment, including installed kernels, system configuration, and startup commands. ```APIDOC ## make_template(kernels, is_docker, ready, debug) ### Description Creates a template configuration for the code-interpreter sandbox. This function defines the base image, system packages, kernel installations, and service startup logic. ### Parameters - **kernels** (list[str]) - Optional - Kernel languages to install. Defaults to ["python", "r", "javascript", "bash", "java"]. Python and JS are always included. - **is_docker** (bool) - Optional - If True, installs start-up.sh for Docker local-dev. If False, installs systemd units. Defaults to False. - **ready** (ReadyCmd | None) - Optional - Readiness command for set_start_cmd. Defaults to wait_for_url("http://localhost:49999/health"). - **debug** (bool) - Optional - If True (and not Docker), routes Jupyter stdout to the system journal. Defaults to False. ### Return Returns an e2b.Template object with the start command and readiness check applied. ### Example ```python from e2b import wait_for_timeout from template import make_template tpl = make_template( kernels=["python", "r"], ready=wait_for_timeout(60_000), debug=True, ) ``` ``` -------------------------------- ### Usage in normal flow Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-envs.md Example of calling get_envs with an access token during the normal production flow. ```python envs = await get_envs(access_token="token123") print(envs) # {'MY_SANDBOX_VAR': '42', ...} ``` -------------------------------- ### Basic PieChart extraction example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-pie.md Demonstrates initializing a PieChart from a matplotlib axes object and dumping the model data. ```python from matplotlib.pyplot import subplots from e2b_charts.charts import PieChart fig, ax = subplots() ax.pie([40, 30, 30], labels=["X", "Y", "Z"]) chart = PieChart(ax=ax) print(chart.model_dump()) # {'type': 'pie', 'elements': [ # {'label': 'X', 'angle': 144.0, 'radius': 1.0}, # {'label': 'Y', 'angle': 108.0, 'radius': 1.0}, # {'label': 'Z', 'angle': 108.0, 'radius': 1.0}]} ``` -------------------------------- ### Usage in local dev mode Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-envs.md Example of calling get_envs when E2B_LOCAL is set to true in the environment. ```python # E2B_LOCAL=true in the environment envs = await get_envs(access_token=None) print(envs) # {'E2B_TEST_VARIABLE': 'true'} ``` -------------------------------- ### Execute Code via POST /execute Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-main.md Example of calling the execute endpoint using httpx to run Python code with environment variables. ```python import httpx resp = httpx.post( "http://localhost:49999/execute", json={"code": "x = 1; x + 1", "language": "python", "env_vars": {"FOO": "bar"}}, headers={"X-Access-Token": "..."}, timeout=None, ) for line in resp.iter_lines(): print(line) # {"type": "number_of_executions", "execution_count": 3} # {"type": "result", "text": "2", "is_main_result": true, ...} # {"type": "end_of_execution"} ``` -------------------------------- ### lifespan(app: FastAPI) async context manager Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-main.md Initializes default Python and JavaScript contexts on startup and cleans up resources on shutdown. If default context creation fails, the application will fail to start. ```python @asynccontextmanager async def lifespan(app: FastAPI): global client client = httpx.AsyncClient() try: python_context = await create_context( client, websockets, "python", "/home/user" ) default_websockets["python"] = python_context.id websockets["default"] = websockets[python_context.id] javascript_context = await create_context( client, websockets, "javascript", "/home/user" ) default_websockets["javascript"] = javascript_context.id logger.info("Connected to default runtime") yield # Will cleanup after application shuts down for ws in websockets.values(): await ws.close() await client.aclose() except Exception as e: logger.error(f"Failed to initialize default context: {e}") raise ``` -------------------------------- ### Handling DataFrame via e2b/data Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-models.md Example of using the e2b/data key to pass structured data, such as a DataFrame, into a Result object. ```python import pandas as pd from e2b_data_formatter import E2BDataFormatter # concept: the formatter output data = { "text/plain": " a b\n0 1 2", "e2b/data": {"a": [1], "b": [2]}, } r = Result(is_main_result=False, data=dict(data)) print(r.data) # {'a': [1], 'b': [2]} ``` -------------------------------- ### Creating a Chart Model from Matplotlib Axes Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-base.md Example of initializing a Chart model by extracting data from an existing matplotlib axes object. ```python from matplotlib.pyplot import subplots from e2b_charts.charts import Chart fig, ax = subplots() ax.set_title("Data") ax.plot([1, 2], [3, 4]) chart = Chart(ax=ax, type=ChartType.UNKNOWN) print(chart.title) # "Data" ``` -------------------------------- ### Build and use custom template Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Commands to build the custom template and instantiate a sandbox using it. ```bash python build.py ``` ```python from e2b import Sandbox sbx = Sandbox.create(template="code-interpreter-custom") execution = sbx.run_code("print('Hello, World!')") print(execution.logs.stdout) ``` -------------------------------- ### Build the production template Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Execute the build script to create the production template, with an option to force a clean rebuild. ```bash python build_prod.py ``` ```bash SKIP_CACHE=true python build_prod.py ``` -------------------------------- ### GET /health Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-main.md Checks the health status of the server. ```APIDOC ## GET /health ### Description Returns the health status of the server. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **body** (string) - Returns "OK" ``` -------------------------------- ### GET /contexts Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/endpoints.md Lists all currently active Jupyter contexts, excluding the default alias. ```APIDOC ## GET /contexts ### Description Lists all live contexts. The "default" alias entry is excluded. ### Method GET ### Endpoint /contexts ### Response #### Success Response (200) - **contexts** (array) - List of Context objects containing id, language, and cwd. ``` -------------------------------- ### Create build script Source: https://github.com/e2b-dev/code-interpreter/blob/main/template/README.md Define the build configuration for the custom template, including resource allocation and logging. ```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(), ) ``` -------------------------------- ### get_chart_from_ax Usage Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/e2b-charts.md Example of using get_chart_from_ax to identify the chart type of a single axes object. ```python from e2b_charts.main import get_chart_from_ax model = get_chart_from_ax(ax) print(model.type) # ChartType.LINE etc. ``` -------------------------------- ### Handle Execution Errors Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-main.md Example of error handling when executing code that results in a runtime exception. ```python resp = httpx.post("http://localhost:49999/execute", json={"code": "1/0", "language": "python"}) for line in resp.iter_lines(): print(line) # {"type": "error", "name": "ZeroDivisionError", "value": "division by zero", # "traceback": "Traceback (most recent call last):..."} # {"type": "end_of_execution"} ``` -------------------------------- ### Standalone LockedMap demonstration Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-locks.md A basic demonstration of initializing a LockedMap, setting values, and using the get_lock method to perform operations under a per-key lock. ```python import asyncio from utils.locks import LockedMap async def demo(): locked = LockedMap() locked["python"] = "ctx-1" async with await locked.get_lock("python"): print(locked["python"]) # ctx-1 — read under the lock # a brand-new key gets its own lock async with await locked.get_lock("r"): locked["r"] = "ctx-2" asyncio.run(demo()) ``` -------------------------------- ### dynamic_round with pie angles Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-utils.md Example of using dynamic_round to process calculated angles for pie charts. ```python from decimal import Decimal from e2b_charts.utils.rounding import dynamic_round angle = abs(dynamic_round(Decimal("270.0000001") - Decimal("90.0"))) print(angle) # 180.00000 ``` -------------------------------- ### SuperChart Usage with Subplots Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/e2b-charts.md Example demonstrating how to convert a Matplotlib figure with multiple subplots into a SuperChart model. ```python fig, (ax1, ax2) = plt.subplots(1, 2) ax1.plot([1, 2], [3, 4]) ax2.bar(["a", "b"], [1, 2]) chart = chart_figure_to_chart(fig) assert chart.type == ChartType.SUPERCHART print(chart.model_dump()) # {'type': 'superchart', 'elements': [{line...}, {bar...}]} ``` -------------------------------- ### create_context(client, websockets, language, cwd) Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-contexts.md Initializes a new execution context by creating a Jupyter session, connecting a WebSocket, and setting the working directory. ```APIDOC ## create_context(client, websockets, language, cwd) ### Description Creates a new Jupyter session, connects a WebSocket for the session, and sets the initial working directory. Returns a Context object on success or a PlainTextResponse on failure. ### Parameters - **client** (httpx.AsyncClient) - Required - HTTP client for Jupyter REST calls. - **websockets** (dict) - Required - The context registry to register the new context in. - **language** (str) - Required - Normalized language name used to determine the kernel. - **cwd** (str) - Required - The initial working directory to set in the kernel. ### Return - **Context** - Returns a Context object containing the id, language, and cwd. - **PlainTextResponse** - Returns a 500 error response if setting the working directory fails. ### Example ```python import httpx from contexts import create_context websockets = {} async def make(): async with httpx.AsyncClient() as client: ctx = await create_context(client, websockets, "r", "/home/user") print(ctx.id, ctx.language, ctx.cwd) ``` ``` -------------------------------- ### Matplotlib configuration file Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/configuration.md The matplotlibrc configuration file installed to .config/matplotlib/.matplotlibrc to ensure CJK glyph rendering. ```ini font.family: sans-serif, Noto Sans CJK JP ``` -------------------------------- ### connect() Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-messaging.md Establishes a WebSocket connection to the Jupyter kernel. ```APIDOC ## async def connect() ### Description Opens a WebSocket connection to the Jupyter kernel channels and spawns a background task to receive messages. ``` -------------------------------- ### POST /contexts Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-main.md Creates a new execution context. ```APIDOC ## POST /contexts ### Description Creates a new execution context with the specified language and working directory. ### Method POST ### Endpoint /contexts ### Parameters #### Request Body - **cwd** (string) - Optional - Working directory (default: /home/user). - **language** (string) - Optional - Programming language (default: python). ### Response #### Success Response (200) - **id** (string) - The context ID. - **language** (string) - The language of the context. - **cwd** (string) - The working directory. ``` -------------------------------- ### Usage of chart_figure_to_dict Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/e2b-charts.md Example showing how to use the function to process a Matplotlib figure and access the resulting dictionary data. ```python from e2b_charts import chart_figure_to_dict result = chart_figure_to_dict(fig) # fig from anywhere if result: print(result["type"], result.get("title")) else: print("figure had no plottable data") ``` -------------------------------- ### ContextWebSocket connect Method Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-messaging.md Establishes a WebSocket connection to the Jupyter kernel and spawns the message receiving task. ```python async def connect(self): logger.debug(f"WebSocket connecting to {self.url}") ws_logger = logger.getChild("websockets.client") ws_logger.setLevel(logging.ERROR) self._ws = await connect( self.url, ping_timeout=PING_TIMEOUT, max_size=None, max_queue=None, logger=ws_logger, ) logger.info(f"WebSocket connected to {self.url}") self._receive_task = asyncio.create_task( self._receive_message(), name="receive_message", ) ``` -------------------------------- ### Execute Code in Sandbox (Python) Source: https://github.com/e2b-dev/code-interpreter/blob/main/README.md Create a sandbox instance and execute code snippets using the Python SDK. ```py 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 ``` -------------------------------- ### Execute Code in Sandbox (JavaScript/TypeScript) Source: https://github.com/e2b-dev/code-interpreter/blob/main/README.md Create a sandbox instance and execute code snippets using the JavaScript SDK. ```ts 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 ``` -------------------------------- ### Chart2D Unit Extraction Example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-base.md Demonstrates how Chart2D automatically extracts units from axis labels using regex patterns. ```python from matplotlib.pyplot import subplots from e2b_charts.charts.base import Chart2D fig, ax = subplots() ax.plot([1, 2, 3], [1, 4, 9]) ax.set_xlabel("time (s)") ax.set_ylabel("distance [m]") c = Chart2D(ax=ax, type=ChartType.UNKNOWN) print(c.x_unit) # "s" print(c.y_unit) # "m" ``` -------------------------------- ### Donut and explode PieChart example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-pie.md Shows how PieChart handles custom radius and explode parameters in matplotlib pie charts. ```python fig, ax = subplots() ax.pie([1, 2, 3], labels=["a", "b", "c"], explode=[0, 0.1, 0], radius=0.8) chart = PieChart(ax=ax) total = sum(el.angle for el in chart.elements) print(total) # 360.0 (angles always sum to a full circle) print(chart.elements[1].radius) # 0.8 ``` -------------------------------- ### BarChart grouped/stacked bars example Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/charts-bars.md Shows how BarChart handles multiple series with explicit labels, resulting in grouped data elements. ```python fig, ax = subplots() ax.bar(["a", "b"], [1, 2], label="Series A") ax.bar(["a", "b"], [3, 4], bottom=[1, 2], label="Series B") chart = BarChart(ax=ax) for el in chart.elements: print(el.label, el.group, el.value) # a Series A 1.0 / b Series A 2.0 / a Series B 3.0 / b Series B 4.0 ``` -------------------------------- ### ContextWebSocket Constructor Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-messaging.md Initializes a new ContextWebSocket instance to manage a specific Jupyter kernel session. ```APIDOC ## Constructor ### Description Initializes the WebSocket client for a specific Jupyter kernel session. ### Parameters - **context_id** (str) - Required - Jupyter kernel id (UUID string). - **session_id** (str) - Required - Jupyter session id (UUID string). - **language** (str) - Required - Canonical language name ("python", "javascript", "r", "java", "bash", "typescript"). - **cwd** (str) - Required - Working directory used for session creation. ``` -------------------------------- ### create_context implementation Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-contexts.md The core function definition for creating a Jupyter session and initializing the context. ```python async def create_context(client, websockets: dict, language: str, cwd: str) -> Context: data = { "path": str(uuid.uuid4()), "kernel": {"name": get_kernel_for_language(language)}, "type": "notebook", "name": str(uuid.uuid4()), } logger.debug(f"Creating new {language} context") response = await client.post(f"{JUPYTER_BASE_URL}/api/sessions", json=data) if not response.is_success: raise Exception( f"Failed to create context: {response.text}", ) session_data = response.json() session_id = session_data["id"] context_id = session_data["kernel"]["id"] logger.debug(f"Created context {context_id}") ws = ContextWebSocket(context_id, session_id, language, cwd) await ws.connect() websockets[context_id] = ws logger.info(f"Setting working directory to {cwd}") try: await ws.change_current_directory(cwd, language) except ExecutionError: return PlainTextResponse( "Failed to set working directory", status_code=500, ) return Context(language=language, id=context_id, cwd=cwd) ``` -------------------------------- ### Streaming Pydantic Models in a FastAPI Handler Source: https://github.com/e2b-dev/code-interpreter/blob/main/_autodocs/api-reference/server-stream.md An example of using StreamingListJsonResponse within a FastAPI route to stream Pydantic models generated by an asynchronous function. ```python import asyncio from fastapi import FastAPI from api.models.logs import Stdout from stream import StreamingListJsonResponse app = FastAPI() async def gen(): yield Stdout(text="hello") await asyncio.sleep(0.1) yield Stdout(text="world") @app.post("/run") async def run(): return StreamingListJsonResponse(gen()) # wire format: # {"type": "stdout", "text": "hello", "timestamp": null} # {"type": "stdout", "text": "world", "timestamp": null} # {"type": "end_of_execution"} ```