# 推論

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

これらのサービスは、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)オブジェクトを介して呼び出すことができます。使用方法の詳細については、[このガイド](../guides/inference)を参照してください。

## 推論クライアント[[huggingface_hub.InferenceClient]]

#### huggingface_hub.InferenceClient[[huggingface_hub.InferenceClient]]

```python
huggingface_hub.InferenceClient(model: str | None = None, provider: typing.Union[typing.Literal['baseten', 'cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], typing.Literal['auto'], NoneType] = None, token: str | None = None, timeout: float | None = None, headers: dict[str, str] | None = None, cookies: dict[str, str] | None = None, bill_to: str | None = None, base_url: str | None = None, api_key: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L124)

**パラメータ:**

model (`str`, `optional`) : 推論を実行するモデル。Hugging Face Hub にホストされているモデル ID (例: `meta-llama/Meta-Llama-3-8B-Instruct`) またはデプロイされた Inference Endpoint の URL を指定できます。デフォルトは None で、この場合、タスクに適した推奨モデルが自動的に選択されます。注: OpenAI のクライアントとの互換性を高めるため、`model` は `base_url` としてエイリアス化されています。これら 2 つの引数は排他的です。チャット補完のために `model` または `base_url` として URL が渡された場合、その URL に `(/v1)/chat/completions` というサフィックスパスが追加されます。

provider (`str`, *任意*) : 推論に使用するプロバイダーの名前。`"baseten"`、`"cerebras"`、`"cohere"`、`"deepinfra"`、`"fal-ai"`、`"featherless-ai"`、`"fireworks-ai"`、`"groq"`、`"hf-inference"`、`"novita"`、`"nscale"`、`"openai"`、`"ovhcloud"`、`"publicai"`、`"replicate"`、`"scaleway"`、`"together"`、`"wavespeed"`、または`"zai-org"`のいずれかです。デフォルトは "auto" です。自動ルーティングを行い、デフォルトでは "fastest" プロバイダーが選択されます。https://hf.co/settings/inference-providers で "cheapest" または "preferred" のプロバイダー順序に切り替えることができます。model が URL の場合、または `base_url` が渡された場合、`provider` は使用されません。

token (`str`, *任意*) : Hugging Face トークン。指定しない場合、ローカルに保存されたトークンがデフォルトで使用されます。なお、OpenAI のクライアントとの互換性を高めるため、`token` は `api_key` としてエイリアス化されています。これら 2 つの引数は排他的であり、動作は完全に同一です。

timeout (`float`, `optional`) : サーバーからの応答を待機する最大秒数。デフォルトは None で、サーバーが利用可能になるまでループし続けます。

headers (`dict[str, str]`、`optional`) : サーバーに送信する追加のヘッダー。デフォルトでは、authorization ヘッダーと user-agent ヘッダーのみが送信されます。この辞書の値は、デフォルトの値を上書きします。

bill_to (`str`, `optional`) : リクエストに使用する請求アカウント。デフォルトでは、リクエストはユーザーのアカウントで請求されます。リクエストは、ユーザーがメンバーであり、かつ Enterprise Hub に加入している組織にのみ請求できます。

cookies (`dict[str, str]`、`optional`) : サーバーに送信する追加のクッキー。

base_url (`str`, `optional`) : 推論を実行するためのベースURLです。`model`からの重複引数であり、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)が`openai.OpenAI`クライアントと同じパターンに従うようにするためのものです。`model`が設定されている場合は使用できません。デフォルト値はNoneです。

api_key (`str`, `optional`) : 認証に使用するトークン。`token`からの重複引数であり、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)が`openai.OpenAI`クライアントと同じパターンに従うようにするためのものです。`token`が設定されている場合は使用できません。デフォルトはNoneです。

新しいInference Clientを初期化します。

[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)は、推論の実行に統一された体験を提供することを目的としています。このクライアントは、（無料の）Inference API、セルフホストされたInference Endpoints、またはサードパーティのInference Providersのいずれともシームレスに使用できます。

#### audio_classification[[huggingface_hub.InferenceClient.audio_classification]]

```python
audio_classification(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, top_k: int | None = None, function_to_apply: typing.Optional[ForwardRef('AudioClassificationOutputTransform')] = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L295)

**パラメータ:**

audio (Union[str, Path, bytes, BinaryIO]) : 分類対象のオーディオコンテンツ。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。

model (`str`, *任意*) : 音声分類に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、音声分類用のデフォルトの推奨モデルが使用されます。

top_k (`int`, *optional*) : 指定すると、出力が最も確率の高い上位K個のクラスに制限されます。

function_to_apply (`"AudioClassificationOutputTransform"`, *任意*) : モデルの出力に適用してスコアを取得するための関数。

**戻り値:** `list[AudioClassificationOutputElement]`

予測ラベルとその信頼度を含む[AudioClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.AudioClassificationOutputElement)の項目のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

提供された音声コンテンツに対して音声分類を実行します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.audio_classification("audio.flac")
[
    AudioClassificationOutputElement(score=0.4976358711719513, label='hap'),
    AudioClassificationOutputElement(score=0.3677836060523987, label='neu'),
    ...
]
```

#### audio_to_audio[[huggingface_hub.InferenceClient.audio_to_audio]]

```python
audio_to_audio(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L352)

**パラメータ:**

audio (Union[str, Path, bytes, BinaryIO]) : モデル用の音声コンテンツ。生の音声バイト、ローカルの音声ファイル、または音声ファイルを指すURLのいずれかです。

model (`str`, *任意*) : モデルは、音声ファイルを受け取り、別の音声ファイルを返す任意のモデルです。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、audio_to_audio のデフォルトで推奨されるモデルが使用されます。

**戻り値:** `list[AudioToAudioOutputElement]`

オーディオのラベル、コンテンツタイプ、およびブロブ形式のオーディオコンテンツを含む[AudioToAudioOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.AudioToAudioOutputElement)の項目のリスト。

**例外:** ``InferenceTimeoutError`` または `HfHubHTTPError`

- ``InferenceTimeoutError`` -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

モデルに応じて、音声から音声への変換に関連する複数のタスクを実行します（例：音声の品質向上、ソース分離）。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> audio_output = client.audio_to_audio("audio.flac")
>>> for i, item in enumerate(audio_output):
>>>     with open(f"output_{i}.flac", "wb") as f:
            f.write(item.blob)
```

#### automatic_speech_recognition[[huggingface_hub.InferenceClient.automatic_speech_recognition]]

```python
automatic_speech_recognition(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, extra_body: dict | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L404)

**パラメータ:**

audio (Union[str, Path, bytes, BinaryIO]) : 文字起こしする内容。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。

model (`str`, *任意*) : ASRに使用するモデル。Hugging Face HubにホストされているモデルID、またはデプロイされたInference EndpointのURLを指定できます。指定しない場合、ASR用のデフォルトの推奨モデルが使用されます。

extra_body (`dict`, *任意*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** [AutomaticSpeechRecognitionOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.AutomaticSpeechRecognitionOutput)

転写テキストと、任意のタイムスタンプチャンクを含むアイテム。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられた音声コンテンツに対して、自動音声認識（ASRまたは音声からテキストへの変換）を実行します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.automatic_speech_recognition("hello_world.flac").text
"hello world"
```

#### chat_completion[[huggingface_hub.InferenceClient.chat_completion]]

```python
chat_completion(messages: list, model: str | None = None, stream: bool = False, frequency_penalty: float | None = None, logit_bias: list[float] | None = None, logprobs: bool | None = None, max_tokens: int | None = None, n: int | None = None, presence_penalty: float | None = None, response_format: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatText, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONSchema, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONObject, NoneType] = None, seed: int | None = None, stop: list[str] | None = None, stream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = None, temperature: float | None = None, tool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None, tool_prompt: str | None = None, tools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = None, top_logprobs: int | None = None, top_p: float | None = None, extra_body: dict | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L531)

**パラメータ:**

messages ([ChatCompletionInputMessage](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionInputMessage) のリスト) : ロールとコンテンツのペアで構成される会話履歴。

model (`str`, *任意*) : チャット補完に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、チャットベースのテキスト生成用のデフォルト推奨モデルが使用されます。詳細は https://huggingface.co/tasks/text-generation を参照してください。`model` がモデル ID の場合、`model` パラメータとしてサーバーに渡されます。リクエストペイロードで `model` を設定しながらカスタム URL を定義したい場合は、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient) を初期化する際に `base_url` を設定する必要があります。

frequency_penalty (`float`, *optional*) : これまでのテキストにおけるトークンの出現頻度に基づいて、新しいトークンをペナルティします。範囲: [-2.0, 2.0]。デフォルト値は 0.0 です。

logit_bias (`list[float]`, *任意*) : 生成された出力に特定のトークンが出現する可能性を調整します。

logprobs (`bool`, *任意*) : 出力トークンの対数確率を返すかどうかを指定します。true の場合、メッセージの content に返される各出力トークンの対数確率が返されます。

max_tokens (`int`, *optional*) : 応答で許可されるトークンの最大数。デフォルト値は100です。

n (`int`, *optional*) : 各プロンプトに対して生成する補完の数。

presence_penalty (`float`, *任意*) : -2.0から2.0の間の数値。正の値は、それまでのテキストにトークンが出現しているかどうかに基づいて新しいトークンをペナルティし、モデルが新しい話題について話す可能性を高めます。

response_format (`ChatCompletionInputGrammarType()`、*任意*) : 文法制約。JSONSchema または正規表現のいずれかです。

seed （任意`int`、*optional*）：再現可能な制御フローのためのシード。デフォルトはNoneです。

stop (`list[str]`, *任意*) : レスポンスの終了をトリガーする最大4つの文字列です。デフォルトは None です。

stream (`bool`, *任意*) : 応答のリアルタイムストリーミングを有効にします。デフォルトは False です。

stream_options ([ChatCompletionInputStreamOptions](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionInputStreamOptions)、*任意*) : ストリーミング補完のオプション。

temperature (`float`, *optional*) : 生成のランダム性を制御します。値が低いほど、より予測可能な補完になります。範囲: [0, 2]。デフォルト値は 1.0 です。

top_logprobs (`int`, *optional*) : 各トークン位置で返す最尤トークンの数を0から5の範囲で指定する整数です。各トークンには対応する対数確率が付与されます。このパラメータを使用する場合は、logprobsをtrueに設定する必要があります。

top_p (`float`, *optional*) : 最も可能性の高い次の単語からサンプリングする割合。0から1の間でなければなりません。デフォルト値は1.0です。

tool_choice ([ChatCompletionInputToolChoiceClass](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionInputToolChoiceClass) または `ChatCompletionInputToolChoiceEnum()`、*任意*) : 補完に使用するツール。デフォルト値は "auto" です。

tool_prompt (`str`, *任意*) : ツールの前に追加されるプロンプト。

tools ([ChatCompletionInputTool](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionInputTool) のリスト、*任意*) : モデルが呼び出す可能性のあるツールのリストです。現在、ツールとしてサポートされているのは関数のみです。モデルが JSON 入力を生成できる関数のリストを指定するために使用します。

extra_body (`dict`, *任意*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** [ChatCompletionOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionOutput) または [ChatCompletionStreamOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionStreamOutput) のイテラブル

サーバーから返された生成テキスト:
- `stream=False`の場合、生成されたテキストは[ChatCompletionOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionOutput)として返されます（デフォルト）。
- `stream=True`の場合、生成されたテキストは[ChatCompletionStreamOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionStreamOutput)のシーケンスとして、トークンごとに返されます。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定された言語モデルを使用して会話を補完するためのメソッド。

> [!TIP]
> `client.chat_completion` メソッドは、OpenAI のクライアントとの互換性のために `client.chat.completions.create` としてエイリアス化されています。入力と出力は完全に同一であり、どちらの構文を使用しても同じ結果が得られます。OpenAI の互換性に関する詳細については、[推論ガイド](https://huggingface.co/docs/huggingface_hub/guides/inference#openai-compatibility)を参照してください。

> [!TIP]
> `extra_body` 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

```py
>>> from huggingface_hub import InferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> 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
    )
)
```

ストリーミングを使用した例:
```py
>>> from huggingface_hub import InferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> for token in client.chat_completion(messages, max_tokens=10, stream=True):
...     print(token)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content='The', role='assistant'), index=0, finish_reason=None)], created=1710498504)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' capital', role='assistant'), index=0, finish_reason=None)], created=1710498504)
(...)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' may', role='assistant'), index=0, finish_reason=None)], created=1710498504)
```

OpenAIの構文を使用した例:
```py
# instead of `from openai import OpenAI`
from huggingface_hub import InferenceClient

# instead of `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)
```

サードパーティプロバイダーを直接使用し、追加の（プロバイダー固有の）パラメータを指定する例。利用料はTogether AIアカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="together",  # Use Together AI provider
...     api_key="<together_api_key>",  # Pass your Together API key directly
... )
>>> client.chat_completion(
...     model="meta-llama/Meta-Llama-3-8B-Instruct",
...     messages=[{"role": "user", "content": "What is the capital of France?"}],
...     extra_body={"safety_model": "Meta-Llama/Llama-Guard-7b"},
... )
```

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="novita",  # Use Novita provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> client.chat_completion(
...     model="meta-llama/Meta-Llama-3-8B-Instruct",
...     messages=[{"role": "user", "content": "What is the capital of France?"}],
... )
```

画像とテキストを入力として使用する例:
```py
>>> from huggingface_hub import InferenceClient

# provide a remote URL
>>> image_url ="https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
# or a base64-encoded image
>>> image_path = "/path/to/image.jpeg"
>>> with open(image_path, "rb") as f:
...     base64_image = base64.b64encode(f.read()).decode("utf-8")
>>> image_url = f"data:image/jpeg;base64,{base64_image}"

>>> client = InferenceClient("meta-llama/Llama-3.2-11B-Vision-Instruct")
>>> output = client.chat.completions.create(
...     messages=[
...         {
...             "role": "user",
...             "content": [
...                 {
...                     "type": "image_url",
...                     "image_url": {"url": image_url},
...                 },
...                 {
...                     "type": "text",
...                     "text": "Describe this image in one sentence.",
...                 },
...             ],
...         },
...     ],
... )
>>> output
The image depicts the iconic Statue of Liberty situated in New York Harbor, New York, on a clear day.
```

ツールを使用した例:
```py
>>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
...     {
...         "role": "system",
...         "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
...     },
...     {
...         "role": "user",
...         "content": "What's the weather like the next 3 days in San Francisco, CA?",
...     },
... ]
>>> tools = [
...     {
...         "type": "function",
...         "function": {
...             "name": "get_current_weather",
...             "description": "Get the current weather",
...             "parameters": {
...                 "type": "object",
...                 "properties": {
...                     "location": {
...                         "type": "string",
...                         "description": "The city and state, e.g. San Francisco, CA",
...                     },
...                     "format": {
...                         "type": "string",
...                         "enum": ["celsius", "fahrenheit"],
...                         "description": "The temperature unit to use. Infer this from the users location.",
...                     },
...                 },
...                 "required": ["location", "format"],
...             },
...         },
...     },
...     {
...         "type": "function",
...         "function": {
...             "name": "get_n_day_weather_forecast",
...             "description": "Get an N-day weather forecast",
...             "parameters": {
...                 "type": "object",
...                 "properties": {
...                     "location": {
...                         "type": "string",
...                         "description": "The city and state, e.g. San Francisco, CA",
...                     },
...                     "format": {
...                         "type": "string",
...                         "enum": ["celsius", "fahrenheit"],
...                         "description": "The temperature unit to use. Infer this from the users location.",
...                     },
...                     "num_days": {
...                         "type": "integer",
...                         "description": "The number of days to forecast",
...                     },
...                 },
...                 "required": ["location", "format", "num_days"],
...             },
...         },
...     },
... ]

>>> response = client.chat_completion(
...     model="meta-llama/Meta-Llama-3-70B-Instruct",
...     messages=messages,
...     tools=tools,
...     tool_choice="auto",
...     max_tokens=500,
... )
>>> response.choices[0].message.tool_calls[0].function
ChatCompletionOutputFunctionDefinition(
    arguments={
        'location': 'San Francisco, CA',
        'format': 'fahrenheit',
        'num_days': 3
    },
    name='get_n_day_weather_forecast',
    description=None
)
```

response_format を使用した例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
...     {
...         "role": "user",
...         "content": "I saw a puppy a cat and a raccoon during my bike ride in the park. What did I see and when?",
...     },
... ]
>>> response_format = {
...     "type": "json",
...     "value": {
...         "properties": {
...             "location": {"type": "string"},
...             "activity": {"type": "string"},
...             "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
...             "animals": {"type": "array", "items": {"type": "string"}},
...         },
...         "required": ["location", "activity", "animals_seen", "animals"],
...     },
... }
>>> response = client.chat_completion(
...     messages=messages,
...     response_format=response_format,
...     max_tokens=500,
... )
>>> response.choices[0].message.content
'{

y": "bike ride",
": ["puppy", "cat", "raccoon"],
_seen": 3,
n": "park"}'
```

