The TypeScript SDK is currently in beta. It’s an experimental SDK that allows you to interact with Beam’s infrastructure and resources. Please contact us if you have any feedback or questions.
Beam’s TypeScript SDK provides a powerful client library for interacting with the Beam platform. Unlike decorators and frameworks in the Python SDK, the TypeScript SDK focuses on programmatic access to Beam’s infrastructure and resources. This reference outlines every available class, method, and configuration option in the TypeScript SDK.

Installation

Install the package with npm:
npm install @beamcloud/beam-js@rc
…or using yarn:
yarn add @beamcloud/beam-js@rc

Configuration

Locate your Beam Token (API Key) and Workspace ID in the dashboard and set them as environment variables.
export BEAM_TOKEN=YOUR_BEAM_TOKEN
export BEAM_WORKSPACE_ID=YOUR_WORKSPACE_ID

beamOpts

Global configuration object for the Beam client.
import { beamOpts } from "@beamcloud/beam-js";

beamOpts.token = process.env.BEAM_TOKEN!;
beamOpts.workspaceId = process.env.BEAM_WORKSPACE_ID!;
beamOpts.gatewayUrl = "https://app.beam.cloud"; // Optional, defaults to https://app.beam.cloud
Required Configuration:
  • token: Your Beam authentication token
  • workspaceId: Your Beam workspace ID
