Skip to main content
The Template class provides a fluent API for building custom VM templates. Templates allow you to pre-configure environments with packages, files, and settings that boot in under 100ms using memory snapshots.

Overview

Templates are built using a step-based approach similar to Dockerfiles. You define a series of steps (install packages, copy files, run commands) and the SDK handles the build process, file uploads, and progress tracking.

Installation

The Template builder is included in the main SDK:
npm install @hopx-ai/sdk

Quick Start

import { Template } from '@hopx-ai/sdk';

// Define template with fluent API
const template = new Template()
  .fromUbuntuImage('22.04')
  .aptInstall('curl', 'git', 'build-essential')
  .pipInstall('numpy', 'pandas', 'scikit-learn')
  .setEnv('PYTHONUNBUFFERED', '1')
  .setWorkdir('/workspace');

// Build it
const result = await Template.build(template, {
  alias: 'my-ml-template',
  apiKey: 'hopx_live_...',
  cpu: 2,
  memory: 2048,
  diskGB: 10
});

console.log(`Template created: ${result.templateID}`);

Template Class

Creating a Template

import { Template } from '@hopx-ai/sdk';

const template = new Template();

Base Images

Start your template from a base Docker image:
// Ubuntu
template.fromUbuntuImage('22.04');

// Python
template.fromPythonImage('3.11');

// Node.js
template.fromNodeImage('18');

// Custom image
template.fromImage('my-registry/image:tag');

// Private registries
template.fromGCPRegistry('gcr.io/project/image', gcpAuth);
template.fromAWSRegistry('123456789.dkr.ecr.us-east-1.amazonaws.com/image', awsAuth);

Package Installation

Install packages using helper methods:
// System packages (apt)
template.aptInstall('curl', 'git', 'build-essential');

// Python packages (pip)
template.pipInstall('numpy', 'pandas', 'scikit-learn');

// Node.js packages (npm)
template.npmInstall('express', 'axios');

// Go packages
template.goInstall('github.com/gin-gonic/gin');

// Rust packages
template.cargoInstall('cargo-watch');
Multiple argument styles supported:
// Style 1: Multiple arguments
.pipInstall('numpy', 'pandas', 'scikit-learn')

// Style 2: Array
.pipInstall(['numpy', 'pandas', 'scikit-learn'])

// Style 3: Chained
.pipInstall('numpy').pipInstall('pandas')

File Operations

Copy files into the template:
// Single file
template.copy('config.json', '/workspace/config.json');

// Multiple files
template.copy(['file1.txt', 'file2.txt'], '/workspace/');

// Directory
template.copy('src/', '/workspace/src/');

Commands

Execute shell commands:
template.runCmd('apt-get update && apt-get install -y python3');
template.runCmd('curl -fsSL https://bun.sh/install | bash');

Environment Variables

Set environment variables:
// Single variable
template.setEnv('PYTHONUNBUFFERED', '1');

// Multiple variables
template.setEnvs({
  'NODE_ENV': 'production',
  'API_URL': 'https://api.example.com'
});

Working Directory

Set the working directory:
template.setWorkdir('/workspace');

User

Set the user for subsequent commands:
template.setUser('appuser');

Git Operations

Clone repositories:
template.gitClone('https://github.com/user/repo.git', '/workspace/repo');

Start Command

Set a command to run when sandbox starts:
import { waitForPort } from '@hopx-ai/sdk';

// Simple command
template.setStartCmd('node /app/main.js');

// With ready check (wait for port)
template.setStartCmd('node /app/main.js', waitForPort(8000));

Cache Control

Skip cache for a step:
template.skipCache();

Building Templates

BuildOptions

Configure the build process:
interface BuildOptions {
  alias: string;              // Template name (required)
  apiKey: string;             // API key (required)
  baseURL?: string;           // API base URL
  cpu?: number;               // vCPUs (1-64)
  memory?: number;            // Memory in MB
  diskGB?: number;            // Disk in GB
  onLog?: (log: Log) => void; // Log callback
  onProgress?: (progress: number) => void;  // Progress callback
}

