Huggingface.js documentation

πŸ€— Inferensi Hugging Face

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

πŸ€— Inferensi Hugging Face

Wrapper yang didukung Typescript yang menyediakan antarmuka terpadu untuk menjalankan inferensi di berbagai layanan untuk model yang dihosting di Hugging Face Hub:

  1. Inference Providers: akses yang terpadu dan efisien ke ratusan model machine learning, didukung oleh mitra inferensi serverless kami. Pendekatan baru ini dibangun di atas Serverless Inference API kami sebelumnya, menawarkan lebih banyak model, kinerja yang lebih baik, dan keandalan yang lebih tinggi berkat penyedia kelas dunia. Lihat dokumentasi untuk daftar penyedia yang didukung.
  2. Inference Endpoints: produk untuk dengan mudah mendeploy model ke produksi. Inferensi dijalankan oleh Hugging Face di infrastruktur khusus yang sepenuhnya dikelola pada penyedia cloud pilihan Anda.
  3. Endpoint lokal: Anda juga dapat menjalankan inferensi dengan server inferensi lokal seperti llama.cpp, Ollama, vLLM, LiteLLM, atau Text Generation Inference (TGI) dengan menghubungkan klien ke endpoint lokal ini.

Memulai

Instal

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";

Inisialisasi

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

const hf = new InferenceClient('your access token');

❗Penting: Selalu berikan token akses. Bergabunglah dengan Hugging Face lalu kunjungi token akses untuk membuat token akses Anda gratis.

Token akses Anda harus dijaga kerahasiaannya. Jika Anda perlu melindunginya di aplikasi front-end, kami menyarankan untuk mengatur server proxy yang menyimpan token akses.

Menggunakan Penyedia Inferensi

Anda dapat mengirim permintaan inferensi ke penyedia pihak ketiga dengan klien inferensi.

Saat ini, kami mendukung penyedia berikut:

Untuk mengirim permintaan ke penyedia pihak ketiga, Anda harus meneruskan parameter provider ke fungsi inferensi. Nilai default parameter provider adalah β€œauto”, yang akan memilih penyedia pertama yang tersedia untuk model tersebut, diurutkan sesuai urutan preferensi Anda di 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"
})

Anda juga harus memastikan permintaan Anda terautentikasi dengan token akses. Ketika terautentikasi dengan token akses Hugging Face, permintaan akan diarahkan melalui https://huggingface.co. Ketika terautentikasi dengan kunci penyedia pihak ketiga, permintaan dilakukan langsung terhadap API inferensi penyedia tersebut.

Hanya sebagian model yang didukung saat meminta penyedia pihak ketiga. Anda dapat memeriksa daftar model yang didukung per tugas pipeline di sini:

❗Catatan penting: Agar kompatibel, API pihak ketiga harus mematuhi bentuk API β€œstandar” yang kami harapkan pada halaman model HF untuk setiap jenis tugas pipeline. Ini bukan masalah untuk LLM karena semua orang sudah bersepakat pada API OpenAI, tetapi bisa lebih rumit untuk tugas lain seperti β€œtext-to-image” atau β€œautomatic-speech-recognition” di mana tidak ada API standar. Beri tahu kami jika ada bantuan yang diperlukan atau jika kami bisa membuat hal ini lebih mudah untuk Anda!

πŸ‘‹Ingin menambahkan provider lain? Hubungi kami jika Anda ingin menambahkan dukungan untuk provider Inference lain, dan/atau ajukan permintaan di https://huggingface.co/spaces/huggingface/HuggingDiscussions/discussions/49

Tree-shaking

Anda dapat mengimpor fungsi yang Anda butuhkan langsung dari modul alih-alih menggunakan kelas InferenceClient.

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

await textGeneration({
  accessToken: "hf_...",
  model: "model_or_endpoint",
  inputs: ...,
  parameters: ...
})

Hal ini akan memungkinkan tree-shaking oleh bundler Anda.

Penanganan error

Paket inferensi menyediakan tipe error tertentu untuk membantu Anda menangani berbagai skenario error secara efektif.

Jenis Kesalahan

Paket ini mendefinisikan beberapa tipe error yang memperluas kelas dasar Error:

  • InferenceClientError: Kelas error dasar untuk semua error Hugging Face Inference
  • InferenceClientInputError: Dilempar ketika ada masalah dengan parameter input
  • InferenceClientProviderApiError: Dilempar ketika terdapat kesalahan tingkat API dari penyedia
  • InferenceClientHubApiError: Dilempar ketika terdapat kesalahan pada level API dari Hugging Face Hub
  • InferenceClientProviderOutputError: Dilempar ketika terdapat masalah dengan format respons API dari penyedia

Contoh Penggunaan

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);
  }
}

Detail Kesalahan

InferenceClientProviderApiError

