Huggingface.js documentation

Thư viện JS của Hugging Face

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started


huggingface javascript library logo

// Programmatically interact with the Hub

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

await uploadFile({
  repo: "my-user/nlp-model",
  accessToken: HF_TOKEN,
  // Can work with native File in browsers
  file: {
    path: "pytorch_model.bin",
    content: new Blob(...)
  }
});

// Use all supported Inference Providers!

await inference.chatCompletion({
  model: "meta-llama/Llama-3.1-8B-Instruct",
  provider: "sambanova", // or together, fal-ai, replicate, cohere …
  messages: [
    {
      role: "user",
      content: "Hello, nice to meet you!",
    },
  ],
  max_tokens: 512,
  temperature: 0.5,
});

await inference.textToImage({
  model: "black-forest-labs/FLUX.1-dev",
  provider: "replicate",
  inputs: "a picture of a green bird",
});

// and much more…

Thư viện JS của Hugging Face

Đây là bộ sưu tập các thư viện JS để tương tác với Hugging Face API, có kèm theo các kiểu TS.

  • @huggingface/hub: Tương tác với huggingface.co để tạo hoặc xóa repos và commit / tải xuống các tệp
  • @huggingface/inference: Sử dụng tất cả các Inference Providers (serverless) được hỗ trợ hoặc chuyển sang Inference Endpoints (dedicated) để gọi hơn 100.000 mô hình Machine Learning
  • @huggingface/mcp-client: Một client của Model Context Protocol (MCP) và một thư viện Agent nhỏ, được xây dựng dựa trên InferenceClient.
  • @huggingface/gguf: Trình phân tích GGUF hoạt động trên các tệp được lưu trữ từ xa.
  • @huggingface/dduf: Gói tương tự cho DDUF (DDUF Diffusers Unified Format)
  • @huggingface/lerobot: Bộ phân tích cho các bộ dữ liệu robot LeRobot, đọc các bố cục v2.x và v3.0 qua các yêu cầu HTTP có phạm vi.
  • @huggingface/usd-web-viewer: Trình xem OpenUSD cho web: kết hợp các tệp .usd, .usda, .usdc và .usdz trong WebAssembly và hiển thị chúng bằng three.js.
  • @huggingface/tasks: Các tệp định nghĩa và nguồn thông tin chính xác cho các nguyên thủy chính của Hub như pipeline tasks, model libraries, v.v.
  • @huggingface/jinja: Một bản triển khai JS tối giản của bộ máy mẫu Jinja, dùng cho các mẫu chat ML.
  • @huggingface/space-header: Sử dụng Space mini_header bên ngoài Hugging Face
  • @huggingface/ollama-utils: Các tiện ích khác nhau để duy trì khả năng tương thích của Ollama với các model trên Hugging Face Hub.
  • @huggingface/tiny-agents: Thư viện nhỏ, không phụ thuộc mô hình để xây dựng các AI agent có thể sử dụng công cụ.

Chúng tôi sử dụng các tính năng hiện đại để tránh polyfill và các phụ thuộc, do đó các thư viện chỉ hoạt động trên trình duyệt hiện đại / Node.js >= 18 / Bun / Deno.

Các thư viện vẫn còn rất non trẻ, vui lòng giúp chúng tôi bằng cách mở các issue!

Cài đặt

Từ NPM

Để cài đặt qua NPM, bạn có thể tải xuống các thư viện khi cần:

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

Sau đó, import các thư viện trong mã của bạn:

import { createRepo, commit, deleteRepo, listFiles } from "@huggingface/hub";
import { InferenceClient } from "@huggingface/inference";
import { McpClient } from "@huggingface/mcp-client";
import type { RepoId } from "@huggingface/hub";

Từ CDN hoặc lưu trữ tĩnh

Bạn có thể chạy các gói của chúng tôi với JS thuần, không cần bundler, bằng cách sử dụng CDN hoặc lưu trữ tĩnh. Sử dụng mô-đun ES, tức là <script type="module">, bạn có thể import các thư viện trong mã của mình:

