huggingface/huggingface.js · 上手攻略

  • 仓库:huggingface/huggingface.js
  • 链接:https://github.com/huggingface/huggingface.js
  • 分类:llm-infra / JS 生态 SDK
  • 作者:spark
  • 更新:2026-07-27

是什么

huggingface.js 是 Hugging Face 官方维护的 JavaScript / TypeScript 工具套件,本身是个 monorepo,里面按职责拆分成了若干独立发布的 npm 包:

  • @huggingface/hub:与 huggingface.co 交互——创建/删除仓库、上传/下载/列出文件、提交 commit。覆盖 Model / Dataset / Space。
  • @huggingface/inference:统一推理客户端 InferenceClient,把 Hub 上 100k+ 模型(包括 Hugging Face Serverless Inference 和 sambanova / together / fal-ai / replicate / cohere 等第三方 Provider)的调用收口到一套 API:chatCompletion、textToImage、translation、imageToText 等。
  • @huggingface/mcp-client:基于 InferenceClientMCP 客户端 + 极简 Agent,可以接入任意 MCP server(Playwright、文件系统、自定义工具),并自动选择模型驱动 tool use。
  • @huggingface/gguf / @huggingface/dduf:远程 GGUF / DDUF(Diffusers Unified Format)文件的解析器,能在不下载整模型的前提下读 tensor 信息、metadata。
  • @huggingface/tasks:Hub 的 pipeline task / model library 元数据源头。
  • @huggingface/jinja:纯 JS 实现的 Jinja 模板引擎,专为 ML chat template 设计。
  • @huggingface/tiny-agents:与模型无关的小型 Agent 库,可通过 MCP 使用工具。
  • 其它space-header(把 Space 的 mini header 移植到外部站点)、ollama-utils(把 HF Hub 上的模型同步给 Ollama)。

整个仓库 TypeScript 优先、ESM 现代特性、无 polyfill,要求 Node ≥ 18 / 现代浏览器 / Bun / Deno

解决什么问题

  • 后端/前端 JS 工程师想把 HF Hub 当数据源:以前只能用 REST + 自己拼 token、签名、commit endpoint,现在一个 npm 包解决。
  • 统一调用 HF 推理,不管底层是 HF 官方 serverless、还是第三方 inference provider,或者自己部署的 Inference Endpoints:同一个 InferenceClient.chatCompletion() 切换 provider 即可。
  • 在浏览器/Edge / Deno / Bun 里直接调用模型——支持原生 File / Blob 上传、ESM CDN(jsdelivr / esm.sh / npm: import),不需要 bundler。
  • 远程检查 GGUF/DDUF 文件而不必先下载整个模型(10GB+ 模型开箱友好)。
  • JS 生态做 Agent:MCP 客户端 + tiny-agents 让 JS 工程师不必依赖 Python 生态就能搭出 tool-use agent。

快速安装

按需安装即可,仓库不强求装全:

npm install @huggingface/hub
npm install @huggingface/inference
npm install @huggingface/mcp-client

bun:

bun add @huggingface/inference @huggingface/hub

不需要 bundler,直接用 CDN(+esm 是 jsdelivr 的 ESM 编译入口):

<script type="module">
  import { InferenceClient } from 'https://cdn.jsdelivr.net/npm/@huggingface/inference@4.13.23/+esm';
  import { createRepo, listFiles } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.13.3/+esm";
  // esm.sh / Deno 的 npm: 别名同样可用
</script>

Deno:

import { InferenceClient } from "npm:@huggingface/inference";
import { createRepo } from "npm:@huggingface/hub";

版本号(4.13.23 / 2.13.3 等)随 minor 版本变化,请以 npm 上当前版本为准。

核心用法

1. @huggingface/hub —— 仓库与文件

import { createRepo, uploadFile, commit, deleteFiles, listFiles } from "@huggingface/hub";

const HF_TOKEN = "hf_..."; // 在 https://huggingface.co/settings/tokens 取

await createRepo({ repo: "my-user/nlp-model", accessToken: HF_TOKEN });

await uploadFile({
  repo: "my-user/nlp-model",
  accessToken: HF_TOKEN,
  file: { path: "pytorch_model.bin", content: new Blob([/* ... */]) },
});

await deleteFiles({
  repo: { type: "space", name: "my-user/my-space" },
  accessToken: HF_TOKEN,
  paths: ["README.md", ".gitattributes"],
});

// 列出文件:
const files = await listFiles({ repo: "bert-base-uncased", recursive: true });

2. @huggingface/inference —— 统一推理客户端

import { InferenceClient } from "@huggingface/inference";
const client = new InferenceClient(process.env.HF_TOKEN);

// 文本生成 / 翻译(默认走 HF serverless)
await client.translation({
  inputs: "My name is Wolfgang and I live in Amsterdam",
  parameters: { src_lang: "en", tgt_lang: "fr" },
});

// 切换第三方 Provider
await client.chatCompletion({
  model: "meta-llama/Llama-3.1-8B-Instruct",
  provider: "sambanova", // together / fal-ai / replicate / cohere ...
  messages: [{ role: "user", content: "Hello!" }],
  max_tokens: 512,
  temperature: 0.5,
});

// 流式
for await (const chunk of client.chatCompletionStream({
  model: "meta-llama/Llama-3.1-8B-Instruct",
  messages: [{ role: "user", content: "Hello!" }],
  max_tokens: 512,
})) {
  process.stdout.write(chunk.choices[0].delta.content ?? "");
}