#### document_question_answering[[huggingface_hub.InferenceClient.document_question_answering]]

```python
document_question_answering(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, model: str | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, lang: str | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None, word_boxes: list[list[float] | str] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L933)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO]`) : コンテキスト用の入力画像です。生のバイト列、画像ファイル、またはオンライン画像へのURLを指定できます。

question (`str`) : 回答する質問。

model (`str`, *任意*) : ドキュメント質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるドキュメント質問応答モデルが使用されます。デフォルト値は None です。

doc_stride (`int`, *optional*) : ドキュメント内の単語が長すぎて、モデルの質問と合わせて収まらない場合、いくつかのチャンクに分割され、一部が重複します。この引数は、その重複のサイズを制御します。

handle_impossible_answer (`bool`, *任意*) : 不可能を回答として受け入れるかどうか

lang (`str`, *任意*) : OCR実行時に使用する言語。デフォルトは英語です。

max_answer_len (`int`, *optional*) : 予測される回答の最大長（例：より短い長さの回答のみが考慮されます）。

max_question_len (`int`, *optional*) : トークナイズ後の質問の最大長です。必要に応じて切り詰められます。

max_seq_len (`int`, *optional*) : モデルに渡される各チャンクにおける、文全体（コンテキスト + 質問）の最大トークン数。必要に応じて、コンテキストは複数のチャンクに分割されます（重複として doc_stride を使用）。

top_k (`int`, *optional*) : 返す回答の数（可能性の高い順に選択されます）。コンテキスト内に十分な選択肢がない場合、top_k より少ない数の回答が返されることがあります。

word_boxes (`list[Union[list[float], str`, *optional*) : 単語とバウンディングボックス（正規化済み 0->1000）のリストです。指定された場合、推論は OCR ステップをスキップし、代わりに指定されたバウンディングボックスを使用します。

**戻り値:** `list[DocumentQuestionAnsweringOutputElement]`

予測ラベル、関連する確率、単語 ID、ページ番号を含む[DocumentQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.DocumentQuestionAnsweringOutputElement)のアイテムのリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

ドキュメントの画像に関する質問に回答します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?")
[DocumentQuestionAnsweringOutputElement(answer='us-001', end=16, score=0.9999666213989258, start=16)]
```

#### feature_extraction[[huggingface_hub.InferenceClient.feature_extraction]]

```python
feature_extraction(text: str | list[str], normalize: bool | None = None, prompt_name: str | None = None, truncate: bool | None = None, truncation_direction: typing.Optional[typing.Literal['left', 'right']] = None, dimensions: int | None = None, encoding_format: typing.Optional[typing.Literal['float', 'base64']] = None, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1020)

**パラメータ:**

text (*str* または *list[str]*) : 埋め込むテキストまたはテキストのリスト。

model (*str*, *optional*) : 特徴抽出タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される特徴抽出モデルが使用されます。デフォルト値は None です。

normalize (*bool*, *optional*) : 埋め込みを正規化するか否か。Text-Embedding-Inference によるサーバーでのみ利用可能です。

prompt_name (*str*, *optional*) : The name of the prompt that should be used by for encoding. If not set, no prompt will be applied. Must be a key in the *Sentence Transformers* configuration *prompts* dictionary. For example if `prompt_name` is "query" and the `prompts` is &amp;lcub;"query": "query: ",...}, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the prompt text will be prepended before any text to encode.

truncate (*bool*, *optional*) : 埋め込みを切り詰めるかどうか。Text-Embedding-Inference によるサーバーでのみ利用可能です。

truncation_direction (*Literal["left", "right"]*, *optional*) : *truncate=True* が渡された場合、入力のどの側を切り詰めるかを指定します。

dimensions (*int*, *optional*) : 出力される埋め込みベクトルの次元数です。OpenAI互換の埋め込みエンドポイントでのみ利用可能です。

encoding_format (*Literal["float", "base64"]*, *optional*) : 出力埋め込みの形式です。"float"または"base64"のいずれかです。OpenAI互換の埋め込みエンドポイントでのみ利用可能です。

**戻り値:** `*np.ndarray*`

float32型のNumPy配列として入力テキストを表す埋め込み。

**例外:** [*InferenceTimeoutError*] または [*HfHubHTTPError*]

- [*InferenceTimeoutError*] -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- [*HfHubHTTPError*] -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたテキストまたはテキストのバッチに対して埋め込みを生成します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.feature_extraction("Hi, who are you?")
array([[ 2.424802  ,  2.93384   ,  1.1750331 , ...,  1.240499, -0.13776633, -0.7889173 ],
[-0.42943227, -0.6364878 , -1.693462  , ...,  0.41978157, -2.4336355 ,  0.6162071 ],
...,
[ 0.28552425, -0.928395  , -1.2077185 , ...,  0.76810825, -2.1069427 ,  0.6236161 ]], dtype=float32)
```

#### fill_mask[[huggingface_hub.InferenceClient.fill_mask]]

```python
fill_mask(text: str, model: str | None = None, targets: list[str] | None = None, top_k: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1103)

**パラメータ:**

text (`str`) : 埋め込む対象の文字列。[MASK] トークンを含む必要があります（マスクの正確な名称はモデルカードを確認してください）。

model (`str`, *任意*) : fill mask タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される fill mask モデルが使用されます。

targets (`list[str`, *optional*) : 指定された場合、モデルは語彙全体を検索するのではなく、指定されたターゲットにスコアを制限します。提供されたターゲットがモデルの語彙に存在しない場合、それらはトークン化され、結果として得られた最初のトークンが使用されます（警告が表示され、処理が遅くなる可能性があります）。

top_k (`int`, *optional*) : 指定すると、返す予測の数を上書きします。

**戻り値:** `list[FillMaskOutputElement]`

予測ラベル、関連する確率、トークン参照、および補完されたテキストを含む[FillMaskOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.FillMaskOutputElement)の項目のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

欠落した単語（正確にはトークン）で穴を埋めます。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.fill_mask("The goal of life is <mask>.")
[
    FillMaskOutputElement(score=0.06897063553333282, token=11098, token_str=' happiness', sequence='The goal of life is happiness.'),
    FillMaskOutputElement(score=0.06554922461509705, token=45075, token_str=' immortality', sequence='The goal of life is immortality.')
]
```

#### get_endpoint_info[[huggingface_hub.InferenceClient.get_endpoint_info]]

```python
get_endpoint_info(model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3250)

**パラメータ:**

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

**戻り値:** `dict[str, Any]`

エンドポイントに関する情報。

デプロイされたエンドポイントに関する情報を取得します。

このエンドポイントは、Text-Generation-Inference (TGI) または Text-Embedding-Inference (TEI) によって提供されるエンドポイントでのみ利用可能です。`transformers` によって提供されるエンドポイントは、空のペイロードを返します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> client.get_endpoint_info()
{
    'model_id': 'meta-llama/Meta-Llama-3-70B-Instruct',
    'model_sha': None,
    'model_dtype': 'torch.float16',
    'model_device_type': 'cuda',
    'model_pipeline_tag': None,
    'max_concurrent_requests': 128,
    'max_best_of': 2,
    'max_stop_sequences': 4,
    'max_input_length': 8191,
    'max_total_tokens': 8192,
    'waiting_served_ratio': 0.3,
    'max_batch_total_tokens': 1259392,
    'max_waiting_tokens': 20,
    'max_batch_size': None,
    'validation_workers': 32,
    'max_client_batch_size': 4,
    'version': '2.0.2',
    'sha': 'dccab72549635c7eb5ddb17f43f0b7cdff07c214',
    'docker_label': 'sha-dccab72'
}
```

#### health_check[[huggingface_hub.InferenceClient.health_check]]

```python
health_check(model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3308)

**パラメータ:**

model (`str`, *任意*) : Inference Endpoint の URL。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

**戻り値:** `bool`

すべてが正常に動作している場合はTrue。

デプロイされたエンドポイントの健全性を確認します。

Health checkは、Text-Generation-Inference (TGI) または Text-Embedding-Inference (TEI) による Inference Endpoints のみで利用可能です。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient("https://jzgu0buei5.us-east-1.aws.endpoints.huggingface.cloud")
>>> client.health_check()
True
```

#### image_classification[[huggingface_hub.InferenceClient.image_classification]]

```python
image_classification(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, function_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = None, top_k: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1159)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : 分類対象の画像です。生のバイト列、画像ファイル、オンライン画像のURL、またはPIL Imageを指定できます。

model (`str`, *任意*) : 画像分類に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、画像分類用のデフォルトの推奨モデルが使用されます。

function_to_apply (`"ImageClassificationOutputTransform"`, *任意*) : モデルの出力に適用してスコアを取得するための関数。

top_k (`int`, *optional*) : 指定すると、出力が最も確率の高い上位K個のクラスに制限されます。

**戻り値:** `list[ImageClassificationOutputElement]`

予測ラベルと関連する確率を含む[ImageClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ImageClassificationOutputElement)のリスト

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられた画像で画像分類を実行します。

例:
```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")
[ImageClassificationOutputElement(label='Blenheim spaniel', score=0.9779096841812134), ...]
```

#### image_segmentation[[huggingface_hub.InferenceClient.image_segmentation]]

```python
image_segmentation(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, mask_threshold: float | None = None, overlap_mask_area_threshold: float | None = None, subtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = None, threshold: float | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1209)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : セグメント化対象の画像。生のバイト列、画像ファイル、オンライン画像のURL、またはPIL Imageを指定できます。

model (`str`, *任意*) : 画像セグメンテーションに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、画像セグメンテーション用のデフォルトの推奨モデルが使用されます。

mask_threshold (`float`, *任意*) : 予測されたマスクをバイナリ値に変換する際に使用するしきい値。

overlap_mask_area_threshold (`float`, *任意*) : 小さい、断片化されたセグメントを除去するためのマスク重複の閾値。

subtask (`"ImageSegmentationSubtask"`, *任意*) : モデルの機能に応じて実行されるセグメンテーションタスク。

threshold (`float`, *任意*) : 予測されたマスクをフィルタリングするための確率の閾値。

**戻り値:** `list[ImageSegmentationOutputElement]`

セグメンテーションされたマスクと関連する属性を含む、[ImageSegmentationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ImageSegmentationOutputElement) の項目のリストです。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられた画像に対して画像セグメンテーションを実行します。

> [!WARNING]
> 画像を扱うには、`PIL`のインストールが必要です（`pip install Pillow`）。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.image_segmentation("cat.jpg")
[ImageSegmentationOutputElement(score=0.989008, label='LABEL_184', mask=<PIL.PngImagePlugin.PngImageFile image mode=L size=400x300 at 0x7FDD2B129CC0>), ...]
```

#### image_to_image[[huggingface_hub.InferenceClient.image_to_image]]

```python
image_to_image(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], prompt: str | None = None, negative_prompt: str | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, model: str | None = None, target_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1277)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : 翻訳の入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。

prompt (`str`, *任意*) : 画像生成を導くためのテキストプロンプト。

negative_prompt (`str`, *任意*) : 画像生成に含めるべきでない内容を指示するプロンプト。

num_inference_steps (`int`, *optional*) : 拡散モデル用。デノイジングのステップ数です。デノイジングのステップ数が多いほど、推論速度が遅くなる代わりに、より高品質な画像が得られる傾向があります。

guidance_scale (`float`, *optional*) : 拡散モデル用です。guidance scale の値を高くすると、テキストプロンプトと密接に関連した画像を生成するようモデルに促されますが、その代わり画像の品質が低下します。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

target_size (`ImageToImageTargetSize`, *任意*) : 出力画像のピクセルサイズです。このパラメータは、一部のプロバイダーおよび特定のモデルでのみサポートされています。サポートされていない場合は無視されます。

**戻り値:** `Image`

変換された画像。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、画像から画像への翻訳を実行します。

> [!WARNING]
> 画像を扱うには、`PIL`のインストールが必要です（`pip install Pillow`）。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> image = client.image_to_image("cat.jpg", prompt="turn the cat into a tiger")
>>> image.save("tiger.jpg")
```

#### image_to_text[[huggingface_hub.InferenceClient.image_to_text]]

```python
image_to_text(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1432)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : キャプションを付与する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageのいずれかです。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

**戻り値:** [ImageToTextOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ImageToTextOutput)

生成されたテキスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力画像を受け取り、テキストを返します。

モデルの出力は、ユースケース（画像キャプション生成、光学文字認識（OCR）、Pix2Struct など）によって大きく異なる場合があります。モデル固有の詳細については、モデルカードをご参照ください。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.image_to_text("cat.jpg")
'a cat standing in a grassy field '
>>> client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
'a dog laying on the grass next to a flower pot '
```

#### image_to_video[[huggingface_hub.InferenceClient.image_to_video]]

```python
image_to_video(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, prompt: str | None = None, negative_prompt: str | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1353)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : 動画の生成に使用する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

prompt (`str`, *任意*) : 動画生成をガイドするためのテキストプロンプト。

negative_prompt (`str`, *任意*) : 動画生成に含めるべきでない内容を指示するプロンプト。

num_frames (`float`, *任意*) : num_frames パラメータは、生成される動画フレームの数を決定します。

num_inference_steps (`int`, *optional*) : 拡散モデル用。デノイジングのステップ数です。デノイジングのステップ数が多いほど、推論速度が遅くなる代わりに、より高品質な画像が得られる傾向があります。

guidance_scale (`float`, *optional*) : 拡散モデル用です。guidance scale の値を高くすると、テキストプロンプトと密接に関連した動画を生成するようモデルを促しますが、画像の品質が低下する可能性があります。

seed (`int`, *optional*) : 動画生成に使用するシード。

target_size (`ImageToVideoTargetSize`, *任意*) : 出力される動画フレームのピクセルサイズ。

num_inference_steps (`int`, *optional*) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。

seed (`int`, *任意*) : 乱数生成器のシード。

**戻り値:** `bytes`

生成された動画。

入力画像から動画を生成します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> video = client.image_to_video("cat.jpg", model="Wan-AI/Wan2.2-I2V-A14B", prompt="turn the cat into a tiger")
>>> with open("tiger.mp4", "wb") as f:
...     f.write(video)
```

#### object_detection[[huggingface_hub.InferenceClient.object_detection]]

```python
object_detection(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, threshold: float | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1478)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : 対象物の検出を行う画像です。生のバイト列、画像ファイル、オンライン画像のURL、またはPIL Imageを指定できます。

model (`str`, *任意*) : オブジェクト検出に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、オブジェクト検出のデフォルト推奨モデル (DETR) が使用されます。

threshold (`float`, *任意*) : 予測を行うために必要な確率。

**戻り値:** `list[ObjectDetectionOutputElement]`

バウンディングボックスと関連する属性を含む[ObjectDetectionOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ObjectDetectionOutputElement)の項目のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError` または ``ValueError``

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。
- ``ValueError`` -- リクエストの出力が List ではない場合。

指定されたモデルを使用して、与えられた画像で物体検出を実行します。

> [!WARNING]
> 画像を扱うには、`PIL`のインストールが必要です（`pip install Pillow`）。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.object_detection("people.jpg")
[ObjectDetectionOutputElement(score=0.9486683011054993, label='person', box=ObjectDetectionBoundingBox(xmin=59, ymin=39, xmax=420, ymax=510)), ...]
```

#### question_answering[[huggingface_hub.InferenceClient.question_answering]]

```python
question_answering(question: str, context: str, model: str | None = None, align_to_words: bool | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1526)

**パラメータ:**

question (`str`) : 回答する質問。

context (`str`) : 質問のコンテキスト。

model (`str`) : 質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。

align_to_words (`bool`、*任意*) : 回答を実際の単語に整列させようとします。スペース区切り言語での品質を向上させます。スペースで区切られない言語（日本語や中国語など）では品質が低下する可能性があります。

doc_stride (`int`, *optional*) : モデルが質問とコンテキストを処理できないほどコンテキストが長い場合、コンテキストは重複を伴う複数のチャンクに分割されます。この引数は、その重複のサイズを制御します。

handle_impossible_answer (`bool`, *任意*) : 不可能を回答として受け入れるかどうか。

max_answer_len (`int`, *optional*) : 予測される回答の最大長（例：より短い長さの回答のみが考慮されます）。

max_question_len (`int`, *optional*) : トークナイズ後の質問の最大長です。必要に応じて切り詰められます。

max_seq_len (`int`, *optional*) : モデルに渡される各チャンクにおける、文全体（コンテキスト + 質問）の最大トークン数。必要に応じて、コンテキストは複数のチャンクに分割されます（重複として docStride を使用）。

top_k (`int`, *optional*) : 返す回答の数（可能性の高い順に選択されます）。コンテキスト内に十分な選択肢がない場合、topk より少ない数の回答が返されます。

