Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat: add template background build helpers (#1011)

Jakub Dobry6b74009972f0
diff --git a/.changeset/happy-bobcats-unite.md b/.changeset/happy-bobcats-unite.md
new file mode 100644
index 000000000..97a5fb0d7
--- /dev/null
+++ b/.changeset/happy-bobcats-unite.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': patch
+'e2b': patch
+---
+
+add background template build options
diff --git a/packages/js-sdk/src/template/buildApi.ts b/packages/js-sdk/src/template/buildApi.ts
index e3320782f..9403c073b 100644
--- a/packages/js-sdk/src/template/buildApi.ts
+++ b/packages/js-sdk/src/template/buildApi.ts
@@ -24,7 +24,7 @@ type TriggerBuildInput = {
type GetBuildStatusInput = {
templateID: string
buildID: string
- logsOffset: number
+ logsOffset?: number
}
export type GetBuildStatusResponse =
@@ -154,7 +154,7 @@ export async function triggerBuild(
export async function getBuildStatus(
client: ApiClient,
{ templateID, buildID, logsOffset }: GetBuildStatusInput
-) {
+): Promise<GetBuildStatusResponse> {
const buildStatusRes = await client.api.GET(
'/templates/{templateID}/builds/{buildID}/status',
{
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index ffb701bab..91bfbe17c 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -4,6 +4,8 @@ import { ConnectionConfig } from '../connectionConfig'
import { BuildError } from '../errors'
import { runtime } from '../utils'
import {
+ getBuildStatus,
+ GetBuildStatusResponse,
getFileUploadLink,
requestBuild,
triggerBuild,
@@ -16,8 +18,10 @@ import { parseDockerfile } from './dockerfileParser'
import { LogEntry, LogEntryEnd, LogEntryStart } from './logger'
import { ReadyCmd, waitForFile } from './readycmd'
import {
+ BuildInfo,
BuildOptions,
CopyItem,
+ GetBuildStatusOptions,
Instruction,
InstructionType,
McpServerName,
@@ -113,15 +117,94 @@ export class TemplateBase
static async build(
template: TemplateClass,
options: BuildOptions
- ): Promise<void> {
+ ): Promise<BuildInfo> {
try {
options.onBuildLogs?.(new LogEntryStart(new Date(), 'Build started'))
- return await (template as TemplateBase).build(options)
+ const baseTemplate = template as TemplateBase
+
+ const config = new ConnectionConfig({
+ domain: options.domain,
+ apiKey: options.apiKey,
+ })
+ const client = new ApiClient(config)
+
+ const data = await baseTemplate.build(client, options)
+
+ options.onBuildLogs?.(
+ new LogEntry(new Date(), 'info', 'Waiting for logs...')
+ )
+
+ await waitForBuildFinish(client, {
+ templateID: data.templateId,
+ buildID: data.buildId,
+ onBuildLogs: options.onBuildLogs,
+ logsRefreshFrequency: baseTemplate.logsRefreshFrequency,
+ stackTraces: baseTemplate.stackTraces,
+ })
+
+ return data
} finally {
options.onBuildLogs?.(new LogEntryEnd(new Date(), 'Build finished'))
}
}
+ /**
+ * Build and deploy a template to E2B infrastructure.
+ *
+ * @param template The template to build
+ * @param options Build configuration options
+ *
+ * @example
+ * ```ts
+ * const template = Template().fromPythonImage('3')
+ * const data = await Template.buildInBackground(template, {
+ * alias: 'my-python-env',
+ * cpuCount: 2,
+ * memoryMB: 1024
+ * })
+ * ```
+ */
+ static async buildInBackground(
+ template: TemplateClass,
+ options: BuildOptions
+ ): Promise<BuildInfo> {
+ const config = new ConnectionConfig({
+ domain: options.domain,
+ apiKey: options.apiKey,
+ })
+ const client = new ApiClient(config)
+
+ return await (template as TemplateBase).build(client, options)
+ }
+
+ /**
+ * Get the status of a build.
+ *
+ * @param data Build identifiers
+ * @param options Authentication options
+ *
+ * @example
+ * ```ts
+ * const status = await Template.getBuildStatus(data, { logsOffset: 0 })
+ * ```
+ */
+ static async getBuildStatus(
+ data: Pick<BuildInfo, 'templateId' | 'buildId'>,
+ options?: GetBuildStatusOptions
+ ): Promise<GetBuildStatusResponse> {
+ const config = new ConnectionConfig({
+ domain: options?.domain,
+ apiKey: options?.apiKey,
+ })
+ const client = new ApiClient(config)
+
+ return await getBuildStatus(client, {
+ templateID: data.templateId,
+ buildID: data.buildId,
+ logsOffset: options?.logsOffset,
+ })
+ }
+
fromDebianImage(variant: string = 'stable'): TemplateBuilder {
return this.fromImage(`debian:${variant}`)
}
@@ -768,16 +851,14 @@ export class TemplateBase
/**
* Internal implementation of the template build process.
*
+ * @param client API client for communicating with E2B backend
* @param options Build configuration options
* @throws BuildError if the build fails
*/
- private async build(options: BuildOptions): Promise<void> {
- const config = new ConnectionConfig({
- domain: options.domain,
- apiKey: options.apiKey,
- })
- const client = new ApiClient(config)
-
+ private async build(
+ client: ApiClient,
+ options: BuildOptions
+ ): Promise<BuildInfo> {
if (options.skipCache) {
this.force = true
}
@@ -880,17 +961,11 @@ export class TemplateBase
template: this.serialize(instructionsWithHashes),
})
- options.onBuildLogs?.(
- new LogEntry(new Date(), 'info', 'Waiting for logs...')
- )
-
- await waitForBuildFinish(client, {
- templateID,
- buildID,
- onBuildLogs: options.onBuildLogs,
- logsRefreshFrequency: this.logsRefreshFrequency,
- stackTraces: this.stackTraces,
- })
+ return {
+ alias: options.alias,
+ templateId: templateID,
+ buildId: buildID,
+ }
}
/**
@@ -989,12 +1064,16 @@ export function Template(options?: TemplateOptions): TemplateFromImage {
}
Template.build = TemplateBase.build
+Template.buildInBackground = TemplateBase.buildInBackground
+Template.getBuildStatus = TemplateBase.getBuildStatus
Template.toJSON = TemplateBase.toJSON
Template.toDockerfile = TemplateBase.toDockerfile
export type {
+ BuildInfo,
BuildOptions,
CopyItem,
+ GetBuildStatusOptions,
McpServerName,
TemplateBuilder,
TemplateClass,
diff --git a/packages/js-sdk/src/template/types.ts b/packages/js-sdk/src/template/types.ts
index 0529d366d..4c9808d6c 100644
--- a/packages/js-sdk/src/template/types.ts
+++ b/packages/js-sdk/src/template/types.ts
@@ -48,9 +48,9 @@ export type BasicBuildOptions = {
}
/**
- * Options for building a template with authentication.
+ * Authentication options for E2B API.
*/
-export type BuildOptions = BasicBuildOptions & {
+export type AuthOptions = {
/**
* E2B API key for authentication.
*/
@@ -61,6 +61,25 @@ export type BuildOptions = BasicBuildOptions & {
domain?: string
}
+/**
+ * Options for building a template with authentication.
+ */
+export type BuildOptions = AuthOptions & BasicBuildOptions
+
+/**
+ * Information about a built template.
+ */
+export type BuildInfo = {
+ alias: string
+ templateId: string
+ buildId: string
+}
+
+/**
+ * Response from getting build status.
+ */
+export type GetBuildStatusOptions = AuthOptions & { logsOffset?: number }
+
/**
* Types of instructions that can be used in a template.
*/
diff --git a/packages/js-sdk/tests/setup.ts b/packages/js-sdk/tests/setup.ts
index 9d509b607..49fd8ef61 100644
--- a/packages/js-sdk/tests/setup.ts
+++ b/packages/js-sdk/tests/setup.ts
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto'
import { test as base } from 'vitest'
-import { LogEntry, Sandbox, Template, TemplateClass } from '../src'
+import { BuildInfo, LogEntry, Sandbox, Template, TemplateClass } from '../src'
import { template } from './template'
interface SandboxFixture {
@@ -14,7 +14,7 @@ interface BuildTemplateFixture {
template: TemplateClass,
options?: { skipCache?: boolean },
onBuildLogs?: (logEntry: LogEntry) => void
- ) => Promise<void>
+ ) => Promise<BuildInfo>
}
function buildTemplate(
diff --git a/packages/js-sdk/tests/template/backgroundBuild.test.ts b/packages/js-sdk/tests/template/backgroundBuild.test.ts
new file mode 100644
index 000000000..8684f04c3
--- /dev/null
+++ b/packages/js-sdk/tests/template/backgroundBuild.test.ts
@@ -0,0 +1,26 @@
+import { randomUUID } from 'node:crypto'
+import { expect, test } from 'vitest'
+import { Template, waitForTimeout } from '../../src'
+
+test('build template in background', async () => {
+ const template = Template()
+ .fromImage('ubuntu:22.04')
+ .skipCache()
+ .runCmd('sleep 5') // Add a delay to ensure build takes time
+ .setStartCmd('echo "Hello"', waitForTimeout(10_000))
+
+ const alias = `e2b-test-${randomUUID()}`
+
+ const buildInfo = await Template.buildInBackground(template, {
+ alias,
+ cpuCount: 1,
+ memoryMB: 1024,
+ })
+
+ // Should return quickly (within a few seconds), not wait for the full build
+ expect(buildInfo).toBeDefined()
+
+ // Verify the build is actually running
+ const status = await Template.getBuildStatus(buildInfo)
+ expect(status.status).toEqual('building')
+}, 10_000)
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index c7956818a..4501d6660 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -92,7 +92,7 @@ from .template.readycmd import (
wait_for_process,
wait_for_timeout,
)
-from .template.types import CopyItem
+from .template.types import CopyItem, BuildInfo
from .template_async.main import AsyncTemplate
from .template_sync.main import Template
@@ -150,6 +150,7 @@ __all__ = [
"TemplateBase",
"TemplateClass",
"CopyItem",
+ "BuildInfo",
"ReadyCmd",
"wait_for_file",
"wait_for_url",
diff --git a/packages/python-sdk/e2b/template/types.py b/packages/python-sdk/e2b/template/types.py
index d6dfa8476..a1e840694 100644
--- a/packages/python-sdk/e2b/template/types.py
+++ b/packages/python-sdk/e2b/template/types.py
@@ -1,7 +1,7 @@
+from dataclasses import dataclass
from enum import Enum
from pathlib import Path
-from typing import List, Optional, TypedDict, Union
-from typing import Literal
+from typing import List, Literal, Optional, TypedDict, Union
from typing_extensions import NotRequired
@@ -92,3 +92,14 @@ class TemplateType(TypedDict):
readyCmd: NotRequired[str]
steps: List[Instruction]
force: bool
+
+
+@dataclass
+class BuildInfo:
+ """
+ Information about a built template.
+ """
+
+ alias: str
+ template_id: str
+ build_id: str
diff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.py
index de47042ce..f759024c7 100644
--- a/packages/python-sdk/e2b/template_async/main.py
+++ b/packages/python-sdk/e2b/template_async/main.py
@@ -3,12 +3,15 @@ from datetime import datetime
from typing import Callable, Optional
from e2b.api import AsyncApiClient
+from e2b.api.client.client import AuthenticatedClient
from e2b.connection_config import ConnectionConfig
from e2b.template.consts import RESOLVE_SYMLINKS
-from e2b.template.logger import LogEntry, LogEntryStart, LogEntryEnd
+from e2b.template.logger import LogEntry, LogEntryEnd, LogEntryStart
from e2b.template.main import TemplateBase, TemplateClass
-from e2b.template.types import InstructionType
+from e2b.template.types import BuildInfo, InstructionType
+
from .build_api import (
+ get_build_status,
get_file_upload_link,
request_build,
trigger_build,
@@ -22,6 +25,143 @@ class AsyncTemplate(TemplateBase):
Asynchronous template builder for E2B sandboxes.
"""
+ @staticmethod
+ async def _build(
+ template: TemplateClass,
+ api_client: AuthenticatedClient,
+ alias: str,
+ cpu_count: int = 2,
+ memory_mb: int = 1024,
+ skip_cache: bool = False,
+ on_build_logs: Optional[Callable[[LogEntry], None]] = None,
+ ) -> BuildInfo:
+ """
+ Internal implementation of the template build process
+
+ :param template: The template to build
+ :param api_client: Authenticated API client
+ :param alias: Alias name for the template
+ :param cpu_count: Number of CPUs allocated to the sandbox
+ :param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param skip_cache: If True, forces a complete rebuild ignoring cache
+ :param on_build_logs: Callback function to receive build logs during the build process
+ """
+ if skip_cache:
+ template._template._force = True
+
+ # Create template
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message=f"Requesting build for template: {alias}",
+ )
+ )
+
+ response = await request_build(
+ api_client,
+ name=alias,
+ cpu_count=cpu_count,
+ memory_mb=memory_mb,
+ )
+
+ template_id = response.template_id
+ build_id = response.build_id
+
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message=f"Template created with ID: {template_id}, Build ID: {build_id}",
+ )
+ )
+
+ instructions_with_hashes = template._template._instructions_with_hashes()
+
+ # Upload files
+ for index, file_upload in enumerate(instructions_with_hashes):
+ if file_upload["type"] != InstructionType.COPY:
+ continue
+
+ args = file_upload.get("args", [])
+ src = args[0] if len(args) > 0 else None
+ force_upload = file_upload.get("forceUpload")
+ files_hash = file_upload.get("filesHash", None)
+ resolve_symlinks = file_upload.get("resolveSymlinks", RESOLVE_SYMLINKS)
+
+ if src is None or files_hash is None:
+ raise ValueError("Source path and files hash are required")
+
+ stack_trace = None
+ if index + 1 < len(template._template._stack_traces):
+ stack_trace = template._template._stack_traces[index + 1]
+
+ file_info = await get_file_upload_link(
+ api_client, template_id, files_hash, stack_trace
+ )
+
+ if (force_upload and file_info.url) or (
+ file_info.present is False and file_info.url
+ ):
+ await upload_file(
+ src,
+ template._template._file_context_path,
+ file_info.url,
+ resolve_symlinks,
+ stack_trace,
+ )
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message=f"Uploaded '{src}'",
+ )
+ )
+ else:
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message=f"Skipping upload of '{src}', already cached",
+ )
+ )
+
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message="All file uploads completed",
+ )
+ )
+
+ # Start build
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message="Starting building...",
+ )
+ )
+
+ await trigger_build(
+ api_client,
+ template_id,
+ build_id,
+ template._template._serialize(instructions_with_hashes),
+ )
+
+ return BuildInfo(
+ alias=alias,
+ template_id=template_id,
+ build_id=build_id,
+ )
+
@staticmethod
async def build(
template: TemplateClass,
@@ -32,7 +172,7 @@ class AsyncTemplate(TemplateBase):
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
api_key: Optional[str] = None,
domain: Optional[str] = None,
- ) -> None:
+ ) -> BuildInfo:
"""
Build and deploy a template to E2B infrastructure.
@@ -84,119 +224,15 @@ class AsyncTemplate(TemplateBase):
limits=TemplateBase._limits,
)
- if skip_cache:
- template._template._force = True
-
with client as api_client:
- # Create template
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message=f"Requesting build for template: {alias}",
- )
- )
-
- response = await request_build(
- api_client,
- name=alias,
- cpu_count=cpu_count,
- memory_mb=memory_mb,
- )
-
- template_id = response.template_id
- build_id = response.build_id
-
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message=f"Template created with ID: {template_id}, Build ID: {build_id}",
- )
- )
-
- instructions_with_hashes = (
- template._template._instructions_with_hashes()
- )
-
- # Upload files
- for index, file_upload in enumerate(instructions_with_hashes):
- if file_upload["type"] != InstructionType.COPY:
- continue
-
- args = file_upload.get("args", [])
- src = args[0] if len(args) > 0 else None
- force_upload = file_upload.get("forceUpload")
- files_hash = file_upload.get("filesHash", None)
- resolve_symlinks = file_upload.get(
- "resolveSymlinks", RESOLVE_SYMLINKS
- )
-
- if src is None or files_hash is None:
- raise ValueError("Source path and files hash are required")
-
- stack_trace = None
- if index + 1 < len(template._template._stack_traces):
- stack_trace = template._template._stack_traces[index + 1]
-
- file_info = await get_file_upload_link(
- api_client, template_id, files_hash, stack_trace
- )
-
- if (force_upload and file_info.url) or (
- file_info.present is False and file_info.url
- ):
- await upload_file(
- src,
- template._template._file_context_path,
- file_info.url,
- resolve_symlinks,
- stack_trace,
- )
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message=f"Uploaded '{src}'",
- )
- )
- else:
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message=f"Skipping upload of '{src}', already cached",
- )
- )
-
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message="All file uploads completed",
- )
- )
-
- # Start build
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message="Starting building...",
- )
- )
-
- await trigger_build(
+ data = await AsyncTemplate._build(
+ template,
api_client,
- template_id,
- build_id,
- template._template._serialize(instructions_with_hashes),
+ alias,
+ cpu_count,
+ memory_mb,
+ skip_cache,
+ on_build_logs,
)
if on_build_logs:
@@ -210,12 +246,14 @@ class AsyncTemplate(TemplateBase):
await wait_for_build_finish(
api_client,
- template_id,
- build_id,
+ data.template_id,
+ data.build_id,
on_build_logs,
logs_refresh_frequency=TemplateBase._logs_refresh_frequency,
stack_traces=template._template._stack_traces,
)
+
+ return data
finally:
if on_build_logs:
on_build_logs(
@@ -224,3 +262,110 @@ class AsyncTemplate(TemplateBase):
message="Build finished",
)
)
+
+ @staticmethod
+ async def build_in_background(
+ template: TemplateClass,
+ alias: str,
+ cpu_count: int = 2,
+ memory_mb: int = 1024,
+ skip_cache: bool = False,
+ on_build_logs: Optional[Callable[[LogEntry], None]] = None,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ ) -> BuildInfo:
+ """
+ Build and deploy a template to E2B infrastructure without waiting for completion.
+
+ :param template: The template to build
+ :param alias: Alias name for the template
+ :param cpu_count: Number of CPUs allocated to the sandbox
+ :param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param skip_cache: If True, forces a complete rebuild ignoring cache
+ :param api_key: E2B API key for authentication
+ :param domain: Domain of the E2B API
+ :return: BuildInfo containing the template ID and build ID
+
+ Example
+ ```python
+ from e2b import AsyncTemplate
+
+ template = (
+ AsyncTemplate()
+ .from_python_image('3')
+ .run_cmd('echo "test"')
+ .set_start_cmd('echo "Hello"', 'sleep 1')
+ )
+
+ build_info = await AsyncTemplate.build_in_background(
+ template,
+ alias='my-python-env',
+ cpu_count=2,
+ memory_mb=1024
+ )
+ ```
+ """
+ domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
+ config = ConnectionConfig(
+ domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
+ )
+ client = AsyncApiClient(
+ config,
+ require_api_key=True,
+ require_access_token=False,
+ limits=TemplateBase._limits,
+ )
+
+ with client as api_client:
+ return await AsyncTemplate._build(
+ template,
+ api_client,
+ alias,
+ cpu_count,
+ memory_mb,
+ skip_cache,
+ on_build_logs,
+ )
+
+ @staticmethod
+ async def get_build_status(
+ build_info: BuildInfo,
+ logs_offset: int = 0,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ ):
+ """
+ Get the status of a build.
+
+ :param build_info: Build identifiers returned from build_in_background
+ :param logs_offset: Offset for fetching logs
+ :param api_key: E2B API key for authentication
+ :param domain: Domain of the E2B API
+ :return: TemplateBuild containing the build status and logs
+
+ Example
+ ```python
+ from e2b import AsyncTemplate
+
+ build_info = await AsyncTemplate.build_in_background(template, alias='my-template')
+ status = await AsyncTemplate.get_build_status(build_info, logs_offset=0)
+ ```
+ """
+ domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
+ config = ConnectionConfig(
+ domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
+ )
+ client = AsyncApiClient(
+ config,
+ require_api_key=True,
+ require_access_token=False,
+ limits=TemplateBase._limits,
+ )
+
+ with client as api_client:
+ return await get_build_status(
+ api_client,
+ build_info.template_id,
+ build_info.build_id,
+ logs_offset,
+ )
diff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.py
index f61806cb5..8987118a4 100644
--- a/packages/python-sdk/e2b/template_sync/main.py
+++ b/packages/python-sdk/e2b/template_sync/main.py
@@ -3,12 +3,14 @@ from datetime import datetime
from typing import Callable, Optional
from e2b.api import ApiClient
+from e2b.api.client.client import AuthenticatedClient
from e2b.connection_config import ConnectionConfig
from e2b.template.consts import RESOLVE_SYMLINKS
-from e2b.template.logger import LogEntry, LogEntryStart, LogEntryEnd
+from e2b.template.logger import LogEntry, LogEntryEnd, LogEntryStart
from e2b.template.main import TemplateBase, TemplateClass
-from e2b.template.types import InstructionType
+from e2b.template.types import BuildInfo, InstructionType
from e2b.template_sync.build_api import (
+ get_build_status,
get_file_upload_link,
request_build,
trigger_build,
@@ -22,6 +24,143 @@ class Template(TemplateBase):
Synchronous template builder for E2B sandboxes.
"""
+ @staticmethod
+ def _build(
+ template: TemplateClass,
+ api_client: AuthenticatedClient,
+ alias: str,
+ cpu_count: int = 2,
+ memory_mb: int = 1024,
+ skip_cache: bool = False,
+ on_build_logs: Optional[Callable[[LogEntry], None]] = None,
+ ) -> BuildInfo:
+ """
+ Internal implementation of the template build process
+
+ :param template: The template to build
+ :param api_client: Authenticated API client
+ :param alias: Alias name for the template
+ :param cpu_count: Number of CPUs allocated to the sandbox
+ :param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param skip_cache: If True, forces a complete rebuild ignoring cache
+ :param on_build_logs: Callback function to receive build logs during the build process
+ """
+ if skip_cache:
+ template._template._force = True
+
+ # Create template
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message=f"Requesting build for template: {alias}",
+ )
+ )
+
+ response = request_build(
+ api_client,
+ name=alias,
+ cpu_count=cpu_count,
+ memory_mb=memory_mb,
+ )
+
+ template_id = response.template_id
+ build_id = response.build_id
+
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message=f"Template created with ID: {template_id}, Build ID: {build_id}",
+ )
+ )
+
+ instructions_with_hashes = template._template._instructions_with_hashes()
+
+ # Upload files
+ for index, file_upload in enumerate(instructions_with_hashes):
+ if file_upload["type"] != InstructionType.COPY:
+ continue
+
+ args = file_upload.get("args", [])
+ src = args[0] if len(args) > 0 else None
+ force_upload = file_upload.get("forceUpload")
+ files_hash = file_upload.get("filesHash", None)
+ resolve_symlinks = file_upload.get("resolveSymlinks", RESOLVE_SYMLINKS)
+
+ if src is None or files_hash is None:
+ raise ValueError("Source path and files hash are required")
+
+ stack_trace = None
+ if index + 1 < len(template._template._stack_traces):
+ stack_trace = template._template._stack_traces[index + 1]
+
+ file_info = get_file_upload_link(
+ api_client, template_id, files_hash, stack_trace
+ )
+
+ if (force_upload and file_info.url) or (
+ file_info.present is False and file_info.url
+ ):
+ upload_file(
+ src,
+ template._template._file_context_path,
+ file_info.url,
+ resolve_symlinks,
+ stack_trace,
+ )
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message=f"Uploaded '{src}'",
+ )
+ )
+ else:
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message=f"Skipping upload of '{src}', already cached",
+ )
+ )
+
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message="All file uploads completed",
+ )
+ )
+
+ # Start build
+ if on_build_logs:
+ on_build_logs(
+ LogEntry(
+ timestamp=datetime.now(),
+ level="info",
+ message="Starting building...",
+ )
+ )
+
+ trigger_build(
+ api_client,
+ template_id,
+ build_id,
+ template._template._serialize(instructions_with_hashes),
+ )
+
+ return BuildInfo(
+ alias=alias,
+ template_id=template_id,
+ build_id=build_id,
+ )
+
@staticmethod
def build(
template: TemplateClass,
@@ -32,7 +171,7 @@ class Template(TemplateBase):
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
api_key: Optional[str] = None,
domain: Optional[str] = None,
- ) -> None:
+ ) -> BuildInfo:
"""
Build and deploy a template to E2B infrastructure.
@@ -84,119 +223,15 @@ class Template(TemplateBase):
limits=TemplateBase._limits,
)
- if skip_cache:
- template._template._force = True
-
with client as api_client:
- # Create template
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message=f"Requesting build for template: {alias}",
- )
- )
-
- response = request_build(
+ data = Template._build(
+ template,
api_client,
- name=alias,
- cpu_count=cpu_count,
- memory_mb=memory_mb,
- )
-
- template_id = response.template_id
- build_id = response.build_id
-
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message=f"Template created with ID: {template_id}, Build ID: {build_id}",
- )
- )
-
- instructions_with_hashes = (
- template._template._instructions_with_hashes()
- )
-
- # Upload files
- for index, file_upload in enumerate(instructions_with_hashes):
- if file_upload["type"] != InstructionType.COPY:
- continue
-
- args = file_upload.get("args", [])
- src = args[0] if len(args) > 0 else None
- force_upload = file_upload.get("forceUpload")
- files_hash = file_upload.get("filesHash", None)
- resolve_symlinks = file_upload.get(
- "resolveSymlinks", RESOLVE_SYMLINKS
- )
-
- if src is None or files_hash is None:
- raise ValueError("Source path and files hash are required")
-
- stack_trace = None
- if index + 1 < len(template._template._stack_traces):
- stack_trace = template._template._stack_traces[index + 1]
-
- file_info = get_file_upload_link(
- api_client, template_id, files_hash, stack_trace
- )
-
- if (force_upload and file_info.url) or (
- file_info.present is False and file_info.url
- ):
- upload_file(
- src,
- template._template._file_context_path,
- file_info.url,
- resolve_symlinks,
- stack_trace,
- )
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message=f"Uploaded '{src}'",
- )
- )
- else:
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message=f"Skipping upload of '{src}', already cached",
- )
- )
-
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message="All file uploads completed",
- )
- )
-
- # Start build
- if on_build_logs:
- on_build_logs(
- LogEntry(
- timestamp=datetime.now(),
- level="info",
- message="Starting building...",
- )
- )
-
- trigger_build(
- api_client,
- template_id,
- build_id,
- template._template._serialize(instructions_with_hashes),
+ alias,
+ cpu_count,
+ memory_mb,
+ skip_cache,
+ on_build_logs,
)
if on_build_logs:
@@ -210,12 +245,14 @@ class Template(TemplateBase):
wait_for_build_finish(
api_client,
- template_id,
- build_id,
+ data.template_id,
+ data.build_id,
on_build_logs,
logs_refresh_frequency=TemplateBase._logs_refresh_frequency,
stack_traces=template._template._stack_traces,
)
+
+ return data
finally:
if on_build_logs:
on_build_logs(
@@ -224,3 +261,110 @@ class Template(TemplateBase):
message="Build finished",
)
)
+
+ @staticmethod
+ def build_in_background(
+ template: TemplateClass,
+ alias: str,
+ cpu_count: int = 2,
+ memory_mb: int = 1024,
+ skip_cache: bool = False,
+ on_build_logs: Optional[Callable[[LogEntry], None]] = None,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ ) -> BuildInfo:
+ """
+ Build and deploy a template to E2B infrastructure without waiting for completion.
+
+ :param template: The template to build
+ :param alias: Alias name for the template
+ :param cpu_count: Number of CPUs allocated to the sandbox
+ :param memory_mb: Amount of memory in MB allocated to the sandbox
+ :param skip_cache: If True, forces a complete rebuild ignoring cache
+ :param api_key: E2B API key for authentication
+ :param domain: Domain of the E2B API
+ :return: BuildInfo containing the template ID and build ID
+
+ Example
+ ```python
+ from e2b import Template
+
+ template = (
+ Template()
+ .from_python_image('3')
+ .run_cmd('echo "test"')
+ .set_start_cmd('echo "Hello"', 'sleep 1')
+ )
+
+ build_info = Template.build_in_background(
+ template,
+ alias='my-python-env',
+ cpu_count=2,
+ memory_mb=1024
+ )
+ ```
+ """
+ domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
+ config = ConnectionConfig(
+ domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
+ )
+ client = ApiClient(
+ config,
+ require_api_key=True,
+ require_access_token=False,
+ limits=TemplateBase._limits,
+ )
+
+ with client as api_client:
+ return Template._build(
+ template,
+ api_client,
+ alias,
+ cpu_count,
+ memory_mb,
+ skip_cache,
+ on_build_logs,
+ )
+
+ @staticmethod
+ def get_build_status(
+ build_info: BuildInfo,
+ logs_offset: int = 0,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ ):
+ """
+ Get the status of a build.
+
+ :param build_info: Build identifiers returned from build_in_background
+ :param logs_offset: Offset for fetching logs
+ :param api_key: E2B API key for authentication
+ :param domain: Domain of the E2B API
+ :return: TemplateBuild containing the build status and logs
+
+ Example
+ ```python
+ from e2b import Template
+
+ build_info = Template.build_in_background(template, alias='my-template')
+ status = Template.get_build_status(build_info, logs_offset=0)
+ ```
+ """
+ domain = domain or os.environ.get("E2B_DOMAIN", "e2b.dev")
+ config = ConnectionConfig(
+ domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY")
+ )
+ client = ApiClient(
+ config,
+ require_api_key=True,
+ require_access_token=False,
+ limits=TemplateBase._limits,
+ )
+
+ with client as api_client:
+ return get_build_status(
+ api_client,
+ build_info.template_id,
+ build_info.build_id,
+ logs_offset,
+ )
diff --git a/packages/python-sdk/tests/async/template_async/test_background_build.py b/packages/python-sdk/tests/async/template_async/test_background_build.py
new file mode 100644
index 000000000..783a766b8
--- /dev/null
+++ b/packages/python-sdk/tests/async/template_async/test_background_build.py
@@ -0,0 +1,34 @@
+import uuid
+
+import pytest
+
+from e2b import AsyncTemplate, wait_for_timeout
+
+
+async def test_build_in_background_should_start_build_and_return_info():
+ """Test that build_in_background returns immediately without waiting for build to complete."""
+ template = (
+ AsyncTemplate()
+ .from_image("ubuntu:22.04")
+ .skip_cache()
+ .run_cmd("sleep 5") # Add a delay to ensure build takes time
+ .set_start_cmd('echo "Hello"', wait_for_timeout(10_000))
+ )
+
+ alias = f"e2b-test-{uuid.uuid4()}"
+
+ build_info = await AsyncTemplate.build_in_background(
+ template,
+ alias=alias,
+ cpu_count=1,
+ memory_mb=1024,
+ )
+
+ # Should return quickly (within a few seconds), not wait for the full build
+ assert build_info is not None
+
+ # Verify the build is actually running
+ status = await AsyncTemplate.get_build_status(build_info)
+ assert status.status.value == "building"
diff --git a/packages/python-sdk/tests/async/template_async/test_build.py b/packages/python-sdk/tests/async/template_async/test_build.py
index 00814d2f2..5aba74d40 100644
--- a/packages/python-sdk/tests/async/template_async/test_build.py
+++ b/packages/python-sdk/tests/async/template_async/test_build.py
@@ -1,10 +1,10 @@
+import os
+import shutil
import tempfile
import pytest
-import os
-import shutil
-from e2b import AsyncTemplate, wait_for_timeout, default_build_logger
+from e2b import AsyncTemplate, default_build_logger, wait_for_timeout
@pytest.fixture(scope="module")
diff --git a/packages/python-sdk/tests/sync/template_sync/test_background_build.py b/packages/python-sdk/tests/sync/template_sync/test_background_build.py
new file mode 100644
index 000000000..56fd1576d
--- /dev/null
+++ b/packages/python-sdk/tests/sync/template_sync/test_background_build.py
@@ -0,0 +1,34 @@
+import uuid
+
+import pytest
+
+from e2b import Template, wait_for_timeout
+
+
+def test_build_in_background_should_start_build_and_return_info():
+ """Test that build_in_background returns immediately without waiting for build to complete."""
+ template = (
+ Template()
+ .from_image("ubuntu:22.04")
+ .skip_cache()
+ .run_cmd("sleep 5") # Add a delay to ensure build takes time
+ .set_start_cmd('echo "Hello"', wait_for_timeout(10_000))
+ )
+
+ alias = f"e2b-test-{uuid.uuid4()}"
+
+ build_info = Template.build_in_background(
+ template,
+ alias=alias,
+ cpu_count=1,
+ memory_mb=1024,
+ )
+
+ # Should return quickly (within a few seconds), not wait for the full build
+ assert build_info is not None
+
+ # Verify the build is actually running
+ status = Template.get_build_status(build_info)
+ assert status.status.value == "building"