// 文生图
await client.textToImage({
  model: "black-forest-labs/FLUX.1-dev",
  inputs: "a picture of a green bird",
  provider: "fal-ai",
});

// 直接传 Blob/URL 做多模态
await client.imageToText({
  model: "nlpconnect/vit-gpt2-image-captioning",
  data: await (await fetch("https://picsum.photos/300/300")).blob(),
});

// 指向自己的 Inference Endpoints
const ep = client.endpoint("https://xyz.eu-west-1.aws.endpoints.huggingface.cloud/gpt2");
const { generated_text } = await ep.textGeneration({ inputs: "The answer to the universe is" });

3. @huggingface/mcp-client —— Agent

import { Agent } from "@huggingface/mcp-client";

const agent = new Agent({
  provider: "auto",
  model: "Qwen/Qwen2.5-72B-Instruct",
  apiKey: process.env.HF_TOKEN,
  servers: [
    { command: "npx", args: ["@playwright/mcp@latest"] },
  ],
});

await agent.loadTools();

for await (const chunk of agent.run("What are the top 5 trending models on Hugging Face?")) {
  if ("choices" in chunk) {
    const delta = chunk.choices[0]?.delta;
    if (delta?.content) process.stdout.write(delta.content);
  }
}

provider: "auto" 让库自动挑选 chat-completion 友好的 Provider;想固定就用 "hf-inference" 或上面的第三方。

4. @huggingface/gguf —— 远程 GGUF 文件解析

import { GGMLQuantizationType, gguf } from "@huggingface/gguf";
const { metadata, tensorInfos } = await gguf("./model.gguf");

适合在下载前判断 quantization 类型、文件大小、tensor shape。

典型适用场景

  • Node / Bun / Deno 后端服务调用 HF Hub API(上传、CI 自动化、模型分发)。
  • 浏览器端 demo / Web 应用直接对接 serverless inference,免后端代理。@huggingface/inference 支持浏览器 CORS。
  • 跨 Provider 模型路由:同一段代码在 HF serverless、sambanova、fal-ai、replicate 之间切换,方便做 A/B、限流、回退。
  • Edge Function / Cloudflare Workers / Vercel Edge:ESM import + token 即可触发推理。
  • JS 工程师构建 Agent:MCP client + tiny-agents 让你不依赖 LangChain / LlamaIndex 也能跑 tool-use agent。
  • 前端工具:远程解析 GGUF tensor 信息、做模型预览、上传校验。

坑与注意

  1. 包还年轻:仓库 README 明说 "The libraries are still very young",API 偶有 breaking change,升级前看 changelog。
  2. Token 泄露HF_TOKEN 是读写权限的密钥,绝不能打进前端 bundle。要么走后端代理,要么用专门 scope 较小的 fine-grained token。
  3. Provider 覆盖 ≠ 模型覆盖:第三方 Provider 不一定支持任意 HF 上的开源模型;选定模型前查 inference.huggingface.co 或对应 Provider 文档。
  4. CORS / 浏览器限制InferenceClient 多数调用支持浏览器直连,但部分大文件上传 / dataset commit 走的是上传专用 endpoint,需要后端转发。
  5. GGUF 远程解析:在网络差时首次请求会等到 headers 拉完,对大模型(>10GB)要设置更长 timeout。
  6. Node 版本:必须 ≥ 18,且 ESM 模式优先——CJS 入口虽然有,但不是默认路径,老旧工具链可能踩坑。
  7. MCP client 的 Agent 还在演进@huggingface/mcp-client 行为比 LangGraph / CrewAI 更「轻」,tool 调度循环相对简单,复杂 multi-step 任务可能需要自己扩展 loop。
  8. @huggingface/jinja 不是完整 Jinja:只覆盖 chat template 常用语法,复杂控制流/扩展别指望。
  9. inference 速率限制:HF Serverless Inference 免费档有 QPS / 月配额,生产场景建议走 Inference Endpoints 或第三方 Provider。

与同类对比

定位 与 huggingface.js 的差异
huggingface_hub (Python) HF 官方 Python SDK API 等价,生态更成熟,PyTorch / Transformers / Diffusers 深度集成。JS 版功能略少,但补齐了纯 JS 生态。
LangChain.js / LlamaIndex.TS Agent / RAG 框架 通用 LLM 应用框架,HF 只是其中一个 provider;HF 官方 SDK 在 Hub 操作、inference 路由上更直接。
OpenAI SDK / Anthropic SDK 单家 provider SDK 只接自家模型,HF 优势在于「多 Provider + 100k+ 模型」统一抽象。
直接调 REST API 最低层 自己处理 token、签名、分页、commit;HF 官方 SDK 等价于把这些封装好了。
Model Context Protocol 客户端(其它实现) MCP 客户端 huggingface/mcp-client 是 HF 自家实现 + 内置 InferenceClient,与官方 MCP 规范一致;其它实现(如 mcp-client-ts)通常不带模型路由。

一句话推荐

前端 / Node 工程师想在 JS 生态里「读 HF Hub、跑 HF 推理、搭 MCP Agent」,直接装 @huggingface/hub + @huggingface/inference + @huggingface/mcp-client,别再自己拼 REST。


参考来源:仓库 README(github.com/huggingface/huggingface.js,2026-07-27 抓取)、各子包 README(packages/hubpackages/inferencepackages/mcp-clientpackages/gguf)、HF 官方 Inference 文档。版本号(@huggingface/inference@4.13.23 等)随 minor 版本变化,请以 npm 当前发布版本为准。