# 🤗 Hugging Face Inference

Hugging Face Hub에 호스팅된 모델에 대해 여러 서비스에서 추론을 실행할 수 있는 통합 인터페이스를 제공하는 Typescript 기반 래퍼입니다:

1.  [Inference Providers](https://huggingface.co/docs/inference-providers/index): 서버리스 추론 파트너가 제공하는 수백 개의 머신러닝 모델에 대한 간소화되고 통합된 접근 방식입니다. 이 새로운 접근 방식은 기존의 Serverless Inference API를 기반으로 하며, 세계 수준의 제공업체 덕분에 더 많은 모델, 향상된 성능, 그리고 더 높은 신뢰성을 제공합니다. 지원되는 제공업체 목록은 [문서](https://huggingface.co/docs/inference-providers/index#partners)를 참조하세요.
2.  [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index): 모델을 프로덕션에 쉽게 배포할 수 있는 제품입니다. 추론은 사용자가 선택한 클라우드 제공자의 전용, 완전 관리형 인프라에서 Hugging Face에 의해 실행됩니다.
3.  로컬 엔드포인트: 클라이언트를 이러한 로컬 엔드포인트에 연결하여 [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), 또는 [Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference)와 같은 로컬 추론 서버로 추론을 실행할 수도 있습니다.

## 시작하기

### 설치

#### 노드

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

### 초기화

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

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

❗**중요한 참고 사항:** 항상 액세스 토큰을 전달하세요. [Hugging Face](https://huggingface.co/join)에 가입한 후 [access tokens](https://huggingface.co/settings/tokens) 페이지를 방문하여 **무료로** 액세스 토큰을 생성하세요.

access token은 비공개로 유지해야 합니다. 프론트엔드 애플리케이션에서 이를 보호해야 하는 경우, access token을 저장하는 프록시 서버를 설정하는 것을 권장합니다.

## Inference Providers 사용

inference client를 사용하여 서드파티 제공업체에 추론 요청을 보낼 수 있습니다.

현재 다음 프로바이더를 지원합니다:
- [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](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/)

서드파티 프로바이더에 요청을 보내려면 추론 함수에 `provider` 매개변수를 전달해야 합니다. `provider` 매개변수의 기본값은 "auto"이며, 이는 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"
})
```

요청이 액세스 토큰으로 인증되었는지 확인해야 합니다. Hugging Face 액세스 토큰으로 인증된 경우, 요청은 https://huggingface.co를 통해 라우팅됩니다. 서드파티 제공자 키로 인증된 경우, 요청은 해당 제공자의 추론 API에 직접 전송됩니다.

서드파티 제공자를 요청할 경우 일부 모델만 지원됩니다. 파이프라인 작업별 지원 모델 목록은 여기서 확인할 수 있습니다:
- [Fal.ai 지원 모델](https://huggingface.co/api/partners/fal-ai/models)
- [Featherless AI 지원 모델](https://huggingface.co/api/partners/featherless-ai/models)
- [Fireworks AI 지원 모델](https://huggingface.co/api/partners/fireworks-ai/models)
- [HF Inference 지원 모델](https://huggingface.co/api/partners/hf-inference/models)
- [Humain AI 지원 모델](https://huggingface.co/api/partners/humain-ai/models)
- [Nscale 지원 모델](https://huggingface.co/api/partners/nscale/models)
- [OpenRouter 지원 모델](https://huggingface.co/api/partners/openrouter/models)
- [OVHcloud 지원 모델](https://huggingface.co/api/partners/ovhcloud/models)
- [지원되는 모델 복제](https://huggingface.co/api/partners/replicate/models)
- [Scaleway 지원 모델](https://huggingface.co/api/partners/scaleway/models)
- [Together 지원 모델](https://huggingface.co/api/partners/together/models)
- [Baseten 지원 모델](https://huggingface.co/api/partners/baseten/models)
- [Cohere 지원 모델](https://huggingface.co/api/partners/cohere/models)
- [Cerebras 지원 모델](https://huggingface.co/api/partners/cerebras/models)
- [DeepInfra 지원 모델](https://huggingface.co/api/partners/deepinfra/models)
- [Groq 지원 모델](https://console.groq.com/docs/models)
- [Novita AI 지원 모델](https://huggingface.co/api/partners/novita/models)
- [Wavespeed.ai 지원 모델](https://huggingface.co/api/partners/wavespeed/models)
- [Z.ai 지원 모델](https://huggingface.co/api/partners/zai-org/models)

❗**중요 참고:** 호환성을 위해 서드파티 API는 각 파이프라인 작업 유형에 대해 HF 모델 페이지에서 기대하는 "표준" shape API를 준수해야 합니다. LLM의 경우 모든 사용자가 OpenAI API로 수렴했기 때문에 문제가 되지 않지만, 표준 API가 존재하지 않는 "text-to-image"나 "automatic-speech-recognition"과 같은 다른 작업에서는 더 까다로울 수 있습니다. 도움이 필요하시거나 더 쉽게 만들 수 있는 부분이 있다면 알려주세요!

👋**다른 제공자를 추가하고 싶으신가요?** 다른 Inference 제공자에 대한 지원을 추가하거나, https://huggingface.co/spaces/huggingface/HuggingDiscussions/discussions/49에서 요청을 남기려면 문의해 주세요.

### Tree-shaking

`InferenceClient` 클래스를 사용하지 않고 모듈에서 필요한 함수를 직접 가져올 수 있습니다.

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

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

이것은 번들러의 트리 셰이킹을 활성화합니다.

### 오류 처리

inference 패키지는 다양한 오류 시나리오를 효과적으로 처리할 수 있도록 구체적인 오류 유형을 제공합니다.

#### 오류 유형

이 패키지는 기본 `Error` 클래스를 확장하는 여러 오류 유형을 정의합니다:

- `InferenceClientError`: Hugging Face Inference의 모든 오류에 대한 기본 오류 클래스
- `InferenceClientInputError`: 입력 매개변수에 문제가 있을 때 발생
- `InferenceClientProviderApiError`: 프로바이더에서 API 수준의 오류가 발생했을 때 throw됩니다
- `InferenceClientHubApiError`: Hugging Face Hub에서 API 수준의 오류가 발생했을 때 발생
- `InferenceClientProviderOutputError`: 프로바이더의 API 응답 형식에 문제가 있을 때 발생

### 사용 예시

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

### 오류 세부 정보

#### InferenceClientProviderApiError

선택한 provider에서 추론을 수행하는 동안 API 요청에 문제가 있을 때 이 오류가 발생합니다.

여러 가지 속성이 있습니다:
- `message`: 설명적인 오류 메시지
- `httpRequest`: 실패한 요청에 대한 세부 정보(URL, method, headers)
- `httpResponse`: 상태 코드와 본문이 포함된 응답 세부 정보

#### InferenceClientHubApiError

Hugging Face Hub API를 요청할 때 API 요청에 문제가 있으면 이 오류가 발생합니다.

여러 가지 속성이 있습니다:
- `message`: 설명적인 오류 메시지
- `httpRequest`: 실패한 요청에 대한 세부 정보(URL, method, headers)
- `httpResponse`: 상태 코드와 본문이 포함된 응답 세부 정보

#### InferenceClientProviderOutputError

이 오류는 프로바이더가 예상하지 못한 형식으로 응답을 반환할 때 발생합니다.

#### InferenceClientInputError

이 오류는 입력 매개변수가 잘못되었거나 누락된 경우 발생합니다. 오류 메시지는 입력의 문제점을 설명합니다.

### 자연어 처리

#### 텍스트 생성

입력 프롬프트에서 텍스트를 생성합니다.

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

#### 채팅 완성

대화 내용을 구성하는 메시지 목록에서 모델 응답을 생성합니다.

```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;
  }
}
```
#### Feature Extraction

이 작업은 텍스트를 읽고, 일반적으로 의미론적 데이터베이스/의미론적 검색의 일부로 소비되는 원시 float 값을 출력합니다.

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

#### Fill Mask

누락된 단어(정확히는 토큰)로 구멍을 채우도록 시도합니다.

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

#### 요약

긴 텍스트를 짧은 텍스트로 요약합니다. 주의: 일부 모델은 입력 길이에 최대 제한이 있습니다.

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

#### 질문 답변

제공하는 컨텍스트를 기반으로 질문에 답변합니다.

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

#### 테이블 질의응답

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

#### 텍스트 분류

감정 분석에 자주 사용되는 이 방법은 주어진 텍스트에 라벨을 할당하고 해당 라벨의 확률 점수를 함께 제공합니다.

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

#### 토큰 분류

문장 분석에 사용되며, 문법 분석 또는 텍스트에 포함된 키워드를 이해하기 위한 Named Entity Recognition (NER)을 수행합니다.

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

#### 번역

한 언어의 텍스트를 다른 언어로 변환합니다.

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

#### Zero-Shot 분류

…

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

#### 문장 유사도

하나의 텍스트와 다른 문장 목록 사이의 의미 유사도를 계산합니다.

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

#### 텍스트 랭킹

쿼리에 대한 관련성 순서로 문서를 정렬합니다.

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

### 오디오

#### 자동 음성 인식

오디오 파일에서 음성 전사를 수행합니다.

[데모](https://huggingface.co/spaces/huggingfacejs/speech-recognition-vue)

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

#### 오디오 분류

주어진 오디오에 라벨을 할당하고 해당 라벨의 확률 점수를 함께 제공합니다.

[데모](https://huggingface.co/spaces/huggingfacejs/audio-classification-vue)

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

#### 텍스트 음성 변환

텍스트 입력에서 자연스러운 음성의 음성 합성을 생성합니다.

[인터랙티브 튜토리얼](https://scrimba.com/scrim/co8da4d23b49b648f77f4848a?pl=pkVnrP7uP)

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

#### 오디오에서 오디오로

입력 오디오에서 하나 이상의 생성된 오디오를 출력하며, 주로 음성 향상 및 소스 분리(source separation)에 사용됩니다.

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

### 컴퓨터 비전

#### 이미지 분류

주어진 이미지에 라벨을 할당하고 해당 라벨의 확률 점수를 함께 제공합니다.

[데모](https://huggingface.co/spaces/huggingfacejs/image-classification-vue)

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

#### 객체 감지

이미지 내의 객체를 감지하고, 해당 객체에 대한 라벨, 바운딩 박스, 확률 점수를 반환합니다.

[데모](https://huggingface.co/spaces/huggingfacejs/object-detection-vue)

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

#### 이미지 분할

이미지 내 세그먼트를 감지하고, 해당 바운딩 박스 및 확률 점수와 함께 라벨을 반환합니다.

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

#### 이미지에서 텍스트로

주어진 이미지에서 텍스트를 출력하며, 캡셔닝 또는 광학 문자 인식에 일반적으로 사용됩니다.

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

#### 텍스트에서 이미지

텍스트 프롬프트에서 이미지를 생성합니다.

[데모](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'
})
```