**戻り値:** Union[`QuestionAnsweringOutputElement`, list[QuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.QuestionAnsweringOutputElement)]

When top_k is 1 or not provided, it returns a single `QuestionAnsweringOutputElement`. When top_k is greater than 1, it returns a list of `QuestionAnsweringOutputElement`.

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストから、質問に対する回答を取得します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.question_answering(question="What's my name?", context="My name is Clara and I live in Berkeley.")
QuestionAnsweringOutputElement(answer='Clara', end=16, score=0.9326565265655518, start=11)
```

#### sentence_similarity[[huggingface_hub.InferenceClient.sentence_similarity]]

```python
sentence_similarity(sentence: str, other_sentences: list, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1610)

**パラメータ:**

sentence (`str`) : 他と比較する主な文。

other_sentences (`list[str]`) : 比較対象となる文のリスト。

model (`str`, *任意*) : 文の類似度タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される文の類似度モデルが使用されます。デフォルト値は None です。

**戻り値:** `list[float]`

入力テキストを表す埋め込み。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

埋め込みを比較することにより、文と他の文のリストとの間の意味的類似度を計算します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.sentence_similarity(
...     "Machine learning is so easy.",
...     other_sentences=[
...         "Deep learning is so straightforward.",
...         "This is so difficult, like rocket science.",
...         "I can't believe how much I struggled with this.",
...     ],
... )
[0.7785726189613342, 0.45876261591911316, 0.2906220555305481]
```

#### 要約[[huggingface_hub.InferenceClient.summarization]]

```python
summarization(text: str, model: str | None = None, clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: typing.Optional[ForwardRef('SummarizationTruncationStrategy')] = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1663)

**パラメータ:**

text (`str`) : 要約する対象のテキスト。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、要約用のデフォルト推奨モデルが使用されます。

clean_up_tokenization_spaces (`bool`, *任意*) : テキスト出力に含まれる可能性のある余分なスペースをクリーンアップするかどうか。

generate_parameters (`dict[str, Any]`、*任意*) : テキスト生成アルゴリズムの追加のパラメータ設定。

truncation (`"SummarizationTruncationStrategy"`, *任意*) : 使用する切り詰め戦略です。

**戻り値:** [SummarizationOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.SummarizationOutput)

生成された要約テキスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられたテキストの要約を生成します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.summarization("The Eiffel tower...")
SummarizationOutput(generated_text="The Eiffel tower is one of the most famous landmarks in the world....")
```

#### table_question_answering[[huggingface_hub.InferenceClient.table_question_answering]]

```python
table_question_answering(table: dict, query: str, model: str | None = None, padding: typing.Optional[ForwardRef('Padding')] = None, sequential: bool | None = None, truncation: bool | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1721)

**パラメータ:**

table (`str`) : 各エントリがヘッダー、リストがすべての値であるリストの辞書として表されたデータテーブル。すべてのリストは同じサイズでなければなりません。

query (`str`) : テーブルに尋ねたいクエリをプレーンテキストで表したものです。

model (`str`) : テーブル質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。

padding (`"Padding"`, *任意*) : パディングの有効化と制御を行います。

sequential (`bool`, *任意*) : 推論をシーケンシャルに実行するか、バッチとして実行するかどうか。バッチ処理は高速ですが、SQAのようなモデルは、その会話的な性質から、シーケンス内の関係を抽出するために、推論をシーケンシャルに実行する必要があります。

truncation (`bool`, *任意*) : トルンケーションを有効化し、制御します。

**戻り値:** [TableQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TableQuestionAnsweringOutputElement)

回答、座標、セル、および使用されたアグリゲーターを含むテーブル質問応答の出力

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

表に示された情報から、質問に対する答えを取得します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> query = "How many stars does the transformers repository have?"
>>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]}
>>> client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq")
TableQuestionAnsweringOutputElement(answer='36542', coordinates=[[0, 1]], cells=['36542'], aggregator='AVERAGE')
```

#### tabular_classification[[huggingface_hub.InferenceClient.tabular_classification]]

```python
tabular_classification(table: dict, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1783)

**パラメータ:**

table (`dict[str, Any]`) : 分類する属性のセット。

model (`str`, *任意*) : 表形式分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される表形式分類モデルが使用されます。デフォルト値は None です。

**戻り値:** `List`

初期テーブルの各行に対応するラベルのリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

属性のセットに基づいてターゲットカテゴリ（グループ）を分類します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> table = {
...     "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"],
... }
>>> client.tabular_classification(table=table, model="julien-c/wine-quality")
["5", "5", "5"]
```

#### tabular_regression[[huggingface_hub.InferenceClient.tabular_regression]]

```python
tabular_regression(table: dict, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1838)

**パラメータ:**

table (`dict[str, Any]`) : テーブルに保存される属性のセットです。ターゲットを予測するために使用される属性は、数値型とカテゴリ型の両方を含むことができます。

model (`str`, *任意*) : 表形式の回帰タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される表形式の回帰モデルが使用されます。デフォルト値は None です。

**戻り値:** `List`

予測された数値ターゲット値のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

テーブル内の属性/特徴のセットが与えられたときに、数値のターゲット値を予測します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> table = {
...     "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"],
... }
>>> client.tabular_regression(table, model="scikit-learn/Fish-Weight")
[110, 120, 130]
```

#### text_classification[[huggingface_hub.InferenceClient.text_classification]]

```python
text_classification(text: str, model: str | None = None, top_k: int | None = None, function_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L1888)

**パラメータ:**

text (`str`) : 分類対象の文字列。

model (`str`, *任意*) : テキスト分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキスト分類モデルが使用されます。デフォルト値は None です。

top_k (`int`, *optional*) : 指定すると、出力が最も確率の高い上位K個のクラスに制限されます。

function_to_apply (`"TextClassificationOutputTransform"`, *任意*) : モデルの出力に適用してスコアを取得するための関数。

**戻り値:** `list[TextClassificationOutputElement]`

予測ラベルと関連する確率を含む[TextClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TextClassificationOutputElement)のリスト

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストに対してテキスト分類（例：感情分析）を実行します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.text_classification("I like you")
[
    TextClassificationOutputElement(label='POSITIVE', score=0.9998695850372314),
    TextClassificationOutputElement(label='NEGATIVE', score=0.0001304351753788069),
]
```

#### text_generation[[huggingface_hub.InferenceClient.text_generation]]

```python
text_generation(prompt: str, details: bool | None = None, stream: bool | None = None, model: str | None = None, adapter_id: str | None = None, best_of: int | None = None, decoder_input_details: bool | None = None, do_sample: bool | None = None, frequency_penalty: float | None = None, grammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = None, max_new_tokens: int | None = None, repetition_penalty: float | None = None, return_full_text: bool | None = None, seed: int | None = None, stop: list[str] | None = None, temperature: float | None = None, top_k: int | None = None, top_n_tokens: int | None = None, top_p: float | None = None, truncate: int | None = None, typical_p: float | None = None, watermark: bool | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2091)

**パラメータ:**

prompt (`str`) : 入力テキスト。

details (`bool`, *省略可能*) : デフォルトでは、text_generation は文字列を返します。詳細な出力（トークン、確率、シード、終了理由など）が必要な場合は、`details=True` を渡してください。`text-generation-inference` バックエンドで実行されているモデルでのみ利用可能です。

stream (`bool`, *任意*) : デフォルトでは、text_generation は生成されたテキスト全体を返します。トークンのストリームを返す場合は、`stream=True` を渡してください。`text-generation-inference` バックエンドで実行されているモデルでのみ利用可能です。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

adapter_id (`str`, *任意*) : Lora アダプター ID。

best_of (`int`, *optional*) : best_of 個のシーケンスを生成し、最も高いトークン logprobs を持つものを返します。

decoder_input_details (`bool`, *任意*) : デコーダー入力トークンの logprobs と id を返します。これを有効にするには、`details=True` も設定する必要があります。デフォルトは `False` です。

do_sample (`bool`, *任意*) : logits サンプリングを有効にします

frequency_penalty (`float`, *任意*) : -2.0から2.0の間の数値。正の値は、テキスト内でそれまでに出現した頻度に基づいて新しいトークンを減点し、モデルが同じ行をそのまま繰り返す可能性を低くします。

grammar ([TextGenerationInputGrammarType](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TextGenerationInputGrammarType)、*optional*) : 文法制約。JSONSchemaまたは正規表現のいずれかです。

max_new_tokens (`int`, *optional*) : 生成されるトークンの最大数。デフォルト値は100です。

repetition_penalty (`float`, *任意*) : 反復ペナルティのパラメータです。1.0 はペナルティなしを意味します。詳細は[この論文](https://arxiv.org/pdf/1909.05858.pdf)を参照してください。

return_full_text (`bool`, *任意*) : 生成テキストの先頭にプロンプトを付加するかどうか

seed (`int`, *任意*) : ランダムサンプリングのシード

stop (`list[str]`, *任意*) : `stop` のメンバーが生成された場合、トークンの生成を停止します。

temperature (`float`, *任意*) : logits の分布をモジュレートするために使用される値。

top_n_tokens (`int`, *任意*) : サンプルされたトークンのみではなく、各生成ステップにおいて最も確率の高い`top_n_tokens`個のトークンに関する情報を返します。

top_k (`int`, *optional`) : top-kフィルタリングのために保持する、確率の高い語彙トークンの数。

top_p (`float`, *optional`) : If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.

truncate (`int`, *optional`) : 入力トークンを指定されたサイズに切り詰めます。

typical_p (`float`, *optional`) : Typical Decoding の質量。詳細については、[Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666)を参照してください

watermark (`bool`, *任意*) : [大規模言語モデルのためのウォーターマーク](https://arxiv.org/abs/2301.10226) を用いたウォーターマーキング

**戻り値:** `Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]`

サーバーから返された生成テキスト:
- `stream=False`かつ`details=False`の場合、生成されたテキストは`str`として返されます（デフォルト）
- `stream=True`かつ`details=False`の場合、生成されたテキストは`Iterable[str]`としてトークン単位で返されます。
- `stream=False`かつ`details=True`の場合、生成されたテキストは[TextGenerationOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TextGenerationOutput)として、より詳細な情報とともに返されます。
- `details=True`かつ`stream=True`の場合、生成されたテキストは[TextGenerationStreamOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TextGenerationStreamOutput)のイテラブルとしてトークン単位で返されます。

**例外:** ``ValidationError`` または [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- ``ValidationError`` -- 入力値が有効でない場合。サーバーへのHTTP呼び出しは行われません。
- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

プロンプトが与えられた場合、以下のテキストを生成します。

> [!TIP]
> チャットメッセージから応答を生成したい場合は、[InferenceClient.chat_completion()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) メソッドを使用してください。このメソッドは、単一のテキストプロンプトの代わりにメッセージのリストを受け取り、チャットテンプレート処理を自動で行います。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()

# Case 1: generate text
>>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12)
'100% open source and built to be easy to use.'

# Case 2: iterate over the generated tokens. Useful for large generation.
>>> for token in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, stream=True):
...     print(token)
100
%
open
source
and
built
to
be
easy
to
use
.

# Case 3: get more details about the generation process.
>>> client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True)
TextGenerationOutput(
    generated_text='100% open source and built to be easy to use.',
    details=TextGenerationDetails(
        finish_reason='length',
        generated_tokens=12,
        seed=None,
        prefill=[
            TextGenerationPrefillOutputToken(id=487, text='The', logprob=None),
            TextGenerationPrefillOutputToken(id=53789, text=' hugging', logprob=-13.171875),
            (...)
            TextGenerationPrefillOutputToken(id=204, text=' ', logprob=-7.0390625)
        ],
        tokens=[
            TokenElement(id=1425, text='100', logprob=-1.0175781, special=False),
            TokenElement(id=16, text='%', logprob=-0.0463562, special=False),
            (...)
            TokenElement(id=25, text='.', logprob=-0.5703125, special=False)
        ],
        best_of_sequences=None
    )
)

# Case 4: iterate over the generated tokens with more details.
# Last object is more complete, containing the full generated text and the finish reason.
>>> for details in client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True, stream=True):
...     print(details)
...
TextGenerationStreamOutput(token=TokenElement(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(
    id=25,
    text='.',
    logprob=-0.5703125,
    special=False),
    generated_text='100% open source and built to be easy to use.',
    details=TextGenerationStreamOutputStreamDetails(finish_reason='length', generated_tokens=12, seed=None)
)

# Case 5: generate constrained output using grammar
>>> response = client.text_generation(
...     prompt="I saw a puppy a cat and a raccoon during my bike ride in the park",
...     model="HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1",
...     max_new_tokens=100,
...     repetition_penalty=1.3,
...     grammar={
...         "type": "json",
...         "value": {
...             "properties": {
...                 "location": {"type": "string"},
...                 "activity": {"type": "string"},
...                 "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
...                 "animals": {"type": "array", "items": {"type": "string"}},
...             },
...             "required": ["location", "activity", "animals_seen", "animals"],
...         },
...     },
... )
>>> json.loads(response)
{
    "activity": "bike riding",
    "animals": ["puppy", "cat", "raccoon"],
    "animals_seen": 3,
    "location": "park"
}
```

#### text_to_image[[huggingface_hub.InferenceClient.text_to_image]]

```python
text_to_image(prompt: str, negative_prompt: str | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, model: str | None = None, scheduler: str | None = None, seed: int | None = None, extra_body: dict[str, typing.Any] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2418)

**パラメータ:**

prompt (`str`) : 画像を生成するためのプロンプト。

negative_prompt (`str`, *任意*) : 画像生成に含めるべきでない内容を指示するプロンプト。

height (`int`, *任意*) : 出力画像のピクセル単位の縦幅

width (`int`, *任意*) : 出力画像の幅（ピクセル単位）

num_inference_steps (`int`, *optional*) : デノイジングのステップ数です。デノイジングのステップ数が多いほど、推論速度が遅くなる代わりに、より高品質な画像が得られる傾向があります。

guidance_scale (`float`, *任意*) : ガイダンススケールの値を高くすると、モデルはテキストプロンプトと密接に関連した画像を生成するよう促されますが、値が高すぎると飽和やその他のアーティファクトが発生する可能性があります。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキストから画像生成へのモデルが使用されます。デフォルト値は None です。

scheduler (`str`, *任意*) : スケジューラを互換性のあるものに上書きします。

seed (`int`, *任意*) : 乱数生成器のシード。

extra_body (`dict[str, Any]`, *省略可能*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** `Image`

生成された画像。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられたテキストに基づいて画像を生成します。

> [!WARNING]
> 画像を扱うには、`PIL`のインストールが必要です（`pip install Pillow`）。

> [!TIP]
> `extra_body` 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()

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

>>> image = client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     negative_prompt="low resolution, blurry",
...     model="stabilityai/stable-diffusion-2-1",
... )
>>> image.save("better_astronaut.png")
```

サードパーティプロバイダーを直接使用する例。利用料はfal.aiアカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="fal-ai",  # Use fal.ai provider
...     api_key="fal-ai-api-key",  # Pass your fal.ai API key
... )
>>> image = client.text_to_image(
...     "A majestic lion in a fantasy forest",
...     model="black-forest-labs/FLUX.1-schnell",
... )
>>> image.save("lion.png")
```

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Use replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> image = client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     model="black-forest-labs/FLUX.1-dev",
... )
>>> image.save("astronaut.png")
```

Replicateプロバイダーを、追加パラメータ付きで使用する例

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Use replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> image = client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     model="black-forest-labs/FLUX.1-schnell",
...     extra_body={"output_quality": 100},
... )
>>> image.save("astronaut.png")
```

#### text_to_speech[[huggingface_hub.InferenceClient.text_to_speech]]

