Official agent skill

Transformers.js

by huggingface in huggingface/skills

Runs pre-trained Hugging Face models in JavaScript or TypeScript with Transformers.js, in browsers or Node.js, Bun and Deno, for text, vision, audio and multimodal tasks.

OfficialApache-2.0Auto-check passedAI & LLM Engineering

Install Transformers.js

skills CLI
$ npx skills add huggingface/skills --skill transformers-js -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install huggingface/skills transformers-js --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/huggingface/skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/transformers-js .claude/skills/transformers-js && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
transformers-js
GitHub stars
11k
Used in
1 other repo
Token cost
~6.2k tokens
SKILL.md length
1,325 words
Files
8 (incl. references)
Skills in repo
25
Repo updated
First seen
Licence
Apache-2.0

At a glance

Runs pre-trained Hugging Face models in JavaScript or TypeScript with Transformers.js, in browsers or Node.js, Bun and Deno, for text, vision, audio and multimodal tasks.

  • Works in 4 steps: Pipeline API → Model Selection → Device Selection → …
  • Running a sentiment or classification model in the browser without a backend
  • SKILL.md covers When to Use This Skill, Installation, Core Concepts and Supported Tasks, plus 3 more sections
  • Calls npm; reaches huggingface.co and cdn.jsdelivr.net; needs HF_TOKEN

What it does

Transformers.js runs machine learning models directly in JavaScript with no Python server. The skill centers on the pipeline API, which bundles preprocessing, inference and postprocessing, and shows how to pick a task or a specific model from the Hugging Face Hub, choose a device, and install through npm or a CDN script tag.

Tasks include text classification, translation and summarization, image classification and object detection, speech recognition and audio classification, and multimodal work. It warns that every pipeline must be released with pipe.dispose() to avoid memory leaks. Reference files cover cache, configuration, examples, model architectures, a model registry, pipeline options and text generation. WebGPU needs runtime and hardware support, with WASM as the broad fallback.

When your agent uses it

  • Running a sentiment or classification model in the browser without a backend
  • Adding speech recognition to a Node.js app
  • Doing image classification or object detection from JavaScript
  • Choosing a Transformers.js-compatible model on the Hub

Example prompts

  • “Add client-side sentiment analysis to our feedback form with Transformers.js.”
  • “Transcribe audio files in a Node.js script with a speech recognition pipeline.”
  • “Find an image classification model for Transformers.js and wire it into the gallery page.”
  • “My pipeline loop is leaking memory, so fix the cleanup.”

Requirements

  • Node.js 18 or later, a compatible Bun or Deno runtime, or a modern browser with ES modules
  • Internet access to download models from the Hugging Face Hub, unless local models are used
  • Compatibility (from SKILL.md): 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).

Workflow steps

4 steps, taken from the step headings in SKILL.md.

  1. Pipeline API
  2. Model Selection
  3. Device Selection
  4. Quantization Options

What it can do on your machine

Read from SKILL.md and the folder at commit ca0325b. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • npm

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • huggingface.co
    • cdn.jsdelivr.net

    Also links to:

    • github.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • HF_TOKEN

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • 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).

    From compatibility in the SKILL.md frontmatter.

Context cost

Transformers.js loads about 6.2k tokens when it runs, and up to ~24k if it reads all its reference files. Until then it costs about 110 tokens; SKILL.md has 1,325 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~110
When it runs · the whole SKILL.md, loaded when a task matches
~6.2k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~24k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from huggingface/skills at commit ca0325b, republished under its Apache-2.0 licence (© huggingface). 1,325 words, ~6,225 tokens.

Download SKILL.mdSave it as .claude/skills/transformers-js/SKILL.md (or your agent's skills folder). This skill also uses 7 other files; get the full folder from GitHub.
name
transformers-js
description
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.
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).
license
Apache-2.0
metadata.author
huggingface
metadata.version
4.x
metadata.category
machine-learning
metadata.repository
https://github.com/huggingface/transformers.js

Transformers.js - Machine Learning for JavaScript

Transformers.js enables running state-of-the-art machine learning models directly in JavaScript across browsers and server-side runtimes (Node.js, Bun, Deno), with no Python server required.

When to Use This Skill

