# 🤗 Hugging Face Inference

Hugging Face Hub'da barındırılan modeller için birden fazla servis üzerinde çıkarım (inference) çalıştırmak için birleşik bir arayüz sunan, Typescript destekli bir sarmalayıcı (wrapper):

1.  [Inference Providers](https://huggingface.co/docs/inference-providers/index): sunucusuz çıkarım ortaklarımız tarafından desteklenen, yüzlerce makine öğrenimi modeline akıcı ve birleşik erişim. Bu yeni yaklaşım, önceki Sunucusuz Çıkarım API'miz üzerine inşa edilerek dünya çapında sağlayıcılar sayesinde daha fazla model, geliştirilmiş performans ve daha yüksek güvenilirlik sunmaktadır. Desteklenen sağlayıcıların listesine [belgeler](https://huggingface.co/docs/inference-providers/index#partners) bölümünden ulaşabilirsiniz.
2.  [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index): modelleri üretime kolayca dağıtmak için bir ürün. Çıkarım, seçtiğiniz bulut sağlayıcısında Hugging Face tarafından özel, tamamen yönetilen bir altyapıda çalıştırılır.
3.  Yerel uç noktalar: istemciyi bu yerel uç noktalara bağlayarak [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) veya [Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference) gibi yerel çıkarım sunucuları ile de çıkarım çalıştırabilirsiniz.

## Başlangıç

### Yükle

#### Düğüm

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

### Başlat

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

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

❗**Önemli not:** Her zaman bir erişim belirteci geçirin. [Hugging Face](https://huggingface.co/join) platformuna katılın ve ardından [erişim belirteçleri](https://huggingface.co/settings/tokens) sayfasını ziyaret ederek **ücretsiz** olarak erişim belirtecinizi oluşturun.

Erişim anahtarınız gizli tutulmalıdır. Ön uç uygulamalarda korumanız gerekiyorsa, erişim anahtarını saklayan bir vekil sunucu (proxy server) kurmanızı öneririz.

## Inference Providers Kullanımı

inference client ile üçüncü taraf sağlayıcılara çıkarım istekleri gönderebilirsiniz.

Şu anda aşağıdaki sağlayıcıları destekliyoruz:
- [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/)
- [Herkese Açık Yapay Zeka](https://publicai.co)
- [Replicate](https://replicate.com)
- [Scaleway](https://www.scaleway.com/en/generative-apis/)
- [Birlikte](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/)

Üçüncü taraf bir sağlayıcıya istek göndermek için, çıkarım işlevine `provider` parametresini iletmeniz gerekir. `provider` parametresinin varsayılan değeri "auto"dur; bu değer, model için kullanılabilir sağlayıcıların https://hf.co/settings/inference-providers adresindeki tercih sıranıza göre sıralanmış ilkini seçer.

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

Ayrıca, isteğinizin bir erişim jetonu ile kimlik doğrulaması yapıldığından emin olmanız gerekir. Hugging Face erişim jetonu ile kimlik doğrulaması yapıldığında, istek https://huggingface.co üzerinden yönlendirilir. Üçüncü taraf bir sağlayıcı anahtarı ile kimlik doğrulaması yapıldığında, istek doğrudan o sağlayıcının çıkarım API'sine yapılır.

Üçüncü taraf sağlayıcılar için istek yapıldığında yalnızca modellerin bir alt kümesi desteklenir. Görev başına desteklenen modellerin listesini buradan kontrol edebilirsiniz:
- [Fal.ai desteklenen modeller](https://huggingface.co/api/partners/fal-ai/models)
- [Featherless AI destekli modeller](https://huggingface.co/api/partners/featherless-ai/models)
- [Fireworks AI desteklenen modeller](https://huggingface.co/api/partners/fireworks-ai/models)
- [HF Inference desteklenen modeller](https://huggingface.co/api/partners/hf-inference/models)
- [Humain AI destekli modeller](https://huggingface.co/api/partners/humain-ai/models)
- [Nscale desteklenen modeller](https://huggingface.co/api/partners/nscale/models)
- [OpenRouter desteklenen modeller](https://huggingface.co/api/partners/openrouter/models)
- [OVHcloud destekli modeller](https://huggingface.co/api/partners/ovhcloud/models)
- [Desteklenen modelleri kopyala](https://huggingface.co/api/partners/replicate/models)
- [Scaleway desteklenen modeller](https://huggingface.co/api/partners/scaleway/models)
- [Together tarafından desteklenen modeller](https://huggingface.co/api/partners/together/models)
- [Baseten desteklenen modeller](https://huggingface.co/api/partners/baseten/models)
- [Cohere destekli modeller](https://huggingface.co/api/partners/cohere/models)
- [Cerebras tarafından desteklenen modeller](https://huggingface.co/api/partners/cerebras/models)
- [DeepInfra desteklenen modeller](https://huggingface.co/api/partners/deepinfra/models)
- [Groq desteklenen modeller](https://console.groq.com/docs/models)
- [Novita AI desteklenen modeller](https://huggingface.co/api/partners/novita/models)
- [Wavespeed.ai desteklenen modeller](https://huggingface.co/api/partners/wavespeed/models)
- [Z.ai desteklenen modeller](https://huggingface.co/api/partners/zai-org/models)

❗**Önemli not:** Uyumlu olabilmesi için üçüncü taraf API'nin, her pipeline görev türü için HF model sayfalarında beklediğimiz "standart" şekil API'sine uyması gerekir. LLM'ler için bu bir sorun değildir, çünkü herkes zaten OpenAI API'sinde birleşti; ancak standart bir API'si olmayan "text-to-image" veya "automatic-speech-recognition" gibi diğer görevler için daha karmaşık olabilir. Herhangi bir yardıma ihtiyacınız varsa veya size işleri kolaylaştırmamız mümkünse bize bildirin!

👋**Başka bir sağlayıcı eklemek ister misiniz?** Başka bir Inference sağlayıcısı için destek eklemek ve/veya talep oluşturmak isterseniz bizimle iletişime geçin veya https://huggingface.co/spaces/huggingface/HuggingDiscussions/discussions/49 adresinde talep oluşturun

### Tree-shaking

`InferenceClient` sınıfını kullanmak yerine, ihtiyaç duyduğunuz işlevleri doğrudan modülden içe aktarabilirsiniz.

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

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

Bu, paketleyicinizin ağaç sarsma (tree-shaking) işlevini etkinleştirecektir.

### Hata yönetimi

inference paketi, farklı hata senaryolarını etkili bir şekilde yönetmenize yardımcı olmak için belirli hata türleri sağlar.

#### Hata Türleri

Paket, temel `Error` sınıfını genişleten birkaç hata türü tanımlar:

- `InferenceClientError`: Hugging Face Inference hatalarının tümü için temel hata sınıfı
- `InferenceClientInputError`: Girdi parametrelerinde sorunlar olduğunda atılır
- `InferenceClientProviderApiError`: Sağlayıcılardan API düzeyinde hatalar olduğunda atılır
- `InferenceClientHubApiError`: Hugging Face Hub'dan API düzeyinde hatalar olduğunda atılır
- `InferenceClientProviderOutputError`: Sağlayıcıların API yanıtı biçimiyle ilgili sorunlar olduğunda atılır

### Örnek Kullanım

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

### Hata Detayları

#### InferenceClientProviderApiError

Bu hata, seçilen sağlayıcıda çıkarım (inference) yapılırken API isteğinde sorunlar olduğunda oluşur.

Birkaç özelliğe sahiptir:
- `message`: Açıklayıcı bir hata mesajı
- `httpRequest`: Başarısız istekle ilgili ayrıntılar (URL, yöntem, başlıklar)
- `httpResponse`: Durum kodu ve gövde dahil olmak üzere yanıt ayrıntıları

#### InferenceClientHubApiError

Bu hata, Hugging Face Hub API'sine istek gönderilirken API isteğinde sorunlar olduğunda oluşur.

Birkaç özelliğe sahiptir:
- `message`: Açıklayıcı bir hata mesajı
- `httpRequest`: Başarısız istekle ilgili ayrıntılar (URL, yöntem, başlıklar)
- `httpResponse`: Durum kodu ve gövde dahil olmak üzere yanıt ayrıntıları

#### InferenceClientProviderOutputError

Bu hata, bir sağlayıcının beklenmedik bir biçimde yanıt döndürdüğünde oluşur.

#### InferenceClientInputError

Bu hata, girdi parametreleri geçersiz veya eksik olduğunda oluşur. Hata mesajı, girdideki sorunu açıklar.

### Doğal Dil İşleme

#### Metin Üretimi

Girdi isteminden metin üretir.

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

#### Chat Tamamlama

Bir konuşmayı oluşturan mesaj listesinden bir model yanıtı üretin.

```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;
  }
}
```
#### Özellik Çıkarımı

Bu görev, bazı metinleri okur ve genellikle bir anlamsal veritabanı/anlamsal arama parçası olarak tüketilen ham float değerlerini çıktılar.

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

#### Fill Mask

Eksik bir kelime (daha doğrusu token) olan bir boşluğu doldurmaya çalışır.

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

#### Özetleme

Daha uzun metinleri daha kısa metinlere özetler. Dikkatli olun, bazı modellerin girdi için bir maksimum uzunluğu vardır.

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

#### Soru Cevaplama

Sağladığınız bağlama dayalı olarak soruları yanıtlar.

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

#### Tablo Soru Cevaplama

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

#### Metin Sınıflandırma

Genellikle duygu analizi için kullanılan bu yöntem, verilen metne, o etiketin olasılık puanıyla birlikte etiketler atar.

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

#### Token Sınıflandırma

Cümle ayrıştırma için kullanılır; dilbilgisel ayrıştırma veya metin içindeki anahtar kelimeleri anlamak için Adlandırılmış Varlık Tanıma (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'
})
```

#### Çeviri

Bir dilden diğerine metin çevirir.

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

#### Sıfır Atıflı Sınıflandırma

Sağladığınız etiket kümesine bir girdi metninin ne kadar iyi uyduğunu kontrol eder.

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

#### Cümle Benzerliği

Bir metin ile diğer cümlelerin oluşturduğu liste arasındaki anlamsal benzerliği hesaplayın.

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

#### Metin Sıralama

Belgeleri bir sorguya göre ilgili olma derecesine göre sıralayı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.'
    ]
  }
})
```

### Ses

#### Otomatik Konuşma Tanıma

Bir ses dosyasından konuşmayı transkribe eder.

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

#### Ses Sınıflandırma

Verilen ses için etiketleri ve bu etiketin olasılık puanını atar.

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

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

#### Sesli Metin

Metin girdisinden doğal sesli konuşma üretir.

[Etkileşimli eğitim](https://scrimba.com/scrim/co8da4d23b49b648f77f4848a?pl=pkVnrP7uP)

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

#### Sesten Sese

Giriş sesi, genellikle konuşma iyileştirme ve kaynak ayrımı için kullanılan bir veya birden fazla üretilmiş ses çıktısı sağlar.

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

### Bilgisayar Görüsü

#### Görsel Sınıflandırma

Belirli bir görüntüye, o etiketin olasılık puanıyla birlikte etiketler atar.

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

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

#### Nesne Algılama

Bir görüntü içindeki nesneleri algılar ve ilgili sınırlayıcı kutularla ve olasılık puanlarıyla etiketleri döndürür.

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

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

#### Görüntü Segmentasyonu

Bir görüntü içindeki segmentleri algılar ve ilgili sınırlayıcı kutularla ve olasılık puanlarıyla etiketleri döndürür.

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

#### Görselden Metne

Verilen bir görüntüden metin çıkarır; genellikle görüntü açıklaması veya optik karakter tanıma için kullanılır.

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

#### Metinden Görsele

Bir metin komutundan bir görüntü oluşturur.

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

#### Görselden Görsel

Image-to-image, kaynak bir görüntünün hedef bir görüntünün veya hedef bir görüntü alanının özellikleriyle eşleşecek şekilde dönüştürülmesi görevidir.

[Etkileşimli eğitim](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",
});
```

#### Sıfır Örnekli Görüntü Sınıflandırma

Sağladığınız etiket kümesine bir giriş görüntüsünün ne kadar iyi uyduğunu kontrol eder.

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

### Çok Modallı

#### Görsel Soru Cevaplama

Görsel Soru Cevaplama, bir görsel temelinde açık uçlu soruları yanıtlama görevidir. Doğal dilde sorulan sorulara doğal dilde yanıtlar üretirler.

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

#### Belge Soru Cevaplama

Belge soru-cevap modelleri, (belge, soru) çiftini girdi olarak alır ve doğal dilde bir yanıt döndürür.

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

### Tablo

#### Tablo Geri Dönüşümü

Tabular regression, bir dizi öznitelik verildiğinde sayısal bir değerin tahmin edilmesidir.

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

#### Tablo Sınıflandırma

Tabular sınıflandırma, bir hedef kategoriyi (bir grubu) bir dizi öznitelğe dayanarak sınıflandırma görevidir.

```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` yöntemiyle herhangi bir Chat Completion API uyumlu sağlayıcıyı kullanabilirsiniz.

```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 Kullanımı

Yukarıda gördüğümüz örnekler çıkarım sağlayıcılarını kullanır. Bunlar prototipleme ve hızlı test için son derece faydalıdır. Modelinizi üretime dağıtmaya hazır olduğunuzda, özel bir altyapı kullanmanız gerekir. İşte [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index) burada devreye girer. Herhangi bir modeli dağıtmanıza ve onu özel bir API olarak sunmanıza olanak tanır. Dağıtım tamamlandığında, bağlanabileceğiniz bir URL alırsınız:

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

Varsayılan olarak, çıkarım uç noktasına yapılan tüm çağrılar, model yüklenene kadar bekler. Uç noktada [0'a ölçekleme](https://huggingface.co/docs/inference-endpoints/en/autoscaling#scaling-to-0) etkinleştirildiğinde, bu durum göz ardı edilemeyecek bir bekleme süresine yol açabilir. Bu davranışı devre dışı bırakıp uç noktanın döndürdüğü 500 HTTP hatalarını kendiniz ele almak isterseniz, bunu şu şekilde yapabilirsiniz:

```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,
	}
);
```
## Yerel uç noktaları kullanma

Kendi makinenizde çalışan yerel çıkarım sunucularıyla (llama.cpp, vllm, litellm server, TGI, mlx vb.) sohbet tamamlama çalıştırmak için `InferenceClient` kullanabilirsiniz. API, OpenAI API ile uyumlu olmalıdır.

```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 istemcisi gibi, `InferenceClient` herhangi bir OpenAI REST API uyumlu uç noktasında Chat Completion çıkarımı çalıştırmak için kullanılabilir.

## Testleri çalıştırma

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

## Uygun modelleri bulma

Her görev için kullanılabilir modelleri listelemek ve her görevin nasıl çalıştığını ayrıntılı olarak açıklamak amacıyla [Görevler](https://huggingface.co/tasks) adında bilgilendirici bir dokümantasyon projemiz var.

Ayrıca, ML tarafına daha derinlemesine inmek isterseniz, demolar, örnek çıktılar ve diğer kaynaklar da içerir.

## Bağımlılıklar

- `@huggingface/tasks` : Yalnızca tipler