```python
text_to_speech(text: str, model: str | None = None, do_sample: bool | None = None, early_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None, extra_body: dict[str, typing.Any] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2655)

**パラメータ:**

text (`str`) : 合成するテキスト。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキスト読み上げモデルが使用されます。デフォルト値は None です。

do_sample (`bool`, *任意*) : 新しいトークンを生成する際に、グリーディーデコーディングではなくサンプリングを使用するかどうか。

early_stopping (`Union[bool, "TextToSpeechEarlyStoppingEnum"]`, *任意*) : ビームベースの手法における停止条件を制御します。

epsilon_cutoff (`float`, *任意*) : 0 と 1 の間の float 値に設定すると、条件付き確率が epsilon_cutoff より大きいトークンのみがサンプリングされます。論文では、モデルのサイズに応じて推奨値は 3e-4 から 9e-4 の範囲とされています。詳細は [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) を参照してください。

eta_cutoff (`float`, *任意*) : Eta サンプリングは、ローカル・ティピカル・サンプリングとエプシロン・サンプリングのハイブリッドです。0 と 1 の間の float 値に設定すると、トークンは eta_cutoff または sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))) のいずれかよりも大きい場合にのみ考慮されます。後者の項は、sqrt(eta_cutoff) によってスケーリングされた、次のトークンの期待確率と直感的に解釈できます。論文では、モデルのサイズに応じて、推奨値は 3e-4 から 2e-3 の範囲とされています。詳細については、[Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191)を参照してください。

max_length (`int`, *任意*) : 入力を含む生成テキストの最大長（トークン数）。

max_new_tokens (`int`, *optional*) : 生成するトークンの最大数。max_length より優先されます。

min_length (`int`, *任意*) : 生成テキストの最小長（トークン数）。入力を含みます。

min_new_tokens (`int`, *optional*) : 生成するトークンの最小数。min_length より優先されます。

num_beam_groups (`int`, *任意*) : ビームの多様性を確保するために、num_beams を分割するグループ数。詳細は[この論文](https://hf.co/papers/1610.02424)を参照してください。

num_beams (`int`, *任意*) : ビームサーチに使用するビームの数。

penalty_alpha (`float`, *任意*) : contrastive search によるデコーディングにおいて、モデルの信頼度と退化ペナルティのバランスを調整する値です。

temperature (`float`, *任意*) : 次のトークンの確率を調整するために使用される値。

top_k (`int`, *optional*) : top-kフィルタリングのために保持する、最も確率の高い語彙トークンの数。

top_p (`float`, *optional*) : float < 1 に設定すると、生成には、確率が top_p 以上になる最小のトークンセットのみが保持されます。

typical_p (`float`, *任意*) : Local typicality は、すでに生成された部分テキストが与えられた条件下で、次のターゲットトークンを予測する条件付き確率が、次のランダムなトークンを予測する期待される条件付き確率とどれだけ類似しているかを測定します。float < 1 に設定すると、確率の合計が typical_p 以上となる最も局所的に典型的なトークンの最小集合が生成のために保持されます。詳細は[この論文](https://hf.co/papers/2202.00666)を参照してください。

use_cache (`bool`, *任意*) : モデルがデコードを高速化するために、過去の最後のキー/バリューアテンションを使用すべきかどうか

extra_body (`dict[str, Any]`, *省略可能*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** `bytes`

生成されたオーディオ。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたテキストを発音する音声のオーディオを合成します。

> [!TIP]
> `extra_body` 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:
```py
>>> from pathlib import Path
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()

>>> audio = client.text_to_speech("Hello world")
>>> Path("hello_world.flac").write_bytes(audio)
```

サードパーティプロバイダーを直接使用する例。使用料はあなたのReplicateアカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",
...     api_key="your-replicate-api-key",  # Pass your Replicate API key directly
... )
>>> audio = client.text_to_speech(
...     text="Hello world",
...     model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
```

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",
...     api_key="hf_...",  # Pass your HF token
... )
>>> audio =client.text_to_speech(
...     text="Hello world",
...     model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
```

Replicateプロバイダーを、追加パラメータ付きで使用する例

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Use replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> audio = client.text_to_speech(
...     "Hello, my name is Kororo, an awesome text-to-speech model.",
...     model="hexgrad/Kokoro-82M",
...     extra_body={"voice": "af_nicole"},
... )
>>> Path("hello.flac").write_bytes(audio)
```

fal.ai上で"YuE-s1-7B-anneal-en-cot"を使用した音楽生成の例

```py
>>> from huggingface_hub import InferenceClient
>>> lyrics = '''
... [verse]
... In the town where I was born
... Lived a man who sailed to sea
... And he told us of his life
... In the land of submarines
... So we sailed on to the sun
... 'Til we found a sea of green
... And we lived beneath the waves
... In our yellow submarine

... [chorus]
... We all live in a yellow submarine
... Yellow submarine, yellow submarine
... We all live in a yellow submarine
... Yellow submarine, yellow submarine
... '''
>>> genres = "pavarotti-style tenor voice"
>>> client = InferenceClient(
...     provider="fal-ai",
...     model="m-a-p/YuE-s1-7B-anneal-en-cot",
...     api_key=...,
... )
>>> audio = client.text_to_speech(lyrics, extra_body={"genres": genres})
>>> with open("output.mp3", "wb") as f:
...     f.write(audio)
```

#### text_to_video[[huggingface_hub.InferenceClient.text_to_video]]

```python
text_to_video(prompt: str, model: str | None = None, guidance_scale: float | None = None, negative_prompt: list[str] | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, seed: int | None = None, extra_body: dict[str, typing.Any] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2558)

**パラメータ:**

prompt (`str`) : 動画の生成に使用するプロンプト。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキストから動画生成へのモデルが使用されます。デフォルト値は None です。

guidance_scale (`float`, *任意*) : ガイダンススケールの値を高くすると、モデルはテキストプロンプトと密接に関連した動画を生成するよう促されますが、値が高すぎると飽和やその他のアーティファクトが発生する可能性があります。

negative_prompt (`list[str]`、*任意*) : 動画生成に含めるべきでない内容を指示するプロンプトを1つ以上指定します。

num_frames (`float`, *任意*) : num_frames パラメータは、生成される動画フレームの数を決定します。

num_inference_steps (`int`, *optional*) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。

seed (`int`, *任意*) : 乱数生成器のシード。

extra_body (`dict[str, Any]`, *省略可能*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** `bytes`

生成された動画。

与えられたテキストに基づいて動画を生成します。

> [!TIP]
> `extra_body` 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

サードパーティプロバイダーを直接使用する例。利用料はfal.aiアカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="fal-ai",  # Using fal.ai provider
...     api_key="fal-ai-api-key",  # Pass your fal.ai API key
... )
>>> video = client.text_to_video(
...     "A majestic lion running in a fantasy forest",
...     model="tencent/HunyuanVideo",
... )
>>> with open("lion.mp4", "wb") as file:
...     file.write(video)
```

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Using replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> video = client.text_to_video(
...     "A cat running in a park",
...     model="genmo/mochi-1-preview",
... )
>>> with open("cat.mp4", "wb") as file:
...     file.write(video)
```

#### token_classification[[huggingface_hub.InferenceClient.token_classification]]

```python
token_classification(text: str, model: str | None = None, aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None, ignore_labels: list[str] | None = None, stride: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2863)

**パラメータ:**

text (`str`) : 分類対象の文字列。

model (`str`, *任意*) : トークン分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるトークン分類モデルが使用されます。デフォルト値は None です。

aggregation_strategy (`"TokenClassificationAggregationStrategy"`, *任意*) : モデルの予測に基づいてトークンを融合するために使用される戦略

ignore_labels (`list[str`, *optional*) : 無視するラベルのリスト

stride (`int`, *任意*) : 入力テキストを分割する際に、チャンク間で重複するトークンの数。

**戻り値:** `list[TokenClassificationOutputElement]`

エンティティグループ、信頼度スコア、単語、開始および終了インデックスを含む[TokenClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TokenClassificationOutputElement)の項目のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストに対してトークン分類を実行します。文の解析（文法的な解析または）に通常使用され、テキストに含まれるキーワードを理解するために用いられます。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica")
[
    TokenClassificationOutputElement(
        entity_group='PER',
        score=0.9971321225166321,
        word='Sarah Jessica Parker',
        start=11,
        end=31,
    ),
    TokenClassificationOutputElement(
        entity_group='PER',
        score=0.9773476123809814,
        word='Jessica',
        start=52,
        end=59,
    )
]
```

#### 翻訳[[huggingface_hub.InferenceClient.translation]]

```python
translation(text: str, model: str | None = None, src_lang: str | None = None, tgt_lang: str | None = None, clean_up_tokenization_spaces: bool | None = None, truncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = None, generate_parameters: dict[str, typing.Any] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L2938)

**パラメータ:**

text (`str`) : 翻訳対象の文字列。

model (`str`, *任意*) : 翻訳タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される翻訳モデルが使用されます。デフォルト値は None です。

src_lang (`str`, *任意*) : テキストのソース言語です。複数言語からの翻訳に対応するモデルでは必須です。

tgt_lang (`str`, *任意*) : 翻訳先のターゲット言語。複数の言語への翻訳に対応するモデルでは必須です。

clean_up_tokenization_spaces (`bool`, *任意*) : テキスト出力に含まれる可能性のある余分なスペースをクリーンアップするかどうか。

truncation (`"TranslationTruncationStrategy"`, *任意*) : 使用する切り詰め戦略。

generate_parameters (`dict[str, Any]`、*任意*) : テキスト生成アルゴリズムの追加のパラメータ設定。

**戻り値:** [TranslationOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TranslationOutput)

生成された翻訳テキスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError` または ``ValueError``

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。
- ``ValueError`` -- `src_lang` と `tgt_lang` の引数のうち、片方だけが提供された場合。

テキストをある言語から別の言語に変換します。

特定のユースケースに最適なモデルの選び方については、https://huggingface.co/tasks/translation をご覧ください。ソース言語とターゲット言語は通常、モデルによって決まります。ただし、一部のモデルではソース言語とターゲット言語を指定できます。これらのモデルを使用している場合は、`src_lang` と `tgt_lang` 引数を使って、該当する情報を渡すことができます。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.translation("My name is Wolfgang and I live in Berlin")
'Mein Name ist Wolfgang und ich lebe in Berlin.'
>>> client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr")
TranslationOutput(translation_text='Je m'appelle Wolfgang et je vis à Berlin.')
```

言語の指定:
```py
>>> client.translation("My name is Sarah Jessica Parker but you can call me Jessica", model="facebook/mbart-large-50-many-to-many-mmt", src_lang="en_XX", tgt_lang="fr_XX")
"Mon nom est Sarah Jessica Parker mais vous pouvez m'appeler Jessica"
```

#### visual_question_answering[[huggingface_hub.InferenceClient.visual_question_answering]]

```python
visual_question_answering(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, model: str | None = None, top_k: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3027)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : コンテキスト用の入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。

question (`str`) : 回答する質問。

model (`str`, *任意*) : 視覚的質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される視覚的質問応答モデルが使用されます。デフォルト値は None です。

top_k (`int`, *optional*) : 返す回答の数（可能性の高い順に選択されます）。コンテキスト内に十分な選択肢がない場合、topk より少ない数の回答が返されます。

**戻り値:** `list[VisualQuestionAnsweringOutputElement]`

予測ラベルと関連する確率を含む[VisualQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.VisualQuestionAnsweringOutputElement)のリスト

**例外:** ``InferenceTimeoutError`` または `HfHubHTTPError`

- ``InferenceTimeoutError`` -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

画像に基づいてオープンエンドな質問に答える。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.visual_question_answering(
...     image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg",
...     question="What is the animal doing?"
... )
[
    VisualQuestionAnsweringOutputElement(score=0.778609573841095, answer='laying down'),
    VisualQuestionAnsweringOutputElement(score=0.6957435607910156, answer='sitting'),
]
```

#### zero_shot_classification[[huggingface_hub.InferenceClient.zero_shot_classification]]

```python
zero_shot_classification(text: str, candidate_labels: list, multi_label: bool | None = False, hypothesis_template: str | None = None, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3086)

**パラメータ:**

text (`str`) : 分類する入力テキスト。

candidate_labels (`list[str]`) : テキストを分類するための、可能なクラスラベルの集合。

multi_label (`bool`, *任意*) : 複数の候補ラベルが同時に真になり得るかどうか。false の場合、各シーケンスにおけるラベルの尤度の和が 1 になるようにスコアが正規化されます。true の場合、ラベルは独立であるとみなされ、各候補ごとに確率が正規化されます。

hypothesis_template (`str`, *任意*) : `candidate_labels` と組み合わせてテキスト分類を試みるために使用される文。プレースホルダーを候補ラベルに置き換えます。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。指定しない場合、デフォルトで推奨されるゼロショット分類モデルが使用されます。

**戻り値:** `list[ZeroShotClassificationOutputElement]`

予測ラベルとその信頼度を含む[ZeroShotClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ZeroShotClassificationOutputElement)のリストです。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力としてテキストと、そのテキストを分類するための候補ラベルのセットを指定します。

`multi_label=False`の例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> text = (
...     "A new model offers an explanation for how the Galilean satellites formed around the solar system's"
...     "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling"
...     " mysteries when he went for a run up a hill in Nice, France."
... )
>>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"]
>>> client.zero_shot_classification(text, labels)
[
    ZeroShotClassificationOutputElement(label='scientific discovery', score=0.7961668968200684),
    ZeroShotClassificationOutputElement(label='space & cosmos', score=0.18570658564567566),
    ZeroShotClassificationOutputElement(label='microbiology', score=0.00730885099619627),
    ZeroShotClassificationOutputElement(label='archeology', score=0.006258360575884581),
    ZeroShotClassificationOutputElement(label='robots', score=0.004559356719255447),
]
>>> client.zero_shot_classification(text, labels, multi_label=True)
[
    ZeroShotClassificationOutputElement(label='scientific discovery', score=0.9829297661781311),
    ZeroShotClassificationOutputElement(label='space & cosmos', score=0.755190908908844),
    ZeroShotClassificationOutputElement(label='microbiology', score=0.0005462635890580714),
    ZeroShotClassificationOutputElement(label='archeology', score=0.00047131875180639327),
    ZeroShotClassificationOutputElement(label='robots', score=0.00030448526376858354),
]
```

`multi_label=True`とカスタムの`hypothesis_template`を用いた例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.zero_shot_classification(
...    text="I really like our dinner and I'm very happy. I don't like the weather though.",
...    candidate_labels=["positive", "negative", "pessimistic", "optimistic"],
...    multi_label=True,
...    hypothesis_template="This text is {} towards the weather"
... )
[
    ZeroShotClassificationOutputElement(label='negative', score=0.9231801629066467),
    ZeroShotClassificationOutputElement(label='pessimistic', score=0.8760990500450134),
    ZeroShotClassificationOutputElement(label='optimistic', score=0.0008674879791215062),
    ZeroShotClassificationOutputElement(label='positive', score=0.0005250611575320363)
]
```

#### zero_shot_image_classification[[huggingface_hub.InferenceClient.zero_shot_image_classification]]

```python
zero_shot_image_classification(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], candidate_labels: list, model: str | None = None, hypothesis_template: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_client.py#L3187)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : キャプションを付与する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageのいずれかです。

candidate_labels (`list[str]`) : この画像の候補ラベル

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。指定しない場合、デフォルトで推奨されるゼロショット画像分類モデルが使用されます。

hypothesis_template (`str`, *任意*) : `candidate_labels` と組み合わせて画像分類を試みる際に使用される文。プレースホルダーを候補ラベルに置き換えます。

**戻り値:** `list[ZeroShotImageClassificationOutputElement]`

予測ラベルとその信頼度を含む[ZeroShotImageClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ZeroShotImageClassificationOutputElement)のリストです。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力画像とテキストラベルを指定して、画像のテキストラベルを予測します。

例:
```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()

>>> client.zero_shot_image_classification(
...     "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg",
...     candidate_labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]
```

## 非同期推論クライアント[[huggingface_hub.AsyncInferenceClient]]

`asyncio`と`httpx2`をベースとした、クライアントの非同期バージョンも提供されています。

#### huggingface_hub.AsyncInferenceClient[[huggingface_hub.AsyncInferenceClient]]

```python
huggingface_hub.AsyncInferenceClient(model: str | None = None, provider: typing.Union[typing.Literal['baseten', 'cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], typing.Literal['auto'], NoneType] = None, token: str | None = None, timeout: float | None = None, headers: dict[str, str] | None = None, cookies: dict[str, str] | None = None, bill_to: str | None = None, base_url: str | None = None, api_key: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L112)

**パラメータ:**

model (`str`, `optional`) : 推論を実行するモデル。Hugging Face Hub にホストされているモデル ID (例: `meta-llama/Meta-Llama-3-8B-Instruct`) またはデプロイされた Inference Endpoint の URL を指定できます。デフォルトは None で、この場合、タスクに適した推奨モデルが自動的に選択されます。注: OpenAI のクライアントとの互換性を高めるため、`model` は `base_url` としてエイリアス化されています。これら 2 つの引数は排他的です。チャット補完のために `model` または `base_url` として URL が渡された場合、その URL に `(/v1)/chat/completions` というサフィックスパスが追加されます。

provider (`str`, *任意*) : 推論に使用するプロバイダーの名前。`"baseten"`、`"cerebras"`、`"cohere"`、`"deepinfra"`、`"fal-ai"`、`"featherless-ai"`、`"fireworks-ai"`、`"groq"`、`"hf-inference"`、`"novita"`、`"nscale"`、`"openai"`、`"ovhcloud"`、`"publicai"`、`"replicate"`、`"scaleway"`、`"together"`、`"wavespeed"`、または`"zai-org"`のいずれかです。デフォルトは "auto" です。自動ルーティングを行い、デフォルトでは "fastest" プロバイダーが選択されます。https://hf.co/settings/inference-providers で "cheapest" または "preferred" のプロバイダー順序に切り替えることができます。model が URL の場合、または `base_url` が渡された場合、`provider` は使用されません。

token (`str`, *任意*) : Hugging Face トークン。指定しない場合、ローカルに保存されたトークンがデフォルトで使用されます。なお、OpenAI のクライアントとの互換性を高めるため、`token` は `api_key` としてエイリアス化されています。これら 2 つの引数は排他的であり、動作は完全に同一です。

timeout (`float`, `optional`) : サーバーからの応答を待機する最大秒数。デフォルトは None で、サーバーが利用可能になるまでループし続けます。

headers (`dict[str, str]`、`optional`) : サーバーに送信する追加のヘッダー。デフォルトでは、authorization ヘッダーと user-agent ヘッダーのみが送信されます。この辞書の値は、デフォルトの値を上書きします。

bill_to (`str`, `optional`) : リクエストに使用する請求アカウント。デフォルトでは、リクエストはユーザーのアカウントで請求されます。リクエストは、ユーザーがメンバーであり、かつ Enterprise Hub に加入している組織にのみ請求できます。

cookies (`dict[str, str]`、`optional`) : サーバーに送信する追加のクッキー。

base_url (`str`, `optional`) : 推論を実行するためのベースURLです。`model`からの重複引数であり、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)が`openai.OpenAI`クライアントと同じパターンに従うようにするためのものです。`model`が設定されている場合は使用できません。デフォルト値はNoneです。

api_key (`str`, `optional`) : 認証に使用するトークン。`token`からの重複引数であり、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)が`openai.OpenAI`クライアントと同じパターンに従うようにするためのものです。`token`が設定されている場合は使用できません。デフォルトはNoneです。

新しいInference Clientを初期化します。

[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient)は、推論の実行に統一された体験を提供することを目的としています。このクライアントは、（無料の）Inference API、セルフホストされたInference Endpoints、またはサードパーティのInference Providersのいずれともシームレスに使用できます。

#### audio_classification[[huggingface_hub.AsyncInferenceClient.audio_classification]]

```python
audio_classification(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, top_k: int | None = None, function_to_apply: typing.Optional[ForwardRef('AudioClassificationOutputTransform')] = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L313)

**パラメータ:**

audio (Union[str, Path, bytes, BinaryIO]) : 分類対象のオーディオコンテンツ。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。

model (`str`, *任意*) : 音声分類に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、音声分類用のデフォルトの推奨モデルが使用されます。

top_k (`int`, *optional*) : 指定すると、出力が最も確率の高い上位K個のクラスに制限されます。

function_to_apply (`"AudioClassificationOutputTransform"`, *任意*) : モデルの出力に適用してスコアを取得するための関数。

**戻り値:** `list[AudioClassificationOutputElement]`

予測ラベルとその信頼度を含む[AudioClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.AudioClassificationOutputElement)の項目のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

提供された音声コンテンツに対して音声分類を実行します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.audio_classification("audio.flac")
[
    AudioClassificationOutputElement(score=0.4976358711719513, label='hap'),
    AudioClassificationOutputElement(score=0.3677836060523987, label='neu'),
    ...
]
```

#### audio_to_audio[[huggingface_hub.AsyncInferenceClient.audio_to_audio]]

```python
audio_to_audio(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L371)

**パラメータ:**

audio (Union[str, Path, bytes, BinaryIO]) : モデル用の音声コンテンツ。生の音声バイト、ローカルの音声ファイル、または音声ファイルを指すURLのいずれかです。

model (`str`, *任意*) : モデルは、音声ファイルを受け取り、別の音声ファイルを返す任意のモデルです。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、audio_to_audio のデフォルトで推奨されるモデルが使用されます。

**戻り値:** `list[AudioToAudioOutputElement]`

オーディオのラベル、コンテンツタイプ、およびブロブ形式のオーディオコンテンツを含む[AudioToAudioOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.AudioToAudioOutputElement)の項目のリスト。

**例外:** ``InferenceTimeoutError`` または `HfHubHTTPError`

- ``InferenceTimeoutError`` -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

モデルに応じて、音声から音声への変換に関連する複数のタスクを実行します（例：音声の品質向上、ソース分離）。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> audio_output = await client.audio_to_audio("audio.flac")
>>> async for i, item in enumerate(audio_output):
>>>     with open(f"output_{i}.flac", "wb") as f:
            f.write(item.blob)
```

#### automatic_speech_recognition[[huggingface_hub.AsyncInferenceClient.automatic_speech_recognition]]

```python
automatic_speech_recognition(audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, extra_body: dict | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L424)

**パラメータ:**

audio (Union[str, Path, bytes, BinaryIO]) : 文字起こしする内容。生のオーディオバイト、ローカルのオーディオファイル、またはオーディオファイルへのURLを指定できます。

model (`str`, *任意*) : ASRに使用するモデル。Hugging Face HubにホストされているモデルID、またはデプロイされたInference EndpointのURLを指定できます。指定しない場合、ASR用のデフォルトの推奨モデルが使用されます。

extra_body (`dict`, *任意*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** [AutomaticSpeechRecognitionOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.AutomaticSpeechRecognitionOutput)

転写テキストと、任意のタイムスタンプチャンクを含むアイテム。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられた音声コンテンツに対して、自動音声認識（ASRまたは音声からテキストへの変換）を実行します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.automatic_speech_recognition("hello_world.flac").text
"hello world"
```

#### chat_completion[[huggingface_hub.AsyncInferenceClient.chat_completion]]

```python
chat_completion(messages: list, model: str | None = None, stream: bool = False, frequency_penalty: float | None = None, logit_bias: list[float] | None = None, logprobs: bool | None = None, max_tokens: int | None = None, n: int | None = None, presence_penalty: float | None = None, response_format: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatText, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONSchema, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONObject, NoneType] = None, seed: int | None = None, stop: list[str] | None = None, stream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = None, temperature: float | None = None, tool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None, tool_prompt: str | None = None, tools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = None, top_logprobs: int | None = None, top_p: float | None = None, extra_body: dict | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L552)

**パラメータ:**

messages ([ChatCompletionInputMessage](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionInputMessage) のリスト) : ロールとコンテンツのペアで構成される会話履歴。

model (`str`, *任意*) : チャット補完に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、チャットベースのテキスト生成用のデフォルト推奨モデルが使用されます。詳細は https://huggingface.co/tasks/text-generation を参照してください。`model` がモデル ID の場合、`model` パラメータとしてサーバーに渡されます。リクエストペイロードで `model` を設定しながらカスタム URL を定義したい場合は、[InferenceClient](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient) を初期化する際に `base_url` を設定する必要があります。

frequency_penalty (`float`, *optional*) : これまでのテキストにおけるトークンの出現頻度に基づいて、新しいトークンをペナルティします。範囲: [-2.0, 2.0]。デフォルト値は 0.0 です。

logit_bias (`list[float]`, *任意*) : 生成された出力に特定のトークンが出現する可能性を調整します。

logprobs (`bool`, *任意*) : 出力トークンの対数確率を返すかどうかを指定します。true の場合、メッセージの content に返される各出力トークンの対数確率が返されます。

max_tokens (`int`, *optional*) : 応答で許可されるトークンの最大数。デフォルト値は100です。

n (`int`, *optional*) : 各プロンプトに対して生成する補完の数。

presence_penalty (`float`, *任意*) : -2.0から2.0の間の数値。正の値は、それまでのテキストにトークンが出現しているかどうかに基づいて新しいトークンをペナルティし、モデルが新しい話題について話す可能性を高めます。

response_format (`ChatCompletionInputGrammarType()`、*任意*) : 文法制約。JSONSchema または正規表現のいずれかです。

seed （任意`int`、*optional*）：再現可能な制御フローのためのシード。デフォルトはNoneです。

stop (`list[str]`, *任意*) : レスポンスの終了をトリガーする最大4つの文字列です。デフォルトは None です。

stream (`bool`, *任意*) : 応答のリアルタイムストリーミングを有効にします。デフォルトは False です。

stream_options ([ChatCompletionInputStreamOptions](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionInputStreamOptions)、*任意*) : ストリーミング補完のオプション。

temperature (`float`, *optional*) : 生成のランダム性を制御します。値が低いほど、より予測可能な補完になります。範囲: [0, 2]。デフォルト値は 1.0 です。

top_logprobs (`int`, *optional*) : 各トークン位置で返す最尤トークンの数を0から5の範囲で指定する整数です。各トークンには対応する対数確率が付与されます。このパラメータを使用する場合は、logprobsをtrueに設定する必要があります。

top_p (`float`, *optional*) : 最も可能性の高い次の単語からサンプリングする割合。0から1の間でなければなりません。デフォルト値は1.0です。

tool_choice ([ChatCompletionInputToolChoiceClass](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionInputToolChoiceClass) または `ChatCompletionInputToolChoiceEnum()`、*任意*) : 補完に使用するツール。デフォルト値は "auto" です。

tool_prompt (`str`, *任意*) : ツールの前に追加されるプロンプト。

tools ([ChatCompletionInputTool](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionInputTool) のリスト、*任意*) : モデルが呼び出す可能性のあるツールのリストです。現在、ツールとしてサポートされているのは関数のみです。モデルが JSON 入力を生成できる関数のリストを指定するために使用します。

extra_body (`dict`, *任意*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** [ChatCompletionOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionOutput) または [ChatCompletionStreamOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionStreamOutput) のイテラブル

サーバーから返された生成テキスト:
- `stream=False`の場合、生成されたテキストは[ChatCompletionOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionOutput)として返されます（デフォルト）。
- `stream=True`の場合、生成されたテキストは[ChatCompletionStreamOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ChatCompletionStreamOutput)のシーケンスとして、トークンごとに返されます。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定された言語モデルを使用して会話を補完するためのメソッド。

> [!TIP]
> `client.chat_completion` メソッドは、OpenAI のクライアントとの互換性のために `client.chat.completions.create` としてエイリアス化されています。入力と出力は完全に同一であり、どちらの構文を使用しても同じ結果が得られます。OpenAI の互換性に関する詳細については、[推論ガイド](https://huggingface.co/docs/huggingface_hub/guides/inference#openai-compatibility)を参照してください。

> [!TIP]
> `extra_body` 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> await 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
    )
)
```

ストリーミングを使用した例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> async for token in await client.chat_completion(messages, max_tokens=10, stream=True):
...     print(token)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content='The', role='assistant'), index=0, finish_reason=None)], created=1710498504)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' capital', role='assistant'), index=0, finish_reason=None)], created=1710498504)
(...)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' may', role='assistant'), index=0, finish_reason=None)], created=1710498504)
```

OpenAIの構文を使用した例:
```py
# Must be run in an async context
# instead of `from openai import OpenAI`
from huggingface_hub import AsyncInferenceClient

# instead of `client = OpenAI(...)`
client = AsyncInferenceClient(
    base_url=...,
    api_key=...,
)

output = await 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)
```

サードパーティプロバイダーを直接使用し、追加の（プロバイダー固有の）パラメータを指定する例。利用料はTogether AIアカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="together",  # Use Together AI provider
...     api_key="<together_api_key>",  # Pass your Together API key directly
... )
>>> client.chat_completion(
...     model="meta-llama/Meta-Llama-3-8B-Instruct",
...     messages=[{"role": "user", "content": "What is the capital of France?"}],
...     extra_body={"safety_model": "Meta-Llama/Llama-Guard-7b"},
... )
```

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="novita",  # Use Novita provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> client.chat_completion(
...     model="meta-llama/Meta-Llama-3-8B-Instruct",
...     messages=[{"role": "user", "content": "What is the capital of France?"}],
... )
```