Use this skill when you need to:

  • Run ML models for text analysis, generation, or translation in JavaScript
  • Perform image classification, object detection, or segmentation
  • Implement speech recognition or audio processing
  • Build multimodal AI applications (text-to-image, image-to-text, etc.)
  • Run models client-side in the browser without a backend

Installation

NPM Installation
bash
npm install @huggingface/transformers
Browser Usage (CDN)
javascript
<script type="module">
  import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers';
</script>

Core Concepts

1. Pipeline API

The pipeline API is the easiest way to use models. It groups together preprocessing, model inference, and postprocessing:

javascript
import { pipeline } from '@huggingface/transformers';

// Create a pipeline for a specific task
const pipe = await pipeline('sentiment-analysis');

// Use the pipeline
const result = await pipe('I love transformers!');
// Output: [{ label: 'POSITIVE', score: 0.999817686 }]

// IMPORTANT: Always dispose when done to free memory
await pipe.dispose();

⚠️ Memory Management: All pipelines must be disposed with pipe.dispose() when finished to prevent memory leaks. See examples in Code Examples for cleanup patterns across different environments.

2. Model Selection

You can specify a custom model as the second argument:

javascript
const pipe = await pipeline(
  'sentiment-analysis',
  'Xenova/bert-base-multilingual-uncased-sentiment'
);

Finding Models:

Browse available Transformers.js models on Hugging Face Hub:

Tip: Filter by task type, sort by trending/downloads, and check model cards for performance metrics and usage examples.

3. Device Selection

Choose where to run the model:

javascript
// Run on CPU (default for WASM)
const pipe = await pipeline('sentiment-analysis', 'model-id');

// Run on GPU (WebGPU)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  device: 'webgpu',
});
4. Quantization Options

Control model precision vs. performance:

javascript
// Use quantized model (faster, smaller)
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'q4',  // Options: 'fp32', 'fp16', 'q8', 'q4'
});

Supported Tasks

Note: All examples below show basic usage.

Natural Language Processing
Text Classification
javascript
const classifier = await pipeline('text-classification');
const result = await classifier('This movie was amazing!');
Named Entity Recognition (NER)
javascript
const ner = await pipeline('token-classification');
const entities = await ner('My name is John and I live in New York.');
Question Answering
javascript
const qa = await pipeline('question-answering');
const answer = await qa({
  question: 'What is the capital of France?',
  context: 'Paris is the capital and largest city of France.'
});
Text Generation
javascript
const generator = await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX');
const text = await generator('Once upon a time', {
  max_new_tokens: 100,
  temperature: 0.7
});

For streaming and chat: See Text Generation Guide for:

  • Streaming token-by-token output with TextStreamer
  • Chat/conversation format with system/user/assistant roles
  • Generation parameters (temperature, top_k, top_p)
  • Browser and Node.js examples
  • React components and API endpoints
Translation
javascript
const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M');
const output = await translator('Hello, how are you?', {
  src_lang: 'eng_Latn',
  tgt_lang: 'fra_Latn'
});
Summarization
javascript
const summarizer = await pipeline('summarization');
const summary = await summarizer(longText, {
  max_length: 100,
  min_length: 30
});
Zero-Shot Classification
javascript
const classifier = await pipeline('zero-shot-classification');
const result = await classifier('This is a story about sports.', ['politics', 'sports', 'technology']);
Computer Vision
Image Classification
javascript
const classifier = await pipeline('image-classification');
const result = await classifier('https://example.com/image.jpg');
// Or with local file
const result = await classifier(imageUrl);
Object Detection
javascript
const detector = await pipeline('object-detection');
const objects = await detector('https://example.com/image.jpg');
// Returns: [{ label: 'person', score: 0.95, box: { xmin, ymin, xmax, ymax } }, ...]
Image Segmentation
javascript
const segmenter = await pipeline('image-segmentation');
const segments = await segmenter('https://example.com/image.jpg');
Depth Estimation
javascript
const depthEstimator = await pipeline('depth-estimation');
const depth = await depthEstimator('https://example.com/image.jpg');
Zero-Shot Image Classification
javascript
const classifier = await pipeline('zero-shot-image-classification');
const result = await classifier('image.jpg', ['cat', 'dog', 'bird']);
Audio Processing
Automatic Speech Recognition
javascript
const transcriber = await pipeline('automatic-speech-recognition');
const result = await transcriber('audio.wav');
// Returns: { text: 'transcribed text here' }
Audio Classification
javascript
const classifier = await pipeline('audio-classification');
const result = await classifier('audio.wav');
Text-to-Speech
javascript
const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts');
const audio = await synthesizer('Hello, this is a test.', {
  speaker_embeddings: speakerEmbeddings
});
Multimodal
Image-to-Text (Image Captioning)
javascript
const captioner = await pipeline('image-to-text');
const caption = await captioner('image.jpg');
Document Question Answering
javascript
const docQA = await pipeline('document-question-answering');
const answer = await docQA('document-image.jpg', 'What is the total amount?');
Zero-Shot Object Detection
javascript
const detector = await pipeline('zero-shot-object-detection');
const objects = await detector('image.jpg', ['person', 'car', 'tree']);
Feature Extraction (Embeddings)
javascript
const extractor = await pipeline('feature-extraction');
const embeddings = await extractor('This is a sentence to embed.');
// Returns: tensor of shape [1, sequence_length, hidden_size]