Optional Configuration:
  • gatewayUrl: The Beam gateway URL (defaults to https://app.beam.cloud)

Quickstart

Run a simple Node.js server in a sandbox. This example uses the Image class to create a custom container image and the Sandbox class to create a sandbox instance.
import { beamOpts, Image, Sandbox } from "@beamcloud/beam-js";

beamOpts.token = process.env.BEAM_TOKEN!;
beamOpts.workspaceId = process.env.BEAM_WORKSPACE_ID!;

async function main() {
  const image = new Image({
    baseImage: "node:20",
    commands: [
      "apt update",
      "apt install -y nodejs npm",
      "git clone https://github.com/beam-cloud/quickstart-node.git /app",
    ],
  });

  const sandbox = new Sandbox({
    name: "quickstart",
    image: image,
    cpu: 2,
    memory: 1024,
    keepWarmSeconds: 300,
  });

  const instance = await sandbox.create();

  const process4 = await instance.exec("sh", "-c", "cd /app && node server.js");

  const url = await instance.exposePort(3000);
  console.log(`Server is running at ${url}`);
}

main();

Environment

Image

Defines a custom container image that your code will run in. An Image object encapsulates the configuration of a custom container image that will be used as the runtime environment for executing tasks.
import {
  Image,
  PythonVersion,
  PythonVersionAlias,
  GpuType,
  GpuTypeAlias,
} from "@beamcloud/beam-js";

const image = new Image({
  baseImage: "docker.io/nvidia/cuda:12.3.1-runtime-ubuntu20.04",
  pythonVersion: PythonVersion.Python311, // Type-safe enum approach
  commands: ["apt-get update -y", "apt-get install ffmpeg -y"],
  pythonPackages: ["transformers", "torch"],
  gpu: GpuType.A10G, // Type-safe enum approach
});

await image.build();

// Alternative using string literals for convenience
const imageWithStringLiterals = new Image({
  baseImage: "docker.io/nvidia/cuda:12.3.1-runtime-ubuntu20.04",
  pythonVersion: "python3.11", // String literal for Python version
  commands: ["apt-get update -y", "apt-get install ffmpeg -y"],
  pythonPackages: ["transformers", "torch"],
  gpu: "A10G", // String literal for GPU
});

await imageWithStringLiterals.build();
Constructor Parameters:
pythonVersion
PythonVersionAlias
default:"PythonVersion.Python3"
The Python version to be used in the image. Can be a PythonVersion enum (e.g., PythonVersion.Python311) or string literal (e.g., “python3.11”). Defaults to Python 3.
pythonPackages
string[] | string
default:"[]"
A list of Python packages to install in the container image. Alternatively, a string containing a path to a requirements.txt can be provided.
commands
string[]
default:"[]"
A list of shell commands to run when building your container image. These commands can be used for setting up the environment, installing dependencies, etc.
baseImage
string
default:""
A custom base image to replace the default ubuntu20.04 image used in your container. This can be a public or private image from Docker Hub, Amazon ECR, Google Cloud Artifact Registry, or NVIDIA GPU Cloud Registry.
baseImageCreds
ImageCredentials
default:"{}"
Credentials for accessing private registries. Can be a dictionary of key/value pairs or an array of environment variable names.
envVars
string[]
default:"[]"
Environment variables to add to the image. These will be available when building the image and when the container is running.
secrets
string[]
default:"[]"
A list of secrets that are injected into the container as environment variables.
gpu
GpuTypeAlias
default:""
Builds the image on a GPU node. Can be a GpuType enum (e.g., GpuType.H100) or string literal (e.g., “H100”).

Image.fromDockerfile()

Create an Image from a local Dockerfile.
import { Image } from "@beamcloud/beam-js";

const image = await Image.fromDockerfile("./Dockerfile", "./context");
dockerfilePath
string
required
Path to the Dockerfile.
contextDir
string
default:"undefined"
Directory to sync as build context. Defaults to the Dockerfile directory.

Image.addPythonPackages()

Add pip packages to install during the build. Accepts a list or a path to requirements.txt.
// Using an array of package names
image.addPythonPackages(["transformers==4.44.0", "torch==2.4.0"]);

// Using a requirements.txt file
image.addPythonPackages("./requirements.txt");
packages
string[] | string
required
Package names or a requirements.txt path.

Image.withEnvs()

Add environment variables available during build and at runtime.
image.withEnvs({ HF_HOME: "/models", HF_HUB_ENABLE_HF_TRANSFER: "1" });
envVars
string[] | Record<string, string> | string
required
Environment variables as key/value pairs, array of “KEY=VALUE” strings, or single string.

Image.withSecrets()

Expose platform secrets to the build environment.
image.withSecrets(["HF_TOKEN"]);
secrets
string[]
required
Secret names created via the platform.

Image.micromamba()

Switch package management to micromamba and target a micromamba Python.
image.micromamba();

Image.addMicromambaPackages()

Install micromamba packages and optional channels.
image.addMicromambaPackages(["pandas", "numpy"], ["conda-forge"]);
packages
string[] | string
required
Package names or a requirements.txt path.
channels
string[]
default:"[]"
Micromamba channels.

Image.build()

Build the image and return the result.
const result = await image.build();
console.log("Build successful:", result.success);

Deployments

Deployments

You can use this to manage and interact with deployed Beam applications.
import { Deployments } from "@beamcloud/beam-js";

// List all deployments
const deployments = await Deployments.list();

// Get a deployment by ID
const deployment = await Deployments.get({ id: "deployment-id" });

// Get a deployment by name and stub type
const deployment = await Deployments.get({
  name: "my-app",
  stubType: "endpoint/deployment",
});

// Call the deployment
const response = await deployment.call({ message: "Hello World" });

// Connect to realtime deployment
const ws = await deployment.realtime("/", (event) => {
  console.log("Received:", event.data);
});

Deployments.list()

List all deployments in your workspace.
const deployments = await Deployments.list({
  stubType: "endpoint/deployment",
  active: true,
  limit: 10,
});

Deployments.get()

Retrieve a deployment by ID, name, or URL.
// By ID
const deployment = await Deployments.get({ id: "deployment-id" });

// By name and stub type
const deployment = await Deployments.get({
  name: "my-app",
  stubType: "endpoint/deployment",
});
id
string
The deployment ID to retrieve.
name
string
The deployment name (must be used with stubType).
stubType
string
The stub type (must be used with name).
url
string
The deployment URL.

Deployment

A deployment instance with methods for interaction.

Deployment.call()

Call the deployment with data.
const response = await deployment.call(
  { message: "Hello World" },
  "/endpoint-path", // optional path
  "POST" // optional HTTP method
);
data
any
required
The data to send to the deployment.
path
string
default:""
Optional path to append to the deployment URL.
method
'GET' | 'POST'
default:"'POST'"
HTTP method to use for the request.

Deployment.realtime()

Connect to a realtime deployment via WebSocket.
const ws = await deployment.realtime("/", (event) => {
  console.log("Message received:", event.data);
});

// Send a message
ws.send(JSON.stringify({ message: "Hello" }));
path
string
default:""
Optional path to append to the WebSocket URL.
onmessage
(event: MessageEvent) => void
Optional message handler function.

Deployment.httpUrl() / Deployment.websocketUrl()

Get the HTTP or WebSocket URL for the deployment.
const httpUrl = deployment.httpUrl("/api/predict");
const wsUrl = deployment.websocketUrl("/realtime");

Sandbox

A sandboxed container for running Python code or arbitrary processes. You can use this to create isolated environments where you can execute code, manage files, and run processes.
import { Sandbox, Image, GpuType } from "@beamcloud/beam-js";

const sandbox = new Sandbox({
  name: "my-sandbox",
  cpu: 2,
  memory: "1Gi",
  gpu: GpuType.T4, // Using enum
  image: new Image({
    pythonPackages: ["numpy", "pandas"],
  }),
  keepWarmSeconds: 300,
});

// Alternative with string literal
const sandboxWithStringGpu = new Sandbox({
  name: "my-sandbox-2",
  cpu: 2,
  memory: "1Gi",
  gpu: "T4", // Using string literal
  image: new Image({
    pythonPackages: ["numpy", "pandas"],
  }),
  keepWarmSeconds: 300,
});

// Create a new sandbox instance
const instance = await sandbox.create();

// Or connect to an existing one
const existingInstance = await sandbox.connect("sandbox-id");

Sandbox.create()

Create a new sandbox instance.
const instance = await sandbox.create(["python", "app.py"]); // optional entrypoint
console.log(`Sandbox created with ID: ${instance.sandboxId}`);

Sandbox.connect()

Connect to an existing sandbox instance by ID.
const instance = await sandbox.connect("sandbox-123");
id
string
required
The container ID of the existing sandbox instance.

Sandbox.createFromSnapshot()

Create a sandbox instance from a filesystem snapshot.
const instance = await sandbox.createFromSnapshot("snapshot-123");
snapshotId
string
required
The ID of the snapshot to create the sandbox from.

SandboxInstance

A sandbox instance that provides access to the sandbox internals.

SandboxInstance.runCode()

Run Python code in the sandbox.
const result = await instance.runCode(`
import numpy as np
print("NumPy version:", np.__version__)
result = np.array([1, 2, 3, 4, 5])
print("Array:", result)
`);

console.log("Output:", result.result);
code
string
required
The Python code to execute.
blocking
boolean
default:"true"
Whether to wait for the process to complete.

SandboxInstance.exec()

Run an arbitrary command in the sandbox.
const process = await instance.exec("ls", "-la", "/workspace");
const exitCode = await process.wait();

// Get the process ID
const pid = process.pid;

// Read output
const stdout = process.stdout.read();
const stderr = process.stderr.read();
...args
string[]
required
The command and its arguments to execute.

SandboxInstance.exposePort()

Dynamically expose a port to the internet.
const url = await instance.exposePort(8000);
console.log(`Web service available at: ${url}`);
port
number
required
The port number to expose within the sandbox.

SandboxInstance.snapshot()

Create a filesystem snapshot of the current sandbox.
const snapshotId = await instance.snapshot();
console.log(`Created snapshot: ${snapshotId}`);

SandboxInstance.updateTtl()

Update the keep warm setting of the sandbox.
// Keep alive for 1 hour
await instance.updateTtl(3600);

// Make it never timeout
await instance.updateTtl(-1);
ttl
number
required
The number of seconds to keep the sandbox alive. Use -1 for sandboxes that never timeout.

SandboxInstance.sandboxId()

Get the ID of the sandbox.
const sandboxId = instance.sandboxId();

SandboxInstance.terminate()

Terminate the container associated with this sandbox instance.
const success = await instance.terminate();

SandboxProcess

Represents a running process within a sandbox.

SandboxProcess.wait()

Wait for the process to complete.
const process = await instance.exec("sleep", "5");
const exitCode = await process.wait();
console.log("Process exited with code:", exitCode);

SandboxProcess.kill()

Kill the process.
const process = await instance.exec("sleep", "100");
await process.kill();

SandboxProcess.status()

Get the status of the process.
const [exitCode, status] = await process.status();
if (exitCode >= 0) {
  console.log("Process finished with exit code:", exitCode);
}

SandboxProcess.stdout / SandboxProcess.stderr

Get handles to the process output streams.
const process = await instance.exec("echo", "Hello World");
const output = process.stdout.read();
console.log("Output:", output);

SandboxFileSystem

File system interface for managing files within a sandbox.

SandboxFileSystem.uploadFile()

Upload a local file to the sandbox.
await instance.fs.uploadFile("./local-file.txt", "workspace/uploaded-file.txt");
localPath
string
required
The path to the local file to upload.
sandboxPath
string
required
The destination path within the sandbox.

SandboxFileSystem.downloadFile()

Download a file from the sandbox to a local path.
await instance.fs.downloadFile(
  "workspace/output.txt",
  "./downloaded-output.txt"
);
sandboxPath
string
required
The path to the file within the sandbox.
localPath
string
required
The destination path on the local filesystem.

SandboxFileSystem.listFiles()

List the files in a directory in the sandbox.
const files = await instance.fs.listFiles("/workspace");
for (const file of files) {
  console.log(`${file.name} (${file.isDir ? "directory" : "file"})`);
}
sandboxPath
string
required
The path to the directory within the sandbox.

SandboxFileSystem.deleteFile()

Delete a file in the sandbox.
await instance.fs.deleteFile("/tmp/temp-file.txt");
sandboxPath
string
required
The path to the file within the sandbox.

SandboxFileSystem.statFile()

Get metadata of a file in the sandbox.
const fileInfo = await instance.fs.statFile("/path/to/file.txt");
console.log(`File size: ${fileInfo.size} bytes`);
console.log(`Is directory: ${fileInfo.isDir}`);
sandboxPath
string
required
The path to the file within the sandbox.

Pod

A Pod is an object that allows you to run arbitrary services in a fast, scalable, and secure remote container on Beam. You can think of a Pod as a lightweight compute environment that you fully control—complete with a custom container, ports you can expose, environment variables, volumes, secrets, and GPUs.
import { Pod, Image } from "@beamcloud/beam-js";

// Create a Pod that runs a simple HTTP server
const pod = new Pod({
  name: "web-server",
  cpu: 2,
  memory: "512Mi",
  image: new Image({
    baseImage: "python:3.9-slim",
    pythonPackages: ["requests"],
  }),
  ports: [8000],
});

// Create the pod container
const result = await pod.create(["python", "-m", "http.server", "8000"]);

console.log("Container ID:", result.containerId);
console.log("URL:", result.url);

Pod.create()

Create a new container that runs until it completes or is explicitly killed.
const result = await pod.create(["python", "app.py"]);
console.log("Pod created successfully:", result.url);
entrypoint
string[]
The command to run in the container.

Storage

Volume

Creates a Volume instance. When your container runs, your volume will be available at ./{mountPath} and /volumes/{name}.
import { Volume } from "@beamcloud/beam-js";

const volume = new Volume("model-weights", "./weights");
await volume.getOrCreate();

// Use with Pod or Sandbox
const pod = new Pod({
  name: "my-pod",
  volumes: [volume],
  // ... other config
});
name
string
required
The name of the volume, a descriptive identifier for the data volume.
mountPath
string
required
The path where the volume is mounted within the container environment.

Volume.getOrCreate()

Get or create the volume in the platform.
const success = await volume.getOrCreate();
console.log("Volume ready:", volume.ready);

Utils

TaskPolicy

Task policy for managing the lifecycle of individual tasks.
import { TaskPolicy } from "@beamcloud/beam-js";

const policy = new TaskPolicy({
  maxRetries: 3,
  timeout: 300,
  ttl: 3600,
});
maxRetries
number
default:"0"
The maximum number of times a task will be retried if the container crashes.
timeout
number
default:"0"
The maximum number of seconds a task can run before it times out. Set it to -1 to disable the timeout.
ttl
number
default:"0"
The expiration time for a task in seconds. Must be greater than 0 and less than 24 hours (86400 seconds).

Types

The TypeScript SDK includes comprehensive type definitions for all resources:
  • GpuType: Enum of available GPU types (T4, A10G, A100, H100, etc.)
  • GpuTypeAlias: Union type allowing both enum values and string literals for GPU specification
  • PythonVersion: Enum of supported Python versions
  • PythonVersionAlias: Union type allowing both enum values and string literals for Python version specification
  • TaskStatus: Enum of task statuses (PENDING, RUNNING, COMPLETE, etc.)
  • DeploymentData: Interface for deployment data
  • TaskData: Interface for task data
  • PodInstanceData: Interface for pod instance data
  • And many more…
import {
  GpuType,
  GpuTypeAlias,
  PythonVersion,
  PythonVersionAlias,
  TaskStatus,
  DeploymentData,
} from "@beamcloud/beam-js";

// Use types for better TypeScript support
const gpu: GpuType = GpuType.A10G; // Enum approach
const gpuAlias: GpuTypeAlias = "A10G"; // String literal approach
const anotherGpu: GpuTypeAlias = GpuType.H100; // Both work with GpuTypeAlias

const python: PythonVersion = PythonVersion.Python311; // Enum approach
const pythonAlias: PythonVersionAlias = "python3.11"; // String literal approach
const anotherPython: PythonVersionAlias = PythonVersion.Python310; // Both work with PythonVersionAlias

// Both approaches work seamlessly for any alias type
function createResource(gpu: GpuTypeAlias, python: PythonVersionAlias) {
  console.log(`Using GPU: ${gpu}, Python: ${python}`);
}

createResource(GpuType.H100, PythonVersion.Python311); // ✅ Works with enums
createResource("H100", "python3.11"); // ✅ Works with strings
createResource("A10G", PythonVersion.Python310); // ✅ Works with mixed approaches