Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Expose sandbox metrics in SDKs and CLI (#828)
Jakub Nováke34d69525f1e
diff --git a/.changeset/dull-snakes-unite.md b/.changeset/dull-snakes-unite.mdnew file mode 100644index 000000000..b71a1794d--- /dev/null+++ b/.changeset/dull-snakes-unite.md@@ -0,0 +1,7 @@+---+'@e2b/python-sdk': minor+'e2b': minor+'@e2b/cli': minor+---++Expose sandbox metricsdiff --git a/apps/web/src/app/(docs)/docs/sandbox/installing-beta-sdks/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/installing-beta-sdks/page.mdxindex 590c593f1..69bdca363 100644--- a/apps/web/src/app/(docs)/docs/sandbox/installing-beta-sdks/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/installing-beta-sdks/page.mdx@@ -1,6 +1,6 @@# Installing beta SDKs-To use features like [sandbox persistence](/docs/sandbox/persistence) and [metrics](/docs/sandbox/metrics), you need to install the beta version of the SDKs.+To use features like [sandbox persistence](/docs/sandbox/persistence) you need to install the beta version of the SDKs.### Code Interpreter SDKdiff --git a/apps/web/src/app/(docs)/docs/sandbox/metrics/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/metrics/page.mdxindex 395c386f5..f1ac71785 100644--- a/apps/web/src/app/(docs)/docs/sandbox/metrics/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/metrics/page.mdx@@ -1,22 +1,10 @@# Sandbox metrics-<Note>-This feature is in a private beta.-</Note>--The sandbox metrics allows you to get information about the sandbox's CPU and memory usage.--## Installation--To get sandbox metrics, you need to install the beta version of the SDKs and CLI:--- [Installing beta SDKs](/docs/sandbox/installing-beta-sdks)--- [Installing beta CLI](/docs/cli#beta-cli)+The sandbox metrics allows you to get information about the sandbox's CPU, memory and disk usage.## Getting sandbox metrics-Getting the metrics of a sandbox returns an array of timestamped metrics containing CPU and memory usage information.-The metrics are collected at the start of the sandbox, then every 2 seconds, and finally right before the sandbox is deleted.+Getting the metrics of a sandbox returns an array of timestamped metrics containing CPU, memory and disk usage information.+The metrics are collected every 5 seconds.### Getting sandbox metrics using the SDKs@@ -27,6 +15,9 @@ import { Sandbox } from '@e2b/code-interpreter'const sbx = await Sandbox.create()console.log('Sandbox created', sbx.sandboxId)+// Wait for a few seconds to collect some metrics+await new Promise((resolve) => setTimeout(resolve, 10_000))+const metrics = await sbx.getMetrics() // $HighlightLine// You can also get the metrics by sandbox ID:@@ -34,30 +25,38 @@ const metrics = await sbx.getMetrics() // $HighlightLineconsole.log('Sandbox metrics:', metrics)+// Sandbox metrics:// [// {+// timestamp: 2025-07-28T08:04:05.000Z,+// cpuUsedPct: 20.33,// cpuCount: 2,-// cpuUsedPct: 50.05,-// memTotalMiB: 484,-// memUsedMiB: 37,-// timestamp: '2025-01-23T23:44:12.222Z'+// memUsed: 32681984, // in bytes+// memTotal: 507592704, // in bytes+// diskUsed: 1514856448, // in bytes+// diskTotal: 2573185024 // in bytes// },// {+// timestamp: 2025-07-28T08:04:10.000Z,+// cpuUsedPct: 0.2,// cpuCount: 2,-// cpuUsedPct: 4.5,-// memTotalMiB: 484,-// memUsedMiB: 37,-// timestamp: '2025-01-23T23:44:13.220Z'+// memUsed: 33316864, // in bytes+// memTotal: 507592704, // in bytes+// diskUsed: 1514856448, // in bytes+// diskTotal: 2573185024 // in bytes// }// ]-``````python+from time import sleepfrom e2b_code_interpreter import Sandboxsbx = Sandbox()print('Sandbox created', sbx.sandbox_id)+# Wait for a few seconds to collect some metrics+sleep(10)+metrics = sbx.get_metrics() # $HighlightLine# You can also get the metrics by sandbox ID:@@ -65,21 +64,26 @@ metrics = sbx.get_metrics() # $HighlightLineprint('Sandbox metrics', metrics)+# Sandbox metrics# [-# SandboxMetrics(timestamp=datetime.datetime(-# 2025, 1, 23, 23, 58, 42, 84050, tzinfo=tzutc()),-# cpu_count=2,-# cpu_used_pct=50.07,-# mem_total_mib=484-# mem_used_mib=37,-# ),-# SandboxMetrics(timestamp=datetime.datetime(-# 2025, 1, 23, 23, 58, 44, 84845, tzinfo=tzutc()),-# cpu_count=2,-# cpu_used_pct=4.75,-# mem_total_mib=484-# mem_used_mib=38,-# ),+# SandboxMetric(+# cpu_count=2,+# cpu_used_pct=13.97,+# disk_total=2573185024, # in bytes+# disk_used=1514856448, # in bytes+# mem_total=507592704, # in bytes+# mem_used=30588928, # in bytes+# timestamp=datetime.datetime(2025, 7, 28, 8, 8, 15, tzinfo=tzutc()),+# ),+# SandboxMetric(+# cpu_count=2,+# cpu_used_pct=0.1,+# disk_total=2573185024, # in bytes+# disk_used=1514856448, # in bytes+# mem_total=507592704, # in bytes+# mem_used=31084544, # in bytes+# timestamp=datetime.datetime(2025, 7, 28, 8, 8, 20, tzinfo=tzutc()),+# ),# ]```</CodeGroup>@@ -91,11 +95,13 @@ e2b sandbox metrics <sandbox_id> # $HighlightLine# Metrics for sandbox <sandbox_id>#-# [2025-01-23 00:58:58.829Z] { cpuCount: 2, cpuUsedPct: 50.21, logger: '', memTotalMiB: 484, memUsedMiB: 38, timestamp: '2025-01-23T00:58:58.829638869Z' }-# [2025-01-23 00:59:03.814Z] { cpuCount: 2, cpuUsedPct: 5.16, logger: '', memTotalMiB: 484, memUsedMiB: 37, timestamp: '2025-01-23T00:59:03.814028031Z' }-# [2025-01-23 00:59:08.815Z] { cpuCount: 2, cpuUsedPct: 1.6, logger: '', memTotalMiB: 484, memUsedMiB: 37, timestamp: '2025-01-23T00:59:08.815933749Z' }+# [2025-07-25 14:05:55Z] CPU: 8.27% / 2 Cores | Memory: 31 / 484 MiB | Disk: 1445 / 2453 MiB+# [2025-07-25 14:06:00Z] CPU: 0.5% / 2 Cores | Memory: 32 / 484 MiB | Disk: 1445 / 2453 MiB+# [2025-07-25 14:06:05Z] CPU: 0.1% / 2 Cores | Memory: 32 / 484 MiB | Disk: 1445 / 2453 MiB+# [2025-07-25 14:06:10Z] CPU: 0.3% / 2 Cores | Memory: 32 / 484 MiB | Disk: 1445 / 2453 MiB```</CodeGroup>-## Limitations while in beta-- It may take a second or more to get the metrics after the sandbox is created. Until the logs are collected from the sandbox, you will get an empty array.\ No newline at end of file+<Note>+ It may take a second or more to get the first metrics after the sandbox is created. Until the first metrics are collected from the sandbox, you will get an empty array.+</Note>diff --git a/packages/cli/src/commands/sandbox/index.ts b/packages/cli/src/commands/sandbox/index.tsindex 538ad5bff..3c61df848 100644--- a/packages/cli/src/commands/sandbox/index.ts+++ b/packages/cli/src/commands/sandbox/index.ts@@ -5,6 +5,7 @@ import { listCommand } from './list'import { killCommand } from './kill'import { spawnCommand } from './spawn'import { logsCommand } from './logs'+import { metricsCommand } from './metrics'export const sandboxCommand = new commander.Command('sandbox').description('work with sandboxes')@@ -14,3 +15,4 @@ export const sandboxCommand = new commander.Command('sandbox').addCommand(killCommand).addCommand(spawnCommand).addCommand(logsCommand)+ .addCommand(metricsCommand)diff --git a/packages/cli/src/commands/sandbox/logs.ts b/packages/cli/src/commands/sandbox/logs.tsindex 846259e43..4c5ee90f3 100644--- a/packages/cli/src/commands/sandbox/logs.ts+++ b/packages/cli/src/commands/sandbox/logs.ts@@ -8,45 +8,7 @@ import { asBold, asTimestamp, withUnderline } from 'src/utils/format'import { listSandboxes } from './list'import { wait } from 'src/utils/wait'import { handleE2BRequestError } from '../../utils/errors'--const maxRuntime = 24 * 60 * 60 * 1000 // 24 hours in milliseconds--function getShortID(sandboxID: string) {- return sandboxID.split('-')[0]-}--function waitForSandboxEnd(sandboxID: string) {- let isRunning = true-- async function monitor() {- const startTime = new Date().getTime()-- // eslint-disable-next-line no-constant-condition- while (true) {- const currentTime = new Date().getTime()- const elapsedTime = currentTime - startTime // Time elapsed in milliseconds-- // Check if 24 hours (in milliseconds) have passed- if (elapsedTime >= maxRuntime) {- break- }-- const response = await listSandboxes()- const sandbox = response.find(- (s) => s.sandboxID === getShortID(sandboxID)- )- if (!sandbox) {- isRunning = false- break- }- await wait(5000)- }- }-- monitor()-- return () => isRunning-}+import { waitForSandboxEnd, formatEnum, Format, getShortID } from './utils'enum LogLevel {DEBUG = 'DEBUG',@@ -76,17 +38,6 @@ function isLevelIncluded(level: LogLevel, allowedLevel?: LogLevel) {}}-function formatEnum(e: { [key: string]: string }) {- return Object.values(e)- .map((level) => asBold(level))- .join(', ')-}--enum LogFormat {- JSON = 'json',- PRETTY = 'pretty',-}-function cleanLogger(logger?: string) {if (!logger) {return ''@@ -112,8 +63,8 @@ export const logsCommand = new commander.Command('logs').option('-f, --follow', 'keep streaming logs until the sandbox is closed').option('--format <format>',- `specify format for printing logs (${formatEnum(LogFormat)})`,- LogFormat.PRETTY+ `specify format for printing logs (${formatEnum(Format)})`,+ Format.PRETTY).option('--loggers [loggers]',@@ -126,7 +77,7 @@ export const logsCommand = new commander.Command('logs')opts?: {level: stringfollow: boolean- format: LogFormat+ format: Formatloggers?: string[]}) => {@@ -136,8 +87,8 @@ export const logsCommand = new commander.Command('logs')throw new Error(`Invalid log level: ${level}`)}- const format = opts?.format.toLowerCase() as LogFormat | undefined- if (format && !Object.values(LogFormat).includes(format)) {+ const format = opts?.format.toLowerCase() as Format | undefined+ if (format && !Object.values(Format).includes(format)) {throw new Error(`Invalid log format: ${format}`)}@@ -149,7 +100,7 @@ export const logsCommand = new commander.Command('logs')let isFirstRun = truelet firstLogsPrinted = false- if (format === LogFormat.PRETTY) {+ if (format === Format.PRETTY) {console.log(`\nLogs for sandbox ${asBold(sandboxID)}:`)}@@ -178,7 +129,7 @@ export const logsCommand = new commander.Command('logs')const isRunning = await isRunningPromiseif (!isRunning && logs.length === 0 && isFirstRun) {- if (format === LogFormat.PRETTY) {+ if (format === Format.PRETTY) {console.log(`\nStopped printing logs — sandbox ${withUnderline('not found'@@ -189,7 +140,7 @@ export const logsCommand = new commander.Command('logs')}if (!isRunning) {- if (format === LogFormat.PRETTY) {+ if (format === Format.PRETTY) {console.log(`\nStopped printing logs — sandbox is ${withUnderline('closed'@@ -219,7 +170,7 @@ function printLog(timestamp: string,line: string,allowedLevel: LogLevel | undefined,- format: LogFormat | undefined,+ format: Format | undefined,allowedLoggers?: string[] | undefined) {const log = JSON.parse(line)@@ -266,7 +217,7 @@ function printLog(delete log['envID']delete log['sandboxID']- if (format === LogFormat.JSON) {+ if (format === Format.JSON) {console.log(JSON.stringify({timestamp: new Date(timestamp).toISOString(),diff --git a/packages/cli/src/commands/sandbox/metrics.ts b/packages/cli/src/commands/sandbox/metrics.tsnew file mode 100644index 000000000..d67ff6ab6--- /dev/null+++ b/packages/cli/src/commands/sandbox/metrics.ts@@ -0,0 +1,144 @@+import * as chalk from 'chalk'+import * as commander from 'commander'++import { asBold, asTimestamp, withUnderline } from 'src/utils/format'+import { wait } from 'src/utils/wait'+import { listSandboxes } from './list'+import { formatEnum, getShortID, Format } from './utils'+import { Sandbox } from 'e2b'++export const metricsCommand = new commander.Command('metrics')+ .description('show metrics for sandbox')+ .argument(+ '<sandboxID>',+ `show metrics for sandbox specified by ${asBold('<sandboxID>')}`+ )+ .alias('mt')+ .option('-f, --follow', 'keep streaming metrics until the sandbox is closed')+ .option(+ '--format <format>',+ `specify format for printing metrics (${formatEnum(Format)})`,+ Format.PRETTY+ )+ .action(+ async (+ sandboxID: string,+ opts?: {+ follow: boolean+ format: Format+ }+ ) => {+ try {+ const format = opts?.format.toLowerCase() as Format | undefined+ if (format && !Object.values(Format).includes(format)) {+ throw new Error(`Invalid log format: ${format}`)+ }++ let start: Date | undefined+ let isFirstRun = true+ let firstMetricsPrinted = false++ if (format === Format.PRETTY) {+ console.log(`\nMetrics for sandbox ${asBold(sandboxID)}:`)+ }++ const isRunningPromise = listSandboxes()+ .then((r) => r.find((s) => s.sandboxID === getShortID(sandboxID)))+ .then((s) => !!s)++ do {+ const metrics = await Sandbox.getMetrics(sandboxID, { start })++ if (metrics.length !== 0 && !firstMetricsPrinted) {+ firstMetricsPrinted = true+ process.stdout.write('\n')+ }++ for (const metric of metrics) {+ if (start && metric.timestamp <= start) {+ // Skip the metric if it has the same timestamp as the last one+ continue+ }+ start = metric.timestamp++ printMetric(metric.timestamp, JSON.stringify(metric), format)+ }++ const isRunning = await isRunningPromise++ if (!isRunning && metrics.length === 0 && isFirstRun) {+ if (format === Format.PRETTY) {+ console.log(+ `\nStopped printing metrics — sandbox ${withUnderline(+ 'not found'+ )}`+ )+ }+ break+ }++ if (!isRunning) {+ if (format === Format.PRETTY) {+ console.log(+ `\nStopped printing metrics — sandbox is ${withUnderline(+ 'closed'+ )}`+ )+ }+ break+ }++ await wait(400)+ isFirstRun = false+ } while (opts?.follow)+ } catch (err: any) {+ console.error(err)+ process.exit(1)+ }+ }+ )++function printMetric(+ timestamp: Date,+ line: string,+ format: Format | undefined+) {+ const metric = JSON.parse(line)+ const level = chalk.default.green()++ if (format === Format.JSON) {+ console.log(+ JSON.stringify({+ timestamp: timestamp.toISOString(),+ ...metric,+ })+ )+ } else {+ const time = `[${timestamp+ .toISOString()+ .replace(/\.\d{3}Z/, 'Z')+ .replace(/T/, ' ')}]`+ delete metric['timestamp']+ const multipleCores = metric.cpuCount > 1+ metric.cpuCount += 0+ console.log(+ `${asTimestamp(time)} ${level} ` ++ asBold('CPU') ++ `: ${metric.cpuUsedPct.toString().padStart(5)}% / ${metric.cpuCount+ .toString()+ .padStart(2)} Core${multipleCores && 's'} | ` ++ asBold('Memory') ++ `: ${(metric.memUsed >>> 20).toString().padStart(5)} / ${(+ metric.memTotal >>> 20+ )+ .toString()+ .padEnd(5)} MiB | ` ++ asBold('Disk') ++ `: ${(metric.diskUsed >>> 20).toString().padStart(5)} / ${(+ metric.diskTotal >>> 20+ )+ .toString()+ .padEnd(5)} MiB`+ )+ }+}diff --git a/packages/cli/src/commands/sandbox/utils.ts b/packages/cli/src/commands/sandbox/utils.tsnew file mode 100644index 000000000..1f2fc6ab1--- /dev/null+++ b/packages/cli/src/commands/sandbox/utils.ts@@ -0,0 +1,55 @@+import { listSandboxes } from './list'+import { wait } from '../../utils/wait'+import {asBold} from '../../utils/format'+++export function formatEnum(e: { [key: string]: string }) {+ return Object.values(e)+ .map((level) => asBold(level))+ .join(', ')+}++export enum Format {+ JSON = 'json',+ PRETTY = 'pretty',+}+++const maxRuntime = 24 * 60 * 60 * 1000 // 24 hours in milliseconds++export function waitForSandboxEnd(sandboxID: string) {+ let isRunning = true++ async function monitor() {+ const startTime = new Date().getTime()++ // eslint-disable-next-line no-constant-condition+ while (true) {+ const currentTime = new Date().getTime()+ const elapsedTime = currentTime - startTime // Time elapsed in milliseconds++ // Check if 24 hours (in milliseconds) have passed+ if (elapsedTime >= maxRuntime) {+ break+ }++ const response = await listSandboxes()+ const sandbox = response.find(+ (s) => s.sandboxID === getShortID(sandboxID)+ )+ if (!sandbox) {+ isRunning = false+ break+ }+ await wait(5000)+ }+ }++ monitor()++ return () => isRunning+}++export function getShortID(sandboxID: string) {+ return sandboxID.split('-')[0]+}diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.tsindex a0acdbf20..ac07d6bf3 100644--- a/packages/js-sdk/src/index.ts+++ b/packages/js-sdk/src/index.ts@@ -44,7 +44,7 @@ export type {} from './sandbox/commands'export type { SandboxOpts } from './sandbox'-export type { SandboxInfo } from './sandbox/sandboxApi'+export type { SandboxInfo, SandboxMetrics } from './sandbox/sandboxApi'export { Sandbox }import { Sandbox } from './sandbox'export default Sandboxdiff --git a/packages/js-sdk/src/logs.ts b/packages/js-sdk/src/logs.tsindex 87422b95f..5d6d51a2b 100644--- a/packages/js-sdk/src/logs.ts+++ b/packages/js-sdk/src/logs.ts@@ -13,6 +13,10 @@ export interface Logger {* Info level logging method.*/info?: (...args: any[]) => void+ /**+ * Warn level logging method.+ */+ warn?: (...args: any[]) => void/*** Error level logging method.*/diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.tsindex 9d9502fdf..321dab312 100644--- a/packages/js-sdk/src/sandbox/index.ts+++ b/packages/js-sdk/src/sandbox/index.ts@@ -10,8 +10,10 @@ import { EnvdApiClient, handleEnvdApiError } from '../envd/api'import { createRpcLogger } from '../logs'import { Commands, Pty } from './commands'import { Filesystem } from './filesystem'-import { SandboxApi } from './sandboxApi'+import { SandboxApi, SandboxMetricsOpts } from './sandboxApi'import { getSignature } from './signature'+import { compareVersions } from 'compare-versions'+import { SandboxError } from '../errors'/*** Options for creating a new Sandbox.@@ -524,6 +526,35 @@ export class Sandbox extends SandboxApi {})}+ /**+ * Get the metrics of the sandbox.+ *+ * @param opts connection options.+ *+ * @returns List of sandbox metrics containing CPU, memory and disk usage information.+ */+ async getMetrics(opts?: Pick<SandboxMetricsOpts, 'start' | 'end' | 'requestTimeoutMs'>) {+ if (this.envdApi.version) {+ if (compareVersions(this.envdApi.version, '0.1.5') < 0) {+ throw new SandboxError(+ 'You need to update the template to use the new SDK. ' ++ 'You can do this by running `e2b template build` in the directory with the template.'+ )+ }++ if (compareVersions(this.envdApi.version, '0.2.4') < 0) {+ this.connectionConfig.logger?.warn?.(+ 'Disk metrics are not supported in this version of the sandbox, please rebuild the template to get disk metrics.'+ )+ }+ }++ return await Sandbox.getMetrics(this.sandboxId, {+ ...this.connectionConfig,+ ...opts,+ })+ }+private fileUrl(path?: string, username?: string) {const url = new URL('/files', this.envdApiUrl)diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.tsindex 2e75cdbec..1c3579545 100644--- a/packages/js-sdk/src/sandbox/sandboxApi.ts+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts@@ -21,6 +21,17 @@ export interface SandboxListOpts extends SandboxApiOpts {query?: { metadata?: Record<string, string> }}+export interface SandboxMetricsOpts extends SandboxApiOpts {+ /**+ * Start time for the metrics, defaults to the start of the sandbox+ */+ start?: string | Date+ /**+ * End time for the metrics, defaults to the current time+ */+ end?: string | Date+}+/*** Information about a sandbox.*/@@ -80,33 +91,33 @@ export interface ListedSandbox {/*** Template ID alias.*/- alias?: string;+ alias?: string/*** Template ID.*/- templateId: string;+ templateId: string/*** Client ID.* @deprecated*/- clientId: string;+ clientId: string/*** Sandbox state.*/- state: 'running' | 'paused';+ state: 'running' | 'paused'/*** Sandbox CPU count.*/- cpuCount: number;+ cpuCount: number/*** Sandbox Memory size in MB.*/- memoryMB: number;+ memoryMB: number/*** Saved sandbox metadata.@@ -116,14 +127,53 @@ export interface ListedSandbox {/*** Sandbox expected end time.*/- endAt: Date;+ endAt: Date/*** Sandbox start time.*/- startedAt: Date;+ startedAt: Date}+/**+ * Sandbox resource usage metrics.+ */+export interface SandboxMetrics {+ /**+ * Timestamp of the metrics.+ */+ timestamp: Date++ /**+ * CPU usage in percentage.+ */+ cpuUsedPct: number++ /**+ * Number of CPU cores.+ */+ cpuCount: number++ /**+ * Memory usage in bytes.+ */+ memUsed: number++ /**+ * Total memory available in bytes.+ */+ memTotal: number++ /**+ * Used disk space in bytes.+ */+ diskUsed: number++ /**+ * Total disk space available in bytes.+ */+ diskTotal: number+}export class SandboxApi {protected constructor() {}@@ -202,7 +252,7 @@ export class SandboxApi {return (res.data?.map((sandbox: components['schemas']['ListedSandbox']) => ({- sandboxId: sandbox.sandboxID,+ sandboxId: sandbox.sandboxID,templateId: sandbox.templateID,clientId: sandbox.clientID,state: sandbox.state,@@ -262,6 +312,50 @@ export class SandboxApi {}}+ /**+ * Get the metrics of the sandbox.+ *+ * @param sandboxId sandbox ID.+ * @param opts sandbox metrics options.+ *+ * @returns List of sandbox metrics containing CPU, memory and disk usage information.+ */+ static async getMetrics(+ sandboxId: string,+ opts?: SandboxMetricsOpts+ ): Promise<SandboxMetrics[]> {+ const config = new ConnectionConfig(opts)+ const client = new ApiClient(config)++ const res = await client.api.GET('/sandboxes/{sandboxID}/metrics', {+ params: {+ path: {+ sandboxID: sandboxId,+ start: opts?.start,+ end: opts?.end,+ },+ },+ signal: config.getSignal(opts?.requestTimeoutMs),+ })++ const err = handleApiError(res)+ if (err) {+ throw err+ }++ return (+ res.data?.map((metric: components['schemas']['SandboxMetric']) => ({+ timestamp: new Date(metric.timestamp),+ cpuUsedPct: metric.cpuUsedPct,+ cpuCount: metric.cpuCount,+ memUsed: metric.memUsed,+ memTotal: metric.memTotal,+ diskUsed: metric.diskUsed,+ diskTotal: metric.diskTotal,+ })) ?? []+ )+ }+/*** Set the timeout of the specified sandbox.* After the timeout expires the sandbox will be automatically killed.@@ -346,7 +440,7 @@ export class SandboxApi {sandboxId: res.data!.sandboxID,sandboxDomain: res.data!.domain || undefined,envdVersion: res.data!.envdVersion,- envdAccessToken: res.data!.envdAccessToken+ envdAccessToken: res.data!.envdAccessToken,}}diff --git a/packages/js-sdk/tests/sandbox/metrics.test.ts b/packages/js-sdk/tests/sandbox/metrics.test.tsnew file mode 100644index 000000000..b67543243--- /dev/null+++ b/packages/js-sdk/tests/sandbox/metrics.test.ts@@ -0,0 +1,24 @@+import { expect } from 'vitest'++import { SandboxMetrics } from '../../src'+import {sandboxTest, isDebug, wait} from '../setup.js'++sandboxTest.skipIf(isDebug)('sbx metrics', async ({ sandbox }) => {+ let metrics: SandboxMetrics[]+ for (let i = 0; i < 10; i++) {+ metrics = await sandbox.getMetrics()+ if (metrics.length > 0) {+ break+ }+ await wait(1_000)+ }++ expect(metrics.length).toBeGreaterThan(0)+ const metric = metrics[0]+ expect(metric.diskTotal).toBeDefined()+ expect(metric.diskUsed).toBeDefined()+ expect(metric.memTotal).toBeDefined()+ expect(metric.memUsed).toBeDefined()+ expect(metric.cpuUsedPct).toBeDefined()+ expect(metric.cpuCount).toBeDefined()+})diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.pyindex 9610017e1..d8d85aec3 100644--- a/packages/python-sdk/e2b/__init__.py+++ b/packages/python-sdk/e2b/__init__.py@@ -42,7 +42,7 @@ from .exceptions import (NotEnoughSpaceException,TemplateException,)-from .sandbox.sandbox_api import SandboxInfo+from .sandbox.sandbox_api import SandboxInfo, SandboxMetricsfrom .sandbox.commands.main import ProcessInfofrom .sandbox.commands.command_handle import (CommandResult,@@ -84,6 +84,7 @@ __all__ = ["TemplateException",# Sandbox API"SandboxInfo",+ "SandboxMetrics","ProcessInfo",# Command handle"CommandResult",diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.pyindex f928a4039..49ec991f3 100644--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py@@ -63,6 +63,26 @@ class SandboxQuery:"""Filter sandboxes by metadata."""+@dataclass+class SandboxMetrics:+ """Sandbox metrics."""++ cpu_count: int+ """Number of CPUs."""+ cpu_used_pct: float+ """CPU usage percentage."""+ disk_total: int+ """Total disk space in bytes."""+ disk_used: int+ """Disk used in bytes."""+ mem_total: int+ """Total memory in bytes."""+ mem_used: int+ """Memory used in bytes."""+ timestamp: datetime+ """Timestamp of the metric entry."""++class SandboxApiBase(ABC):_limits = Limits(max_keepalive_connections=10,diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.pyindex 27f60b915..69a591658 100644--- a/packages/python-sdk/e2b/sandbox_async/main.py+++ b/packages/python-sdk/e2b/sandbox_async/main.py@@ -1,14 +1,18 @@+import datetimeimport loggingimport httpx-from typing import Dict, Optional, TypedDict, overload+from typing import Dict, Optional, TypedDict, overload, List++from packaging.version import Versionfrom typing_extensions import Unpackfrom e2b.api.client.types import Unsetfrom e2b.connection_config import ConnectionConfig, ProxyTypesfrom e2b.envd.api import ENVD_API_HEALTH_ROUTE, ahandle_envd_api_exception-from e2b.exceptions import format_request_timeout_error+from e2b.exceptions import format_request_timeout_error, SandboxExceptionfrom e2b.sandbox.main import SandboxSetup+from e2b.sandbox.sandbox_api import SandboxMetricsfrom e2b.sandbox.utils import class_method_variantfrom e2b.sandbox_async.filesystem.filesystem import Filesystemfrom e2b.sandbox_async.commands.command import Commands@@ -508,3 +512,85 @@ class AsyncSandbox(SandboxSetup, SandboxApi):sandbox_id=self.sandbox_id,**config_dict,)++ @overload+ async def get_metrics( # type: ignore+ self,+ start: Optional[datetime.datetime] = None,+ end: Optional[datetime.datetime] = None,+ request_timeout: Optional[float] = None,+ ) -> List[SandboxMetrics]:+ """+ Get the metrics of the current sandbox.++ :param start: Start time for the metrics, defaults to the start of the sandbox+ :param end: End time for the metrics, defaults to current time+ :param request_timeout: Timeout for the request in **seconds**++ :return: List of sandbox metrics containing CPU, memory and disk usage information+ """+ ...++ @overload+ @staticmethod+ async def get_metrics(+ sandbox_id: str,+ start: Optional[datetime.datetime] = None,+ end: Optional[datetime.datetime] = None,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ ) -> List[SandboxMetrics]:+ """+ Get the metrics of the sandbox specified by sandbox ID.++ :param sandbox_id: Sandbox ID+ :param start: Start time for the metrics, defaults to the start of the sandbox+ :param end: End time for the metrics, defaults to current time+ :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable+ :param request_timeout: Timeout for the request in **seconds**++ :return: List of sandbox metrics containing CPU, memory and disk usage information+ """+ ...++ @class_method_variant("_cls_get_metrics")+ async def get_metrics( # type: ignore+ self,+ start: Optional[datetime.datetime] = None,+ end: Optional[datetime.datetime] = None,+ request_timeout: Optional[float] = None,+ ) -> List[SandboxMetrics]:+ """+ Get the metrics of the current sandbox.++ :param start: Start time for the metrics, defaults to the start of the sandbox+ :param end: End time for the metrics, defaults to current time+ :param request_timeout: Timeout for the request in **seconds**++ :return: List of sandbox metrics containing CPU, memory and disk usage information+ """+ if self._envd_version:+ if Version(self._envd_version) < Version("0.1.5"):+ raise SandboxException(+ "Metrics are not supported in this version of the sandbox, please rebuild your template."+ )++ if Version(self._envd_version) < Version("0.2.4"):+ logger.warning(+ "Disk metrics are not supported in this version of the sandbox, please rebuild the template to get disk metrics."+ )++ config_dict = self.connection_config.__dict__+ config_dict.pop("access_token", None)+ config_dict.pop("api_url", None)+ if request_timeout:+ config_dict["request_timeout"] = request_timeout++ return await self._cls_get_metrics(+ sandbox_id=self.sandbox_id,+ start=start,+ end=end,+ **config_dict,+ )diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.pyindex 6ef22bb76..200fab131 100644--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py@@ -1,3 +1,4 @@+import datetimeimport urllib.parsefrom typing import Optional, Dict, List@@ -9,16 +10,22 @@ from e2b.sandbox.sandbox_api import (SandboxApiBase,SandboxQuery,ListedSandbox,+ SandboxMetrics,)-from e2b.exceptions import TemplateException+from e2b.exceptions import TemplateException, SandboxExceptionfrom e2b.api import AsyncApiClient, SandboxCreateResponse-from e2b.api.client.models import NewSandbox, PostSandboxesSandboxIDTimeoutBody+from e2b.api.client.models import (+ NewSandbox,+ PostSandboxesSandboxIDTimeoutBody,+ Error,+)from e2b.api.client.api.sandboxes import (get_sandboxes_sandbox_id,post_sandboxes_sandbox_id_timeout,get_sandboxes,delete_sandboxes_sandbox_id,post_sandboxes,+ get_sandboxes_sandbox_id_metrics,)from e2b.connection_config import ConnectionConfig, ProxyTypesfrom e2b.api import handle_api_exception@@ -298,3 +305,64 @@ class SandboxApi(SandboxApiBase):envd_version=res.parsed.envd_version,envd_access_token=res.parsed.envd_access_token,)++ @classmethod+ async def _cls_get_metrics(+ cls,+ sandbox_id: str,+ start: Optional[datetime.datetime] = None,+ end: Optional[datetime.datetime] = None,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ headers: Optional[Dict[str, str]] = None,+ proxy: Optional[ProxyTypes] = None,+ ) -> List[SandboxMetrics]:+ config = ConnectionConfig(+ api_key=api_key,+ domain=domain,+ debug=debug,+ headers=headers,+ request_timeout=request_timeout,+ proxy=proxy,+ )++ if config.debug:+ # Skip getting the metrics in debug mode+ return []++ async with AsyncApiClient(+ config,+ limits=cls._limits,+ ) as api_client:+ res = await get_sandboxes_sandbox_id_metrics.asyncio_detailed(+ sandbox_id,+ start=int(start.timestamp() * 1000) if start else None,+ end=int(end.timestamp() * 1000) if end else None,+ client=api_client,+ )++ if res.status_code >= 300:+ raise handle_api_exception(res)++ if res.parsed is None:+ return []++ # Check if res.parse is Error+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")++ # Convert to typed SandboxMetrics objects+ return [+ SandboxMetrics(+ cpu_count=metric.cpu_count,+ cpu_used_pct=metric.cpu_used_pct,+ disk_total=metric.disk_total,+ disk_used=metric.disk_used,+ mem_total=metric.mem_total,+ mem_used=metric.mem_used,+ timestamp=metric.timestamp,+ )+ for metric in res.parsed+ ]diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.pyindex b09cc8190..bbe99b01b 100644--- a/packages/python-sdk/e2b/sandbox_sync/main.py+++ b/packages/python-sdk/e2b/sandbox_sync/main.py@@ -1,13 +1,17 @@+import datetimeimport loggingimport httpx-from typing import Dict, Optional, overload+from typing import Dict, Optional, overload, List++from packaging.version import Versionfrom e2b.api.client.types import Unsetfrom e2b.connection_config import ConnectionConfig, ProxyTypesfrom e2b.envd.api import ENVD_API_HEALTH_ROUTE, handle_envd_api_exceptionfrom e2b.exceptions import SandboxException, format_request_timeout_errorfrom e2b.sandbox.main import SandboxSetup+from e2b.sandbox.sandbox_api import SandboxMetricsfrom e2b.sandbox.utils import class_method_variantfrom e2b.sandbox_sync.filesystem.filesystem import Filesystemfrom e2b.sandbox_sync.commands.command import Commands@@ -484,3 +488,85 @@ class Sandbox(SandboxSetup, SandboxApi):sandbox_id=self.sandbox_id,**config_dict,)++ @overload+ def get_metrics( # type: ignore+ self,+ start: Optional[datetime.datetime] = None,+ end: Optional[datetime.datetime] = None,+ request_timeout: Optional[float] = None,+ ) -> List[SandboxMetrics]:+ """+ Get the metrics of the current sandbox.++ :param start: Start time for the metrics, defaults to the start of the sandbox+ :param end: End time for the metrics, defaults to current time+ :param request_timeout: Timeout for the request in **seconds**++ :return: List of sandbox metrics containing CPU, memory and disk usage information+ """+ ...++ @overload+ @staticmethod+ def get_metrics(+ sandbox_id: str,+ start: Optional[datetime.datetime] = None,+ end: Optional[datetime.datetime] = None,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ ) -> List[SandboxMetrics]:+ """+ Get the metrics of the sandbox specified by sandbox ID.++ :param sandbox_id: Sandbox ID+ :param start: Start time for the metrics, defaults to the start of the sandbox+ :param end: End time for the metrics, defaults to current time+ :param api_key: E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable+ :param request_timeout: Timeout for the request in **seconds**++ :return: List of sandbox metrics containing CPU, memory and disk usage information+ """+ ...++ @class_method_variant("_cls_get_metrics")+ def get_metrics( # type: ignore+ self,+ start: Optional[datetime.datetime] = None,+ end: Optional[datetime.datetime] = None,+ request_timeout: Optional[float] = None,+ ) -> List[SandboxMetrics]:+ """+ Get the metrics of the current sandbox.++ :param start: Start time for the metrics, defaults to the start of the sandbox+ :param end: End time for the metrics, defaults to current time+ :param request_timeout: Timeout for the request in **seconds**++ :return: List of sandbox metrics containing CPU, memory and disk usage information+ """+ if self._envd_version:+ if Version(self._envd_version) < Version("0.1.5"):+ raise SandboxException(+ "Metrics are not supported in this version of the sandbox, please rebuild your template."+ )++ if Version(self._envd_version) < Version("0.2.4"):+ logger.warning(+ "Disk metrics are not supported in this version of the sandbox, please rebuild the template to get disk metrics."+ )++ config_dict = self.connection_config.__dict__+ config_dict.pop("access_token", None)+ config_dict.pop("api_url", None)+ if request_timeout:+ config_dict["request_timeout"] = request_timeout++ return self._cls_get_metrics(+ sandbox_id=self.sandbox_id,+ start=start,+ end=end,+ **config_dict,+ )diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.pyindex e817276dc..109d3235c 100644--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py@@ -1,3 +1,4 @@+import datetimeimport urllib.parsefrom typing import Optional, Dict, List@@ -8,16 +9,22 @@ from e2b.sandbox.sandbox_api import (SandboxApiBase,SandboxQuery,ListedSandbox,+ SandboxMetrics,)-from e2b.exceptions import TemplateException+from e2b.exceptions import TemplateException, SandboxExceptionfrom e2b.api import ApiClient, SandboxCreateResponse-from e2b.api.client.models import NewSandbox, PostSandboxesSandboxIDTimeoutBody+from e2b.api.client.models import (+ NewSandbox,+ PostSandboxesSandboxIDTimeoutBody,+ Error,+)from e2b.api.client.api.sandboxes import (get_sandboxes_sandbox_id,post_sandboxes_sandbox_id_timeout,get_sandboxes,delete_sandboxes_sandbox_id,post_sandboxes,+ get_sandboxes_sandbox_id_metrics,)from e2b.connection_config import ConnectionConfig, ProxyTypesfrom e2b.api import handle_api_exception@@ -290,3 +297,63 @@ class SandboxApi(SandboxApiBase):envd_version=res.parsed.envd_version,envd_access_token=res.parsed.envd_access_token,)++ @classmethod+ def _cls_get_metrics(+ cls,+ sandbox_id: str,+ start: Optional[datetime.datetime] = None,+ end: Optional[datetime.datetime] = None,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ headers: Optional[Dict[str, str]] = None,+ proxy: Optional[ProxyTypes] = None,+ ) -> List[SandboxMetrics]:+ config = ConnectionConfig(+ api_key=api_key,+ domain=domain,+ debug=debug,+ request_timeout=request_timeout,+ headers=headers,+ proxy=proxy,+ )++ if config.debug:+ # Skip getting the metrics in debug mode+ return []++ with ApiClient(+ config,+ limits=cls._limits,+ ) as api_client:+ res = get_sandboxes_sandbox_id_metrics.sync_detailed(+ sandbox_id,+ start=int(start.timestamp() * 1000) if start else None,+ end=int(end.timestamp() * 1000) if end else None,+ client=api_client,+ )++ if res.status_code >= 300:+ raise handle_api_exception(res)++ if res.parsed is None:+ return []++ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")++ # Convert to typed SandboxMetrics objects+ return [+ SandboxMetrics(+ cpu_count=metric.cpu_count,+ cpu_used_pct=metric.cpu_used_pct,+ disk_total=metric.disk_total,+ disk_used=metric.disk_used,+ mem_total=metric.mem_total,+ mem_used=metric.mem_used,+ timestamp=metric.timestamp,+ )+ for metric in res.parsed+ ]diff --git a/packages/python-sdk/tests/async/sandbox_async/test_metrics.py b/packages/python-sdk/tests/async/sandbox_async/test_metrics.pynew file mode 100644index 000000000..3d1e30a11--- /dev/null+++ b/packages/python-sdk/tests/async/sandbox_async/test_metrics.py@@ -0,0 +1,26 @@+import asyncio++import pytest++from e2b import AsyncSandbox++[email protected]_debug()+async def test_sbx_metrics(async_sandbox: AsyncSandbox):+ # Wait for the sandbox to have some metrics+ metrics = []+ for _ in range(10):+ metrics = await async_sandbox.get_metrics()+ if len(metrics) > 0:+ break+ await asyncio.sleep(1)++ assert len(metrics) > 0++ metric = metrics[0]+ assert metric.cpu_count is not None+ assert metric.cpu_used_pct is not None+ assert metric.mem_used is not None+ assert metric.mem_total is not None+ assert metric.disk_used is not None+ assert metric.disk_total is not Nonediff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_metrics.py b/packages/python-sdk/tests/sync/sandbox_sync/test_metrics.pynew file mode 100644index 000000000..03c5eb92c--- /dev/null+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_metrics.py@@ -0,0 +1,26 @@+import time++import pytest++from e2b import Sandbox++[email protected]_debug()+def test_sbx_metrics(sandbox: Sandbox):+ # Wait for the sandbox to have some metrics+ metrics = []+ for _ in range(10):+ metrics = sandbox.get_metrics()+ if len(metrics) > 0:+ break+ time.sleep(1)++ assert len(metrics) > 0++ metric = metrics[0]+ assert metric.cpu_count is not None+ assert metric.cpu_used_pct is not None+ assert metric.mem_used is not None+ assert metric.mem_total is not None+ assert metric.disk_used is not None+ assert metric.disk_total is not None