All skills
huggingface avatar

/transformers-js

@4db6015 official
by Hugging Facehuggingface/skills11k stars
753

Use Transformers.js to run state-of-the-art machine learning models directly in JavaScript/TypeScript. Supports NLP (text classification, translation, summarization), computer vision (image classification, object detection), audio (speech recognition, audio classification), and multimodal tasks. Works in browsers and server-side runtimes (Node.js, Bun, Deno) with WebGPU/WASM using pre-trained models from Hugging Face Hub.

Use this Skill: https://skilld.dev/gh/huggingface/skills/transformers-js

This session only. Nothing lands on disk.

referencesCONFIGURATION.md

≈2.8k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Environment Configuration Reference

Complete guide to configuring Transformers.js behavior using the env object.

Table of Contents

  1. Overview
  2. Remote Model Configuration
  3. Local Model Configuration
  4. Cache Configuration
  5. WASM Configuration
  6. Network and Logging Controls
  7. Common Configuration Patterns
  8. Environment Best Practices

Overview

The env object provides comprehensive control over Transformers.js execution, caching, and model loading:

import { env } from '@huggingface/transformers';

// View current version
console.log(env.version); // e.g., '4.x'

Available Properties

interface TransformersEnvironment {
  // Version info
  version: string;
  
  // Backend configuration
  backends: {
    onnx: Partial<ONNXEnv>;
  };
  
  // Remote model settings
  allowRemoteModels: boolean;
  remoteHost: string;
  remotePathTemplate: string;
  
  // Local model settings
  allowLocalModels: boolean;
  localModelPath: string;
  useFS: boolean;
  
  // Cache settings
  useBrowserCache: boolean;
  useFSCache: boolean;
  cacheDir: string | null;
  useCustomCache: boolean;
  customCache: CacheInterface | null;
  useWasmCache: boolean;
  cacheKey: string;

  // Networking and logging (v4)
  fetch: typeof globalThis.fetch;
  logLevel: LogLevel;
}

Remote Model Configuration

Control how models are loaded from remote sources (default: Hugging Face Hub).

Disable Remote Loading

import { env } from '@huggingface/transformers';

// Force local-only mode (no network requests)
env.allowRemoteModels = false;

Use case: Offline applications, security requirements, or air-gapped environments.

Custom Model Host

import { env } from '@huggingface/transformers';

// Use your own CDN or model server
env.remoteHost = 'https://cdn.example.com/models';

// Customize the URL pattern
// Default: '{model}/resolve/{revision}/{file}'
env.remotePathTemplate = 'custom/{model}/{file}';

Use case: Self-hosting models, using a CDN for faster downloads, or corporate proxies.

Example: Private Model Server

import { env, pipeline } from '@huggingface/transformers';

// Configure custom model host
env.remoteHost = 'https://models.mycompany.com';
env.remotePathTemplate = '{model}/{file}';

// Models will be loaded from:
// https://models.mycompany.com/my-model/model.onnx
const pipe = await pipeline('sentiment-analysis', 'my-model');

Local Model Configuration

Control loading models from the local file system.

Enable Local Models

import { env } from '@huggingface/transformers';

// Enable local file system loading
env.allowLocalModels = true;

// Set the base path for local models
env.localModelPath = '/path/to/models/';

Default values:

  • Browser: allowLocalModels = false, localModelPath = '/models/'
  • Node.js: allowLocalModels = true, localModelPath = '/models/'

File System Control

import { env } from '@huggingface/transformers';

// Disable file system usage entirely (Node.js only)
env.useFS = false;

Example: Local Model Directory Structure

/app/models/
├── onnx-community/
│   ├── Supertonic-TTS-ONNX/
│   │   ├── config.json
│   │   ├── tokenizer.json
│   │   ├── model.onnx
│   │   └── ...
│   └── yolo26l-pose-ONNX/
│       ├── config.json
│       ├── preprocessor_config.json
│       ├── model.onnx
│       └── ...
env.allowLocalModels = true;
env.localModelPath = '/app/models/';
env.allowRemoteModels = false; // Offline mode

const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english');

Cache Configuration

Transformers.js supports multiple caching strategies to improve performance and reduce network usage.