#### 이미지에서 이미지로

Image-to-image는 소스 이미지를 대상 이미지 또는 대상 이미지 도메인의 특성에 맞게 변환하는 작업입니다.

[인터랙티브 튜토리얼](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",
});
```

#### Zero Shot 이미지 분류

…

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

### 멀티모달

#### 시각 질의응답

Visual Question Answering은 이미지를 기반으로 열린 형식의 질문에 답하는 작업입니다. 자연어 질문에 대해 자연어 응답을 출력합니다.

[데모](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()
  }
})
```

#### 문서 질의응답

Document question answering 모델은 (문서, 질문) 쌍을 입력으로 받아 자연어 형식의 답변을 반환합니다.

[데모](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(),
  }
})
```

### 테이블

#### 표형 회귀

Tabular regression는 속성 집합이 주어졌을 때 수치 값을 예측하는 작업입니다.

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

#### 표형 데이터 분류

Tabular classification은 속성 집합을 기반으로 대상 카테고리(그룹)를 분류하는 작업입니다.

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

`chatCompletion` 메서드와 호환되는 Chat Completion API 제공자를 사용할 수 있습니다.

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

## Inference Endpoints 사용

위에서 살펴본 예제는 추론 제공자(inference provider)를 사용합니다. 이러한 방식은 프로토타이핑과 빠른 테스트에 매우 유용합니다. 하지만 모델을 프로덕션 환경에 배포할 준비가 되었다면 전용 인프라를 사용해야 합니다. 이때 [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index)가 활용됩니다. 이를 통해 어떤 모델이든 배포하고 이를 비공개 API로 노출할 수 있습니다. 배포가 완료되면 연결할 수 있는 URL을 받게 됩니다:

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

기본적으로 추론 엔드포인트에 대한 모든 호출은 모델이 로드될 때까지 대기합니다. 엔드포인트에서 [0으로 스케일링](https://huggingface.co/docs/inference-endpoints/en/autoscaling#scaling-to-0)이 활성화되어 있으면 상당한 대기 시간이 발생할 수 있습니다. 이 동작을 비활성화하고 엔드포인트가 반환하는 500 HTTP 오류를 직접 처리하려면 다음과 같이 설정할 수 있습니다:

```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,
	}
);
```
## 로컬 엔드포인트 사용

`InferenceClient`를 사용하여 자체 머신에서 실행 중인 로컬 추론 서버(llama.cpp, vllm, litellm server, TGI, mlx 등)로 채팅 완성을 수행할 수 있습니다. API는 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);
```

OpenAI JS 클라이언트와 마찬가지로, `InferenceClient`는 OpenAI REST API 호환 엔드포인트에서 Chat Completion 추론을 실행하는 데 사용할 수 있습니다.

## 테스트 실행

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

## 적합한 모델 찾기

각 태스크별로 사용 가능한 모델을 나열하고 각 태스크가 어떻게 작동하는지 자세히 설명하는 [Tasks](https://huggingface.co/tasks)라는 유용한 문서 프로젝트가 있습니다.

ML 측면을 더 깊이 파고들고자 하시는 경우를 위해 데모, 예시 출력 및 기타 리소스도 포함되어 있습니다.

## 의존성

- `@huggingface/tasks` : 타입 정의만 포함

