Huggingface.js 文档
🤗 Hugging Face 推理
并获得增强的文档体验
开始使用
🤗 Hugging Face 推理
一个由 Typescript 驱动的包装器,提供统一的接口,用于在 Hugging Face Hub 上托管的模型在多个服务之间运行推理。
- 推理提供商:通过我们的无服务器推理合作伙伴,提供对数百个机器学习模型的简化统一访问。这种新方法基于我们之前的无服务器推理 API,通过世界一流的提供商,提供更多模型、改进的性能和更高的可靠性。有关受支持的提供商列表,请参阅文档。
- 推理端点:一种轻松将模型部署到生产环境的产品。推理由 Hugging Face 在您选择的云提供商的专用、完全托管的基础设施中运行。
- 本地端点:您还可以通过将客户端连接到本地推理服务器,例如 llama.cpp、Ollama、vLLM、LiteLLM 或 Text Generation Inference (TGI) 来运行推理。
入门
安装
Node
npm install @huggingface/inference pnpm add @huggingface/inference yarn add @huggingface/inference
Deno
// esm.sh
import { InferenceClient } from "https://esm.sh/@huggingface/inference";
// or npm:
import { InferenceClient } from "npm:@huggingface/inference";
初始化
import { InferenceClient } from '@huggingface/inference';
const hf = new InferenceClient('your access token');
❗重要提示:始终传递访问令牌。加入Hugging Face,然后访问访问令牌以免费生成您的访问令牌。
您的访问令牌应保密。如果您需要在前端应用程序中保护它,我们建议设置一个存储访问令牌的代理服务器。
使用推理提供商
您可以使用推理客户端向第三方提供商发送推理请求。
目前,我们支持以下提供商:
- Fal.ai
- Featherless AI
- Fireworks AI
- HF 推理
- Hyperbolic
- Nebius
- Novita
- Nscale
- OVHcloud
- Replicate
- Sambanova
- Together
- Blackforestlabs
- Cohere
- Cerebras
- Groq
要向第三方提供商发送请求,您必须将 provider
参数传递给推理函数。provider
参数的默认值为“auto”,它将根据您在 https://huggingface.co/settings/inference-providers 中首选的排序顺序,选择模型可用的第一个提供商。
const accessToken = "hf_..."; // Either a HF access token, or an API key from the third-party provider (Replicate in this example)
const client = new InferenceClient(accessToken);
await client.textToImage({
provider: "replicate",
model:"black-forest-labs/Flux.1-dev",
inputs: "A black forest cake"
})
您还必须确保您的请求使用访问令牌进行身份验证。当使用 Hugging Face 访问令牌进行身份验证时,请求通过 https://huggingface.co. 进行路由。当使用第三方提供商密钥进行身份验证时,请求直接针对该提供商的推理 API 发出。
请求第三方提供商时,仅支持部分模型。您可以在此处查看每个管道任务支持的模型列表:
- Fal.ai 支持的模型
- Featherless AI 支持的模型
- Fireworks AI 支持的模型
- HF Inference 支持的模型
- Hyperbolic 支持的模型
- Nebius 支持的模型
- Nscale 支持的模型
- OVHcloud 支持的模型
- Replicate 支持的模型
- Sambanova 支持的模型
- Together 支持的模型
- Cohere 支持的模型
- Cerebras 支持的模型
- Groq 支持的模型
- Novita AI 支持的模型
❗重要提示:为了兼容,第三方 API 必须遵守我们在 HF 模型页面上为每种管道任务类型所期望的“标准”API 形式。对于 LLM 来说这不是问题,因为所有人都已经统一到 OpenAI API,但对于“文本到图像”或“自动语音识别”等其他任务来说可能更复杂,因为没有标准的 API。如果您需要任何帮助,或者我们可以为您提供便利,请告诉我们!
👋想添加其他提供商吗?如果您想添加对其他推理提供商的支持,和/或在 https://huggingface.co/spaces/huggingface/HuggingDiscussions/discussions/49 上提出请求,请联系我们。
Tree-shaking
您可以直接从模块导入所需函数,而不是使用 InferenceClient
类。
import { textGeneration } from "@huggingface/inference";
await textGeneration({
accessToken: "hf_...",
model: "model_or_endpoint",
inputs: ...,
parameters: ...
})
这将使您的打包工具能够进行 Tree-shaking。
错误处理
推理包提供了特定的错误类型,以帮助您有效地处理不同的错误场景。
错误类型
该包定义了几个继承自基本 Error
类的错误类型:
InferenceClientError
:所有 Hugging Face 推理错误的基本错误类InferenceClientInputError
:输入参数出现问题时抛出InferenceClientProviderApiError
:来自提供商的 API 级别错误时抛出InferenceClientHubApiError
:来自 Hugging Face Hub 的 API 级别错误时抛出InferenceClientProviderOutputError
:提供商的 API 响应格式出现问题时抛出
使用示例
import { InferenceClient } from "@huggingface/inference";
import {
InferenceClientError,
InferenceClientProviderApiError,
InferenceClientProviderOutputError,
InferenceClientHubApiError,
} from "@huggingface/inference";
const client = new InferenceClient();
try {
const result = await client.textGeneration({
model: "gpt2",
inputs: "Hello, I'm a language model",
});
} catch (error) {
if (error instanceof InferenceClientProviderApiError) {
// Handle API errors (e.g., rate limits, authentication issues)
console.error("Provider API Error:", error.message);
console.error("HTTP Request details:", error.request);
console.error("HTTP Response details:", error.response);
if (error instanceof InferenceClientHubApiError) {
// Handle API errors (e.g., rate limits, authentication issues)
console.error("Hub API Error:", error.message);
console.error("HTTP Request details:", error.request);
console.error("HTTP Response details:", error.response);
} else if (error instanceof InferenceClientProviderOutputError) {
// Handle malformed responses from providers
console.error("Provider Output Error:", error.message);
} else if (error instanceof InferenceClientInputError) {
// Handle invalid input parameters
console.error("Input Error:", error.message);
} else {
// Handle unexpected errors
console.error("Unexpected error:", error);
}
}
/// Catch all errors from @huggingface/inference
try {
const result = await client.textGeneration({
model: "gpt2",
inputs: "Hello, I'm a language model",
});
} catch (error) {
if (error instanceof InferenceClientError) {
// Handle errors from @huggingface/inference
console.error("Error from InferenceClient:", error);
} else {
// Handle unexpected errors
console.error("Unexpected error:", error);
}
}
错误详情
InferenceClientProviderApiError
当在所选提供商执行推理时,API 请求出现问题时会发生此错误。
它有几个属性:
message
:描述性错误消息request
:有关失败请求的详细信息(URL、方法、标头)response
:响应详细信息,包括状态码和正文
InferenceClientHubApiError
当请求 Hugging Face Hub API 时,API 请求出现问题时会发生此错误。
它有几个属性:
message
:描述性错误消息request
:有关失败请求的详细信息(URL、方法、标头)response
:响应详细信息,包括状态码和正文
InferenceClientProviderOutputError
当提供商返回意外格式的响应时,会发生此错误。
InferenceClientInputError
当输入参数无效或缺失时,会发生此错误。错误消息描述了输入的问题。
自然语言处理
文本生成
根据输入提示生成文本。
await hf.textGeneration({
model: 'mistralai/Mixtral-8x7B-v0.1',
provider: "together",
inputs: 'The answer to the universe is'
})
for await (const output of hf.textGenerationStream({
model: "mistralai/Mixtral-8x7B-v0.1",
provider: "together",
inputs: 'repeat "one two three four"',
parameters: { max_new_tokens: 250 }
})) {
console.log(output.token.text, output.generated_text);
}
聊天补全
从包含对话的消息列表中生成模型响应。
// Non-streaming API
const out = await hf.chatCompletion({
model: "Qwen/Qwen3-32B",
provider: "cerebras",
messages: [{ role: "user", content: "Hello, nice to meet you!" }],
max_tokens: 512,
temperature: 0.1,
});
// Streaming API
let out = "";
for await (const chunk of hf.chatCompletionStream({
model: "Qwen/Qwen3-32B",
provider: "cerebras",
messages: [
{ role: "user", content: "Can you help me solve an equation?" },
],
max_tokens: 512,
temperature: 0.1,
})) {
if (chunk.choices && chunk.choices.length > 0) {
out += chunk.choices[0].delta.content;
}
}
特征提取
此任务读取一些文本并输出原始浮点值,这些值通常作为语义数据库/语义搜索的一部分被使用。
await hf.featureExtraction({
model: "sentence-transformers/distilbert-base-nli-mean-tokens",
inputs: "That is a happy person",
});
填充掩码
尝试用缺失的单词(确切地说是令牌)填充空白。
await hf.fillMask({
model: 'bert-base-uncased',
inputs: '[MASK] world!'
})
摘要
将较长的文本总结为较短的文本。请注意,有些模型有最大输入长度限制。
await hf.summarization({
model: 'facebook/bart-large-cnn',
inputs:
'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest man-made structure in the world, a title it held for 41 years until the Chrysler Building in New York City was finished in 1930.',
parameters: {
max_length: 100
}
})
问答
根据您提供的上下文回答问题。
await hf.questionAnswering({
model: 'deepset/roberta-base-squad2',
inputs: {
question: 'What is the capital of France?',
context: 'The capital of France is Paris.'
}
})
表格问答
await hf.tableQuestionAnswering({
model: 'google/tapas-base-finetuned-wtq',
inputs: {
query: 'How many stars does the transformers repository have?',
table: {
Repository: ['Transformers', 'Datasets', 'Tokenizers'],
Stars: ['36542', '4512', '3934'],
Contributors: ['651', '77', '34'],
'Programming language': ['Python', 'Python', 'Rust, Python and NodeJS']
}
}
})
文本分类
通常用于情感分析,此方法会将标签以及该标签的概率分数分配给给定文本。
await hf.textClassification({
model: 'distilbert-base-uncased-finetuned-sst-2-english',
inputs: 'I like you. I love you.'
})
令牌分类
用于句子解析,可以是语法解析,也可以是命名实体识别 (NER),以理解文本中包含的关键词。
await hf.tokenClassification({
model: 'dbmdz/bert-large-cased-finetuned-conll03-english',
inputs: 'My name is Sarah Jessica Parker but you can call me Jessica'
})
翻译
将文本从一种语言转换为另一种语言。
await hf.translation({
model: 't5-base',
inputs: 'My name is Wolfgang and I live in Berlin'
})
await hf.translation({
model: 'facebook/mbart-large-50-many-to-many-mmt',
inputs: textToTranslate,
parameters: {
"src_lang": "en_XX",
"tgt_lang": "fr_XX"
}
})
零样本分类
检查输入文本与您提供的一组标签的匹配程度。
await hf.zeroShotClassification({
model: 'facebook/bart-large-mnli',
inputs: [
'Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!'
],
parameters: { candidate_labels: ['refund', 'legal', 'faq'] }
})
句子相似度
计算一个文本与一系列其他句子的语义相似度。
await hf.sentenceSimilarity({
model: 'sentence-transformers/paraphrase-xlm-r-multilingual-v1',
inputs: {
source_sentence: 'That is a happy person',
sentences: [
'That is a happy dog',
'That is a very happy person',
'Today is a sunny day'
]
}
})
音频
自动语音识别
将音频文件中的语音转录为文本。
await hf.automaticSpeechRecognition({
model: 'facebook/wav2vec2-large-960h-lv60-self',
data: readFileSync('test/sample1.flac')
})
音频分类
为给定音频分配标签及其概率分数。
await hf.audioClassification({
model: 'superb/hubert-large-superb-er',
data: readFileSync('test/sample1.flac')
})
文本到语音
从文本输入生成自然语音。
await hf.textToSpeech({
model: 'espnet/kan-bayashi_ljspeech_vits',
inputs: 'Hello world!'
})
音频到音频
从输入音频输出一个或多个生成的音频,通常用于语音增强和声源分离。
await hf.audioToAudio({
model: 'speechbrain/sepformer-wham',
data: readFileSync('test/sample1.flac')
})
计算机视觉
图像分类
为给定图像分配标签及其概率分数。
await hf.imageClassification({
data: readFileSync('test/cheetah.png'),
model: 'google/vit-base-patch16-224'
})
目标检测
检测图像中的对象,并返回带有相应边界框和概率分数的标签。
await hf.objectDetection({
data: readFileSync('test/cats.png'),
model: 'facebook/detr-resnet-50'
})
图像分割
检测图像中的片段,并返回带有相应边界框和概率分数的标签。
await hf.imageSegmentation({
data: readFileSync('test/cats.png'),
model: 'facebook/detr-resnet-50-panoptic'
})
图像到文本
从给定图像输出文本,通常用于图像描述或光学字符识别。
await hf.imageToText({
data: readFileSync('test/cats.png'),
model: 'nlpconnect/vit-gpt2-image-captioning'
})
文本到图像
根据文本提示创建图像。
await hf.textToImage({
model: 'black-forest-labs/FLUX.1-dev',
inputs: 'a picture of a green bird'
})
图像到图像
图像到图像是将源图像转换为匹配目标图像或目标图像域特征的任务。
await hf.imageToImage({
inputs: new Blob([readFileSync("test/stormtrooper_depth.png")]),
parameters: {
prompt: "elmo's lecture",
},
model: "lllyasviel/sd-controlnet-depth",
});
零样本图像分类
检查输入图像与您提供的一组标签的匹配程度。
await hf.zeroShotImageClassification({
model: 'openai/clip-vit-large-patch14-336',
inputs: {
image: await (await fetch('https://placekitten.com/300/300')).blob()
},
parameters: {
candidate_labels: ['cat', 'dog']
}
})
多模态
视觉问答
视觉问答是根据图像回答开放式问题的任务。它们以自然语言回答自然语言问题。
await hf.visualQuestionAnswering({
model: 'dandelin/vilt-b32-finetuned-vqa',
inputs: {
question: 'How many cats are lying down?',
image: await (await fetch('https://placekitten.com/300/300')).blob()
}
})
文档问答
文档问答模型接收(文档,问题)对作为输入,并以自然语言返回答案。
await hf.documentQuestionAnswering({
model: 'impira/layoutlm-document-qa',
inputs: {
question: 'Invoice number?',
image: await (await fetch('https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png')).blob(),
}
})
表格
表格回归
表格回归是在给定一组属性的情况下预测数值的任务。
await hf.tabularRegression({
model: "scikit-learn/Fish-Weight",
inputs: {
data: {
"Height": ["11.52", "12.48", "12.3778"],
"Length1": ["23.2", "24", "23.9"],
"Length2": ["25.4", "26.3", "26.5"],
"Length3": ["30", "31.2", "31.1"],
"Species": ["Bream", "Bream", "Bream"],
"Width": ["4.02", "4.3056", "4.6961"]
},
},
})
表格分类
表格分类是根据一组属性对目标类别(一个组)进行分类的任务。
await hf.tabularClassification({
model: "vvmnnnkv/wine-quality",
inputs: {
data: {
"fixed_acidity": ["7.4", "7.8", "10.3"],
"volatile_acidity": ["0.7", "0.88", "0.32"],
"citric_acid": ["0", "0", "0.45"],
"residual_sugar": ["1.9", "2.6", "6.4"],
"chlorides": ["0.076", "0.098", "0.073"],
"free_sulfur_dioxide": ["11", "25", "5"],
"total_sulfur_dioxide": ["34", "67", "13"],
"density": ["0.9978", "0.9968", "0.9976"],
"pH": ["3.51", "3.2", "3.23"],
"sulphates": ["0.56", "0.68", "0.82"],
"alcohol": ["9.4", "9.8", "12.6"]
},
},
})
您可以使用任何与 `chatCompletion` 方法兼容的 Chat Completion API 提供程序。
// Chat Completion Example
const MISTRAL_KEY = process.env.MISTRAL_KEY;
const hf = new InferenceClient(MISTRAL_KEY, {
endpointUrl: "https://api.mistral.ai",
});
const stream = hf.chatCompletionStream({
model: "mistral-tiny",
messages: [{ role: "user", content: "Complete the equation one + one = , just the answer" }],
});
let out = "";
for await (const chunk of stream) {
if (chunk.choices && chunk.choices.length > 0) {
out += chunk.choices[0].delta.content;
console.log(out);
}
}
使用推理端点
我们上面看到的示例使用了推理提供程序。虽然这些对于快速原型设计和测试非常有用,但一旦您准备将模型部署到生产环境,您将需要使用专用的基础设施。这就是 推理端点 的用武之地。它允许您部署任何模型并将其作为私有 API 公开。部署后,您将获得一个可以连接到的 URL。
import { InferenceClient } from '@huggingface/inference';
const hf = new InferenceClient("hf_xxxxxxxxxxxxxx", {
endpointUrl: "https://j3z5luu0ooo76jnl.us-east-1.aws.endpoints.huggingface.cloud/v1/",
});
const response = await hf.chatCompletion({
messages: [
{
role: "user",
content: "What is the capital of France?",
},
],
});
console.log(response.choices[0].message.content);
默认情况下,对推理端点的所有调用都会等到模型加载完成。当端点上启用缩放到 0 时,这可能会导致不容忽视的等待时间。如果您宁愿禁用此行为并自行处理端点返回的 500 HTTP 错误,可以这样做:
const hf = new InferenceClient("hf_xxxxxxxxxxxxxx", {
endpointUrl: "https://j3z5luu0ooo76jnl.us-east-1.aws.endpoints.huggingface.cloud/v1/",
});
const response = await hf.chatCompletion(
{
messages: [
{
role: "user",
content: "What is the capital of France?",
},
],
},
{
retry_on_error: false,
}
);
使用本地端点
您可以使用 `InferenceClient` 在您自己的机器上运行本地推理服务器(llama.cpp、vllm、litellm server、TGI、mlx 等)进行聊天补全。API 应与 OpenAI API 兼容。
import { InferenceClient } from '@huggingface/inference';
const hf = new InferenceClient(undefined, {
endpointUrl: "https://:8080",
});
const response = await hf.chatCompletion({
messages: [
{
role: "user",
content: "What is the capital of France?",
},
],
});
console.log(response.choices[0].message.content);
与 OpenAI JS 客户端类似,`InferenceClient` 可用于通过任何与 OpenAI REST API 兼容的端点运行聊天补全推理。
运行测试
HF_TOKEN="your access token" pnpm run test
查找合适的模型
我们有一个内容丰富的文档项目,名为 Tasks,用于列出每个任务可用的模型并详细解释每个任务的工作原理。
它还包含演示、示例输出和其他资源,如果您想深入了解机器学习方面的内容。
依赖项
@huggingface/tasks
:仅类型定义