Quick Configuration

import { env } from '@huggingface/transformers';

// Browser cache (Cache API)
env.useBrowserCache = true; // default: true
env.cacheKey = 'my-app-transformers-cache'; // default: 'transformers-cache'

// Node.js filesystem cache
env.useFSCache = true; // default: true
env.cacheDir = './custom-cache-dir'; // default: './.cache'

// Custom cache implementation
env.useCustomCache = true;
env.customCache = new CustomCache(); // Implement Cache API interface

// WASM binary caching
env.useWasmCache = true; // default: true

Disable Caching

import { env } from '@huggingface/transformers';

// Disable all caching (re-download on every load)
env.useFSCache = false;
env.useBrowserCache = false;
env.useWasmCache = false;
env.cacheDir = null;

For comprehensive caching documentation including:

  • Browser Cache API details and storage limits
  • Node.js filesystem cache structure and management
  • Custom cache implementations (Redis, database, S3)
  • Cache clearing and monitoring strategies
  • Best practices and troubleshooting

See Caching Reference

WASM Configuration

Configure ONNX Runtime Web Assembly backend settings.

Basic WASM Settings

import { env } from '@huggingface/transformers';

// Set custom WASM paths
env.backends.onnx.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/';

// Configure number of threads (Node.js only)
env.backends.onnx.wasm.numThreads = 4;

// Enable/disable SIMD (single instruction, multiple data)
env.backends.onnx.wasm.simd = true;

Proxy Configuration

import { env } from '@huggingface/transformers';

// Configure proxy for WASM downloads
env.backends.onnx.wasm.proxy = true;

Self-Hosted WASM Files

import { env } from '@huggingface/transformers';

// Host WASM files on your own server
env.backends.onnx.wasm.wasmPaths = '/static/wasm/';

Required files:

  • ort-wasm.wasm - Main WASM binary
  • ort-wasm-simd.wasm - SIMD-enabled WASM binary
  • ort-wasm-threaded.wasm - Multi-threaded WASM binary
  • ort-wasm-simd-threaded.wasm - SIMD + multi-threaded WASM binary

Network and Logging Controls

Transformers.js v4 adds environment controls for authenticated fetching and cleaner runtime logs.

Custom Fetch (env.fetch)

Use env.fetch to inject auth headers, retries, custom routing, or abort handling.

import { env } from '@huggingface/transformers';

const HF_TOKEN = process.env.HF_TOKEN;

env.fetch = (url, options) =>
  fetch(url, {
    ...options,
    headers: {
      ...options?.headers,
      Authorization: `Bearer ${HF_TOKEN}`,
    },
  });

Logging Level (env.logLevel)

Use env.logLevel to override runtime verbosity. The default is LogLevel.WARNING.

import { env, LogLevel } from '@huggingface/transformers';

// Enable more detailed logs during development
env.logLevel = LogLevel.INFO;

Common values:

  • LogLevel.DEBUG
  • LogLevel.INFO
  • LogLevel.WARNING
  • LogLevel.ERROR
  • LogLevel.NONE

For ONNX Runtime session-level logging controls, see session_options in Pipeline Options.

Common Configuration Patterns

Development Setup

import { env } from '@huggingface/transformers';

// Fast iteration with caching
env.allowRemoteModels = true;
env.useBrowserCache = true; // Browser
env.useFSCache = true;      // Node.js
env.cacheDir = './.cache';

Production (Local Models)

import { env } from '@huggingface/transformers';

// Secure, offline-capable setup
env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = '/app/models/';
env.useFSCache = false; // Models already local

Offline-First Application

import { env } from '@huggingface/transformers';

// Try local first, fall back to remote
env.allowLocalModels = true;
env.localModelPath = './models/';
env.allowRemoteModels = true;
env.useFSCache = true;
env.cacheDir = './cache';

Custom CDN

import { env } from '@huggingface/transformers';

// Use your own model hosting
env.remoteHost = 'https://cdn.example.com/ml-models';
env.remotePathTemplate = '{model}/{file}';
env.useBrowserCache = true;

Memory-Constrained Environment

import { env } from '@huggingface/transformers';