<script type="module">
    import { InferenceClient } from 'https://cdn.jsdelivr.net/npm/@huggingface/inference@4.13.32/+esm';
    import { createRepo, commit, deleteRepo, listFiles } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.17.10/+esm";
</script>

Deno

// esm.sh
import { InferenceClient } from "https://esm.sh/@huggingface/inference"

import { createRepo, commit, deleteRepo, listFiles } from "https://esm.sh/@huggingface/hub"
// or npm:
import { InferenceClient } from "npm:@huggingface/inference"

import { createRepo, commit, deleteRepo, listFiles } from "npm:@huggingface/hub"

Ví dụ sử dụng

Lấy token truy cập HF của bạn trong cài đặt tài khoản.

Ví dụ @huggingface/inference

import { InferenceClient } from "@huggingface/inference";

const HF_TOKEN = "hf_...";

const client = new InferenceClient(HF_TOKEN);

// Chat completion API
const out = await client.chatCompletion({
  model: "meta-llama/Llama-3.1-8B-Instruct",
  messages: [{ role: "user", content: "Hello, nice to meet you!" }],
  max_tokens: 512
});
console.log(out.choices[0].message);

// Streaming chat completion API
for await (const chunk of client.chatCompletionStream({
  model: "meta-llama/Llama-3.1-8B-Instruct",
  messages: [{ role: "user", content: "Hello, nice to meet you!" }],
  max_tokens: 512
})) {
  console.log(chunk.choices[0].delta.content);
}

/// Using a third-party provider:
await client.chatCompletion({
  model: "meta-llama/Llama-3.1-8B-Instruct",
  messages: [{ role: "user", content: "Hello, nice to meet you!" }],
  max_tokens: 512,
  provider: "sambanova", // or together, fal-ai, replicate, cohere …
})

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



// You can also omit "model" to use the recommended model for the task
await client.translation({
  inputs: "My name is Wolfgang and I live in Amsterdam",
  parameters: {
    src_lang: "en",
    tgt_lang: "fr",
  },
});

// pass multimodal files or URLs as inputs
await client.imageToText({
  model: 'nlpconnect/vit-gpt2-image-captioning',
  data: await (await fetch('https://picsum.photos/300/300')).blob(),
})

// Using your own dedicated inference endpoint: https://hf.co/docs/inference-endpoints/
const gpt2Client = client.endpoint('https://xyz.eu-west-1.aws.endpoints.huggingface.cloud/gpt2');
const { generated_text } = await gpt2Client.textGeneration({ inputs: 'The answer to the universe is' });

// Chat Completion
const llamaEndpoint = client.endpoint(
  "https://huggingface.co/proxy/router.huggingface.co/hf-inference/models/meta-llama/Llama-3.1-8B-Instruct"
);
const out = await llamaEndpoint.chatCompletion({
  model: "meta-llama/Llama-3.1-8B-Instruct",
  messages: [{ role: "user", content: "Hello, nice to meet you!" }],
  max_tokens: 512,
});
console.log(out.choices[0].message);

Ví dụ @huggingface/hub

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

const HF_TOKEN = "hf_...";

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

await uploadFile({
  repo: "my-user/nlp-model",
  accessToken: HF_TOKEN,
  // Can work with native File in browsers
  file: {
    path: "pytorch_model.bin",
    content: new Blob(...)
  }
});

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

Ví dụ @huggingface/mcp-client

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

const HF_TOKEN = "hf_...";

const agent = new Agent({
  provider: "auto",
  model: "Qwen/Qwen2.5-72B-Instruct",
  apiKey: HF_TOKEN,
  servers: [
    {
      // Playwright MCP
      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) {
            console.log(delta.content);
        }
    }
}

Tất nhiên là còn nhiều tính năng hơn nữa, hãy xem README của từng thư viện!

Định dạng & kiểm thử

sudo corepack enable
pnpm install

pnpm -r format:check
pnpm -r lint:check
pnpm -r test

Xây dựng

pnpm -r build

Điều này sẽ tạo ra các tệp javascript ESM và CJS trong packages/*/dist, ví dụ packages/inference/dist/index.mjs.

Update on GitHub