Huggingface.js documentation
🤗 Hugging Face Inference
🤗 Hugging Face Inference
Hugging Face Hubにホストされているモデルに対して、複数のサービスで推論を実行するための統一インターフェースを提供する、TypeScript製のラッパーです:
- Inference Providers: サーバーレス推論パートナーが提供する、数百の機械学習モデルへの統一かつ簡素化されたアクセスです。この新しいアプローチは、従来の Serverless Inference API を基盤として構築されており、世界クラスのプロバイダーのおかげで、より多くのモデル、パフォーマンスの向上、そして高い信頼性を提供します。サポートされているプロバイダーの一覧については、ドキュメントを参照してください。
- Inference Endpoints: モデルを本番環境に簡単にデプロイするためのプロダクトです。推論は、Hugging Face が選択したクラウドプロバイダー上で、専用かつフルマネージドのインフラストラクチャで実行されます。
- ローカルエンドポイント: llama.cpp、Ollama、vLLM、LiteLLM、Text Generation Inference (TGI)などのローカル推論サーバーにクライアントを接続することで、これらを使用して推論を実行することもできます。
はじめる
インストール
ノード
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 に参加し、access tokens にアクセスして、無料でアクセストークンを生成してください。
アクセストークンは秘密に保つ必要があります。フロントエンドアプリケーションで保護する必要がある場合は、アクセストークンを保存するプロキシサーバーを設定することをお勧めします。
Inference Providersの使用
推論クライアントを使用して、サードパーティのプロバイダーに推論リクエストを送信できます。
現在、以下のプロバイダーをサポートしています:
- Fal.ai
- Featherless AI
- Fireworks AI
- HF Inference
- Humain AI
- Novita
- Nscale
- OpenRouter
- OVHcloud
- パブリックAI
- Replicate
- Scaleway
- Together
- Baseten
- Cohere
- Cerebras
- DeepInfra
- Groq
- Wavespeed.ai
- Z.ai
サードパーティプロバイダーにリクエストを送信するには、推論関数にproviderパラメーターを渡す必要があります。providerパラメーターのデフォルト値は“auto”で、https://hf.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がサポートするモデル
- Humain AIがサポートするモデル
- Nscaleがサポートするモデル
- OpenRouterがサポートするモデル
- OVHcloudがサポートするモデル
- サポートされているモデルを複製する
- Scalewayがサポートするモデル
- Togetherがサポートするモデル
- Basetenがサポートするモデル
- Cohereがサポートするモデル
- Cerebrasがサポートするモデル
- DeepInfraがサポートするモデル
- Groqがサポートするモデル
- Novita AIがサポートするモデル
- Wavespeed.aiがサポートするモデル
- Z.aiがサポートするモデル
❗重要な注意: 互換性を確保するには、サードパーティのAPIが、HFのモデルページで各パイプラインタスクタイプに対して想定している「標準」の形状APIに準拠している必要があります。 LLMについては、いずれにせよOpenAI APIに収束しているため問題になりませんが、「text-to-image」や「automatic-speech-recognition」のように標準的なAPIが存在しない他のタスクでは、より複雑になる可能性があります。ご支援が必要な場合や、より使いやすくできる点があれば、お知らせください!
👋別のプロバイダーを追加したいですか? 別の Inference プロバイダーのサポートを追加したい場合、または 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: ...
})これにより、バンドラーによるツリーシェイキングが有効になります。
エラー処理
推論パッケージは、異なるエラーシナリオを効果的に処理できるよう、特定のエラータイプを提供します。
エラーの種類
このパッケージは、ベースのErrorクラスを継承する複数のエラータイプを定義しています:
InferenceClientError: Hugging Face Inference のすべてのエラーのベースエラークラスInferenceClientInputError: 入力パラメータに問題がある場合にスローされますInferenceClientProviderApiError: プロバイダーから API レベルのエラーが発生した場合にスローされますInferenceClientHubApiError: Hugging Face HubからAPIレベルのエラーが発生した場合にスローされますInferenceClientProviderOutputError: プロバイダーの API 応答の形式に問題がある場合にスローされます
使用例
import { InferenceClient } from "@huggingface/inference";
import {
InferenceClientError,
InferenceClientInputError,
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.httpRequest);
console.error("HTTP Response details:", error.httpResponse);
} else 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.httpRequest);
console.error("HTTP Response details:", error.httpResponse);
} 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: 説明用のエラーメッセージhttpRequest: 失敗したリクエストの詳細(URL、メソッド、ヘッダー)httpResponse: ステータスコードとボディを含むレスポンスの詳細
InferenceClientHubApiError
Hugging Face Hub APIへのリクエスト時にAPIリクエストに問題がある場合、このエラーが発生します。
いくつかのプロパティがあります:
message: 説明用のエラーメッセージhttpRequest: 失敗したリクエストの詳細(URL、メソッド、ヘッダー)httpResponse: ステータスコードとボディを含むレスポンスの詳細
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;
}
}特徴量抽出
このタスクはテキストを読み取り、通常はセマンティックデータベース/セマンティック検索の一部として消費される生(raw)の浮動小数点数値を出力します。
await hf.featureExtraction({
model: "sentence-transformers/distilbert-base-nli-mean-tokens",
inputs: "That is a happy person",
});Fill Mask
欠落した単語(正確にはトークン)の穴を埋めようとします。
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'] }
})文の類似度
1つのテキストと他の文のリストとの間の意味的類似度を計算します。
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.textRanking({
model: 'cross-encoder/ettin-reranker-68m-v1',
inputs: {
query: 'Which planet is known as the Red Planet?',
texts: [
"Venus is often called Earth's twin because of its similar size and proximity.",
'Mars, known for its reddish appearance, is often referred to as the Red Planet.',
'Jupiter, the largest planet in our solar system, has a prominent red spot.',
'Saturn, famous for its rings, is sometimes mistaken for the Red Planet.'
]
}
})オーディオ
自動音声認識
音声ファイルから音声を文字起こしします。
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!'
})オーディオからオーディオへ
入力音声から1つまたは複数の生成されたオーディオを出力します。主に音声の品質向上や音源分離に使用されます。
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'
})画像からテキストへ
指定された画像からテキストを出力します。キャプション生成や文字認識(OCR)に一般的に使用されます。
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'
})画像から画像へ
Image-to-imageは、ソース画像を変換して、ターゲット画像またはターゲット画像ドメインの特性に一致させるタスクです。
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']
}
})マルチモーダル
視覚的質問応答
Visual Question Answeringは、画像に基づいてオープンエンドな質問に答えるタスクです。自然言語の質問に対して、自然言語の応答を出力します。
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(),
}
})表形式
表形式の回帰
Tabular regressionは、属性のセットが与えられたときに数値を予測するタスクです。
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"]
},
},
})表形式分類
Tabular classificationとは、属性の集合に基づいてターゲットカテゴリ(グループ)を分類するタスクです。
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);
}
}Inference Endpointsの使用
上記の例では推論プロバイダーを使用しました。これらはプロトタイピングや迅速なテストに非常に有用ですが、モデルを本番環境にデプロイする準備が整ったら、専用のインフラストラクチャを使用する必要があります。そこで登場するのがInference Endpointsです。これにより、任意のモデルをデプロイし、プライベートな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: "http://localhost: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互換のエンドポイントでChat Completion推論を実行するために使用できます。
テストの実行
HF_TOKEN="your access token" pnpm run test
適切なモデルの検索
各タスクで利用可能なモデルをリストし、各タスクの動作を詳細に説明する、情報量の多いドキュメントプロジェクト Tasks を用意しています。
また、MLの側面をさらに深く掘り下げたい場合のために、デモ、出力例、その他のリソースも含まれています。
依存関係
@huggingface/tasks: 型定義のみ