// Minimize disk/memory usage
env.useFSCache = false;
env.useBrowserCache = false;
env.useWasmCache = false;
env.cacheDir = null;

Testing/CI Environment

import { env } from '@huggingface/transformers';

// Predictable, isolated testing
env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = './test-fixtures/models/';
env.useFSCache = false;

Environment Best Practices

1. Configure Early

Set env properties before loading any models:

import { env, pipeline } from '@huggingface/transformers';

// ✓ Good: Configure before loading
env.allowRemoteModels = false;
env.localModelPath = '/app/models/';
const pipe = await pipeline('sentiment-analysis');

// ✗ Bad: Configuring after loading may not take effect
const pipe = await pipeline('sentiment-analysis');
env.allowRemoteModels = false; // Too late!

2. Use Environment Variables

import { env } from '@huggingface/transformers';

// Configure based on environment
env.allowRemoteModels = process.env.NODE_ENV === 'development';
env.cacheDir = process.env.MODEL_CACHE_DIR || './.cache';
env.localModelPath = process.env.LOCAL_MODELS_PATH || '/app/models/';

3. Handle Errors Gracefully

import { pipeline, env } from '@huggingface/transformers';

try {
  env.allowRemoteModels = false;
  const pipe = await pipeline('sentiment-analysis', 'my-model');
} catch (error) {
  if (error.message.includes('not found')) {
    console.error('Model not found locally. Enable remote models or download the model.');
  }
  throw error;
}

4. Log Configuration

import { env } from '@huggingface/transformers';

console.log('Transformers.js Configuration:', {
  version: env.version,
  allowRemoteModels: env.allowRemoteModels,
  allowLocalModels: env.allowLocalModels,
  localModelPath: env.localModelPath,
  cacheDir: env.cacheDir,
  useFSCache: env.useFSCache,
  useBrowserCache: env.useBrowserCache
});

Related Documentation

Source: SKILL.md on GitHub

No alerts16d5 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    This skill provides comprehensive documentation and examples for using Transformers.js to run machine learning models. All external dependencies and model resources originate from well-known registries or trusted vendor domains, following industry-standard practices for client-side machine learning.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer6mo

    5/7 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 4db6015. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub last week.

Activeupdated 6 months ago
Other metadata
metadata
{
  "author": "huggingface",
  "version": "4.x",
  "category": "machine-learning",
  "repository": "https://github.com/huggingface/transformers.js"
}
compatibility
Requires Node.js 18+ (or compatible Bun/Deno runtime) or modern browser with ES modules support. WebGPU requires runtime and hardware support; WASM is the broad fallback. Internet access is needed for downloading models from Hugging Face Hub (optional if using local models).
  • TypeScript
  • transformers.js
  • machine-learning
  • nlp
  • computer-vision
  • javascript
  • huggingface
  • text-classification
  • object-detection
  • speech-recognition
  • image-classification

README badge

README badge for huggingface/skills/transformers-js

Runs state-of-the-art ML models directly in JavaScript and TypeScript across browsers and Node.js/Bun/Deno using Transformers.js. Supports NLP tasks (text classification, translation, summarization), computer vision (image classification, object detection), audio (speech recognition), and multimodal workflows with models from Hugging Face Hub.

Generated from the current SKILL.md.

Does this work in the browser?
Yes. Transformers.js runs in modern browsers with ES modules support and can be loaded via CDN. Models run client-side using WebGPU (if available) or WASM as a fallback, with no backend server required.
What runtimes does this support?
Node.js 18+, Bun, Deno, and modern browsers. WebGPU requires runtime and hardware support; WASM is the broad fallback for CPU inference.
Do I need to download models ahead of time?
No. Models are downloaded automatically from Hugging Face Hub on first use. Internet access is required unless you configure local models.
What ML tasks does this support?
NLP (text classification, translation, summarization, question-answering, token classification), computer vision (image classification, object detection, segmentation, depth estimation), audio (speech recognition, audio classification, text-to-speech), and multimodal tasks (image captioning, document QA).
Is memory management required?
Yes. All pipelines must be disposed with `pipe.dispose()` when finished to prevent memory leaks.

Generated from the current SKILL.md. These answers refresh after source changes.