// For sentence embeddings (mean pooling)
const extractor = await pipeline('feature-extraction', 'onnx-community/all-MiniLM-L6-v2-ONNX');
const embeddings = await extractor('Text to embed', { pooling: 'mean', normalize: true });

Finding and Choosing Models

Browsing the Hugging Face Hub

Discover compatible Transformers.js models on Hugging Face Hub:

Base URL (all models):

https://huggingface.co/models?library=transformers.js&sort=trending

Filter by task using the pipeline_tag parameter:

TaskURL
Text Generationhttps://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending
Text Classificationhttps://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js&sort=trending
Translationhttps://huggingface.co/models?pipeline_tag=translation&library=transformers.js&sort=trending
Summarizationhttps://huggingface.co/models?pipeline_tag=summarization&library=transformers.js&sort=trending
Question Answeringhttps://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js&sort=trending
Image Classificationhttps://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js&sort=trending
Object Detectionhttps://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js&sort=trending
Image Segmentationhttps://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js&sort=trending
Speech Recognitionhttps://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js&sort=trending
Audio Classificationhttps://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js&sort=trending
Image-to-Texthttps://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js&sort=trending
Feature Extractionhttps://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js&sort=trending
Zero-Shot Classificationhttps://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js&sort=trending

Sort options:

  • &sort=trending - Most popular recently
  • &sort=downloads - Most downloaded overall
  • &sort=likes - Most liked by community
  • &sort=modified - Recently updated
Choosing the Right Model

Consider these factors when selecting a model:

1. Model Size

  • Small (< 100MB): Fast, suitable for browsers, limited accuracy
  • Medium (100MB - 500MB): Balanced performance, good for most use cases
  • Large (> 500MB): High accuracy, slower, better for Node.js or powerful devices

2. Quantization Models are often available in different quantization levels:

  • fp32 - Full precision (largest, most accurate)
  • fp16 - Half precision (smaller, still accurate)
  • q8 - 8-bit quantized (much smaller, slight accuracy loss)
  • q4 - 4-bit quantized (smallest, noticeable accuracy loss)

3. Task Compatibility Check the model card for:

  • Supported tasks (some models support multiple tasks)
  • Input/output formats
  • Language support (multilingual vs. English-only)
  • License restrictions

4. Performance Metrics Model cards typically show:

  • Accuracy scores
  • Benchmark results
  • Inference speed
  • Memory requirements
Example: Finding a Text Generation Model
javascript
// 1. Visit: https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js&sort=trending

// 2. Browse and select a model (e.g., onnx-community/gemma-3-270m-it-ONNX)

// 3. Check model card for:
//    - Model size: ~270M parameters
//    - Quantization: q4 available
//    - Language: English
//    - Use case: Instruction-following chat

// 4. Use the model:
import { pipeline } from '@huggingface/transformers';

const generator = await pipeline(
  'text-generation',
  'onnx-community/gemma-3-270m-it-ONNX',
  { dtype: 'q4' } // Use quantized version for faster inference
);

const output = await generator('Explain quantum computing in simple terms.', {
  max_new_tokens: 100
});

