# サーバー上で推論を実行する

推論（Inference）とは、学習済みのモデルを使用して新しいデータに対して予測を行うプロセスです。このプロセスは計算負荷が高くなる可能性があるため、専用サービスまたは外部サービス上で実行することは魅力的な選択肢となり得ます。`huggingface_hub` ライブラリは、Hugging Face Hub にホストされているモデルに対して、複数のサービスで推論を実行するための統一されたインターフェースを提供します：

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)などのローカル推論サーバーにクライアントを接続することで、これらを使用して推論を実行することもできます。

> [!TIP]
> [InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)は、当社のAPIに対してHTTP呼び出しを行うPythonクライアントです。お好みのツール（curl、postmanなど）を使用して直接HTTP呼び出しを行いたい場合は、[Inference Providers](https://huggingface.co/docs/inference-providers/index)のドキュメントまたは[Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index)のドキュメントページを参照してください。
>
> Web開発向けに、[JSクライアント](https://huggingface.co/docs/huggingface.js/inference/README)がリリースされました。ゲーム開発にご興味がある場合は、[C#プロジェクト](https://github.com/huggingface/unity-api)をご覧ください。

## はじめる

テキストから画像を生成するタスクから始めましょう:

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

```

上記の例では、サードパーティのプロバイダーである[Replicate](https://replicate.com/)を使用して[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)を初期化しました。プロバイダーを使用する場合は、使用するモデルを指定する必要があります。モデルIDは、サードパーティのプロバイダーのモデルIDではなく、Hugging Face Hub上のモデルのIDである必要があります。この例では、テキストプロンプトから画像を生成しました。返される値は、ファイルに保存できる`PIL.Image`オブジェクトです。詳細については、[text_to_image()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_image)のドキュメントを参照してください。

次に、[chat_completion()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) API を使用した例を見てみましょう。このタスクでは、LLM を使用してメッセージのリストから応答を生成します。

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

上記の例では、サードパーティのプロバイダー（[Together AI](https://www.together.ai/)）を使用し、使用するモデル（`"meta-llama/Meta-Llama-3-8B-Instruct"`）を指定しました。次に、補完するメッセージのリスト（ここでは単一の質問）を与え、APIに追加のパラメーター（`max_token=100`）を渡しました。出力はOpenAI仕様に準拠した`ChatCompletionOutput`オブジェクトです。生成されたコンテンツは`output.choices[0].message.content`でアクセスできます。詳細については、[chat_completion()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion)のドキュメントを参照してください。

> [!WARNING]
> APIはシンプルに設計されています。すべてのパラメータやオプションがエンドユーザー向けに利用可能であるとは限らず、説明も提供されていません。各タスクで利用可能なすべてのパラメータについて詳しく知りたい場合は、[このページ](https://huggingface.co/docs/api-inference/detailed_parameters)をご覧ください。

### 特定のプロバイダーを使用する

特定のプロバイダーを使用したい場合は、クライアントの初期化時に指定できます。デフォルト値は "auto" で、モデルで利用可能なプロバイダーのうち、https://hf.co/settings/inference-providers でユーザーが設定した順序でソートされた最初のものが選択されます。サポートされているプロバイダーの一覧については、[サポートされているプロバイダーとタスク](#supported-providers-and-tasks)セクションを参照してください。

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

### 特定のモデルを使用する

特定のモデルを使用したい場合は、パラメータとして指定するか、インスタンスレベルで直接指定できます。

```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"プロバイダーを使用する場合、各タスクには、Hubで利用可能な100万を超えるモデルから推奨モデルが設定されています。ただし、この推奨は時間とともに変更される可能性があるため、使用するモデルを決定したら、明示的にモデルを設定するのが最善です。サードパーティのプロバイダーを使用する場合は、常にそのプロバイダーと互換性のあるモデルを指定する必要があります。
>
> Hubの[Models](https://huggingface.co/models?inference=warm)ページにアクセスして、Inference Providersを通じて利用可能なモデルを確認してください。

### Inference Endpointsの使用

上記の例では推論プロバイダーを使用しました。これらはプロトタイピングや迅速なテストに非常に有用ですが、モデルを本番環境にデプロイする準備が整ったら、専用のインフラストラクチャを使用する必要があります。そこで登場するのが[Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index)です。これにより、任意のモデルをデプロイし、プライベートなAPIとして公開できます。デプロイが完了すると、以前とまったく同じコードで接続できるURLが取得できます。変更するのは`model`パラメータだけです。

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

URLとプロバイダーの両方を指定することはできません。これらは排他的です。URLは、デプロイされたエンドポイントに直接接続するために使用されます。

### ローカルエンドポイントの使用

[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient) を使用すると、ローカルで動作する推論サーバー（llama.cpp、vllm、litellm server、TGI、mlx など）でチャット補完を実行できます。API は OpenAI API 互換である必要があります。

```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クライアントと同様に、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)は、OpenAI REST API互換のエンドポイントでChat Completion推論を実行するために使用できます。

### 認証

認証は2つの方法で行うことができます:

**Hugging Face 経由でルーティング**：Hugging Face をプロキシとして使用してサードパーティのプロバイダーにアクセスします。呼び出しは Hugging Face のインフラストラクチャを介してルーティングされ、プロバイダーのキーを使用して、利用料金が Hugging Face アカウントに直接請求されます。

[User Access Token](https://huggingface.co/docs/hub/security-tokens) を使用して認証を行うことができます。`api_key` パラメータを直接使用して、Hugging Face トークンを提供できます:

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

`api_key`を*指定しない*場合、クライアントはローカルに保存されたトークンを検索して使用しようとします。これは、以前にログインしたことがある場合に通常発生します。ログインの詳細については、[認証ガイド](https://huggingface.co/docs/huggingface_hub/quick-start#authentication)を参照してください。

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

**プロバイダーへの直接アクセス**: 独自のAPIキーを使用して、プロバイダーのサービスに直接アクセスします:
```python
>>> client = InferenceClient(
    provider="replicate",
    api_key="r8_****"  # Your Replicate API key
)
```

詳細については、[Inference Providersの料金設定に関するドキュメント](https://huggingface.co/docs/inference-providers/pricing#routed-requests-vs-direct-calls)を参照してください。

## サポートされているプロバイダーとタスク

[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)の目標は、Hugging Faceのモデルで推論を実行するための、最も簡単なインターフェースをあらゆるプロバイダーで提供することです。最も一般的なタスクをサポートするシンプルなAPIを備えています。以下は、どのプロバイダーがどのタスクをサポートしているかを示す表です。

| タスク                                                | Baseten | Cerebras | Cohere | DeepInfra | fal-ai | Featherless AI | Fireworks AI | Groq | HF Inference | Novita AI | Nscale | OVHcloud AI Endpoints | パブリックAI | Replicate | Scaleway | Together | Wavespeed | Zai |
| --------------------------------------------------- | ------- | -------- | ------ | --------- | ------ | -------------- | ------------ | ---- | ------------ | --------- | ------ | --------------------- | --------- | --------- | -------- | -------- | --------- | --- |
| [audio_classification()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.audio_classification)           | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [audio_to_audio()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.audio_to_audio)                 | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [automatic_speech_recognition()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.automatic_speech_recognition)   | ❌      | ❌        | ❌      | ✅         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ✅         | ❌        | ❌        | ❌         | ❌   |
| [chat_completion()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion)                | ✅      | ✅        | ✅      | ✅         | ❌      | ✅              | ✅            | ✅    | ✅            | ✅         | ✅      | ✅                     | ✅         | ❌         | ✅        | ✅        | ❌         | ✅   |
| [document_question_answering()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.document_question_answering)    | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [feature_extraction()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.feature_extraction)             | ❌      | ❌        | ❌      | ✅         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ✅        | ✅        | ❌         | ❌   |
| [fill_mask()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.fill_mask)                      | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [image_classification()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.image_classification)           | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [image_segmentation()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.image_segmentation)             | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [image_to_image()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.image_to_image)                 | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ✅         | ❌        | ✅        | ✅         | ❌   |
| [image_to_video()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.image_to_video)                 | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ❌            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ✅        | ✅         | ❌   |
| [image_to_text()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.image_to_text)                  | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [object_detection()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.object_detection)               | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [question_answering()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.question_answering)             | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [sentence_similarity()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.sentence_similarity)            | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [summarization()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.summarization)                  | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [table_question_answering()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.table_question_answering)       | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [text_classification()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.text_classification)            | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [text_generation()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.text_generation)                | ❌      | ❌        | ❌      | ✅         | ❌      | ✅              | ❌            | ❌    | ✅            | ✅         | ❌      | ❌                     | ❌         | ❌         | ❌        | ✅        | ❌         | ❌   |
| [text_to_image()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_image)                  | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ✅      | ❌                     | ❌         | ✅         | ❌        | ✅        | ✅         | ✅   |
| [text_to_speech()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_speech)                 | ❌      | ❌        | ❌      | ✅         | ✅      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ✅         | ❌        | ✅        | ❌         | ❌   |
| [text_to_video()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_video)                  | ❌      | ❌        | ❌      | ❌         | ✅      | ❌              | ❌            | ❌    | ❌            | ✅         | ❌      | ❌                     | ❌         | ✅         | ❌        | ✅        | ✅         | ❌   |
| [tabular_classification()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.tabular_classification)         | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [tabular_regression()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.tabular_regression)             | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [token_classification()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.token_classification)           | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [translation()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.translation)                    | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [visual_question_answering()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.visual_question_answering)      | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [zero_shot_image_classification()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.zero_shot_image_classification) | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |
| [zero_shot_classification()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.zero_shot_classification)       | ❌      | ❌        | ❌      | ❌         | ❌      | ❌              | ❌            | ❌    | ✅            | ❌         | ❌      | ❌                     | ❌         | ❌         | ❌        | ❌        | ❌         | ❌   |

> [!TIP]
> 各タスクの詳細については、[Tasks](https://huggingface.co/tasks)ページをご覧ください。

## OpenAI互換性

`chat_completion` タスクは、[OpenAI の Python クライアント](https://github.com/openai/openai-python) の構文に従います。これは何を意味するのでしょうか。つまり、`OpenAI` の API を扱った経験があれば、コードをわずか 2 行更新するだけで、`huggingface_hub.InferenceClient` に切り替えてオープンソースモデルを扱えるようになるということです。

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

以上です! 必須の変更は、`from openai import OpenAI` を `from huggingface_hub import InferenceClient` に、`client = OpenAI(...)` を `client = InferenceClient(...)` に置き換えることです。Hugging Face Hub から任意の LLM モデルを選択するには、そのモデル ID を `model` パラメータとして渡します。サポートされているモデルの[一覧はこちら](https://huggingface.co/models?pipeline_tag=text-generation&other=conversational,text-generation-inference&sort=trending)です。認証には、有効な[User Access Token](https://huggingface.co/settings/tokens)を `api_key` として渡すか、`huggingface_hub` を使用して認証を行ってください([認証ガイド](https://huggingface.co/docs/huggingface_hub/quick-start#authentication)を参照)。

すべての入力パラメータと出力形式は厳密に同一です。特に、`stream=True`を渡すことで、トークンが生成されるにつれて受け取ることができます。また、[AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.AsyncInferenceClient)を使用して`asyncio`で推論を実行することもできます:

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

OpenAIのクライアントではなく[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)を使用する理由について疑問に思うかもしれません。その理由はいくつかあります。
1. [InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)はHugging Faceサービス用に設定されています。Inference Providersでモデルを実行するには、`base_url`を指定する必要はありません。また、マシンがすでに正しくログインされている場合は、`token`や`api_key`を指定する必要もありません。
2. [InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)は、Text-Generation-Inference (TGI) と `transformers` の両方のフレームワークに対応するように設計されており、常に最新のアップデートと整合性が保たれていることが保証されています。
3. [InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)は、Inference Endpointsサービスと統合されており、Inference Endpointの起動、ステータスの確認、およびその上での推論の実行が容易になります。詳細については、[Inference Endpoints](./inference_endpoints)ガイドを参照してください。

> [!TIP]
> `InferenceClient.chat.completions.create` は `InferenceClient.chat_completion` の別名です。詳細については、[chat_completion()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion)のパッケージリファレンスを参照してください。クライアントをインスタンス化する際の `base_url` と `api_key` パラメータも、それぞれ `model` と `token` の別名です。これらの別名は、`OpenAI` から `InferenceClient` への移行時の摩擦を軽減するために定義されています。

## Function Calling

Function callingにより、LLMは定義された関数やAPIなどの外部ツールとやり取りできます。これにより、ユーザーは特定のユースケースや実世界のタスクに合わせたアプリケーションを簡単に構築できます。`InferenceClient`は、OpenAI Chat Completions APIと同じツール呼び出しインターフェースを実装しています。以下は、[Novita](https://novita.ai/)を推論プロバイダーとして使用したツール呼び出しの簡単な例です。

```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 において、各プロバイダーがどのモデルをサポートしているかを確認するには、各プロバイダーのドキュメントを参照してください。

## 構造化出力 & JSON モード

InferenceClient は、構文的に有効な JSON 応答のための JSON モードと、スキーマで強制された応答のための Structured Outputs をサポートしています。JSON モードは厳密な構造なしで機械可読なデータを提供するのに対し、Structured Outputs は有効な JSON と事前定義されたスキーマへの準拠の両方を保証し、信頼性の高い下流処理を実現します。

JSON モードと Structured Outputs の両方で、OpenAI の API 仕様に準拠しています。`response_format` 引数でこれらを有効にできます。以下は、推論プロバイダーとして [Cerebras](https://www.cerebras.ai/) を使用した Structured Outputs の例です。

```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 および JSON Mode において、プロバイダーがどのモデルをサポートしているかを確認するには、各プロバイダーのドキュメントを参照してください。

## 非同期クライアント

`asyncio`と`httpx2`をベースとした、クライアントの非同期バージョンも提供されています。すべての非同期APIエンドポイントは、[AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.AsyncInferenceClient)経由で利用できます。その初期化とAPIは、同期専用バージョンと完全に同一です。

```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`モジュールの詳細については、[公式ドキュメント](https://docs.python.org/3/library/asyncio.html)を参照してください。

## MCPクライアント

`huggingface_hub` ライブラリには現在、実験的な [MCPClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/mcp#huggingface_hub.MCPClient) が含まれています。これは、[Model Context Protocol](https://modelcontextprotocol.io) (MCP) を介して外部のツールと対話する機能を大規模言語モデル (LLM) に付与するために設計されています。このクライアントは [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.AsyncInferenceClient) を拡張し、ツールの利用をシームレスに統合します。

[MCPClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/mcp#huggingface_hub.MCPClient)は、ツールを公開するMCPサーバー（ローカルの`stdio`スクリプトまたはリモートの`http`/`sse`サービス）に接続します。これらのツールをLLMに提供します（[AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.AsyncInferenceClient)を介して）。LLMがツールの使用を決定した場合、[MCPClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/mcp#huggingface_hub.MCPClient)はMCPサーバーへの実行リクエストを管理し、ツールの出力をLLMに伝達します。多くの場合、結果はリアルタイムでストリーミングされます。

次の例では、[Novita](https://novita.ai/) の推論プロバイダーを介して [Qwen/Qwen2.5-72B-Instruct](https://huggingface.co/Qwen/Qwen2.5-72B-Instruct) モデルを使用します。その後、リモート MCP サーバーを追加します。この場合、Flux 画像生成ツールを LLM に利用可能にする SSE サーバーです。

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

よりシンプルな開発のために、より高レベルの[Agent](/docs/huggingface_hub/v2.4.0/ja/package_reference/mcp#huggingface_hub.Agent)クラスを提供しています。この「Tiny Agent」は、チャットループと状態を管理することで、会話型Agentの作成を簡素化します。実質的には[MCPClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/mcp#huggingface_hub.MCPClient)のラッパーとして機能します。[MCPClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/mcp#huggingface_hub.MCPClient)の上に直接構築されたシンプルなwhileループとして設計されています。これらのAgentはコマンドラインから直接実行できます:

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

```

起動すると、Agentは接続されているMCPサーバーから検出されたToolを読み込み、一覧を表示し、プロンプトの受け入れ準備が整います。

## 高度なヒント

上記のセクションでは、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)の主要な側面を確認しました。ここでは、より高度なヒントについて詳しく見ていきましょう。

### 請求

HF ユーザーとして、Hub 上でさまざまなプロバイダーを通じて推論を実行するための月次クレジットが付与されます。付与されるクレジットの量は、アカウントの種類（Free、PRO、または Enterprise Hub）によって異なります。推論リクエストごとに、プロバイダーの料金表に基づいて課金されます。デフォルトでは、リクエストは個人のアカウントに請求されます。ただし、`InferenceClient` に `bill_to="<your_org_name>"` を渡すだけで、請求先を所属する組織に変更できます。この機能を利用するには、組織が Enterprise Hub に加入している必要があります。請求に関する詳細については、[このガイド](https://huggingface.co/docs/api-inference/pricing#features-using-inference-providers)を参照してください。

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

他のユーザーや、自分が所属していない組織に請求することはできません。他のユーザーにクレジットを付与したい場合は、そのユーザーと共同で組織を作成する必要があります。

### タイムアウト

推論の呼び出しにはかなりの時間がかかる場合があります。デフォルトでは、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)は推論が完了するまで「無期限に」待機します。ワークフローにおいてより細かな制御を行いたい場合は、`timeout`パラメータに秒単位の特定の値を設定できます。タイムアウトの遅延が期限切れになると、[InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError)が発生します。これはコード内でキャッチできます:

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

### バイナリ入力

一部のタスクでは、画像やオーディオファイルの処理など、バイナリ入力が必要です。この場合、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)は可能な限り寛容に動作し、異なる型を受け入れます:
- `bytes` の生データ
- バイナリモードで開かれたファイルライクオブジェクト（`with open("audio.flac", "rb") as f: ...`）
- ローカルファイルへのパス(`str`または`Path`)
- リモートファイル（例: `https://...`）を指す URL（`str`）。この場合、ファイルは
APIに送信されます。

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