画像とテキストを入力として使用する例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient

# provide a remote URL
>>> image_url ="https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
# or a base64-encoded image
>>> image_path = "/path/to/image.jpeg"
>>> with open(image_path, "rb") as f:
...     base64_image = base64.b64encode(f.read()).decode("utf-8")
>>> image_url = f"data:image/jpeg;base64,{base64_image}"

>>> client = AsyncInferenceClient("meta-llama/Llama-3.2-11B-Vision-Instruct")
>>> output = await client.chat.completions.create(
...     messages=[
...         {
...             "role": "user",
...             "content": [
...                 {
...                     "type": "image_url",
...                     "image_url": {"url": image_url},
...                 },
...                 {
...                     "type": "text",
...                     "text": "Describe this image in one sentence.",
...                 },
...             ],
...         },
...     ],
... )
>>> output
The image depicts the iconic Statue of Liberty situated in New York Harbor, New York, on a clear day.
```

ツールを使用した例:
```py
# Must be run in an async context
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
...     {
...         "role": "system",
...         "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
...     },
...     {
...         "role": "user",
...         "content": "What's the weather like the next 3 days in San Francisco, CA?",
...     },
... ]
>>> tools = [
...     {
...         "type": "function",
...         "function": {
...             "name": "get_current_weather",
...             "description": "Get the current weather",
...             "parameters": {
...                 "type": "object",
...                 "properties": {
...                     "location": {
...                         "type": "string",
...                         "description": "The city and state, e.g. San Francisco, CA",
...                     },
...                     "format": {
...                         "type": "string",
...                         "enum": ["celsius", "fahrenheit"],
...                         "description": "The temperature unit to use. Infer this from the users location.",
...                     },
...                 },
...                 "required": ["location", "format"],
...             },
...         },
...     },
...     {
...         "type": "function",
...         "function": {
...             "name": "get_n_day_weather_forecast",
...             "description": "Get an N-day weather forecast",
...             "parameters": {
...                 "type": "object",
...                 "properties": {
...                     "location": {
...                         "type": "string",
...                         "description": "The city and state, e.g. San Francisco, CA",
...                     },
...                     "format": {
...                         "type": "string",
...                         "enum": ["celsius", "fahrenheit"],
...                         "description": "The temperature unit to use. Infer this from the users location.",
...                     },
...                     "num_days": {
...                         "type": "integer",
...                         "description": "The number of days to forecast",
...                     },
...                 },
...                 "required": ["location", "format", "num_days"],
...             },
...         },
...     },
... ]

>>> response = await client.chat_completion(
...     model="meta-llama/Meta-Llama-3-70B-Instruct",
...     messages=messages,
...     tools=tools,
...     tool_choice="auto",
...     max_tokens=500,
... )
>>> response.choices[0].message.tool_calls[0].function
ChatCompletionOutputFunctionDefinition(
    arguments={
        'location': 'San Francisco, CA',
        'format': 'fahrenheit',
        'num_days': 3
    },
    name='get_n_day_weather_forecast',
    description=None
)
```

response_format を使用した例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
...     {
...         "role": "user",
...         "content": "I saw a puppy a cat and a raccoon during my bike ride in the park. What did I see and when?",
...     },
... ]
>>> response_format = {
...     "type": "json",
...     "value": {
...         "properties": {
...             "location": {"type": "string"},
...             "activity": {"type": "string"},
...             "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
...             "animals": {"type": "array", "items": {"type": "string"}},
...         },
...         "required": ["location", "activity", "animals_seen", "animals"],
...     },
... }
>>> response = await client.chat_completion(
...     messages=messages,
...     response_format=response_format,
...     max_tokens=500,
... )
>>> response.choices[0].message.content
'{

y": "bike ride",
": ["puppy", "cat", "raccoon"],
_seen": 3,
n": "park"}'
```

#### 閉じる[[huggingface_hub.AsyncInferenceClient.close]]

