Huggingface.js documentation
Hugging Face JS 库
@huggingface/inference
使用 Inference ClientAPI 参考
类
HfInferenceInferenceClientInferenceClientEndpointInferenceClientErrorInferenceClientHubApiErrorInferenceClientInputErrorInferenceClientProviderApiErrorInferenceClientProviderOutputErrorInferenceClientRoutingError
接口
AudioToAudioOutputAudioToAudioOutputElemBaseArgsBodyParamsHeaderParamsInferenceProviderMappingEntryLogger选项TextGenerationInputTextGenerationOutputTextGenerationStreamBestOfSequenceTextGenerationStreamDetailsTextGenerationStreamOutputTextGenerationStreamPrefillTokenTextGenerationStreamTokenUrlParams
模块
@huggingface/hub
与 Hub 交互API 参考
类
接口
AuthInfoCachedFileInfoCachedRepoInfoCachedRevisionInfoCommitCopyFileCommitDataCommitDeletedEntryCommitEditFileCommitEditFileParamsCommitFileCommitInfoCommitOutputCopyDestinationCopyFilesEntryCopyProgressEventCopySource凭据DatasetEntryFileDownloadInfoOutputHFCacheInfoJobVolumeLfsPathInfoListFileEntryMlxQuantizationConfigModelConfigModelDerivedFieldsModelEntryOAuthResultParallelDownloadOptionsPathInfoQuantizationConfigRangeEditCacheEntryRepoIdSafetensorsIndexJsonSafetensorsShardFileInfoSecurityFileStatusSpaceEntrySpaceResourceConfigSpaceResourceRequirementSpaceRuntimeTensorInfoUserInfoWhoAmIAppWhoAmIOrgWhoAmIUserXetFileInfoXetReadToken
@huggingface/mcp-client
@huggingface/tiny-agents
@huggingface/space-header
@huggingface/gguf
@huggingface/lerobot
@huggingface/usd-web-viewer
// 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…Hugging Face JS 库
这是一组用于与 Hugging Face API 交互的 JS 库,并附带 TS 类型。
- @huggingface/hub:与 huggingface.co 交互,以创建或删除仓库,以及提交/下载文件
- @huggingface/inference:使用所有受支持的(无服务器)Inference Providers,或切换到 Inference Endpoints(专用)以调用 100,000+ 个机器学习模型
- @huggingface/mcp-client:一个基于 InferenceClient 构建的 Model Context Protocol (MCP) 客户端,以及一个小型 Agent 库。
- @huggingface/gguf:一个可以解析远程托管文件的 GGUF 解析器。
- @huggingface/dduf:DDUF(DDUF Diffusers Unified Format)的类似软件包
- @huggingface/lerobot:一个用于解析 LeRobot 机器人数据集的解析器,通过范围 HTTP 请求读取 v2.x 和 v3.0 布局。
- @huggingface/usd-web-viewer:一个面向 Web 的 OpenUSD 查看器:在 WebAssembly 中组合
.usd、.usda、.usdc和.usdz文件,并使用 three.js 进行渲染。 - @huggingface/tasks:Hub 主要原语(如 pipeline 任务、模型库等)的定义文件和权威来源。
- @huggingface/jinja:一个极简的 Jinja 模板引擎 JavaScript 实现,用于机器学习聊天模板。
- @huggingface/space-header:在 Hugging Face 外部使用 Space 的
mini_header - @huggingface/ollama-utils:用于维护 Hugging Face Hub 上模型与 Ollama 兼容性的各种实用工具。
- @huggingface/tiny-agents:一个小巧且与模型无关的库,用于构建能够使用工具的 AI 智能体。
我们使用现代特性以避免 polyfill 和依赖项,因此这些库仅在现代浏览器 / Node.js >= 18 / Bun / Deno 上可用。
这些库目前仍处于非常早期的阶段,欢迎通过提交 issue 来帮助我们!
安装
来自 NPM
要通过 NPM 安装,您可以按需下载库:
npm install @huggingface/hub npm install @huggingface/inference npm install @huggingface/mcp-client
然后在代码中导入这些库:
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";从 CDN 或静态托管
您可以使用 CDN 或静态托管,通过原生 JS 运行我们的软件包,而无需任何打包器。使用 ES 模块,即 <script type="module">,您可以在代码中导入这些库:
<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"使用示例
在您的 账户设置 中获取您的 HF 访问令牌。
@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://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);@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"]
});@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);
}
}
}当然还有更多功能,请查看每个库的 README!
格式化与测试
sudo corepack enable pnpm install pnpm -r format:check pnpm -r lint:check pnpm -r test
构建
pnpm -r build这将在 packages/*/dist 中生成 ESM 和 CJS JavaScript 文件,例如 packages/inference/dist/index.mjs。