await generator.dispose();
Tips for Model Selection
  1. Start Small: Test with a smaller model first, then upgrade if needed
  2. Check ONNX Support: Ensure the model has ONNX files (look for onnx folder in model repo)
  3. Read Model Cards: Model cards contain usage examples, limitations, and benchmarks
  4. Test Locally: Benchmark inference speed and memory usage in your environment
  5. Filter by Library: Use library=transformers.js to find compatible models: https://huggingface.co/models?library=transformers.js
  6. Version Pin: Use specific git commits in production for stability:
    javascript
    const pipe = await pipeline('task', 'model-id', { revision: 'abc123' });

Advanced Configuration

Environment Configuration (env)

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

Quick Overview:

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

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

// Common settings
env.allowRemoteModels = true;  // Load from Hugging Face Hub
env.allowLocalModels = false;  // Load from file system
env.localModelPath = '/models/'; // Local model directory
env.useFSCache = true;         // Cache models on disk (Node.js)
env.useBrowserCache = true;    // Cache models in browser
env.cacheDir = './.cache';     // Cache directory location
// Optional: override logging level (default is LogLevel.WARNING)
env.logLevel = LogLevel.INFO;

// Optional: custom fetch for auth headers, retries, abort signals, etc.
env.fetch = (url, options) =>
  fetch(url, {
    ...options,
    headers: {
      ...options?.headers,
      Authorization: `Bearer ${HF_TOKEN}`,
    },
  });

Configuration Patterns:

javascript
// Development: Fast iteration with remote models
env.allowRemoteModels = true;
env.useFSCache = true;

// Production: Local models only
env.allowRemoteModels = false;
env.allowLocalModels = true;
env.localModelPath = '/app/models/';

// Custom CDN
env.remoteHost = 'https://cdn.example.com/models';

// Disable caching (testing)
env.useFSCache = false;
env.useBrowserCache = false;

For complete documentation on all configuration options, caching strategies, cache management, pre-downloading models, and more, see:

→ Configuration Reference

ModelRegistry (v4)

ModelRegistry gives you visibility and control over model assets before loading a pipeline. Use it to estimate download size, check cache status, inspect available dtypes, and clear cached artifacts for a specific task/model/options tuple.

javascript
import { ModelRegistry } from '@huggingface/transformers';

const task = 'feature-extraction';
const modelId = 'onnx-community/all-MiniLM-L6-v2-ONNX';
const modelOptions = { dtype: 'fp32' };

// List required files for this pipeline
const files = await ModelRegistry.get_pipeline_files(task, modelId, modelOptions);

// Check if assets are already cached
const cached = await ModelRegistry.is_pipeline_cached(task, modelId, modelOptions);

// Inspect precision formats available for this model
const dtypes = await ModelRegistry.get_available_dtypes(modelId);

console.log({ files: files.length, cached, dtypes });

For production patterns and full API coverage, see ModelRegistry Reference.

Standalone Tokenization (@huggingface/tokenizers)

For tokenization-only workflows, use @huggingface/tokenizers. It is a separate lightweight package useful when you need fast tokenization/encoding without loading full model inference pipelines.

bash
npm install @huggingface/tokenizers
javascript
import { Tokenizer } from '@huggingface/tokenizers';
Working with Tensors
javascript
import { AutoTokenizer, AutoModel } from '@huggingface/transformers';

// Load tokenizer and model separately for more control
const tokenizer = await AutoTokenizer.from_pretrained('bert-base-uncased');
const model = await AutoModel.from_pretrained('bert-base-uncased');

// Tokenize input
const inputs = await tokenizer('Hello world!');

// Run model
const outputs = await model(inputs);
Batch Processing
javascript
const classifier = await pipeline('sentiment-analysis');

// Process multiple texts
const results = await classifier([
  'I love this!',
  'This is terrible.',
  'It was okay.'
]);

Runtime-Specific Considerations

WebGPU Usage

WebGPU provides GPU acceleration in browsers and server-side runtimes (when supported):

javascript
const pipe = await pipeline('text-generation', 'onnx-community/gemma-3-270m-it-ONNX', {
  device: 'webgpu',
  dtype: 'fp32'
});

Note: Use webgpu when available and fall back to WASM/CPU when not supported in the current runtime.

WASM Performance

WASM is the most compatible execution backend across runtimes:

javascript
// Optimized for browsers with quantization
const pipe = await pipeline('sentiment-analysis', 'model-id', {
  dtype: 'q8'  // or 'q4' for even smaller size
});
Progress Tracking & Loading Indicators

