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
:僅型別定義