# Sunucularda Çıkarım Çalıştırın

Inference, eğitim görmüş bir modelin yeni veriler üzerinde tahmin yapması için kullanılması sürecidir. Bu süreç yoğun hesaplama gerektirebildiğinden, özel veya harici bir hizmet üzerinde çalıştırılması ilginç bir seçenek olabilir. `huggingface_hub` kütüphanesi, Hugging Face Hub üzerinde barındırılan modeller için birden fazla hizmette inference çalıştırmak üzere birleşik bir arayüz sunar:

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.

> [!TIP]
> [InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient), API'lerimize HTTP çağrıları yapan bir Python istemcisidir. HTTP çağrılarını tercih ettiğiniz araçla (curl, postman, ...) doğrudan yapmak istiyorsanız, [Inference Providers](https://huggingface.co/docs/inference-providers/index) belgelerine veya [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index) belgesi sayfalarına bakın.
>
> Web geliştirme için bir [JS istemcisi](https://huggingface.co/docs/huggingface.js/inference/README) yayımlandı. Oyun geliştirmeyle ilgileniyorsanız, [C# projemize](https://github.com/huggingface/unity-api) göz atabilirsiniz.

## Başlangıç

Bir metinden görüntüye göreviyle başlayalım:

```python
>>> from huggingface_hub import InferenceClient

# Example with an external provider (e.g. replicate)
>>> replicate_client = InferenceClient(
    provider="replicate",
    api_key="my_replicate_api_key",
)
>>> replicate_image = replicate_client.text_to_image(
    "A flying car crossing a futuristic cityscape.",
    model="black-forest-labs/FLUX.1-schnell",
)
>>> replicate_image.save("flying_car.png")

```

Yukarıdaki örnekte, üçüncü taraf bir sağlayıcı olan [Replicate](https://replicate.com/) ile bir [InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient) başlattık. Bir sağlayıcı kullanırken, kullanmak istediğiniz modeli belirtmeniz gerekir. Model kimliği, üçüncü taraf sağlayıcıdaki modelin kimliği değil, Hugging Face Hub'daki modelin kimliği olmalıdır. Örneğimizde, bir metin komutundan bir görüntü ürettik. Dönen değer, bir dosyaya kaydedilebilen bir `PIL.Image` nesnesidir. Daha fazla ayrıntı için [text_to_image()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_image) belgelerine göz atın.

Şimdi [chat_completion()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) API'sini kullanan bir örneğe bakalım. Bu görev, bir mesaj listesinden yanıt üretmek için bir LLM kullanır:

```python
>>> from huggingface_hub import InferenceClient
>>> messages = [
    {
        "role": "user",
        "content": "What is the capital of France?",
    }
]
>>> client = InferenceClient(
    provider="together",
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    api_key="my_together_api_key",
)
>>> client.chat_completion(messages, max_tokens=100)
ChatCompletionOutput(
    choices=[
        ChatCompletionOutputComplete(
            finish_reason="eos_token",
            index=0,
            message=ChatCompletionOutputMessage(
                role="assistant", content="The capital of France is Paris.", name=None, tool_calls=None
            ),
            logprobs=None,
        )
    ],
    created=1719907176,
    id="",
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    object="text_completion",
    system_fingerprint="2.0.4-sha-f426a33",
    usage=ChatCompletionOutputUsage(completion_tokens=8, prompt_tokens=17, total_tokens=25),
)
```

Yukarıdaki örnekte üçüncü taraf bir sağlayıcı ([Together AI](https://www.together.ai/)) kullandık ve kullanmak istediğimiz modeli belirttik (`"meta-llama/Meta-Llama-3-8B-Instruct"`). Ardından tamamlanacak bir mesaj listesi verdik (burada tek bir soru) ve API'ye ek bir parametre ilettik (`max_token=100`). Çıktı, OpenAI spesifikasyonunu takip eden bir `ChatCompletionOutput` nesnesidir. Üretilen içeriğe `output.choices[0].message.content` ile erişilebilir. Daha fazla ayrıntı için [chat_completion()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) belgesine göz atın.

> [!WARNING]
> API basit olacak şekilde tasarlanmıştır. Tüm parametreler ve seçenekler son kullanıcı için mevcut değildir veya açıklanmamıştır. Her görev için kullanılabilen tüm parametreler hakkında daha fazla bilgi edinmek isterseniz [bu sayfaya](https://huggingface.co/docs/api-inference/detailed_parameters) göz atın.

### Belirli bir sağlayıcı kullanma

Belirli bir sağlayıcı kullanmak istiyorsanız, istemciyi başlatırken bunu belirtebilirsiniz. Varsayılan değer "auto"dur ve bu, model için kullanılabilir sağlayıcıların, https://hf.co/settings/inference-providers adresindeki kullanıcı sıralamasına göre sıralanmış ilkini seçer. Desteklenen sağlayıcıların listesi için [Desteklenen sağlayıcılar ve görevler](#supported-providers-and-tasks) bölümüne bakın.

```python
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(provider="replicate", api_key="my_replicate_api_key")
```

### Belirli bir model kullanma

Belirli bir model kullanmak isterseniz ne olur? Bunu bir parametre olarak veya doğrudan bir örnek (instance) düzeyinde belirleyebilirsiniz:

```python
>>> from huggingface_hub import InferenceClient
# Initialize client for a specific model
>>> client = InferenceClient(provider="together", model="meta-llama/Llama-3.1-8B-Instruct")
>>> client.text_to_image(...)
# Or use a generic client but pass your model as an argument
>>> client = InferenceClient(provider="together")
>>> client.text_to_image(..., model="meta-llama/Llama-3.1-8B-Instruct")
```

> [!TIP]
> "hf-inference" sağlayıcısını kullanırken, her görev Hub'daki 1M+ model arasından önerilen bir modelle birlikte gelir. Ancak bu öneri zamanla değişebilir, bu nedenle kullanmak istediğiniz modeli belirledikten sonra modeli açıkça ayarlamak en iyisidir. Üçüncü taraf sağlayıcılar için, her zaman o sağlayıcıyla uyumlu bir model belirtmeniz gerekir.
>
> Hub'daki [Modeller](https://huggingface.co/models?inference=warm) sayfasını ziyaret ederek Inference Providers üzerinden kullanılabilir modelleri keşfedin.

### 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, yalnızca `model` parametresini değiştirerek daha öncekiyle tamamen aynı kodu kullanarak bağlanabileceğiniz bir URL alırsınız:

```python
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(model="https://uu149rez6gw9ehej.eu-west-1.aws.endpoints.huggingface.cloud/deepfloyd-if")
# or
>>> client = InferenceClient()
>>> client.text_to_image(..., model="https://uu149rez6gw9ehej.eu-west-1.aws.endpoints.huggingface.cloud/deepfloyd-if")
```

Bir URL ve bir sağlayıcının aynı anda belirtilemediğini, bunların birbirini dışladığını unutmayın. URL'ler, dağıtılmış uç noktalara doğrudan bağlanmak için kullanılır.

### Yerel uç noktaları kullanma

[InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient) kullanarak kendi makinenizde çalışan yerel çıkarım sunucularıyla (llama.cpp, vllm, litellm server, TGI, mlx vb.) sohbet tamamlama işlemleri gerçekleştirebilirsiniz. API, OpenAI API ile uyumlu olmalıdır.

```python
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(model="http://localhost:8080")

>>> response = client.chat.completions.create(
...     messages=[
...         {"role": "user", "content": "What is the capital of France?"}
...     ],
...     max_tokens=100
... )
>>> print(response.choices[0].message.content)
```

> [!TIP]
> OpenAI Python istemcisi gibi, [InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient) herhangi bir OpenAI REST API uyumlu uç noktasında Chat Completion çıkarımı çalıştırmak için kullanılabilir.

### Kimlik Doğrulama

Kimlik doğrulama iki şekilde yapılabilir:

**Hugging Face üzerinden yönlendirilir** : Üçüncü taraf sağlayıcılara erişmek için Hugging Face'i bir vekil olarak kullanın. Çağrılar, sağlayıcı anahtarlarımızı kullanarak Hugging Face altyapısı üzerinden yönlendirilir ve kullanım doğrudan Hugging Face hesabınıza faturalandırılır.

[Kullanıcı Erişim Belirteci](https://huggingface.co/docs/hub/security-tokens) kullanarak kimlik doğrulaması yapabilirsiniz. Hugging Face belirtecinizi doğrudan `api_key` parametresini kullanarak sağlayabilirsiniz:

```python
>>> client = InferenceClient(
    provider="replicate",
    api_key="hf_****"  # Your HF token
)
```

`api_key` *geçirmezseniz*, istemci, makinenizde yerel olarak saklanan bir belirteci bulmaya ve kullanmaya çalışır. Bu genellikle daha önce oturum açmış olmanız durumunda gerçekleşir. Girişle ilgili ayrıntılar için [Kimlik Doğrulama Kılavuzu](https://huggingface.co/docs/huggingface_hub/quick-start#authentication)'na bakın.

```python
>>> client = InferenceClient(
    provider="replicate",
    token="hf_****"  # Your HF token
)
```

**Sağlayıcıya doğrudan erişim**: Sağlayıcının hizmetiyle doğrudan etkileşime geçmek için kendi API anahtarınızı kullanın:
```python
>>> client = InferenceClient(
    provider="replicate",
    api_key="r8_****"  # Your Replicate API key
)
```

Daha fazla ayrıntı için [Inference Providers fiyatlandırma belgesine](https://huggingface.co/docs/inference-providers/pricing#routed-requests-vs-direct-calls) başvurun.

## Desteklenen sağlayıcılar ve görevler

[InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient)'in amacı, Hugging Face modelleri üzerinde herhangi bir sağlayıcıda çıkarım yapmanın en kolay arayüzünü sağlamaktır. En yaygın görevleri destekleyen basit bir API'ye sahiptir. Aşağıdaki tablo, hangi sağlayıcıların hangi görevleri desteklediğini göstermektedir:

| Görev                                                | Baseten | Cerebras | Cohere | DeepInfra | fal-ai | Featherless AI | Fireworks AI | Groq | HF Inference | Novita AI | Nscale | OVHcloud AI Uç Noktaları | Herkese Açık Yapay Zeka | Yeniden Oluştur | Scaleway | Birlikte | Wavespeed | Zai |
| --------------------------------------------------- | ------- | -------- | ------ | --------- | ------ | -------------- | ------------ | ---- | ------------ | --------- | ------ | --------------------- | --------- | --------- | -------- | -------- | --------- | --- |
| [audio_classification()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.audio_classification)           | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [audio_to_audio()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.audio_to_audio)                 | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [automatic_speech_recognition()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.automatic_speech_recognition)   | ❌      | ❌        | ❌      | ✅         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ✅         | ❌        | ❌        | ❌         | ❌   |
| [chat_completion()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion)                | ✅      | ✅        | ✅      | ✅         | ❌      | ✅              | ✅            | ✅    | ✅            | ✅         | ✅      | ✅                     | ✅         | ❌         | ✅        | ✅        | ❌         | ✅   |
| [document_question_answering()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.document_question_answering)    | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [feature_extraction()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.feature_extraction)             | ❌      | ❌        | ❌      | ✅         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ✅        | ✅        | ❌         | ❌   |
| [fill_mask()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.fill_mask)                      | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [image_classification()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.image_classification)           | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [image_segmentation()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.image_segmentation)             | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [image_to_image()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.image_to_image)                 | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ✅         | ❌        | ✅        | ✅         | ❌   |
| [image_to_video()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.image_to_video)                 | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ❌            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ✅        | ✅         | ❌   |
| [image_to_text()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.image_to_text)                  | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [object_detection()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.object_detection)               | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [question_answering()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.question_answering)             | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [sentence_similarity()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.sentence_similarity)            | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [summarization()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.summarization)                  | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [table_question_answering()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.table_question_answering)       | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [text_classification()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.text_classification)            | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [text_generation()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.text_generation)                | ❌      | ❌        | ❌      | ✅         | ❌      | ✅              | ❌            | ❌    | ✅            | ✅         | ❌      | ❌                     | ❌         | ❌         | ❌        | ✅        | ❌         | ❌   |
| [text_to_image()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_image)                  | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ✅      | ❌                     | ❌         | ✅         | ❌        | ✅        | ✅         | ✅   |
| [text_to_speech()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_speech)                 | ❌      | ❌        | ❌      | ✅         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ✅         | ❌        | ✅        | ❌         | ❌   |
| [text_to_video()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_video)                  | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ❌            | ✅         | ❌      | ❌                     | ❌         | ✅         | ❌        | ✅        | ✅         | ❌   |
| [tabular_classification()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.tabular_classification)         | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [tabular_regression()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.tabular_regression)             | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [token_classification()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.token_classification)           | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [translation()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.translation)                    | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [visual_question_answering()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.visual_question_answering)      | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [zero_shot_image_classification()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.zero_shot_image_classification) | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [zero_shot_classification()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.zero_shot_classification)       | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |

> [!TIP]
> Her görev hakkında daha fazla bilgi edinmek için [Görevler](https://huggingface.co/tasks) sayfasına göz atın.

## OpenAI uyumluluğu

`chat_completion` görevi [OpenAI Python istemcisinin](https://github.com/openai/openai-python) sözdizimini izler. Bu sizin için ne anlama geliyor? `OpenAI` API'leriyle çalışmaya alışkınsanız, yalnızca 2 satır kodu güncelleyerek açık kaynak modellerle çalışmak için `huggingface_hub.InferenceClient`'e geçiş yapabilirsiniz!

```diff
- from openai import OpenAI
+ from huggingface_hub import InferenceClient

- client = OpenAI(
+ client = InferenceClient(
    base_url=...,
    api_key=...,
)

output = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Count to 10"},
    ],
    stream=True,
    max_tokens=1024,
)

for chunk in output:
    print(chunk.choices[0].delta.content)
```

Ve bu kadar! Yapılması gereken tek değişiklik, `from openai import OpenAI` ifadesini `from huggingface_hub import InferenceClient` ile ve `client = OpenAI(...)` ifadesini `client = InferenceClient(...)` ile değiştirmektir. Hugging Face Hub'daki herhangi bir LLM modelini, model kimliğini `model` parametresi olarak geçirerek seçebilirsiniz. Desteklenen modellerin [listesi burada](https://huggingface.co/models?pipeline_tag=text-generation&other=conversational,text-generation-inference&sort=trending). Kimlik doğrulama için geçerli bir [User Access Token](https://huggingface.co/settings/tokens)'ı `api_key` olarak geçirmeniz veya `huggingface_hub` kullanarak kimlik doğrulamanız gerekir (bkz. [kimlik doğrulama kılavuzu](https://huggingface.co/docs/huggingface_hub/quick-start#authentication)).

Tüm giriş parametreleri ve çıktı formatı kesinlikle aynıdır. Özellikle, jetonlar üretildikçe almak için `stream=True` parametresini iletebilirsiniz. Ayrıca `asyncio` kullanarak çıkarım yapmak için [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.AsyncInferenceClient) sınıfını da kullanabilirsiniz:

```diff
import asyncio
- from openai import AsyncOpenAI
+ from huggingface_hub import AsyncInferenceClient

- client = AsyncOpenAI()
+ client = AsyncInferenceClient()

async def main():
    stream = await client.chat.completions.create(
        model="meta-llama/Meta-Llama-3-8B-Instruct",
        messages=[{"role": "user", "content": "Say this is a test"}],
        stream=True,
    )
    async for chunk in stream:
        print(chunk.choices[0].delta.content or "", end="")

asyncio.run(main())
```

[InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient) kullanmak yerine OpenAI'nin istemcisinin neden kullanılmadığını merak ediyor olabilirsiniz. Bunun birkaç nedeni var:
1. [InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient), Hugging Face hizmetleri için yapılandırılmıştır. Inference Providers ile modelleri çalıştırmak için `base_url` belirtmenize gerek yoktur. Makineniz zaten doğru şekilde oturum açılmışsa, `token` veya `api_key` de belirtmenize gerek yoktur.
2. [InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient), hem Text-Generation-Inference (TGI) hem de `transformers` çerçeveleri için tasarlanmıştır; bu sayede her zaman en güncel güncellemelerle uyumlu olduğu garanti edilir.
3. [InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient), Inference Endpoints hizmetimizle entegre edilmiştir; bu sayede bir Inference Endpoint başlatmak, durumunu kontrol etmek ve üzerinde çıkarım (inference) çalıştırmak kolaylaşır. Daha fazla ayrıntı için [Inference Endpoints](./inference_endpoints) kılavuzuna göz atın.

> [!TIP]
> `InferenceClient.chat.completions.create`, `InferenceClient.chat_completion` için basit bir takma addır. Daha fazla ayrıntı için [chat_completion()](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) paket referansına göz atın. İstemciyi örneklerken `base_url` ve `api_key` parametreleri de `model` ve `token` için takma adlardır. Bu takma adlar, `OpenAI`'den `InferenceClient`'e geçişte sürtünmeyi azaltmak için tanımlanmıştır.

## Function Calling

Function calling, LLM'lerin tanımlı işlevler veya API'ler gibi harici araçlarla etkileşime geçmesine olanak tanır. Bu, kullanıcıların belirli kullanım senaryolarına ve gerçek dünya görevlerine uyarlanmış uygulamaları kolayca oluşturmasını sağlar. `InferenceClient`, OpenAI Chat Completions API'si ile aynı araç çağırma arayüzünü uygular. [Novita](https://novita.ai/)'yı çıkarım sağlayıcısı olarak kullanarak araç çağırmanın basit bir örneği aşağıdadır:

```python
from huggingface_hub import InferenceClient

tools = [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get current temperature for a given location.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "City and country e.g. Paris, France"
                        }
                    },
                    "required": ["location"],
                },
            }
        }
]

client = InferenceClient(provider="novita")

response = client.chat.completions.create(
    model="Qwen/Qwen2.5-72B-Instruct",
    messages=[
    {
        "role": "user",
        "content": "What's the weather like the next 3 days in London, UK?"
    }
    ],
    tools=tools,
    tool_choice="auto",
)

print(response.choices[0].message.tool_calls[0].function.arguments)

```

> [!TIP]
> Function/Tool Calling için hangi modellerin desteklendiğini doğrulamak için lütfen sağlayıcıların dokümantasyonuna başvurun.

## Yapılandırılmış Çıktılar & JSON Modu

InferenceClient, sözdizimsel olarak geçerli JSON yanıtları için JSON modunu ve şema dayalı yanıtlar için Structured Outputs'u destekler. JSON modu, katı bir yapı olmadan makine tarafından okunabilir veri sağlar; Structured Outputs ise hem geçerli JSON'u hem de güvenilir aşağı akış işleme için önceden tanımlanmış bir şemaya uyumu garanti eder.

JSON modu ve Yapılandırılmış Çıktılar için OpenAI API spesifikasyonlarını takip ediyoruz. Bunları `response_format` argümanı üzerinden etkinleştirebilirsiniz. [Cerebras](https://www.cerebras.ai/)’ı çıkarım sağlayıcısı olarak kullanan Yapılandırılmış Çıktılar örneği aşağıdadır:

```python
from huggingface_hub import InferenceClient

json_schema = {
    "name": "book",
    "schema": {
        "properties": {
            "name": {
                "title": "Name",
                "type": "string",
            },
            "authors": {
                "items": {"type": "string"},
                "title": "Authors",
                "type": "array",
            },
        },
        "required": ["name", "authors"],
        "title": "Book",
        "type": "object",
    },
    "strict": True,
}

client = InferenceClient(provider="cerebras")

completion = client.chat.completions.create(
    model="Qwen/Qwen3-32B",
    messages=[
        {"role": "system", "content": "Extract the books information."},
        {"role": "user", "content": "I recently read 'The Great Gatsby' by F. Scott Fitzgerald."},
    ],
    response_format={
        "type": "json_schema",
        "json_schema": json_schema,
    },
)

print(completion.choices[0].message)
```
> [!TIP]
> Structured Outputs ve JSON Mode için hangi modellerin desteklendiğini doğrulamak için lütfen sağlayıcıların dokümantasyonuna başvurun.

## Asenkron istemci

İstemcinin, `asyncio` ve `httpx2` tabanlı asenkron bir sürümü de sağlanmaktadır. Tüm asenkron API uç noktaları [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.AsyncInferenceClient) üzerinden kullanılabilir. Başlatma işlemi ve API'leri, yalnızca senkron sürümle birebir aynıdır.

```py
# Code must be run in an asyncio concurrent context.
# $ python -m asyncio
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

>>> image = await client.text_to_image("An astronaut riding a horse on the moon.")
>>> image.save("astronaut.png")

>>> async for token in await client.text_generation("The Huggingface Hub is", stream=True):
...     print(token, end="")
 a platform for sharing and discussing ML-related content.
```

`asyncio` modülü hakkında daha fazla bilgi için [resmi dokümantasyona](https://docs.python.org/3/library/asyncio.html) bakın.

## MCP İstemcisi

`huggingface_hub` kütüphanesi artık, Büyük Dil Modellerinin (LLM) [Model Context Protocol](https://modelcontextprotocol.io) (MCP) aracılığıyla harici Araçlarla etkileşime geçme yeteneğini kazandırmak üzere tasarlanmış deneysel bir [MCPClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/mcp#huggingface_hub.MCPClient) içerir. Bu istemci, Araç kullanımını sorunsuz bir şekilde entegre etmek için bir [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.AsyncInferenceClient) uzantısıdır.

[MCPClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/mcp#huggingface_hub.MCPClient), araçları açıklayan MCP sunucularına (yerel `stdio` betikleri veya uzak `http`/`sse` hizmetleri) bağlanır. Bu araçları bir LLM'e ([AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.AsyncInferenceClient) üzerinden) iletir. LLM bir aracı kullanmaya karar verirse, [MCPClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/mcp#huggingface_hub.MCPClient) MCP sunucusuna yönelik yürütme isteğini yönetir ve aracın çıktısını LLM'e geri iletir; sonuçlar genellikle gerçek zamanlı olarak akış halinde iletilir.

Aşağıdaki örnekte, [Novita](https://novita.ai/) çıkarım sağlayıcısı üzerinden [Qwen/Qwen2.5-72B-Instruct](https://huggingface.co/Qwen/Qwen2.5-72B-Instruct) modeli kullanılır. Ardından bir uzak MCP sunucusu eklenir; bu durumda, Flux görüntü oluşturma aracını LLM'e erişilebilir kılan bir SSE sunucusudur.

```python
import os

from huggingface_hub import ChatCompletionInputMessage, ChatCompletionStreamOutput, MCPClient

async def main():
    async with MCPClient(
        provider="novita",
        model="Qwen/Qwen2.5-72B-Instruct",
        api_key=os.environ["HF_TOKEN"],
    ) as client:
        await client.add_mcp_server(type="sse", url="https://evalstate-flux1-schnell.hf.space/gradio_api/mcp/sse")

        messages = [
            {
                "role": "user",
                "content": "Generate a picture of a cat on the moon",
            }
        ]

        async for chunk in client.process_single_turn_with_tools(messages):
            # Log messages
            if isinstance(chunk, ChatCompletionStreamOutput):
                delta = chunk.choices[0].delta
                if delta.content:
                    print(delta.content, end="")

            # Or tool calls
            elif isinstance(chunk, ChatCompletionInputMessage):
                print(
                    f"\nCalled tool '{chunk.name}'. Result: '{chunk.content if len(chunk.content) < 1000 else chunk.content[:1000] + '...'}'"
                )

if __name__ == "__main__":
    import asyncio

    asyncio.run(main())
```

Daha basit bir geliştirme için daha yüksek seviyeli bir [Agent](/docs/huggingface_hub/v2.4.0/tr/package_reference/mcp#huggingface_hub.Agent) sınıfı sunuyoruz. Bu 'Tiny Agent', sohbet döngüsünü ve durumu yöneterek konuşma tabanlı Agent'lar oluşturmayı kolaylaştırır; temelde [MCPClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/mcp#huggingface_hub.MCPClient) etrafında bir sarmalayıcı olarak çalışır. Doğrudan bir [MCPClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/mcp#huggingface_hub.MCPClient) üzerine inşa edilmiş basit bir while döngüsü olarak tasarlanmıştır. Bu Agent'ları doğrudan komut satırından çalıştırabilirsiniz:

```bash
# install latest version of huggingface_hub with the mcp extra
pip install -U huggingface_hub[mcp]
# Run an agent that uses the Flux image generation tool
tiny-agents run julien-c/flux-schnell-generator

```

Başlatıldığında, Agent, bağlı olduğu MCP sunucularından keşfettiği Araçları yükler ve listeler; ardından komutlarınıza hazır hale gelir!

## Gelişmiş ipuçları

Yukarıdaki bölümde [InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient)'in temel yönlerini inceledik. Şimdi daha ileri düzey ipuçlarına geçelim.

### Faturalandırma

Bir HF kullanıcısı olarak, Hub üzerindeki çeşitli sağlayıcılar aracılığıyla çıkarım (inference) çalıştırmak için aylık kredi alırsınız. Alacağınız kredi miktarı, hesap türünüze (Free, PRO veya Enterprise Hub) bağlıdır. Her çıkarım isteği, ilgili sağlayıcının fiyatlandırma tablosuna göre ücretlendirilir. Varsayılan olarak, istekler kişisel hesabınıza faturalandırılır. Ancak, `InferenceClient` nesnesine `bill_to="<your_org_name>"` parametresini ileterek, isteklerin bir üyesi olduğunuz bir organizasyona faturalandırılacak şekilde ayarlayabilirsiniz. Bunun için organizasyonunuzun Enterprise Hub aboneliğine sahip olması gerekir. Faturalandırma hakkında daha fazla ayrıntı için [bu kılavuza](https://huggingface.co/docs/api-inference/pricing#features-using-inference-providers) göz atın.

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(provider="fal-ai", bill_to="openai")
>>> image = client.text_to_image(
...     "A majestic lion in a fantasy forest",
...     model="black-forest-labs/FLUX.1-schnell",
... )
>>> image.save("lion.png")
```

Bir kullanıcının veya üyesi olmadığınız bir kuruluşun ücretini tahsil etmenin mümkün olmadığını unutmayın. Başka birine kredi tanımlamak istiyorsanız, onlarla ortak bir kuruluş oluşturmanız gerekir.

### Zaman aşımı

Çıkarım çağrıları önemli miktarda zaman alabilir. Varsayılan olarak [InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient), çıkarım tamamlanana kadar "belirsiz" bir süre bekler. İş akışınızda daha fazla kontrol istiyorsanız, `timeout` parametresini saniye cinsinden belirli bir değere ayarlayabilirsiniz. Zaman aşımı süresi dolarsa, kodunuzda yakalayabileceğiniz bir [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) oluşturulur:

```python
>>> from huggingface_hub import InferenceClient, InferenceTimeoutError
>>> client = InferenceClient(timeout=30)
>>> try:
...     client.text_to_image(...)
... except InferenceTimeoutError:
...     print("Inference timed out after 30s.")
```

### İkili girdiler

Bazı görevler ikili girdiler gerektirir, örneğin görüntü veya ses dosyalarıyla çalışırken. Bu durumda [InferenceClient](/docs/huggingface_hub/v2.4.0/tr/package_reference/inference_client#huggingface_hub.InferenceClient) olabildiğince esnek davranmaya ve farklı türleri kabul etmeye çalışır:
- ham `bytes`
- ikili olarak açılmış dosya benzeri bir nesne (`with open("audio.flac", "rb") as f: ...`)
- yerel bir dosyaya işaret eden bir yol (`str` veya `Path`)
- uzak bir dosyaya (ör. `https://...`) işaret eden bir URL (`str`). Bu durumda, dosya yerel olarak indirilir
API'ye gönderiliyor.

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
[{'score': 0.9779096841812134, 'label': 'Blenheim spaniel'}, ...]
```