Models can be large (ranging from a few MB to several GB) and consist of multiple files. Track download progress by passing a callback to the pipeline() function:

javascript
import { pipeline } from '@huggingface/transformers';

// Track progress for each file
const fileProgress = {};

function onProgress(info) {
  if (info.status === 'progress_total') {
    console.log(`Total: ${info.progress.toFixed(1)}%`);
    return;
  }

  console.log(`${info.status}: ${info.file ?? ''}`);
  
  if (info.status === 'progress') {
    fileProgress[info.file] = info.progress;
    console.log(`${info.file}: ${info.progress.toFixed(1)}%`);
  }
  
  if (info.status === 'done') {
    console.log(`✓ ${info.file} complete`);
  }
}

// Pass callback to pipeline
const classifier = await pipeline('sentiment-analysis', null, {
  progress_callback: onProgress
});

Progress Info Properties:

typescript
interface ProgressInfo {
  status: 'initiate' | 'download' | 'progress' | 'progress_total' | 'done' | 'ready';
  name: string;      // Model id or path
  file?: string;     // File being processed (per-file events)
  progress?: number; // Percentage (0-100, for 'progress' and 'progress_total')
  loaded?: number;   // Bytes downloaded (only for 'progress' status)
  total?: number;    // Total bytes (only for 'progress' status)
}

For complete examples including browser UIs, React components, CLI progress bars, and retry logic, see:

→ Pipeline Options - Progress Callback

Show full SKILL.md (519 more words)Show less

Error Handling

javascript
try {
  const pipe = await pipeline('sentiment-analysis', 'model-id');
  const result = await pipe('text to analyze');
} catch (error) {
  if (error.message.includes('fetch')) {
    console.error('Model download failed. Check internet connection.');
  } else if (error.message.includes('ONNX')) {
    console.error('Model execution failed. Check model compatibility.');
  } else {
    console.error('Unknown error:', error);
  }
}

Performance Tips

  1. Reuse Pipelines: Create pipeline once, reuse for multiple inferences
  2. Use Quantization: Start with q8 or q4 for faster inference
  3. Batch Processing: Process multiple inputs together when possible
  4. Cache Models: Models are cached automatically (see Caching Reference for details on browser Cache API, Node.js filesystem cache, and custom implementations)
  5. WebGPU for Large Models: Use WebGPU for models that benefit from GPU acceleration
  6. Prune Context: For text generation, limit max_new_tokens to avoid memory issues
  7. Clean Up Resources: Call pipe.dispose() when done to free memory

Memory Management

IMPORTANT: Always call pipe.dispose() when finished to prevent memory leaks.

javascript
const pipe = await pipeline('sentiment-analysis');
const result = await pipe('Great product!');
await pipe.dispose();  // ✓ Free memory (100MB - several GB per model)

When to dispose:

  • Application shutdown or component unmount
  • Before loading a different model
  • After batch processing in long-running apps

Models consume significant memory and hold GPU/CPU resources. Disposal is critical for browser memory limits and server stability.

For detailed patterns (React cleanup, servers, browser), see Code Examples

Troubleshooting

Model Not Found
  • Verify model exists on Hugging Face Hub
  • Check model name spelling
  • Ensure model has ONNX files (look for onnx folder in model repo)
Memory Issues
  • Use smaller models or quantized versions (dtype: 'q4')
  • Reduce batch size
  • Limit sequence length with max_length
WebGPU Errors
  • Check browser compatibility (Chrome 113+, Edge 113+)
  • Try dtype: 'fp16' if fp32 fails
  • Fall back to WASM if WebGPU unavailable

Reference Documentation

This Skill
Official Transformers.js

Best Practices

  1. Always Dispose Pipelines: Call pipe.dispose() when done - critical for preventing memory leaks
  2. Start with Pipelines: Use the pipeline API unless you need fine-grained control
  3. Test Locally First: Test models with small inputs before deploying
  4. Monitor Model Sizes: Be aware of model download sizes for web applications
  5. Handle Loading States: Show progress indicators for better UX
  6. Version Pin: Pin specific model versions for production stability
  7. Error Boundaries: Always wrap pipeline calls in try-catch blocks
  8. Progressive Enhancement: Provide fallbacks for unsupported browsers
  9. Reuse Models: Load once, use many times - don't recreate pipelines unnecessarily
  10. Graceful Shutdown: Dispose models on SIGTERM/SIGINT in servers