```python
close()
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L226)

クライアントを閉じます。

このメソッドは、クライアントをコンテキストマネージャーとして使用する場合に自動的に呼び出されます。

#### document_question_answering[[huggingface_hub.AsyncInferenceClient.document_question_answering]]

```python
document_question_answering(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, model: str | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, lang: str | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None, word_boxes: list[list[float] | str] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L960)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO]`) : コンテキスト用の入力画像です。生のバイト列、画像ファイル、またはオンライン画像へのURLを指定できます。

question (`str`) : 回答する質問。

model (`str`, *任意*) : ドキュメント質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるドキュメント質問応答モデルが使用されます。デフォルト値は None です。

doc_stride (`int`, *optional*) : ドキュメント内の単語が長すぎて、モデルの質問と合わせて収まらない場合、いくつかのチャンクに分割され、一部が重複します。この引数は、その重複のサイズを制御します。

handle_impossible_answer (`bool`, *任意*) : 不可能を回答として受け入れるかどうか

lang (`str`, *任意*) : OCR実行時に使用する言語。デフォルトは英語です。

max_answer_len (`int`, *optional*) : 予測される回答の最大長（例：より短い長さの回答のみが考慮されます）。

max_question_len (`int`, *optional*) : トークナイズ後の質問の最大長です。必要に応じて切り詰められます。

max_seq_len (`int`, *optional*) : モデルに渡される各チャンクにおける、文全体（コンテキスト + 質問）の最大トークン数。必要に応じて、コンテキストは複数のチャンクに分割されます（重複として doc_stride を使用）。

top_k (`int`, *optional*) : 返す回答の数（可能性の高い順に選択されます）。コンテキスト内に十分な選択肢がない場合、top_k より少ない数の回答が返されることがあります。

word_boxes (`list[Union[list[float], str`, *optional*) : 単語とバウンディングボックス（正規化済み 0->1000）のリストです。指定された場合、推論は OCR ステップをスキップし、代わりに指定されたバウンディングボックスを使用します。

**戻り値:** `list[DocumentQuestionAnsweringOutputElement]`

予測ラベル、関連する確率、単語 ID、ページ番号を含む[DocumentQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.DocumentQuestionAnsweringOutputElement)のアイテムのリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

ドキュメントの画像に関する質問に回答します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?")
[DocumentQuestionAnsweringOutputElement(answer='us-001', end=16, score=0.9999666213989258, start=16)]
```

#### feature_extraction[[huggingface_hub.AsyncInferenceClient.feature_extraction]]

```python
feature_extraction(text: str | list[str], normalize: bool | None = None, prompt_name: str | None = None, truncate: bool | None = None, truncation_direction: typing.Optional[typing.Literal['left', 'right']] = None, dimensions: int | None = None, encoding_format: typing.Optional[typing.Literal['float', 'base64']] = None, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1048)

**パラメータ:**

text (*str* または *list[str]*) : 埋め込むテキストまたはテキストのリスト。

model (*str*, *optional*) : 特徴抽出タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される特徴抽出モデルが使用されます。デフォルト値は None です。

normalize (*bool*, *optional*) : 埋め込みを正規化するか否か。Text-Embedding-Inference によるサーバーでのみ利用可能です。

prompt_name (*str*, *optional*) : The name of the prompt that should be used by for encoding. If not set, no prompt will be applied. Must be a key in the *Sentence Transformers* configuration *prompts* dictionary. For example if `prompt_name` is "query" and the `prompts` is &amp;lcub;"query": "query: ",...}, then the sentence "What is the capital of France?" will be encoded as "query: What is the capital of France?" because the prompt text will be prepended before any text to encode.

truncate (*bool*, *optional*) : 埋め込みを切り詰めるかどうか。Text-Embedding-Inference によるサーバーでのみ利用可能です。

truncation_direction (*Literal["left", "right"]*, *optional*) : *truncate=True* が渡された場合、入力のどの側を切り詰めるかを指定します。

dimensions (*int*, *optional*) : 出力される埋め込みベクトルの次元数です。OpenAI互換の埋め込みエンドポイントでのみ利用可能です。

encoding_format (*Literal["float", "base64"]*, *optional*) : 出力埋め込みの形式です。"float"または"base64"のいずれかです。OpenAI互換の埋め込みエンドポイントでのみ利用可能です。

**戻り値:** `*np.ndarray*`

float32型のNumPy配列として入力テキストを表す埋め込み。

**例外:** [*InferenceTimeoutError*] または [*HfHubHTTPError*]

- [*InferenceTimeoutError*] -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- [*HfHubHTTPError*] -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたテキストまたはテキストのバッチに対して埋め込みを生成します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.feature_extraction("Hi, who are you?")
array([[ 2.424802  ,  2.93384   ,  1.1750331 , ...,  1.240499, -0.13776633, -0.7889173 ],
[-0.42943227, -0.6364878 , -1.693462  , ...,  0.41978157, -2.4336355 ,  0.6162071 ],
...,
[ 0.28552425, -0.928395  , -1.2077185 , ...,  0.76810825, -2.1069427 ,  0.6236161 ]], dtype=float32)
```

#### fill_mask[[huggingface_hub.AsyncInferenceClient.fill_mask]]

```python
fill_mask(text: str, model: str | None = None, targets: list[str] | None = None, top_k: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1132)

**パラメータ:**

text (`str`) : 埋め込む対象の文字列。[MASK] トークンを含む必要があります（マスクの正確な名称はモデルカードを確認してください）。

model (`str`, *任意*) : fill mask タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される fill mask モデルが使用されます。

targets (`list[str`, *optional*) : 指定された場合、モデルは語彙全体を検索するのではなく、指定されたターゲットにスコアを制限します。提供されたターゲットがモデルの語彙に存在しない場合、それらはトークン化され、結果として得られた最初のトークンが使用されます（警告が表示され、処理が遅くなる可能性があります）。

top_k (`int`, *optional*) : 指定すると、返す予測の数を上書きします。

**戻り値:** `list[FillMaskOutputElement]`

予測ラベル、関連する確率、トークン参照、および補完されたテキストを含む[FillMaskOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.FillMaskOutputElement)の項目のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

欠落した単語（正確にはトークン）で穴を埋めます。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.fill_mask("The goal of life is <mask>.")
[
    FillMaskOutputElement(score=0.06897063553333282, token=11098, token_str=' happiness', sequence='The goal of life is happiness.'),
    FillMaskOutputElement(score=0.06554922461509705, token=45075, token_str=' immortality', sequence='The goal of life is immortality.')
]
```

#### get_endpoint_info[[huggingface_hub.AsyncInferenceClient.get_endpoint_info]]

```python
get_endpoint_info(model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3302)

**パラメータ:**

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

**戻り値:** `dict[str, Any]`

エンドポイントに関する情報。

デプロイされたエンドポイントに関する情報を取得します。

このエンドポイントは、Text-Generation-Inference (TGI) または Text-Embedding-Inference (TEI) によって提供されるエンドポイントでのみ利用可能です。`transformers` によって提供されるエンドポイントは、空のペイロードを返します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> await client.get_endpoint_info()
{
    'model_id': 'meta-llama/Meta-Llama-3-70B-Instruct',
    'model_sha': None,
    'model_dtype': 'torch.float16',
    'model_device_type': 'cuda',
    'model_pipeline_tag': None,
    'max_concurrent_requests': 128,
    'max_best_of': 2,
    'max_stop_sequences': 4,
    'max_input_length': 8191,
    'max_total_tokens': 8192,
    'waiting_served_ratio': 0.3,
    'max_batch_total_tokens': 1259392,
    'max_waiting_tokens': 20,
    'max_batch_size': None,
    'validation_workers': 32,
    'max_client_batch_size': 4,
    'version': '2.0.2',
    'sha': 'dccab72549635c7eb5ddb17f43f0b7cdff07c214',
    'docker_label': 'sha-dccab72'
}
```

#### health_check[[huggingface_hub.AsyncInferenceClient.health_check]]

```python
health_check(model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3362)

**パラメータ:**

model (`str`, *任意*) : Inference Endpoint の URL。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

**戻り値:** `bool`

すべてが正常に動作している場合はTrue。

デプロイされたエンドポイントの健全性を確認します。

Health checkは、Text-Generation-Inference (TGI) または Text-Embedding-Inference (TEI) による Inference Endpoints のみで利用可能です。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient("https://jzgu0buei5.us-east-1.aws.endpoints.huggingface.cloud")
>>> await client.health_check()
True
```

#### image_classification[[huggingface_hub.AsyncInferenceClient.image_classification]]

```python
image_classification(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, function_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = None, top_k: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1189)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : 分類対象の画像です。生のバイト列、画像ファイル、オンライン画像のURL、またはPIL Imageを指定できます。

model (`str`, *任意*) : 画像分類に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、画像分類用のデフォルトの推奨モデルが使用されます。

function_to_apply (`"ImageClassificationOutputTransform"`, *任意*) : モデルの出力に適用してスコアを取得するための関数。

top_k (`int`, *optional*) : 指定すると、出力が最も確率の高い上位K個のクラスに制限されます。

**戻り値:** `list[ImageClassificationOutputElement]`

予測ラベルと関連する確率を含む[ImageClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ImageClassificationOutputElement)のリスト

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられた画像で画像分類を実行します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
[ImageClassificationOutputElement(label='Blenheim spaniel', score=0.9779096841812134), ...]
```

#### image_segmentation[[huggingface_hub.AsyncInferenceClient.image_segmentation]]

```python
image_segmentation(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, mask_threshold: float | None = None, overlap_mask_area_threshold: float | None = None, subtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = None, threshold: float | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1240)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : セグメント化対象の画像。生のバイト列、画像ファイル、オンライン画像のURL、またはPIL Imageを指定できます。

model (`str`, *任意*) : 画像セグメンテーションに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、画像セグメンテーション用のデフォルトの推奨モデルが使用されます。

mask_threshold (`float`, *任意*) : 予測されたマスクをバイナリ値に変換する際に使用するしきい値。

overlap_mask_area_threshold (`float`, *任意*) : 小さい、断片化されたセグメントを除去するためのマスク重複の閾値。

subtask (`"ImageSegmentationSubtask"`, *任意*) : モデルの機能に応じて実行されるセグメンテーションタスク。

threshold (`float`, *任意*) : 予測されたマスクをフィルタリングするための確率の閾値。

**戻り値:** `list[ImageSegmentationOutputElement]`

セグメンテーションされたマスクと関連する属性を含む、[ImageSegmentationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ImageSegmentationOutputElement) の項目のリストです。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられた画像に対して画像セグメンテーションを実行します。

> [!WARNING]
> 画像を扱うには、`PIL`のインストールが必要です（`pip install Pillow`）。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.image_segmentation("cat.jpg")
[ImageSegmentationOutputElement(score=0.989008, label='LABEL_184', mask=<PIL.PngImagePlugin.PngImageFile image mode=L size=400x300 at 0x7FDD2B129CC0>), ...]
```

#### image_to_image[[huggingface_hub.AsyncInferenceClient.image_to_image]]

```python
image_to_image(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], prompt: str | None = None, negative_prompt: str | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, model: str | None = None, target_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1309)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : 翻訳の入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。

prompt (`str`, *任意*) : 画像生成を導くためのテキストプロンプト。

negative_prompt (`str`, *任意*) : 画像生成に含めるべきでない内容を指示するプロンプト。

num_inference_steps (`int`, *optional*) : 拡散モデル用。デノイジングのステップ数です。デノイジングのステップ数が多いほど、推論速度が遅くなる代わりに、より高品質な画像が得られる傾向があります。

guidance_scale (`float`, *optional*) : 拡散モデル用です。guidance scale の値を高くすると、テキストプロンプトと密接に関連した画像を生成するようモデルに促されますが、その代わり画像の品質が低下します。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

target_size (`ImageToImageTargetSize`, *任意*) : 出力画像のピクセルサイズです。このパラメータは、一部のプロバイダーおよび特定のモデルでのみサポートされています。サポートされていない場合は無視されます。

**戻り値:** `Image`

変換された画像。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、画像から画像への翻訳を実行します。

> [!WARNING]
> 画像を扱うには、`PIL`のインストールが必要です（`pip install Pillow`）。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> image = await client.image_to_image("cat.jpg", prompt="turn the cat into a tiger")
>>> image.save("tiger.jpg")
```

#### image_to_text[[huggingface_hub.AsyncInferenceClient.image_to_text]]

```python
image_to_text(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1466)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : キャプションを付与する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageのいずれかです。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

**戻り値:** [ImageToTextOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ImageToTextOutput)

生成されたテキスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力画像を受け取り、テキストを返します。

モデルの出力は、ユースケース（画像キャプション生成、光学文字認識（OCR）、Pix2Struct など）によって大きく異なる場合があります。モデル固有の詳細については、モデルカードをご参照ください。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.image_to_text("cat.jpg")
'a cat standing in a grassy field '
>>> await client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
'a dog laying on the grass next to a flower pot '
```

#### image_to_video[[huggingface_hub.AsyncInferenceClient.image_to_video]]

```python
image_to_video(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, prompt: str | None = None, negative_prompt: str | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, seed: int | None = None, target_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1386)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : 動画の生成に使用する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

prompt (`str`, *任意*) : 動画生成をガイドするためのテキストプロンプト。

negative_prompt (`str`, *任意*) : 動画生成に含めるべきでない内容を指示するプロンプト。

num_frames (`float`, *任意*) : num_frames パラメータは、生成される動画フレームの数を決定します。

num_inference_steps (`int`, *optional*) : 拡散モデル用。デノイジングのステップ数です。デノイジングのステップ数が多いほど、推論速度が遅くなる代わりに、より高品質な画像が得られる傾向があります。

guidance_scale (`float`, *optional*) : 拡散モデル用です。guidance scale の値を高くすると、テキストプロンプトと密接に関連した動画を生成するようモデルを促しますが、画像の品質が低下する可能性があります。

seed (`int`, *optional*) : 動画生成に使用するシード。

target_size (`ImageToVideoTargetSize`, *任意*) : 出力される動画フレームのピクセルサイズ。

num_inference_steps (`int`, *optional*) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。

seed (`int`, *任意*) : 乱数生成器のシード。

**戻り値:** `bytes`

生成された動画。

入力画像から動画を生成します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> video = await client.image_to_video("cat.jpg", model="Wan-AI/Wan2.2-I2V-A14B", prompt="turn the cat into a tiger")
>>> with open("tiger.mp4", "wb") as f:
...     f.write(video)
```

#### object_detection[[huggingface_hub.AsyncInferenceClient.object_detection]]

```python
object_detection(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], model: str | None = None, threshold: float | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1513)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : 対象物の検出を行う画像です。生のバイト列、画像ファイル、オンライン画像のURL、またはPIL Imageを指定できます。

model (`str`, *任意*) : オブジェクト検出に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、オブジェクト検出のデフォルト推奨モデル (DETR) が使用されます。

threshold (`float`, *任意*) : 予測を行うために必要な確率。

**戻り値:** `list[ObjectDetectionOutputElement]`

バウンディングボックスと関連する属性を含む[ObjectDetectionOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ObjectDetectionOutputElement)の項目のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError` または ``ValueError``

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。
- ``ValueError`` -- リクエストの出力が List ではない場合。

指定されたモデルを使用して、与えられた画像で物体検出を実行します。

> [!WARNING]
> 画像を扱うには、`PIL`のインストールが必要です（`pip install Pillow`）。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.object_detection("people.jpg")
[ObjectDetectionOutputElement(score=0.9486683011054993, label='person', box=ObjectDetectionBoundingBox(xmin=59, ymin=39, xmax=420, ymax=510)), ...]
```

#### question_answering[[huggingface_hub.AsyncInferenceClient.question_answering]]

```python
question_answering(question: str, context: str, model: str | None = None, align_to_words: bool | None = None, doc_stride: int | None = None, handle_impossible_answer: bool | None = None, max_answer_len: int | None = None, max_question_len: int | None = None, max_seq_len: int | None = None, top_k: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1562)

**パラメータ:**

question (`str`) : 回答する質問。

context (`str`) : 質問のコンテキスト。

model (`str`) : 質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。

align_to_words (`bool`、*任意*) : 回答を実際の単語に整列させようとします。スペース区切り言語での品質を向上させます。スペースで区切られない言語（日本語や中国語など）では品質が低下する可能性があります。

doc_stride (`int`, *optional*) : モデルが質問とコンテキストを処理できないほどコンテキストが長い場合、コンテキストは重複を伴う複数のチャンクに分割されます。この引数は、その重複のサイズを制御します。

handle_impossible_answer (`bool`, *任意*) : 不可能を回答として受け入れるかどうか。

max_answer_len (`int`, *optional*) : 予測される回答の最大長（例：より短い長さの回答のみが考慮されます）。

max_question_len (`int`, *optional*) : トークナイズ後の質問の最大長です。必要に応じて切り詰められます。

max_seq_len (`int`, *optional*) : モデルに渡される各チャンクにおける、文全体（コンテキスト + 質問）の最大トークン数。必要に応じて、コンテキストは複数のチャンクに分割されます（重複として docStride を使用）。

top_k (`int`, *optional*) : 返す回答の数（可能性の高い順に選択されます）。コンテキスト内に十分な選択肢がない場合、topk より少ない数の回答が返されます。

**戻り値:** Union[`QuestionAnsweringOutputElement`, list[QuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.QuestionAnsweringOutputElement)]

top_k が 1 または指定されていない場合、単一の `QuestionAnsweringOutputElement` を返します。top_k が 1 より大きい場合、`QuestionAnsweringOutputElement` のリストを返します。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストから、質問に対する回答を取得します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.question_answering(question="What's my name?", context="My name is Clara and I live in Berkeley.")
QuestionAnsweringOutputElement(answer='Clara', end=16, score=0.9326565265655518, start=11)
```

#### sentence_similarity[[huggingface_hub.AsyncInferenceClient.sentence_similarity]]

```python
sentence_similarity(sentence: str, other_sentences: list, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1647)

**パラメータ:**

sentence (`str`) : 他と比較する主な文。

other_sentences (`list[str]`) : 比較対象となる文のリスト。

model (`str`, *任意*) : 文の類似度タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される文の類似度モデルが使用されます。デフォルト値は None です。

**戻り値:** `list[float]`

入力テキストを表す埋め込み。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

埋め込みを比較することにより、文と他の文のリストとの間の意味的類似度を計算します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.sentence_similarity(
...     "Machine learning is so easy.",
...     other_sentences=[
...         "Deep learning is so straightforward.",
...         "This is so difficult, like rocket science.",
...         "I can't believe how much I struggled with this.",
...     ],
... )
[0.7785726189613342, 0.45876261591911316, 0.2906220555305481]
```

#### 要約[[huggingface_hub.AsyncInferenceClient.summarization]]

```python
summarization(text: str, model: str | None = None, clean_up_tokenization_spaces: bool | None = None, generate_parameters: dict[str, typing.Any] | None = None, truncation: typing.Optional[ForwardRef('SummarizationTruncationStrategy')] = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1701)

**パラメータ:**

text (`str`) : 要約する対象のテキスト。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、要約用のデフォルト推奨モデルが使用されます。

clean_up_tokenization_spaces (`bool`, *任意*) : テキスト出力に含まれる可能性のある余分なスペースをクリーンアップするかどうか。

generate_parameters (`dict[str, Any]`、*任意*) : テキスト生成アルゴリズムの追加のパラメータ設定。

truncation (`"SummarizationTruncationStrategy"`, *任意*) : 使用する切り詰め戦略です。

**戻り値:** [SummarizationOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.SummarizationOutput)

生成された要約テキスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられたテキストの要約を生成します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.summarization("The Eiffel tower...")
SummarizationOutput(generated_text="The Eiffel tower is one of the most famous landmarks in the world....")
```

#### table_question_answering[[huggingface_hub.AsyncInferenceClient.table_question_answering]]

```python
table_question_answering(table: dict, query: str, model: str | None = None, padding: typing.Optional[ForwardRef('Padding')] = None, sequential: bool | None = None, truncation: bool | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1760)

**パラメータ:**

table (`str`) : 各エントリがヘッダー、リストがすべての値であるリストの辞書として表されたデータテーブル。すべてのリストは同じサイズでなければなりません。

query (`str`) : テーブルに尋ねたいクエリをプレーンテキストで表したものです。

model (`str`) : テーブル質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。

padding (`"Padding"`, *任意*) : パディングの有効化と制御を行います。

sequential (`bool`, *任意*) : 推論をシーケンシャルに実行するか、バッチとして実行するかどうか。バッチ処理は高速ですが、SQAのようなモデルは、その会話的な性質から、シーケンス内の関係を抽出するために、推論をシーケンシャルに実行する必要があります。

truncation (`bool`, *任意*) : トルンケーションを有効化し、制御します。

**戻り値:** [TableQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TableQuestionAnsweringOutputElement)

回答、座標、セル、および使用されたアグリゲーターを含むテーブル質問応答の出力

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

表に示された情報から、質問に対する答えを取得します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> query = "How many stars does the transformers repository have?"
>>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]}
>>> await client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq")
TableQuestionAnsweringOutputElement(answer='36542', coordinates=[[0, 1]], cells=['36542'], aggregator='AVERAGE')
```

#### tabular_classification[[huggingface_hub.AsyncInferenceClient.tabular_classification]]

```python
tabular_classification(table: dict, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1823)

**パラメータ:**

table (`dict[str, Any]`) : 分類する属性のセット。

model (`str`, *任意*) : 表形式分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される表形式分類モデルが使用されます。デフォルト値は None です。

**戻り値:** `List`

初期テーブルの各行に対応するラベルのリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

属性のセットに基づいてターゲットカテゴリ（グループ）を分類します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> table = {
...     "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"],
... }
>>> await client.tabular_classification(table=table, model="julien-c/wine-quality")
["5", "5", "5"]
```

#### tabular_regression[[huggingface_hub.AsyncInferenceClient.tabular_regression]]

```python
tabular_regression(table: dict, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1879)

