Skip to content

BeamExecutionEnvironment

Base classes

Name Children Inherits
ExecutionEnvironment
exxec.base
Abstract base class for code execution environments.

⋔ Inheritance diagram

graph TD
  331376749["provider.BeamExecutionEnvironment"]
  2194323221["base.ExecutionEnvironment"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  2194323221 --> 331376749
  925645236 --> 2194323221
  2751680898 --> 925645236

🛈 DocStrings

Bases: ExecutionEnvironment

Executes code in a Beam cloud sandbox.

Source code in src/exxec/beam_provider/provider.py
class BeamExecutionEnvironment(ExecutionEnvironment):
    """Executes code in a Beam cloud sandbox."""

    supports_spawn = True

    def __init__(
        self,
        lifespan_handler: AbstractAsyncContextManager[ServerInfo] | None = None,
        dependencies: list[str] | None = None,
        cpu: float | str = 1.0,
        memory: int | str = 128,
        keep_warm_seconds: int = 600,
        timeout: float = 300.0,
        language: Language = "python",
        cwd: str | None = None,
        env_vars: dict[str, str] | None = None,
        inherit_env: bool = False,
        default_command_timeout: float | None = None,
    ) -> None:
        """Initialize Beam environment.

        Args:
            lifespan_handler: Async context manager for tool server (optional)
            dependencies: List of packages to install via pip / npm
            cpu: CPU cores allocated to the container
            memory: Memory allocated to the container (MiB or string with units)
            keep_warm_seconds: Seconds to keep sandbox alive (-1 for no timeout)
            timeout: Sandbox lifetime timeout in seconds
            language: Programming language to use
            cwd: Working directory for the sandbox
            env_vars: Environment variables to set for all executions
            inherit_env: If True, inherit environment variables from os.environ
            default_command_timeout: Default timeout for command execution in seconds
        """
        super().__init__(
            lifespan_handler=lifespan_handler,
            dependencies=dependencies,
            cwd=cwd,
            env_vars=env_vars,
            inherit_env=inherit_env,
            default_command_timeout=default_command_timeout,
        )
        self.cpu = cpu
        self.memory = memory
        self.keep_warm_seconds = keep_warm_seconds
        self.timeout = timeout
        self.language: Language = language
        self.instance: SandboxInstance | None = None
        # Beam sandboxes run Linux
        self._os_type = "Linux"

    def get_fs(self) -> BeamFS:
        """Return a BeamFS instance for the sandbox."""
        from upathtools.filesystems import BeamFS

        assert self.instance
        return BeamFS(sandbox_id=self.instance.container_id)

    async def __aenter__(self) -> Self:
        """Setup Beam sandbox."""
        await super().__aenter__()
        from beam import Sandbox

        image = get_image(self.language, self.dependencies)
        sandbox = Sandbox(
            cpu=self.cpu,
            memory=self.memory,
            image=image,
            keep_warm_seconds=self.keep_warm_seconds,
        )
        self.instance = sandbox.create()
        self.validate_instance()
        return self

    def validate_instance(self) -> SandboxInstance:
        """Validate the Beam sandbox instance."""
        if not self.instance or not self.instance.ok:
            error_msg = "Beam environment not properly initialized"
            raise RuntimeError(error_msg)
        return self.instance

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Cleanup sandbox."""
        if self.instance and not self.instance.terminated:
            with contextlib.suppress(Exception):
                self.instance.terminate()
        await super().__aexit__(exc_type, exc_val, exc_tb)

    async def execute(self, code: str) -> ExecutionResult:
        """Execute code in the Beam sandbox."""
        from beam import SandboxProcessResponse

        self.instance = self.validate_instance()
        start_time = time.time()
        try:
            lang: Literal["python", "javascript", "typescript"] = (
                "javascript" if self.language == "typescript" else "python"
            )
            wrapped_code = wrap_code(code, lang)
            response = await asyncio.to_thread(
                self.instance.process.run_code,
                wrapped_code,
                blocking=True,
            )
            assert isinstance(response, SandboxProcessResponse)
            output = response.result
            result, error_info = parse_output(output)
            success = response.exit_code == 0 and error_info is None

            if success:
                return ExecutionResult(
                    result=result,
                    duration=time.time() - start_time,
                    success=True,
                    stdout=output,
                    stderr="",  # Beam combines stdout/stderr in result
                )
            return ExecutionResult(
                result=None,
                duration=time.time() - start_time,
                success=False,
                error=error_info.get("error", output) if error_info else output,
                error_type=error_info.get("type", "CommandError") if error_info else "CommandError",
                stdout=output,
                stderr="",
            )

        except Exception as e:  # noqa: BLE001
            return ExecutionResult.failed(e, start_time)

    async def execute_command(
        self,
        command: str,
        *,
        timeout: float | None = None,
    ) -> ExecutionResult:
        """Execute a terminal command in the Beam sandbox."""
        self.instance = self.validate_instance()
        cmd, args = parse_command(command)
        start_time = time.time()
        effective_timeout = timeout if timeout is not None else self.default_command_timeout
        try:
            process = self.instance.process.exec(cmd, *args, env=self.get_env())
            exit_code = await asyncio.wait_for(
                asyncio.to_thread(process.wait),
                timeout=effective_timeout,
            )
            output = "\n".join(line.rstrip("\n\r") for line in process.logs)
            success = exit_code == 0
            return ExecutionResult(
                result=output if success else None,
                duration=time.time() - start_time,
                success=success,
                error=output if not success else None,
                error_type="CommandError" if not success else None,
                exit_code=exit_code,
                stdout=output,
                stderr="",  # Beam combines stdout/stderr
            )

        except TimeoutError:
            return ExecutionResult(
                result=None,
                duration=time.time() - start_time,
                success=False,
                error=f"Command timed out after {effective_timeout} seconds",
                error_type="TimeoutError",
                exit_code=1,
                stdout="",
                stderr="",
            )
        except Exception as e:  # noqa: BLE001
            return ExecutionResult.failed(e, start_time)

    async def stream_code(self, code: str) -> AsyncIterator[ExecutionEvent]:
        """Execute code and stream events using Beam's real-time streaming."""
        from beam import SandboxProcess

        self.instance = self.validate_instance()
        process_id = f"beam_{id(self.instance)}"

        yield ProcessStartedEvent(process_id=process_id, command=f"run_code({len(code)} chars)")

        try:
            lang: Literal["python", "javascript", "typescript"] = (
                "javascript" if self.language == "typescript" else "python"
            )
            wrapped_code = wrap_code(code, lang)
            process = self.instance.process.run_code(wrapped_code, blocking=False)
            assert isinstance(process, SandboxProcess)

            for line in process.logs:
                yield OutputEvent(
                    process_id=process_id, data=line.rstrip("\n\r"), stream="combined"
                )

            exit_code = process.exit_code or 0
            if exit_code == 0:
                yield ProcessCompletedEvent(process_id=process_id, exit_code=exit_code)
            else:
                yield ProcessErrorEvent(
                    process_id=process_id,
                    error=f"Process exited with code {exit_code}",
                    error_type="ProcessError",
                    exit_code=exit_code,
                )

        except Exception as e:  # noqa: BLE001
            yield ProcessErrorEvent.failed(e, process_id=process_id)

    async def spawn(
        self,
        command: str,
        args: list[str] | None = None,
        *,
        cwd: str | None = None,
        env: dict[str, str] | None = None,
        pty: PtySize | None = None,
    ) -> ProcessHandle:
        """Start a process in the Beam sandbox (pipes only: no stdin, no PTY).

        Args:
            command: Program (with `args`) or shell command line (without)
            args: Program arguments, passed without shell interpretation
            cwd: Working directory (defaults to the environment's, else /workspace)
            env: Additional environment variables, merged over `env_vars`
            pty: Not supported by Beam

        Returns:
            Handle to the running process
        """
        from exxec.beam_provider.process_handle import BeamProcessHandle

        self._check_spawn_pty(pty)
        instance = self.validate_instance()
        argv = [command, *args] if args else ["sh", "-c", command]
        merged_env = {**self.env_vars, **(env or {})} or None
        return await BeamProcessHandle.start(instance, argv, cwd=cwd or self.cwd, env=merged_env)

    async def stream_command(
        self,
        command: str,
        *,
        timeout: float | None = None,
    ) -> AsyncIterator[ExecutionEvent]:
        """Execute a shell command and stream its output line by line.

        Runs via `spawn()`, so the synchronous Beam SDK no longer blocks the event loop.
        """
        from exxec.spawn_stream import stream_command_via_spawn

        async for event in stream_command_via_spawn(
            self, command, timeout=timeout, process_id=f"beam_cmd_{id(self)}"
        ):
            yield event

__aenter__ async

__aenter__() -> Self

Setup Beam sandbox.

Source code in src/exxec/beam_provider/provider.py
async def __aenter__(self) -> Self:
    """Setup Beam sandbox."""
    await super().__aenter__()
    from beam import Sandbox

    image = get_image(self.language, self.dependencies)
    sandbox = Sandbox(
        cpu=self.cpu,
        memory=self.memory,
        image=image,
        keep_warm_seconds=self.keep_warm_seconds,
    )
    self.instance = sandbox.create()
    self.validate_instance()
    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Cleanup sandbox.

Source code in src/exxec/beam_provider/provider.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Cleanup sandbox."""
    if self.instance and not self.instance.terminated:
        with contextlib.suppress(Exception):
            self.instance.terminate()
    await super().__aexit__(exc_type, exc_val, exc_tb)

__init__

__init__(
    lifespan_handler: AbstractAsyncContextManager[ServerInfo] | None = None,
    dependencies: list[str] | None = None,
    cpu: float | str = 1.0,
    memory: int | str = 128,
    keep_warm_seconds: int = 600,
    timeout: float = 300.0,
    language: Language = "python",
    cwd: str | None = None,
    env_vars: dict[str, str] | None = None,
    inherit_env: bool = False,
    default_command_timeout: float | None = None,
) -> None

Initialize Beam environment.

Parameters:

Name Type Description Default
lifespan_handler AbstractAsyncContextManager[ServerInfo] | None

Async context manager for tool server (optional)

None
dependencies list[str] | None

List of packages to install via pip / npm

None
cpu float | str

CPU cores allocated to the container

1.0
memory int | str

Memory allocated to the container (MiB or string with units)

128
keep_warm_seconds int

Seconds to keep sandbox alive (-1 for no timeout)

600
timeout float

Sandbox lifetime timeout in seconds

300.0
language Language

Programming language to use

'python'
cwd str | None

Working directory for the sandbox

None
env_vars dict[str, str] | None

Environment variables to set for all executions

None
inherit_env bool

If True, inherit environment variables from os.environ

False
default_command_timeout float | None

Default timeout for command execution in seconds

None
Source code in src/exxec/beam_provider/provider.py
def __init__(
    self,
    lifespan_handler: AbstractAsyncContextManager[ServerInfo] | None = None,
    dependencies: list[str] | None = None,
    cpu: float | str = 1.0,
    memory: int | str = 128,
    keep_warm_seconds: int = 600,
    timeout: float = 300.0,
    language: Language = "python",
    cwd: str | None = None,
    env_vars: dict[str, str] | None = None,
    inherit_env: bool = False,
    default_command_timeout: float | None = None,
) -> None:
    """Initialize Beam environment.

    Args:
        lifespan_handler: Async context manager for tool server (optional)
        dependencies: List of packages to install via pip / npm
        cpu: CPU cores allocated to the container
        memory: Memory allocated to the container (MiB or string with units)
        keep_warm_seconds: Seconds to keep sandbox alive (-1 for no timeout)
        timeout: Sandbox lifetime timeout in seconds
        language: Programming language to use
        cwd: Working directory for the sandbox
        env_vars: Environment variables to set for all executions
        inherit_env: If True, inherit environment variables from os.environ
        default_command_timeout: Default timeout for command execution in seconds
    """
    super().__init__(
        lifespan_handler=lifespan_handler,
        dependencies=dependencies,
        cwd=cwd,
        env_vars=env_vars,
        inherit_env=inherit_env,
        default_command_timeout=default_command_timeout,
    )
    self.cpu = cpu
    self.memory = memory
    self.keep_warm_seconds = keep_warm_seconds
    self.timeout = timeout
    self.language: Language = language
    self.instance: SandboxInstance | None = None
    # Beam sandboxes run Linux
    self._os_type = "Linux"

execute async

execute(code: str) -> ExecutionResult

Execute code in the Beam sandbox.

Source code in src/exxec/beam_provider/provider.py
async def execute(self, code: str) -> ExecutionResult:
    """Execute code in the Beam sandbox."""
    from beam import SandboxProcessResponse

    self.instance = self.validate_instance()
    start_time = time.time()
    try:
        lang: Literal["python", "javascript", "typescript"] = (
            "javascript" if self.language == "typescript" else "python"
        )
        wrapped_code = wrap_code(code, lang)
        response = await asyncio.to_thread(
            self.instance.process.run_code,
            wrapped_code,
            blocking=True,
        )
        assert isinstance(response, SandboxProcessResponse)
        output = response.result
        result, error_info = parse_output(output)
        success = response.exit_code == 0 and error_info is None

        if success:
            return ExecutionResult(
                result=result,
                duration=time.time() - start_time,
                success=True,
                stdout=output,
                stderr="",  # Beam combines stdout/stderr in result
            )
        return ExecutionResult(
            result=None,
            duration=time.time() - start_time,
            success=False,
            error=error_info.get("error", output) if error_info else output,
            error_type=error_info.get("type", "CommandError") if error_info else "CommandError",
            stdout=output,
            stderr="",
        )

    except Exception as e:  # noqa: BLE001
        return ExecutionResult.failed(e, start_time)

execute_command async

execute_command(command: str, *, timeout: float | None = None) -> ExecutionResult

Execute a terminal command in the Beam sandbox.

Source code in src/exxec/beam_provider/provider.py
async def execute_command(
    self,
    command: str,
    *,
    timeout: float | None = None,
) -> ExecutionResult:
    """Execute a terminal command in the Beam sandbox."""
    self.instance = self.validate_instance()
    cmd, args = parse_command(command)
    start_time = time.time()
    effective_timeout = timeout if timeout is not None else self.default_command_timeout
    try:
        process = self.instance.process.exec(cmd, *args, env=self.get_env())
        exit_code = await asyncio.wait_for(
            asyncio.to_thread(process.wait),
            timeout=effective_timeout,
        )
        output = "\n".join(line.rstrip("\n\r") for line in process.logs)
        success = exit_code == 0
        return ExecutionResult(
            result=output if success else None,
            duration=time.time() - start_time,
            success=success,
            error=output if not success else None,
            error_type="CommandError" if not success else None,
            exit_code=exit_code,
            stdout=output,
            stderr="",  # Beam combines stdout/stderr
        )

    except TimeoutError:
        return ExecutionResult(
            result=None,
            duration=time.time() - start_time,
            success=False,
            error=f"Command timed out after {effective_timeout} seconds",
            error_type="TimeoutError",
            exit_code=1,
            stdout="",
            stderr="",
        )
    except Exception as e:  # noqa: BLE001
        return ExecutionResult.failed(e, start_time)

get_fs

get_fs() -> BeamFS

Return a BeamFS instance for the sandbox.

Source code in src/exxec/beam_provider/provider.py
def get_fs(self) -> BeamFS:
    """Return a BeamFS instance for the sandbox."""
    from upathtools.filesystems import BeamFS

    assert self.instance
    return BeamFS(sandbox_id=self.instance.container_id)

spawn async

spawn(
    command: str,
    args: list[str] | None = None,
    *,
    cwd: str | None = None,
    env: dict[str, str] | None = None,
    pty: PtySize | None = None,
) -> ProcessHandle

Start a process in the Beam sandbox (pipes only: no stdin, no PTY).

Parameters:

Name Type Description Default
command str

Program (with args) or shell command line (without)

required
args list[str] | None

Program arguments, passed without shell interpretation

None
cwd str | None

Working directory (defaults to the environment's, else /workspace)

None
env dict[str, str] | None

Additional environment variables, merged over env_vars

None
pty PtySize | None

Not supported by Beam

None

Returns:

Type Description
ProcessHandle

Handle to the running process

Source code in src/exxec/beam_provider/provider.py
async def spawn(
    self,
    command: str,
    args: list[str] | None = None,
    *,
    cwd: str | None = None,
    env: dict[str, str] | None = None,
    pty: PtySize | None = None,
) -> ProcessHandle:
    """Start a process in the Beam sandbox (pipes only: no stdin, no PTY).

    Args:
        command: Program (with `args`) or shell command line (without)
        args: Program arguments, passed without shell interpretation
        cwd: Working directory (defaults to the environment's, else /workspace)
        env: Additional environment variables, merged over `env_vars`
        pty: Not supported by Beam

    Returns:
        Handle to the running process
    """
    from exxec.beam_provider.process_handle import BeamProcessHandle

    self._check_spawn_pty(pty)
    instance = self.validate_instance()
    argv = [command, *args] if args else ["sh", "-c", command]
    merged_env = {**self.env_vars, **(env or {})} or None
    return await BeamProcessHandle.start(instance, argv, cwd=cwd or self.cwd, env=merged_env)

stream_code async

stream_code(code: str) -> AsyncIterator[ExecutionEvent]

Execute code and stream events using Beam's real-time streaming.

Source code in src/exxec/beam_provider/provider.py
async def stream_code(self, code: str) -> AsyncIterator[ExecutionEvent]:
    """Execute code and stream events using Beam's real-time streaming."""
    from beam import SandboxProcess

    self.instance = self.validate_instance()
    process_id = f"beam_{id(self.instance)}"

    yield ProcessStartedEvent(process_id=process_id, command=f"run_code({len(code)} chars)")

    try:
        lang: Literal["python", "javascript", "typescript"] = (
            "javascript" if self.language == "typescript" else "python"
        )
        wrapped_code = wrap_code(code, lang)
        process = self.instance.process.run_code(wrapped_code, blocking=False)
        assert isinstance(process, SandboxProcess)

        for line in process.logs:
            yield OutputEvent(
                process_id=process_id, data=line.rstrip("\n\r"), stream="combined"
            )

        exit_code = process.exit_code or 0
        if exit_code == 0:
            yield ProcessCompletedEvent(process_id=process_id, exit_code=exit_code)
        else:
            yield ProcessErrorEvent(
                process_id=process_id,
                error=f"Process exited with code {exit_code}",
                error_type="ProcessError",
                exit_code=exit_code,
            )

    except Exception as e:  # noqa: BLE001
        yield ProcessErrorEvent.failed(e, process_id=process_id)

stream_command async

stream_command(command: str, *, timeout: float | None = None) -> AsyncIterator[ExecutionEvent]

Execute a shell command and stream its output line by line.

Runs via spawn(), so the synchronous Beam SDK no longer blocks the event loop.

Source code in src/exxec/beam_provider/provider.py
async def stream_command(
    self,
    command: str,
    *,
    timeout: float | None = None,
) -> AsyncIterator[ExecutionEvent]:
    """Execute a shell command and stream its output line by line.

    Runs via `spawn()`, so the synchronous Beam SDK no longer blocks the event loop.
    """
    from exxec.spawn_stream import stream_command_via_spawn

    async for event in stream_command_via_spawn(
        self, command, timeout=timeout, process_id=f"beam_cmd_{id(self)}"
    ):
        yield event

validate_instance

validate_instance() -> SandboxInstance

Validate the Beam sandbox instance.

Source code in src/exxec/beam_provider/provider.py
def validate_instance(self) -> SandboxInstance:
    """Validate the Beam sandbox instance."""
    if not self.instance or not self.instance.ok:
        error_msg = "Beam environment not properly initialized"
        raise RuntimeError(error_msg)
    return self.instance

:fa-brands-github: Show source on GitHub