Kesalahan ini terjadi ketika ada masalah dengan permintaan API saat melakukan inferensi di penyedia yang dipilih.

Ia memiliki beberapa properti:

  • message: Pesan error yang deskriptif
  • httpRequest: Detail tentang permintaan yang gagal (URL, metode, header)
  • httpResponse: Detail respons termasuk kode status dan isi

InferenceClientHubApiError

Kesalahan ini terjadi ketika ada masalah dengan permintaan API saat meminta API Hugging Face Hub.

Ia memiliki beberapa properti:

  • message: Pesan error yang deskriptif
  • httpRequest: Detail tentang permintaan yang gagal (URL, metode, header)
  • httpResponse: Detail respons termasuk kode status dan isi

InferenceClientProviderOutputError

Kesalahan ini terjadi ketika penyedia mengembalikan respons dalam format yang tidak diharapkan.

InferenceClientInputError

Kesalahan ini terjadi ketika parameter input tidak valid atau hilang. Pesan kesalahan menjelaskan apa yang salah dengan input tersebut.

Pemrosesan Bahasa Alami

Generasi Teks

Membuat teks dari prompt masukan.

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);
}

Chat Completion

Generate respons model dari daftar pesan yang membentuk percakapan.

// 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;
  }
}

Ekstraksi Fitur

Tugas ini membaca beberapa teks dan menghasilkan nilai float mentah, yang biasanya dikonsumsi sebagai bagian dari basis data semantik/pencarian semantik.

await hf.featureExtraction({
  model: "sentence-transformers/distilbert-base-nli-mean-tokens",
  inputs: "That is a happy person",
});

Isi Mask

Mencoba mengisi celah dengan kata yang hilang (lebih tepatnya, token).

await hf.fillMask({
  model: 'bert-base-uncased',
  inputs: '[MASK] world!'
})

Ringkasan

Meringkas teks yang lebih panjang menjadi teks yang lebih pendek. Hati-hati, beberapa model memiliki panjang maksimum untuk input.

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
  }
})

Menjawab Pertanyaan

Menjawab pertanyaan berdasarkan konteks yang Anda berikan.

await hf.questionAnswering({
  model: 'deepset/roberta-base-squad2',
  inputs: {
    question: 'What is the capital of France?',
    context: 'The capital of France is Paris.'
  }
})

Jawaban Pertanyaan Tabel

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']
    }
  }
})

Klasifikasi Teks

Sering digunakan untuk analisis sentimen, metode ini akan memberikan label pada teks yang diberikan beserta skor probabilitas untuk label tersebut.

await hf.textClassification({
  model: 'distilbert-base-uncased-finetuned-sst-2-english',
  inputs: 'I like you. I love you.'
})

Klasifikasi Token

Digunakan untuk parsing kalimat, baik secara gramatikal maupun Named Entity Recognition (NER) untuk memahami kata kunci yang terkandung dalam teks.

await hf.tokenClassification({
  model: 'dbmdz/bert-large-cased-finetuned-conll03-english',
  inputs: 'My name is Sarah Jessica Parker but you can call me Jessica'
})

Terjemahan

Mengonversi teks dari satu bahasa ke bahasa lain.

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"
 }
})

Klasifikasi Zero-Shot

Memeriksa seberapa baik teks input cocok dengan seperangkat label yang Anda berikan.

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'] }
})

Kemiripan Kalimat

Hitung kemiripan semantik antara satu teks dan daftar kalimat lainnya.

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'
    ]
  }
})

Peringkat Teks

Urutkan dokumen berdasarkan relevansinya terhadap kueri.

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.'
    ]
  }
})

Audio

Pengakuan Bicara Otomatis

Mentranskripsi ucapan dari file audio.

Demo

await hf.automaticSpeechRecognition({
  model: 'facebook/wav2vec2-large-960h-lv60-self',
  data: readFileSync('test/sample1.flac')
})

Klasifikasi Audio

Menugaskan label ke audio yang diberikan beserta skor probabilitas dari label tersebut.

Demo

await hf.audioClassification({
  model: 'superb/hubert-large-superb-er',
  data: readFileSync('test/sample1.flac')
})

Teks ke Suara

Menghasilkan suara yang terdengar alami dari input teks.

Tutorial interaktif

await hf.textToSpeech({
  model: 'espnet/kan-bayashi_ljspeech_vits',
  inputs: 'Hello world!'
})

Audio Ke Audio

Menghasilkan satu atau beberapa audio yang dihasilkan dari audio input, umumnya digunakan untuk peningkatan ucapan dan pemisahan sumber.

await hf.audioToAudio({
  model: 'speechbrain/sepformer-wham',
  data: readFileSync('test/sample1.flac')
})

Computer Vision

Klasifikasi Gambar

Menugaskan label ke gambar tertentu beserta skor probabilitas dari label tersebut.

Demo