Building

Build the template:
const result = await Template.build(template, options);

// Result contains:
// - templateID: ID of created template
// - buildID: Build job ID
// - status: Build status
// - duration: Build duration in milliseconds

Progress Tracking

Monitor build progress:
const result = await Template.build(template, {
  alias: 'my-template',
  apiKey: apiKey,
  onLog: (log) => {
    console.log(`[${log.level}] ${log.message}`);
  },
  onProgress: (progress) => {
    console.log(`Progress: ${progress}%`);
  }
});

Complete Example

import { Template, Sandbox } from '@hopx-ai/sdk';

async function createMLTemplate(): Promise<string> {
  // Define template
  const template = new Template()
    .fromUbuntuImage('22.04')
    .aptInstall('python3-dev', 'build-essential')
    .pipInstall(
      'numpy==1.24.3',
      'pandas==2.0.3',
      'scikit-learn==1.3.0',
      'matplotlib==3.7.2'
    )
    .setEnv('PYTHONUNBUFFERED', '1')
    .setWorkdir('/workspace');
  
  // Build template
  const result = await Template.build(template, {
    alias: 'ml-template',
    apiKey: process.env.HOPX_API_KEY!,
    cpu: 4,
    memory: 8192,
    diskGB: 20
  });
  
  return result.templateID;
}

// Use the template
const templateID = await createMLTemplate();
const sandbox = await Sandbox.create({ templateID });

Validation

The SDK validates templates before building:
  • ✅ Must have a FROM step (base image)
  • ✅ Must have at least one build step (RUN, COPY, APT, etc.)
  • ❌ Cannot have only FROM + ENV/WORKDIR/USER

Error Handling

import { TemplateBuildError } from '@hopx-ai/sdk';

try {
  const result = await Template.build(template, options);
} catch (error) {
  if (error instanceof TemplateBuildError) {
    console.error(`Build failed: ${error.message}`);
    console.error(`Build ID: ${error.buildID}`);
  }
}

Best Practices

Pin versions for reproducibility:
.pipInstall('numpy==1.24.3', 'pandas==2.0.3')
Combine commands to reduce build time:
.runCmd('apt-get update && apt-get install -y package1 package2')
Configure CPU, memory, and disk for your workload:
{
  alias: 'ml-template',
  cpu: 4,
  memory: 8192,
  diskGB: 50
}
Monitor long builds:
onProgress: (progress) => {
  console.log(`Building: ${progress}%`);
}

API Reference

Template Methods

MethodDescriptionReturns
fromUbuntuImage(version)Start from Ubuntu base imageTemplate
fromPythonImage(version)Start from Python base imageTemplate
fromNodeImage(version)Start from Node.js base imageTemplate
fromImage(image, auth?)Start from custom imageTemplate
aptInstall(...packages)Install system packagesTemplate
pipInstall(...packages)Install Python packagesTemplate
npmInstall(...packages)Install Node.js packagesTemplate
goInstall(...packages)Install Go packagesTemplate
cargoInstall(...packages)Install Rust packagesTemplate
copy(src, dest, options?)Copy files/directoriesTemplate
runCmd(command)Execute shell commandTemplate
setEnv(key, value)Set environment variableTemplate
setEnvs(vars)Set multiple environment variablesTemplate
setWorkdir(path)Set working directoryTemplate
setUser(user)Set user for commandsTemplate
gitClone(url, dest)Clone git repositoryTemplate
setStartCmd(cmd, ready?)Set start commandTemplate
skipCache()Skip cache for next stepTemplate
getSteps()Get all stepsStep[]

Template.build()

Static method to build a template:
static async build(template: Template, options: BuildOptions): Promise<BuildResult>
Parameters:
  • template: Template instance with steps defined
  • options: BuildOptions with alias, API key, and configuration
Returns: Promise<BuildResult> with templateID, buildID, status, and duration

Next Steps