Quick Reference: Task IDs

TaskTask ID
Text classificationtext-classification or sentiment-analysis
Token classificationtoken-classification or ner
Question answeringquestion-answering
Fill maskfill-mask
Summarizationsummarization
Translationtranslation
Text generationtext-generation
Text-to-text generationtext2text-generation
Zero-shot classificationzero-shot-classification
Image classificationimage-classification
Image segmentationimage-segmentation
Object detectionobject-detection
Depth estimationdepth-estimation
Image-to-imageimage-to-image
Zero-shot image classificationzero-shot-image-classification
Zero-shot object detectionzero-shot-object-detection
Automatic speech recognitionautomatic-speech-recognition
Audio classificationaudio-classification
Text-to-speechtext-to-speech or text-to-audio
Image-to-textimage-to-text
Document question answeringdocument-question-answering
Feature extractionfeature-extraction
Sentence similaritysentence-similarity

This skill enables you to integrate state-of-the-art machine learning capabilities directly into JavaScript applications without requiring separate ML servers or Python environments.

© huggingface, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 7 other files (references) in skills/transformers-js of huggingface/skills.

  • SKILL.md
  • references/CACHE.md
  • references/CONFIGURATION.md
  • references/EXAMPLES.md
  • references/MODEL_ARCHITECTURES.md
  • references/MODEL_REGISTRY.md
  • references/PIPELINE_OPTIONS.md
  • references/TEXT_GENERATION.md

Open the folder on GitHubat commit ca0325b

Used in 1 other repository

We found 1 copy of this SKILL.md (exact, near-identical or edited) in other folders, from 1 other GitHub owner. This page covers the copy in huggingface/skills, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Transformers.js next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Transformers.js compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Transformers.js this skillhuggingface/skills11k1 repos~6.2kAutomated safety check: PassApache-2.0
Hugging Face Transformers Usagedavila7/claude-code-templates32k12 repos~1.2kAutomated safety check: PassMIT
Transformers JSwaybarrios/opencode-power-pack533—~1.9kAutomated safety check: PassApache-2.0
Transformers JSsickn33/agentic-awesome-skills47k1 repos~444Automated safety check: PassApache-2.0
Compromise NLP Libraryspencermountain/compromise12k—~2kAutomated safety check: PassMIT
Xybrid Initxybrid-ai/xybrid466—~3kAutomated safety check: PassApache-2.0

Similar skills

  • Hugging Face Transformers Usage

    davila7/claude-code-templates

    Loads pre-trained Hugging Face Transformers models for text, vision and audio tasks, runs inference with pipelines and fine-tunes on custom datasets.

    32k GitHub starsUsed in 12 repos~1.2k tokens
    AI & LLM EngineeringAuto-check passed
  • Transformers JS

    waybarrios/opencode-power-pack

    Run Hugging Face models in JavaScript or TypeScript with Transformers.js, WebGPU, or WASM across browser, Node.js, Bun, and Deno.

    533 GitHub stars~1.9k tokensUpdated 2 days ago
    AI & LLM EngineeringAuto-check passed
  • Transformers JS

    sickn33/agentic-awesome-skills

    Use Transformers.js to run state-of-the-art machine learning models directly in JavaScript/TypeScript.

    47k GitHub starsUsed in 1 repo~444 tokens
    AI & LLM EngineeringAuto-check passed
  • Compromise NLP Library

    spencermountain/compromise

    Helps write and debug JavaScript or TypeScript that uses the compromise English NLP library for matching, entity extraction, tagging and sentence transforms.

    12k GitHub stars~2k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Xybrid Init

    xybrid-ai/xybrid

    Generate model metadata for an ML model so it works with xybrid.

    466 GitHub stars~3k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Azure AI Voicelive TS

    microsoft/skills

    Official

    Azure AI Voice Live SDK for JavaScript/TypeScript. An agent skill from microsoft/skills.

    3.1k GitHub starsUsed in 6 repos~3.4k tokens
    Backend & APIsAuto-check passed

More from huggingface/skills