**パラメータ:**

table (`dict[str, Any]`) : テーブルに保存される属性のセットです。ターゲットを予測するために使用される属性は、数値型とカテゴリ型の両方を含むことができます。

model (`str`, *任意*) : 表形式の回帰タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される表形式の回帰モデルが使用されます。デフォルト値は None です。

**戻り値:** `List`

予測された数値ターゲット値のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

テーブル内の属性/特徴のセットが与えられたときに、数値のターゲット値を予測します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> table = {
...     "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"],
... }
>>> await client.tabular_regression(table, model="scikit-learn/Fish-Weight")
[110, 120, 130]
```

#### text_classification[[huggingface_hub.AsyncInferenceClient.text_classification]]

```python
text_classification(text: str, model: str | None = None, top_k: int | None = None, function_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L1930)

**パラメータ:**

text (`str`) : 分類対象の文字列。

model (`str`, *任意*) : テキスト分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキスト分類モデルが使用されます。デフォルト値は None です。

top_k (`int`, *optional*) : 指定すると、出力が最も確率の高い上位K個のクラスに制限されます。

function_to_apply (`"TextClassificationOutputTransform"`, *任意*) : モデルの出力に適用してスコアを取得するための関数。

**戻り値:** `list[TextClassificationOutputElement]`

予測ラベルと関連する確率を含む[TextClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TextClassificationOutputElement)のリスト

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストに対してテキスト分類（例：感情分析）を実行します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.text_classification("I like you")
[
    TextClassificationOutputElement(label='POSITIVE', score=0.9998695850372314),
    TextClassificationOutputElement(label='NEGATIVE', score=0.0001304351753788069),
]
```

#### text_generation[[huggingface_hub.AsyncInferenceClient.text_generation]]

```python
text_generation(prompt: str, details: bool | None = None, stream: bool | None = None, model: str | None = None, adapter_id: str | None = None, best_of: int | None = None, decoder_input_details: bool | None = None, do_sample: bool | None = None, frequency_penalty: float | None = None, grammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = None, max_new_tokens: int | None = None, repetition_penalty: float | None = None, return_full_text: bool | None = None, seed: int | None = None, stop: list[str] | None = None, temperature: float | None = None, top_k: int | None = None, top_n_tokens: int | None = None, top_p: float | None = None, truncate: int | None = None, typical_p: float | None = None, watermark: bool | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2134)

**パラメータ:**

prompt (`str`) : 入力テキスト。

details (`bool`, *省略可能*) : デフォルトでは、text_generation は文字列を返します。詳細な出力（トークン、確率、シード、終了理由など）が必要な場合は、`details=True` を渡してください。`text-generation-inference` バックエンドで実行されているモデルでのみ利用可能です。

stream (`bool`, *任意*) : デフォルトでは、text_generation は生成されたテキスト全体を返します。トークンのストリームを返す場合は、`stream=True` を渡してください。`text-generation-inference` バックエンドで実行されているモデルでのみ利用可能です。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。デフォルト値は None です。

adapter_id (`str`, *任意*) : Lora アダプター ID。

best_of (`int`, *optional*) : best_of 個のシーケンスを生成し、最も高いトークン logprobs を持つものを返します。

decoder_input_details (`bool`, *任意*) : デコーダー入力トークンの logprobs と id を返します。これを有効にするには、`details=True` も設定する必要があります。デフォルトは `False` です。

do_sample (`bool`, *任意*) : logits サンプリングを有効にします

frequency_penalty (`float`, *任意*) : -2.0から2.0の間の数値。正の値は、テキスト内でそれまでに出現した頻度に基づいて新しいトークンを減点し、モデルが同じ行をそのまま繰り返す可能性を低くします。

grammar ([TextGenerationInputGrammarType](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TextGenerationInputGrammarType)、*optional*) : 文法制約。JSONSchemaまたは正規表現のいずれかです。

max_new_tokens (`int`, *optional*) : 生成されるトークンの最大数。デフォルト値は100です。

repetition_penalty (`float`, *任意*) : 反復ペナルティのパラメータです。1.0 はペナルティなしを意味します。詳細は[この論文](https://arxiv.org/pdf/1909.05858.pdf)を参照してください。

return_full_text (`bool`, *任意*) : 生成テキストの先頭にプロンプトを付加するかどうか

seed (`int`, *任意*) : ランダムサンプリングのシード

stop (`list[str]`, *任意*) : `stop` のメンバーが生成された場合、トークンの生成を停止します。

temperature (`float`, *任意*) : logits の分布をモジュレートするために使用される値。

top_n_tokens (`int`, *任意*) : サンプルされたトークンのみではなく、各生成ステップにおいて最も確率の高い`top_n_tokens`個のトークンに関する情報を返します。

top_k (`int`, *optional`) : top-kフィルタリングのために保持する、確率の高い語彙トークンの数。

top_p (`float`, *optional`) : If set to < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.

truncate (`int`, *optional`) : 入力トークンを指定されたサイズに切り詰めます。

typical_p (`float`, *optional`) : Typical Decoding の質量。詳細については、[Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666)を参照してください

watermark (`bool`, *任意*) : [大規模言語モデルのためのウォーターマーク](https://arxiv.org/abs/2301.10226) を用いたウォーターマーキング

**戻り値:** `Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]`

サーバーから返された生成テキスト:
- `stream=False`かつ`details=False`の場合、生成されたテキストは`str`として返されます（デフォルト）
- `stream=True`かつ`details=False`の場合、生成されたテキストは`AsyncIterable[str]`としてトークン単位で返されます。
- `stream=False`かつ`details=True`の場合、生成されたテキストは[TextGenerationOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TextGenerationOutput)として、より詳細な情報とともに返されます。
- `details=True`かつ`stream=True`の場合、生成されたテキストは[TextGenerationStreamOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TextGenerationStreamOutput)のイテラブルとしてトークン単位で返されます。

**例外:** ``ValidationError`` または [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- ``ValidationError`` -- 入力値が有効でない場合。サーバーへのHTTP呼び出しは行われません。
- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

プロンプトが与えられた場合、以下のテキストを生成します。

> [!TIP]
> チャットメッセージから応答を生成したい場合は、[InferenceClient.chat_completion()](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) メソッドを使用してください。このメソッドは、単一のテキストプロンプトの代わりにメッセージのリストを受け取り、チャットテンプレート処理を自動で行います。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

# Case 1: generate text
>>> await client.text_generation("The huggingface_hub library is ", max_new_tokens=12)
'100% open source and built to be easy to use.'

# Case 2: iterate over the generated tokens. Useful for large generation.
>>> async for token in await client.text_generation("The huggingface_hub library is ", max_new_tokens=12, stream=True):
...     print(token)
100
%
open
source
and
built
to
be
easy
to
use
.

# Case 3: get more details about the generation process.
>>> await client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True)
TextGenerationOutput(
    generated_text='100% open source and built to be easy to use.',
    details=TextGenerationDetails(
        finish_reason='length',
        generated_tokens=12,
        seed=None,
        prefill=[
            TextGenerationPrefillOutputToken(id=487, text='The', logprob=None),
            TextGenerationPrefillOutputToken(id=53789, text=' hugging', logprob=-13.171875),
            (...)
            TextGenerationPrefillOutputToken(id=204, text=' ', logprob=-7.0390625)
        ],
        tokens=[
            TokenElement(id=1425, text='100', logprob=-1.0175781, special=False),
            TokenElement(id=16, text='%', logprob=-0.0463562, special=False),
            (...)
            TokenElement(id=25, text='.', logprob=-0.5703125, special=False)
        ],
        best_of_sequences=None
    )
)

# Case 4: iterate over the generated tokens with more details.
# Last object is more complete, containing the full generated text and the finish reason.
>>> async for details in await client.text_generation("The huggingface_hub library is ", max_new_tokens=12, details=True, stream=True):
...     print(details)
...
TextGenerationStreamOutput(token=TokenElement(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None)
TextGenerationStreamOutput(token=TokenElement(
    id=25,
    text='.',
    logprob=-0.5703125,
    special=False),
    generated_text='100% open source and built to be easy to use.',
    details=TextGenerationStreamOutputStreamDetails(finish_reason='length', generated_tokens=12, seed=None)
)

# Case 5: generate constrained output using grammar
>>> response = await client.text_generation(
...     prompt="I saw a puppy a cat and a raccoon during my bike ride in the park",
...     model="HuggingFaceH4/zephyr-orpo-141b-A35b-v0.1",
...     max_new_tokens=100,
...     repetition_penalty=1.3,
...     grammar={
...         "type": "json",
...         "value": {
...             "properties": {
...                 "location": {"type": "string"},
...                 "activity": {"type": "string"},
...                 "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
...                 "animals": {"type": "array", "items": {"type": "string"}},
...             },
...             "required": ["location", "activity", "animals_seen", "animals"],
...         },
...     },
... )
>>> json.loads(response)
{
    "activity": "bike riding",
    "animals": ["puppy", "cat", "raccoon"],
    "animals_seen": 3,
    "location": "park"
}
```

#### text_to_image[[huggingface_hub.AsyncInferenceClient.text_to_image]]

```python
text_to_image(prompt: str, negative_prompt: str | None = None, height: int | None = None, width: int | None = None, num_inference_steps: int | None = None, guidance_scale: float | None = None, model: str | None = None, scheduler: str | None = None, seed: int | None = None, extra_body: dict[str, typing.Any] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2462)

**パラメータ:**

prompt (`str`) : 画像を生成するためのプロンプト。

negative_prompt (`str`, *任意*) : 画像生成に含めるべきでない内容を指示するプロンプト。

height (`int`, *任意*) : 出力画像のピクセル単位の縦幅

width (`int`, *任意*) : 出力画像の幅（ピクセル単位）

num_inference_steps (`int`, *optional*) : デノイジングのステップ数です。デノイジングのステップ数が多いほど、推論速度が遅くなる代わりに、より高品質な画像が得られる傾向があります。

guidance_scale (`float`, *任意*) : ガイダンススケールの値を高くすると、モデルはテキストプロンプトと密接に関連した画像を生成するよう促されますが、値が高すぎると飽和やその他のアーティファクトが発生する可能性があります。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキストから画像生成へのモデルが使用されます。デフォルト値は None です。

scheduler (`str`, *任意*) : スケジューラを互換性のあるものに上書きします。

seed (`int`, *任意*) : 乱数生成器のシード。

extra_body (`dict[str, Any]`, *省略可能*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** `Image`

生成された画像。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたモデルを使用して、与えられたテキストに基づいて画像を生成します。

> [!WARNING]
> 画像を扱うには、`PIL`のインストールが必要です（`pip install Pillow`）。

> [!TIP]
> `extra_body` 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:
```py
# Must be run in an async context
>>> 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")

>>> image = await client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     negative_prompt="low resolution, blurry",
...     model="stabilityai/stable-diffusion-2-1",
... )
>>> image.save("better_astronaut.png")
```

サードパーティプロバイダーを直接使用する例。利用料はfal.aiアカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="fal-ai",  # Use fal.ai provider
...     api_key="fal-ai-api-key",  # Pass your fal.ai API key
... )
>>> image = client.text_to_image(
...     "A majestic lion in a fantasy forest",
...     model="black-forest-labs/FLUX.1-schnell",
... )
>>> image.save("lion.png")
```

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Use replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> image = client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     model="black-forest-labs/FLUX.1-dev",
... )
>>> image.save("astronaut.png")
```

Replicateプロバイダーを、追加パラメータ付きで使用する例

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Use replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> image = client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     model="black-forest-labs/FLUX.1-schnell",
...     extra_body={"output_quality": 100},
... )
>>> image.save("astronaut.png")
```

#### text_to_speech[[huggingface_hub.AsyncInferenceClient.text_to_speech]]

```python
text_to_speech(text: str, model: str | None = None, do_sample: bool | None = None, early_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None, epsilon_cutoff: float | None = None, eta_cutoff: float | None = None, max_length: int | None = None, max_new_tokens: int | None = None, min_length: int | None = None, min_new_tokens: int | None = None, num_beam_groups: int | None = None, num_beams: int | None = None, penalty_alpha: float | None = None, temperature: float | None = None, top_k: int | None = None, top_p: float | None = None, typical_p: float | None = None, use_cache: bool | None = None, extra_body: dict[str, typing.Any] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2700)

**パラメータ:**

text (`str`) : 合成するテキスト。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキスト読み上げモデルが使用されます。デフォルト値は None です。

do_sample (`bool`, *任意*) : 新しいトークンを生成する際に、グリーディーデコーディングではなくサンプリングを使用するかどうか。

early_stopping (`Union[bool, "TextToSpeechEarlyStoppingEnum"]`, *任意*) : ビームベースの手法における停止条件を制御します。

epsilon_cutoff (`float`, *任意*) : 0 と 1 の間の float 値に設定すると、条件付き確率が epsilon_cutoff より大きいトークンのみがサンプリングされます。論文では、モデルのサイズに応じて推奨値は 3e-4 から 9e-4 の範囲とされています。詳細は [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) を参照してください。

eta_cutoff (`float`, *任意*) : Eta サンプリングは、ローカル・ティピカル・サンプリングとエプシロン・サンプリングのハイブリッドです。0 と 1 の間の float 値に設定すると、トークンは eta_cutoff または sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))) のいずれかよりも大きい場合にのみ考慮されます。後者の項は、sqrt(eta_cutoff) によってスケーリングされた、次のトークンの期待確率と直感的に解釈できます。論文では、モデルのサイズに応じて、推奨値は 3e-4 から 2e-3 の範囲とされています。詳細については、[Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191)を参照してください。

