Transformers js

From findscripter/everything-skills · View interactive version

Transformers js is an AI agent skill from the GitHub repository findscripter/everything-skills. 当需要在浏览器或 Node.js 端、无后端 ML 服务直接运行 Hugging Face 模型(文本/图像/音频/多模态/向量)时使用;做用 pipeline API 加载模型并产出推理结果,含设备(webgpu)、量化(dtype)、缓存与显存释放;不适用于需 Python 后端、训练/微调或超大模型(>数 GB)的生产重负载。触发词:transformers.js、浏览器端推理、pipeline、WebGPU、ONNX、嵌入向量

How to use this skill

Skill file

何时使用

在 JS/TS(Node.js 18+ 或现代浏览器,支持 ES Modules)里直接跑 Hugging Face 模型、不想架 Python 后端时使用。典型场景:

不该用(负边界):

步骤

  1. 安装:Node 端 npm install @huggingface/transformers;浏览器用 CDN import 即可(见示例)。
  2. 选模型:在 Hub 按 library=transformers.js 过滤,再加 pipeline_tag=<任务> 与 sort=trending/downloads。优先选 Xenova、onnx-community 维护的模型;确认有 ONNX 权重。
  3. 建 pipeline:await pipeline(task, modelId, options),按需传 device、dtype、progress_callback。
  4. 推理:调用 await pipe(input, genOptions);可传数组做批处理。
  5. 释放显存:用完务必 await pipe.dispose(),否则内存泄漏(单模型占 100MB ~ 数 GB)。
  6. 生产前固定版本:{ revision: '<git commit>' };用 try/catch 包裹并配加载进度 UI。

指令

示例

基础 pipeline(含释放):

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

const pipe = await pipeline('sentiment-analysis');
const result = await pipe('I love transformers!');
// [{ label: 'POSITIVE', score: 0.9998 }]
await pipe.dispose(); // 必做:释放显存

指定模型 + 量化 + WebGPU(文本生成):

const generator = await pipeline(
  'text-generation',
  'onnx-community/gemma-3-270m-it-ONNX',
  { dtype: 'q4', device: 'webgpu' }
);
const out = await generator('Explain quantum computing simply.', {
  max_new_tokens: 100, temperature: 0.7
});
await generator.dispose();

句向量/嵌入(mean pooling + 归一化):

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

浏览器 CDN:

<script type="module">
  import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers';
</script>

下载进度回调:

const clf = await pipeline('sentiment-analysis', null, {
  progress_callback: (info) => {
    if (info.status === 'progress')
      console.log(`${info.file}: ${info.progress.toFixed(1)}%`);
  }
});

错误处理:

try {
  const pipe = await pipeline('sentiment-analysis', 'model-id');
  await pipe('text');
} catch (e) {
  if (e.message.includes('fetch')) console.error('下载失败,检查网络');
  else if (e.message.includes('ONNX')) console.error('执行失败,检查模型兼容性');
  else console.error('未知错误', e);
}

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT);上游技能源自 huggingface/transformers.js(Apache-2.0)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.