All 25 skills in this repo
  • Official

    Finds or validates a usable SageMaker execution role before deploying or training, so scripts do not try to create IAM roles they lack permission to create.

    11k GitHub starsUsed in 1 repo~1.8k tokens
    Auto-check passed
  • Official

    Chooses the right serving container and current image URI for deploying a Hugging Face model to a SageMaker endpoint, preferring Hugging Face images over generic ones.

    11k GitHub starsUsed in 1 repo~4.6k tokens
    Auto-check passed
  • Hugging Face LLM Trainer

    huggingface/skills

    Official

    Trains or fine-tunes language and vision models with TRL or Unsloth on Hugging Face Jobs cloud GPUs, then converts the results to GGUF.

    11k GitHub starsUsed in 3 repos~7.2k tokens
    Auto-check passed
  • Official

    Routes a sentence-transformers training task to the right model type and required reference docs and example scripts, covering bi-encoders, rerankers, sparse and multi-vector models.

    11k GitHub starsUsed in 1 repo~2.6k tokens
    Auto-check passed
  • Official

    Sets up an isolated Python environment with a supported interpreter and current boto3 before any SageMaker deployment, training or AWS automation code runs.

    11k GitHub starsUsed in 2 repos~1.7k tokens
    Auto-check passed
  • Official

    Runs evaluations of Hugging Face Hub models on local hardware with inspect-ai or lighteval, and helps choose between vLLM, Transformers and accelerate backends.

    11k GitHub starsUsed in 2 repos~1.6k tokens
    Auto-check passed

Questions about Transformers.js

What does Transformers.js do?

Runs pre-trained Hugging Face models in JavaScript or TypeScript with Transformers.js, in browsers or Node.js, Bun and Deno, for text, vision, audio and multimodal tasks. js runs machine learning models directly in JavaScript with no Python server. The skill centers on the pipeline API, which bundles preprocessing, inference and postprocessing, and shows how to pick a task or a specific model from the Hugging Face Hub, choose a device, and install through npm or a CDN script tag.

When should I use Transformers.js?

Transformers.js fits situations like: running a sentiment or classification model in the browser without a backend; adding speech recognition to a Node.js app; doing image classification or object detection from JavaScript; choosing a Transformers.js-compatible model on the Hub.

How do I install Transformers.js in Claude Code?

Run `npx skills add huggingface/skills --skill transformers-js -a claude-code`. Or copy the skill folder (skills/transformers-js in huggingface/skills) into .claude/skills/transformers-js in your project. Claude Code loads it when a task matches its description.

How do I install Transformers.js in Codex?

Run `npx skills add huggingface/skills --skill transformers-js -a codex`. Or copy the skill folder (skills/transformers-js in huggingface/skills) into .agents/skills/transformers-js in your project. Codex loads it when a task matches its description.

Can I use Transformers.js in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add huggingface/skills --skill transformers-js -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/transformers-js, .gemini/skills/transformers-js, .github/skills/transformers-js and .opencode/skills/transformers-js in your project.

What does Transformers.js need to run?

Going by SKILL.md and its folder, Transformers.js needs the command-line tools its instructions call (npm) and credentials named HF_TOKEN. Our summary lists: Node.js 18 or later, a compatible Bun or Deno runtime, or a modern browser with ES modules; Internet access to download models from the Hugging Face Hub, unless local models are used. Compatibility (from SKILL.md): 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)..

Does Transformers.js access the network?

SKILL.md names 3 domains. In commands or code: huggingface.co and cdn.jsdelivr.net; the agent is likely to contact these when it follows the instructions. As links in the text: github.com. This is read from the text; nothing was executed.

Is Transformers.js safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Transformers.js use?

Transformers.js is published under the Apache-2.0 licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Transformers.js use?

About 6.2k tokens (SKILL.md is roughly 25k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 18k tokens, read only when the agent opens those files.

What are the alternatives to Transformers.js?

Skills that share tags, products or a category with Transformers.js: Hugging Face Transformers Usage (davila7/claude-code-templates, 32k stars), Transformers JS (waybarrios/opencode-power-pack, 533 stars), Transformers JS (sickn33/agentic-awesome-skills, 47k stars) and Compromise NLP Library (spencermountain/compromise, 12k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Transformers.js?

huggingface (a GitHub organization, an official publisher) maintains it in huggingface/skills, which has 11,148 GitHub stars. The repository holds 25 skills in this directory. The repository was last updated on October 1, 2026.

Source: huggingface/skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.