# 🤗 Hugging Face Inference

Một wrapper được hỗ trợ bởi Typescript, cung cấp một giao diện thống nhất để chạy suy luận trên nhiều dịch vụ cho các mô hình được lưu trữ trên Hugging Face Hub:

1.  [Nhà cung cấp suy luận](https://huggingface.co/docs/inference-providers/index): truy cập thống nhất, tối giản hàng trăm mô hình học máy, được hỗ trợ bởi các đối tác suy luận serverless của chúng tôi. Cách tiếp cận mới này xây dựng dựa trên API Suy luận Serverless trước đây của chúng tôi, cung cấp nhiều mô hình hơn, hiệu suất được cải thiện và độ tin cậy cao hơn nhờ các nhà cung cấp hàng đầu thế giới. Tham khảo [tài liệu](https://huggingface.co/docs/inference-providers/index#partners) để xem danh sách các nhà cung cấp được hỗ trợ.
2.  [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index): một sản phẩm để triển khai các mô hình lên môi trường production một cách dễ dàng. Việc suy luận được thực hiện bởi Hugging Face trên một hạ tầng được quản lý hoàn toàn, dành riêng, trên nhà cung cấp cloud do bạn lựa chọn.
3.  Các điểm cuối cục bộ: bạn cũng có thể chạy suy luận bằng các máy chủ suy luận cục bộ như [llama.cpp](https://github.com/ggerganov/llama.cpp), [Ollama](https://ollama.com/), [vLLM](https://github.com/vllm-project/vllm), [LiteLLM](https://docs.litellm.ai/docs/simple_proxy), hoặc [Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference) bằng cách kết nối client với các điểm cuối cục bộ này.

## Bắt đầu

### Cài đặt

#### Node

```console
npm install @huggingface/inference

pnpm add @huggingface/inference

yarn add @huggingface/inference
```

#### Deno

```ts
// esm.sh
import { InferenceClient } from "https://esm.sh/@huggingface/inference";
// or npm:
import { InferenceClient } from "npm:@huggingface/inference";
```

### Khởi tạo

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

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

❗**Lưu ý quan trọng:** Luôn truyền access token. Tham gia [Hugging Face](https://huggingface.co/join) và sau đó truy cập [access tokens](https://huggingface.co/settings/tokens) để tạo access token của bạn **một cách miễn phí**.

Token truy cập của bạn nên được giữ bí mật. Nếu bạn cần bảo vệ nó trong các ứng dụng front-end, chúng tôi đề xuất thiết lập một máy chủ proxy lưu trữ token truy cập.

## Sử dụng Nhà cung cấp Suy luận

Bạn có thể gửi các yêu cầu suy luận đến các nhà cung cấp bên thứ ba bằng cách sử dụng client suy luận.

Hiện tại, chúng tôi hỗ trợ các nhà cung cấp sau:
- [Fal.ai](https://fal.ai)
- [Featherless AI](https://featherless.ai)
- [Fireworks AI](https://fireworks.ai)
- [HF Inference](https://huggingface.co/docs/inference-providers/providers/hf-inference)
- [Humain AI](https://node.humain.com/)
- [Novita](https://novita.ai)
- [Nscale](https://nscale.com)
- [OpenRouter](https://openrouter.ai)
- [OVHcloud](https://endpoints.ai.cloud.ovh.net/)
- [AI công khai](https://publicai.co)
- [Replicate](https://replicate.com)
- [Scaleway](https://www.scaleway.com/en/generative-apis/)
- [Together](https://together.xyz)
- [Baseten](https://baseten.co)
- [Cohere](https://cohere.com)
- [Cerebras](https://cerebras.ai/)
- [DeepInfra](https://deepinfra.com)
- [Groq](https://groq.com)
- [Wavespeed.ai](https://wavespeed.ai/)
- [Z.ai](https://z.ai/)

Để gửi yêu cầu đến nhà cung cấp bên thứ ba, bạn phải truyền tham số `provider` vào hàm suy luận. Giá trị mặc định của tham số `provider` là "auto", sẽ chọn nhà cung cấp đầu tiên có sẵn cho mô hình, được sắp xếp theo thứ tự ưu tiên của bạn tại https://hf.co/settings/inference-providers.

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

Bạn cũng phải đảm bảo yêu cầu của bạn được xác thực bằng một access token. Khi xác thực bằng access token của Hugging Face, yêu cầu sẽ được định tuyến qua https://huggingface.co. Khi xác thực bằng khóa của nhà cung cấp bên thứ ba, yêu cầu sẽ được gửi trực tiếp đến inference API của nhà cung cấp đó.

Chỉ một tập con các model được hỗ trợ khi yêu cầu các nhà cung cấp bên thứ ba. Bạn có thể kiểm tra danh sách các model được hỗ trợ theo từng tác vụ pipeline tại đây:
- [Các mô hình được hỗ trợ bởi Fal.ai](https://huggingface.co/api/partners/fal-ai/models)
- [Các mô hình được hỗ trợ bởi Featherless AI](https://huggingface.co/api/partners/featherless-ai/models)
- [Các mô hình được hỗ trợ bởi Fireworks AI](https://huggingface.co/api/partners/fireworks-ai/models)
- [Các mô hình được hỗ trợ bởi HF Inference](https://huggingface.co/api/partners/hf-inference/models)
- [Các mô hình được hỗ trợ bởi Humain AI](https://huggingface.co/api/partners/humain-ai/models)
- [Các mô hình được hỗ trợ bởi Nscale](https://huggingface.co/api/partners/nscale/models)
- [Các mô hình được hỗ trợ bởi OpenRouter](https://huggingface.co/api/partners/openrouter/models)
- [Các mô hình được hỗ trợ bởi OVHcloud](https://huggingface.co/api/partners/ovhcloud/models)
- [Đa dạng hóa các mô hình được hỗ trợ](https://huggingface.co/api/partners/replicate/models)
- [Các mô hình được hỗ trợ bởi Scaleway](https://huggingface.co/api/partners/scaleway/models)
- [Các mô hình được hỗ trợ bởi Together](https://huggingface.co/api/partners/together/models)
- [Các mô hình được hỗ trợ bởi Baseten](https://huggingface.co/api/partners/baseten/models)
- [Các mô hình được hỗ trợ bởi Cohere](https://huggingface.co/api/partners/cohere/models)
- [Các mô hình được hỗ trợ bởi Cerebras](https://huggingface.co/api/partners/cerebras/models)
- [Các mô hình được hỗ trợ bởi DeepInfra](https://huggingface.co/api/partners/deepinfra/models)
- [Các mô hình được hỗ trợ bởi Groq](https://console.groq.com/docs/models)
- [Các mô hình được hỗ trợ bởi Novita AI](https://huggingface.co/api/partners/novita/models)
- [Các mô hình được hỗ trợ bởi Wavespeed.ai](https://huggingface.co/api/partners/wavespeed/models)
- [Các mô hình được hỗ trợ bởi Z.ai](https://huggingface.co/api/partners/zai-org/models)

❗**Lưu ý quan trọng:** Để tương thích, API bên thứ ba phải tuân thủ API hình dạng "chuẩn" mà chúng tôi kỳ vọng trên các trang mô hình HF cho từng loại tác vụ pipeline. Điều này không phải là vấn đề đối với LLM vì mọi người đều đã hội tụ về API OpenAI, nhưng có thể phức tạp hơn đối với các tác vụ khác như "text-to-image" hoặc "automatic-speech-recognition", nơi không tồn tại API chuẩn. Hãy cho chúng tôi biết nếu cần hỗ trợ hoặc nếu chúng tôi có thể giúp bạn dễ dàng hơn!

👋**Bạn muốn thêm một nhà cung cấp khác?** Hãy liên hệ nếu bạn muốn thêm hỗ trợ cho một nhà cung cấp Inference khác, và/hoặc yêu cầu tại https://huggingface.co/spaces/huggingface/HuggingDiscussions/discussions/49

### Tree-shaking

Bạn có thể nhập trực tiếp các hàm cần thiết từ module thay vì sử dụng lớp `InferenceClient`.

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

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

Điều này sẽ cho phép công cụ đóng gói (bundler) của bạn thực hiện tree-shaking.

### Xử lý lỗi

Gói suy luận cung cấp các loại lỗi cụ thể để giúp bạn xử lý hiệu quả các kịch bản lỗi khác nhau.

#### Các loại lỗi

Gói này định nghĩa một số kiểu lỗi kế thừa từ lớp `Error` cơ bản:

- `InferenceClientError`: Lớp lỗi cơ bản cho tất cả các lỗi Hugging Face Inference
- `InferenceClientInputError`: Được ném ra khi có vấn đề với các tham số đầu vào
- `InferenceClientProviderApiError`: Được ném ra khi có các lỗi ở cấp độ API từ các nhà cung cấp
- `InferenceClientHubApiError`: Được ném ra khi có các lỗi ở cấp độ API từ Hugging Face Hub
- `InferenceClientProviderOutputError`: Được ném ra khi có vấn đề với định dạng phản hồi API của các nhà cung cấp

### Ví dụ sử dụng

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

### Chi tiết lỗi

#### InferenceClientProviderApiError

Lỗi này xảy ra khi có sự cố với yêu cầu API khi thực hiện suy luận tại nhà cung cấp đã chọn.

Nó có một số thuộc tính:
- `message`: Thông báo lỗi mô tả
- `httpRequest`: Chi tiết về yêu cầu thất bại (URL, phương thức, tiêu đề)
- `httpResponse`: Chi tiết phản hồi bao gồm mã trạng thái và nội dung

#### InferenceClientHubApiError

Lỗi này xảy ra khi có sự cố với yêu cầu API khi gọi Hugging Face Hub API.

Nó có một số thuộc tính:
- `message`: Thông báo lỗi mô tả
- `httpRequest`: Chi tiết về yêu cầu thất bại (URL, phương thức, tiêu đề)
- `httpResponse`: Chi tiết phản hồi bao gồm mã trạng thái và nội dung

#### InferenceClientProviderOutputError

Lỗi này xảy ra khi một nhà cung cấp trả về phản hồi ở định dạng không mong đợi.

#### InferenceClientInputError

Lỗi này xảy ra khi các tham số đầu vào không hợp lệ hoặc bị thiếu. Thông báo lỗi mô tả vấn đề với đầu vào.

### Xử lý ngôn ngữ tự nhiên

#### Sinh văn bản

Tạo văn bản từ một prompt đầu vào.

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

#### Hoàn thành trò chuyện

Tạo phản hồi của mô hình từ một danh sách các tin nhắn cấu thành một cuộc hội thoại.

```typescript
// 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;
  }
}
```
#### Trích xuất đặc trưng

Nhiệm vụ này đọc một số văn bản và xuất ra các giá trị float thô, thường được sử dụng như một phần của cơ sở dữ liệu ngữ nghĩa/tìm kiếm ngữ nghĩa.

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

#### Điền Mask

Thử điền vào một khoảng trống bằng một từ bị thiếu (chính xác hơn là một token).

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

#### Tóm tắt

Tóm tắt văn bản dài thành văn bản ngắn hơn. Hãy cẩn thận, một số mô hình có độ dài tối đa cho đầu vào.

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

#### Trả lời câu hỏi

Trả lời các câu hỏi dựa trên ngữ cảnh bạn cung cấp.

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

#### Trả lời câu hỏi từ bảng

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

#### Phân loại văn bản

Thường được sử dụng cho phân tích cảm xúc, phương pháp này sẽ gán nhãn cho văn bản được cung cấp cùng với điểm xác suất của nhãn đó.

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

#### Phân loại Token

Được sử dụng để phân tích câu, có thể là phân tích ngữ pháp hoặc Nhận thực thể có tên (NER) nhằm hiểu các từ khóa chứa trong văn bản.

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

#### Bản dịch

Chuyển đổi văn bản từ ngôn ngữ này sang ngôn ngữ khác.

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

#### Phân loại Zero-Shot

Kiểm tra mức độ phù hợp của một văn bản đầu vào với một tập hợp các nhãn do bạn cung cấp.

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

#### Độ tương tự của câu

Tính độ tương đồng ngữ nghĩa giữa một văn bản và danh sách các câu khác.

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

#### Xếp hạng văn bản

Xếp hạng tài liệu theo mức độ liên quan đến truy vấn.

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

### Âm thanh

#### Nhận dạng giọng nói tự động

Chuyển văn bản từ tệp âm thanh.

[Bản demo](https://huggingface.co/spaces/huggingfacejs/speech-recognition-vue)

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

#### Phân loại âm thanh

Gán nhãn cho âm thanh được cung cấp cùng với điểm xác suất của nhãn đó.

[Bản demo](https://huggingface.co/spaces/huggingfacejs/audio-classification-vue)

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

#### Chuyển văn bản thành giọng nói

Tạo giọng nói tự nhiên từ đầu vào dạng văn bản.

[Hướng dẫn tương tác](https://scrimba.com/scrim/co8da4d23b49b648f77f4848a?pl=pkVnrP7uP)

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

#### Âm thanh sang Âm thanh

Xuất ra một hoặc nhiều âm thanh được tạo từ một âm thanh đầu vào, thường được sử dụng cho việc tăng cường giọng nói và tách nguồn.

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

### Thị giác máy tính

#### Phân loại hình ảnh

Gán nhãn cho một hình ảnh cụ thể kèm theo điểm xác suất của nhãn đó.

[Bản demo](https://huggingface.co/spaces/huggingfacejs/image-classification-vue)

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

#### Phát hiện đối tượng

Phát hiện các đối tượng trong hình ảnh và trả về nhãn kèm theo các hộp bao (bounding box) tương ứng cùng điểm số xác suất.

[Bản demo](https://huggingface.co/spaces/huggingfacejs/object-detection-vue)

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

#### Phân đoạn hình ảnh

Phát hiện các phân đoạn trong một hình ảnh và trả về các nhãn kèm theo hộp bao tương ứng cùng điểm số xác suất.

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

#### Hình Ảnh Sang Văn Bản

Xuất văn bản từ một hình ảnh cho trước, thường được sử dụng cho việc chú thích hoặc nhận dạng ký tự quang học.

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

#### Văn Bản Sang Hình Ảnh

Tạo một hình ảnh từ một câu lệnh văn bản.

[Bản demo](https://huggingface.co/spaces/huggingfacejs/image-to-text)

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

#### Hình sang Hình

Image-to-image là nhiệm vụ biến đổi một ảnh nguồn để khớp với các đặc điểm của một ảnh đích hoặc một miền ảnh đích.

[Hướng dẫn tương tác](https://scrimba.com/scrim/co4834bf9a91cc81cfab07969?pl=pkVnrP7uP)

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

#### Phân loại ảnh Zero Shot

Kiểm tra mức độ phù hợp của một hình ảnh đầu vào với một tập nhãn do bạn cung cấp.

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

### Đa phương thức

#### Trả lời câu hỏi trực quan

Visual Question Answering là nhiệm vụ trả lời các câu hỏi mở dựa trên một hình ảnh. Chúng tạo ra các phản hồi bằng ngôn ngữ tự nhiên cho các câu hỏi bằng ngôn ngữ tự nhiên.

[Bản demo](https://huggingface.co/spaces/huggingfacejs/doc-vis-qa)

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

#### Trả lời câu hỏi từ tài liệu

Mô hình trả lời câu hỏi từ tài liệu nhận vào một cặp (tài liệu, câu hỏi) và trả về câu trả lời bằng ngôn ngữ tự nhiên.

[Bản demo](https://huggingface.co/spaces/huggingfacejs/doc-vis-qa)

```typescript
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(),
  }
})
```

### Dữ liệu bảng

#### Hồi quy bảng

Hồi quy bảng là nhiệm vụ dự đoán một giá trị số dựa trên một tập hợp các thuộc tính.

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

#### Phân loại bảng

Phân loại bảng là nhiệm vụ phân loại một danh mục đích (một nhóm) dựa trên một tập hợp các thuộc tính.

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

Bạn có thể sử dụng bất kỳ nhà cung cấp nào tương thích với API Chat Completion với phương thức `chatCompletion`.

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

## Sử dụng Inference Endpoints

Các ví dụ ở trên sử dụng nhà cung cấp suy luận. Mặc dù những nhà cung cấp này rất hữu ích để thử nghiệm và kiểm tra nhanh, nhưng khi bạn sẵn sàng triển khai mô hình của mình lên môi trường sản xuất, bạn sẽ cần sử dụng một hạ tầng chuyên dụng. Đó là lúc [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index) phát huy tác dụng. Nó cho phép bạn triển khai bất kỳ mô hình nào và công bố nó dưới dạng một API riêng tư. Sau khi triển khai, bạn sẽ nhận được một URL để kết nối:

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

Mặc định, tất cả các cuộc gọi đến điểm suy luận sẽ chờ cho đến khi mô hình được tải. Khi [thang máy về 0](https://huggingface.co/docs/inference-endpoints/en/autoscaling#scaling-to-0) được bật trên điểm cuối, điều này có thể dẫn đến thời gian chờ không nhỏ. Nếu bạn muốn tắt hành vi này và tự xử lý các lỗi HTTP 500 do điểm cuối trả về, bạn có thể thực hiện như sau:

```typescript
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,
	}
);
```
## Sử dụng các điểm cuối cục bộ

Bạn có thể sử dụng `InferenceClient` để chạy chat completion với các máy chủ suy luận cục bộ (llama.cpp, vllm, litellm server, TGI, mlx, v.v.) chạy trên máy của bạn. API phải tương thích với OpenAI API.

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

Tương tự như client JS của OpenAI, `InferenceClient` có thể được sử dụng để chạy suy luận Chat Completion với bất kỳ endpoint nào tương thích với REST API của OpenAI.

## Chạy các bài kiểm thử

```console
HF_TOKEN="your access token" pnpm run test
```

## Tìm kiếm các mô hình phù hợp

Chúng tôi có một dự án tài liệu hữu ích mang tên [Tasks](https://huggingface.co/tasks) để liệt kê các model khả dụng cho từng task và giải thích chi tiết cách hoạt động của mỗi task.

Nó cũng bao gồm các bản demo, kết quả ví dụ và các tài nguyên khác nếu bạn muốn tìm hiểu sâu hơn về khía cạnh ML.

## Phụ thuộc

- `@huggingface/tasks` : Chỉ có kiểu