await hf.imageClassification({
  data: readFileSync('test/cheetah.png'),
  model: 'google/vit-base-patch16-224'
})

Deteksi Objek

Mendeteksi objek dalam gambar dan mengembalikan label dengan kotak pembatas dan skor probabilitas yang sesuai.

Demo

await hf.objectDetection({
  data: readFileSync('test/cats.png'),
  model: 'facebook/detr-resnet-50'
})

Segmentasi Gambar

Mendeteksi segmen dalam gambar dan mengembalikan label dengan kotak pembatas dan skor probabilitas yang sesuai.

await hf.imageSegmentation({
  data: readFileSync('test/cats.png'),
  model: 'facebook/detr-resnet-50-panoptic'
})

Gambar Ke Teks

Menghasilkan teks dari gambar yang diberikan, umumnya digunakan untuk pemberian keterangan (captioning) atau pengenalan karakter optik (OCR).

await hf.imageToText({
  data: readFileSync('test/cats.png'),
  model: 'nlpconnect/vit-gpt2-image-captioning'
})

Teks Ke Gambar

Membuat gambar dari prompt teks.

Demo

await hf.textToImage({
  model: 'black-forest-labs/FLUX.1-dev',
  inputs: 'a picture of a green bird'
})

Gambar Ke Gambar

Image-to-image adalah tugas untuk mengubah gambar sumber agar sesuai dengan karakteristik gambar target atau domain gambar target.

Tutorial interaktif

await hf.imageToImage({
  inputs: new Blob([readFileSync("test/stormtrooper_depth.png")]),
  parameters: {
    prompt: "elmo's lecture",
  },
  model: "lllyasviel/sd-controlnet-depth",
});

Klasifikasi Gambar Zero Shot

Memeriksa seberapa baik gambar input cocok dengan seperangkat label yang Anda berikan.

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']
  }
})

Multimodal

Visual Question Answering

Visual Question Answering adalah tugas menjawab pertanyaan terbuka berdasarkan gambar. Model ini menghasilkan respons dalam bahasa alami untuk pertanyaan dalam bahasa alami.

Demo

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()
  }
})

Jawaban Pertanyaan Dokumen

Model document question answering menerima pasangan (dokumen, pertanyaan) sebagai input dan mengembalikan jawaban dalam bahasa alami.

Demo

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

Regresi Tabular

Regresi tabular adalah tugas memprediksi nilai numerik berdasarkan seperangkat atribut.

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"]
    },
  },
})

Klasifikasi Tabular

Klasifikasi tabular adalah tugas mengklasifikasikan kategori target (sebuah grup) berdasarkan seperangkat atribut.

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"]
    },
  },
})

Anda dapat menggunakan penyedia mana pun yang kompatibel dengan API Chat Completion dengan metode chatCompletion.

// 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);
  }
}

Menggunakan Inference Endpoints

Contoh yang kita lihat di atas menggunakan penyedia inferensi. Meskipun ini terbukti sangat berguna untuk membuat prototipe dan menguji sesuatu dengan cepat. Begitu Anda siap untuk mendeploy model Anda ke produksi, Anda perlu menggunakan infrastruktur khusus. Di sinilah Inference Endpoints berperan. Fitur ini memungkinkan Anda untuk mendeploy model apa pun dan mengeksposnya sebagai API privat. Setelah dideploy, Anda akan mendapatkan URL yang dapat Anda hubungkan:

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);

Secara default, semua panggilan ke endpoint inferensi akan menunggu hingga model dimuat. Ketika scaling to 0 diaktifkan pada endpoint, hal ini dapat menyebabkan waktu tunggu yang tidak sedikit. Jika Anda lebih memilih untuk menonaktifkan perilaku ini dan menangani sendiri error HTTP 500 yang dikembalikan oleh endpoint, Anda dapat melakukannya seperti berikut:

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,
	}
);

Menggunakan endpoint lokal

Anda dapat menggunakan InferenceClient untuk menjalankan chat completion dengan server inferensi lokal (llama.cpp, vllm, litellm server, TGI, mlx, dll.) yang berjalan di mesin Anda sendiri. API-nya harus kompatibel dengan 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);

Mirip dengan klien JS OpenAI, InferenceClient dapat digunakan untuk menjalankan inferensi Chat Completion dengan endpoint apa pun yang kompatibel dengan REST API OpenAI.

Menjalankan pengujian

HF_TOKEN="your access token" pnpm run test

Mencari model yang tepat

Kami memiliki proyek dokumentasi yang informatif bernama Tasks untuk mendaftar model yang tersedia untuk setiap tugas dan menjelaskan cara kerja masing-masing tugas secara detail.

Hal ini juga berisi demo, contoh output, dan sumber daya lain jika Anda ingin menggali lebih dalam sisi ML-nya.

Dependensi

  • @huggingface/tasks : Hanya tip
Update on GitHub