max_length (`int`, *任意*) : 入力を含む生成テキストの最大長（トークン数）。

max_new_tokens (`int`, *optional*) : 生成するトークンの最大数。max_length より優先されます。

min_length (`int`, *任意*) : 生成テキストの最小長（トークン数）。入力を含みます。

min_new_tokens (`int`, *optional*) : 生成するトークンの最小数。min_length より優先されます。

num_beam_groups (`int`, *任意*) : ビームの多様性を確保するために、num_beams を分割するグループ数。詳細は[この論文](https://hf.co/papers/1610.02424)を参照してください。

num_beams (`int`, *任意*) : ビームサーチに使用するビームの数。

penalty_alpha (`float`, *任意*) : contrastive search によるデコーディングにおいて、モデルの信頼度と退化ペナルティのバランスを調整する値です。

temperature (`float`, *任意*) : 次のトークンの確率を調整するために使用される値。

top_k (`int`, *optional*) : top-kフィルタリングのために保持する、最も確率の高い語彙トークンの数。

top_p (`float`, *optional*) : float < 1 に設定すると、生成には、確率が top_p 以上になる最小のトークンセットのみが保持されます。

typical_p (`float`, *任意*) : Local typicality は、すでに生成された部分テキストが与えられた条件下で、次のターゲットトークンを予測する条件付き確率が、次のランダムなトークンを予測する期待される条件付き確率とどれだけ類似しているかを測定します。float < 1 に設定すると、確率の合計が typical_p 以上となる最も局所的に典型的なトークンの最小集合が生成のために保持されます。詳細は[この論文](https://hf.co/papers/2202.00666)を参照してください。

use_cache (`bool`, *任意*) : モデルがデコードを高速化するために、過去の最後のキー/バリューアテンションを使用すべきかどうか

extra_body (`dict[str, Any]`, *省略可能*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** `bytes`

生成されたオーディオ。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

指定されたテキストを発音する音声のオーディオを合成します。

> [!TIP]
> `extra_body` 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:
```py
# Must be run in an async context
>>> from pathlib import Path
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

>>> audio = await client.text_to_speech("Hello world")
>>> Path("hello_world.flac").write_bytes(audio)
```

サードパーティプロバイダーを直接使用する例。使用料はあなたのReplicateアカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",
...     api_key="your-replicate-api-key",  # Pass your Replicate API key directly
... )
>>> audio = client.text_to_speech(
...     text="Hello world",
...     model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
```

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",
...     api_key="hf_...",  # Pass your HF token
... )
>>> audio =client.text_to_speech(
...     text="Hello world",
...     model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
```

Replicateプロバイダーを、追加パラメータ付きで使用する例

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Use replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> audio = client.text_to_speech(
...     "Hello, my name is Kororo, an awesome text-to-speech model.",
...     model="hexgrad/Kokoro-82M",
...     extra_body={"voice": "af_nicole"},
... )
>>> Path("hello.flac").write_bytes(audio)
```

fal.ai上で"YuE-s1-7B-anneal-en-cot"を使用した音楽生成の例

```py
>>> from huggingface_hub import InferenceClient
>>> lyrics = '''
... [verse]
... In the town where I was born
... Lived a man who sailed to sea
... And he told us of his life
... In the land of submarines
... So we sailed on to the sun
... 'Til we found a sea of green
... And we lived beneath the waves
... In our yellow submarine

... [chorus]
... We all live in a yellow submarine
... Yellow submarine, yellow submarine
... We all live in a yellow submarine
... Yellow submarine, yellow submarine
... '''
>>> genres = "pavarotti-style tenor voice"
>>> client = InferenceClient(
...     provider="fal-ai",
...     model="m-a-p/YuE-s1-7B-anneal-en-cot",
...     api_key=...,
... )
>>> audio = client.text_to_speech(lyrics, extra_body={"genres": genres})
>>> with open("output.mp3", "wb") as f:
...     f.write(audio)
```

#### text_to_video[[huggingface_hub.AsyncInferenceClient.text_to_video]]

```python
text_to_video(prompt: str, model: str | None = None, guidance_scale: float | None = None, negative_prompt: list[str] | None = None, num_frames: float | None = None, num_inference_steps: int | None = None, seed: int | None = None, extra_body: dict[str, typing.Any] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2603)

**パラメータ:**

prompt (`str`) : 動画の生成に使用するプロンプト。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるテキストから動画生成へのモデルが使用されます。デフォルト値は None です。

guidance_scale (`float`, *任意*) : ガイダンススケールの値を高くすると、モデルはテキストプロンプトと密接に関連した動画を生成するよう促されますが、値が高すぎると飽和やその他のアーティファクトが発生する可能性があります。

negative_prompt (`list[str]`、*任意*) : 動画生成に含めるべきでない内容を指示するプロンプトを1つ以上指定します。

num_frames (`float`, *任意*) : num_frames パラメータは、生成される動画フレームの数を決定します。

num_inference_steps (`int`, *optional*) : デノイジングのステップ数です。デノイジングのステップ数を増やすと、推論速度が遅くなる代わりに、通常、より高品質な動画が生成されます。

seed (`int`, *任意*) : 乱数生成器のシード。

extra_body (`dict[str, Any]`, *省略可能*) : モデルに渡すプロバイダー固有の追加パラメータです。サポートされているパラメータについては、プロバイダーのドキュメントを参照してください。

**戻り値:** `bytes`

生成された動画。

与えられたテキストに基づいて動画を生成します。

> [!TIP]
> `extra_body` 引数を使用して、プロバイダー固有のパラメータをモデルに渡すことができます。

例:

サードパーティプロバイダーを直接使用する例。利用料はfal.aiアカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="fal-ai",  # Using fal.ai provider
...     api_key="fal-ai-api-key",  # Pass your fal.ai API key
... )
>>> video = client.text_to_video(
...     "A majestic lion running in a fantasy forest",
...     model="tencent/HunyuanVideo",
... )
>>> with open("lion.mp4", "wb") as file:
...     file.write(video)
```

Hugging Face Routing を介したサードパーティプロバイダーを使用する例。利用料は Hugging Face アカウントに請求されます。

```py
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Using replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> video = client.text_to_video(
...     "A cat running in a park",
...     model="genmo/mochi-1-preview",
... )
>>> with open("cat.mp4", "wb") as file:
...     file.write(video)
```

#### token_classification[[huggingface_hub.AsyncInferenceClient.token_classification]]

```python
token_classification(text: str, model: str | None = None, aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None, ignore_labels: list[str] | None = None, stride: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2909)

**パラメータ:**

text (`str`) : 分類対象の文字列。

model (`str`, *任意*) : トークン分類タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨されるトークン分類モデルが使用されます。デフォルト値は None です。

aggregation_strategy (`"TokenClassificationAggregationStrategy"`, *任意*) : モデルの予測に基づいてトークンを融合するために使用される戦略

ignore_labels (`list[str`, *optional*) : 無視するラベルのリスト

stride (`int`, *任意*) : 入力テキストを分割する際に、チャンク間で重複するトークンの数。

**戻り値:** `list[TokenClassificationOutputElement]`

エンティティグループ、信頼度スコア、単語、開始および終了インデックスを含む[TokenClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TokenClassificationOutputElement)の項目のリスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

与えられたテキストに対してトークン分類を実行します。文の解析（文法的な解析または）に通常使用され、テキストに含まれるキーワードを理解するために用いられます。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica")
[
    TokenClassificationOutputElement(
        entity_group='PER',
        score=0.9971321225166321,
        word='Sarah Jessica Parker',
        start=11,
        end=31,
    ),
    TokenClassificationOutputElement(
        entity_group='PER',
        score=0.9773476123809814,
        word='Jessica',
        start=52,
        end=59,
    )
]
```

#### 翻訳[[huggingface_hub.AsyncInferenceClient.translation]]

```python
translation(text: str, model: str | None = None, src_lang: str | None = None, tgt_lang: str | None = None, clean_up_tokenization_spaces: bool | None = None, truncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = None, generate_parameters: dict[str, typing.Any] | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L2985)

**パラメータ:**

text (`str`) : 翻訳対象の文字列。

model (`str`, *任意*) : 翻訳タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される翻訳モデルが使用されます。デフォルト値は None です。

src_lang (`str`, *任意*) : テキストのソース言語です。複数言語からの翻訳に対応するモデルでは必須です。

tgt_lang (`str`, *任意*) : 翻訳先のターゲット言語。複数の言語への翻訳に対応するモデルでは必須です。

clean_up_tokenization_spaces (`bool`, *任意*) : テキスト出力に含まれる可能性のある余分なスペースをクリーンアップするかどうか。

truncation (`"TranslationTruncationStrategy"`, *任意*) : 使用する切り詰め戦略。

generate_parameters (`dict[str, Any]`、*任意*) : テキスト生成アルゴリズムの追加のパラメータ設定。

**戻り値:** [TranslationOutput](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.TranslationOutput)

生成された翻訳テキスト。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError` または ``ValueError``

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。
- ``ValueError`` -- `src_lang` と `tgt_lang` の引数のうち、片方だけが提供された場合。

テキストをある言語から別の言語に変換します。

特定のユースケースに最適なモデルの選び方については、https://huggingface.co/tasks/translation をご覧ください。ソース言語とターゲット言語は通常、モデルによって決まります。ただし、一部のモデルではソース言語とターゲット言語を指定できます。これらのモデルを使用している場合は、`src_lang` と `tgt_lang` 引数を使って、該当する情報を渡すことができます。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.translation("My name is Wolfgang and I live in Berlin")
'Mein Name ist Wolfgang und ich lebe in Berlin.'
>>> await client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr")
TranslationOutput(translation_text='Je m'appelle Wolfgang et je vis à Berlin.')
```

言語の指定:
```py
>>> client.translation("My name is Sarah Jessica Parker but you can call me Jessica", model="facebook/mbart-large-50-many-to-many-mmt", src_lang="en_XX", tgt_lang="fr_XX")
"Mon nom est Sarah Jessica Parker mais vous pouvez m'appeler Jessica"
```

#### visual_question_answering[[huggingface_hub.AsyncInferenceClient.visual_question_answering]]

```python
visual_question_answering(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], question: str, model: str | None = None, top_k: int | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3075)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : コンテキスト用の入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageを指定できます。

question (`str`) : 回答する質問。

model (`str`, *任意*) : 視覚的質問応答タスクに使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。指定しない場合、デフォルトで推奨される視覚的質問応答モデルが使用されます。デフォルト値は None です。

top_k (`int`, *optional*) : 返す回答の数（可能性の高い順に選択されます）。コンテキスト内に十分な選択肢がない場合、topk より少ない数の回答が返されます。

**戻り値:** `list[VisualQuestionAnsweringOutputElement]`

予測ラベルと関連する確率を含む[VisualQuestionAnsweringOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.VisualQuestionAnsweringOutputElement)のリスト

**例外:** ``InferenceTimeoutError`` または `HfHubHTTPError`

- ``InferenceTimeoutError`` -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

画像に基づいてオープンエンドな質問に答える。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.visual_question_answering(
...     image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg",
...     question="What is the animal doing?"
... )
[
    VisualQuestionAnsweringOutputElement(score=0.778609573841095, answer='laying down'),
    VisualQuestionAnsweringOutputElement(score=0.6957435607910156, answer='sitting'),
]
```

#### zero_shot_classification[[huggingface_hub.AsyncInferenceClient.zero_shot_classification]]

```python
zero_shot_classification(text: str, candidate_labels: list, multi_label: bool | None = False, hypothesis_template: str | None = None, model: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3135)

**パラメータ:**

text (`str`) : 分類する入力テキスト。

candidate_labels (`list[str]`) : テキストを分類するための、可能なクラスラベルの集合。

multi_label (`bool`, *任意*) : 複数の候補ラベルが同時に真になり得るかどうか。false の場合、各シーケンスにおけるラベルの尤度の和が 1 になるようにスコアが正規化されます。true の場合、ラベルは独立であるとみなされ、各候補ごとに確率が正規化されます。

hypothesis_template (`str`, *任意*) : `candidate_labels` と組み合わせてテキスト分類を試みるために使用される文。プレースホルダーを候補ラベルに置き換えます。

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。指定しない場合、デフォルトで推奨されるゼロショット分類モデルが使用されます。

**戻り値:** `list[ZeroShotClassificationOutputElement]`

予測ラベルとその信頼度を含む[ZeroShotClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ZeroShotClassificationOutputElement)のリストです。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力としてテキストと、そのテキストを分類するための候補ラベルのセットを指定します。

`multi_label=False`の例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> text = (
...     "A new model offers an explanation for how the Galilean satellites formed around the solar system's"
...     "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling"
...     " mysteries when he went for a run up a hill in Nice, France."
... )
>>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"]
>>> await client.zero_shot_classification(text, labels)
[
    ZeroShotClassificationOutputElement(label='scientific discovery', score=0.7961668968200684),
    ZeroShotClassificationOutputElement(label='space & cosmos', score=0.18570658564567566),
    ZeroShotClassificationOutputElement(label='microbiology', score=0.00730885099619627),
    ZeroShotClassificationOutputElement(label='archeology', score=0.006258360575884581),
    ZeroShotClassificationOutputElement(label='robots', score=0.004559356719255447),
]
>>> await client.zero_shot_classification(text, labels, multi_label=True)
[
    ZeroShotClassificationOutputElement(label='scientific discovery', score=0.9829297661781311),
    ZeroShotClassificationOutputElement(label='space & cosmos', score=0.755190908908844),
    ZeroShotClassificationOutputElement(label='microbiology', score=0.0005462635890580714),
    ZeroShotClassificationOutputElement(label='archeology', score=0.00047131875180639327),
    ZeroShotClassificationOutputElement(label='robots', score=0.00030448526376858354),
]
```

`multi_label=True`とカスタムの`hypothesis_template`を用いた例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.zero_shot_classification(
...    text="I really like our dinner and I'm very happy. I don't like the weather though.",
...    candidate_labels=["positive", "negative", "pessimistic", "optimistic"],
...    multi_label=True,
...    hypothesis_template="This text is {} towards the weather"
... )
[
    ZeroShotClassificationOutputElement(label='negative', score=0.9231801629066467),
    ZeroShotClassificationOutputElement(label='pessimistic', score=0.8760990500450134),
    ZeroShotClassificationOutputElement(label='optimistic', score=0.0008674879791215062),
    ZeroShotClassificationOutputElement(label='positive', score=0.0005250611575320363)
]
```

#### zero_shot_image_classification[[huggingface_hub.AsyncInferenceClient.zero_shot_image_classification]]

```python
zero_shot_image_classification(image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview], candidate_labels: list, model: str | None = None, hypothesis_template: str | None = None)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/inference/_generated/_async_client.py#L3238)

**パラメータ:**

image (`Union[str, Path, bytes, BinaryIO, PIL.Image.Image]`) : キャプションを付与する入力画像です。生のバイト列、画像ファイル、オンライン画像へのURL、またはPIL Imageのいずれかです。

candidate_labels (`list[str]`) : この画像の候補ラベル

model (`str`, *任意*) : 推論に使用するモデル。Hugging Face Hub にホストされているモデル ID またはデプロイされた Inference Endpoint の URL を指定できます。このパラメータは、インスタンスレベルで定義されたモデルをオーバーライドします。指定しない場合、デフォルトで推奨されるゼロショット画像分類モデルが使用されます。

hypothesis_template (`str`, *任意*) : `candidate_labels` と組み合わせて画像分類を試みる際に使用される文。プレースホルダーを候補ラベルに置き換えます。

**戻り値:** `list[ZeroShotImageClassificationOutputElement]`

予測ラベルとその信頼度を含む[ZeroShotImageClassificationOutputElement](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_types#huggingface_hub.ZeroShotImageClassificationOutputElement)のリストです。

**例外:** [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) または `HfHubHTTPError`

- [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/ja/package_reference/inference_client#huggingface_hub.InferenceTimeoutError) -- モデルが利用できない場合、またはリクエストがタイムアウトした場合。
- `HfHubHTTPError` -- HTTP 503 以外の HTTP エラーステータスコードでリクエストが失敗した場合。

入力画像とテキストラベルを指定して、画像のテキストラベルを予測します。

例:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

>>> await client.zero_shot_image_classification(
...     "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg",
...     candidate_labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]
```

## InferenceTimeoutError[[huggingface_hub.InferenceTimeoutError]]

#### huggingface_hub.InferenceTimeoutError[[huggingface_hub.InferenceTimeoutError]]

```python
huggingface_hub.InferenceTimeoutError(message: str)
```

[ソース](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/errors.py#L155)

モデルが利用できない場合、またはリクエストがタイムアウトした場合に発生するエラー。

