# 在服务器上运行推理

推理是使用训练好的模型对新数据进行预测的过程。由于该过程可能计算密集，在专用或外部服务上运行是一个值得考虑的选择。`huggingface_hub` 库提供了一个统一接口，用于对托管在 Hugging Face Hub 上的模型在多个服务上运行推理：

1.  [推理服务提供商](https://huggingface.co/docs/inference-providers/index)：通过我们的无服务器推理合作伙伴，提供对数百个机器学习模型的简化、统一访问。这种新方法基于我们之前的 Serverless Inference API，得益于世界级的服务提供商，提供了更多的模型、更好的性能和更高的可靠性。有关支持的服务提供商列表，请参阅[文档](https://huggingface.co/docs/inference-providers/index#partners)。
2.  [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index)：一款可轻松将模型部署到生产环境的产品。推理由 Hugging Face 在您选择的云服务商上，通过专用的全托管基础设施运行。
3.  本地端点：你还可以通过将客户端连接到这些本地端点，使用 [llama.cpp](https://github.com/ggerganov/llama.cpp)、[Ollama](https://ollama.com/)、[vLLM](https://github.com/vllm-project/vllm)、[LiteLLM](https://docs.litellm.ai/docs/simple_proxy) 或 [Text Generation Inference (TGI)](https://github.com/huggingface/text-generation-inference) 等本地推理服务器来运行推理。

> [!TIP]
> [InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 是一个通过 HTTP 调用我们 API 的 Python 客户端。如果您想使用自己偏好的工具（curl、postman 等）直接发起 HTTP 调用，请参阅 [Inference Providers](https://huggingface.co/docs/inference-providers/index) 文档或 [Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index) 文档页面。
>
> 对于 Web 开发，已发布了一个 [JS 客户端](https://huggingface.co/docs/huggingface.js/inference/README)。如果您对游戏开发感兴趣，可以查看我们的 [C# 项目](https://github.com/huggingface/unity-api)。

## 入门

让我们从一个文本到图像的任务开始：

```python
>>> from huggingface_hub import InferenceClient

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

```

在上面的示例中，我们使用第三方提供商 [Replicate](https://replicate.com/) 初始化了一个 [InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient)。使用提供商时，必须指定要使用的模型。模型 id 必须是该模型在 Hugging Face Hub 上的 id，而不是来自第三方提供商的模型 id。在我们的示例中，我们通过文本提示生成了一张图像。返回的值是一个 `PIL.Image` 对象，可以将其保存为文件。有关更多详细信息，请参阅 [text_to_image()](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient.text_to_image) 文档。

下面来看一个使用 [chat_completion()](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) API 的示例。该任务使用 LLM 根据一组消息生成回复：

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

在上面的示例中，我们使用了一个第三方提供商（[Together AI](https://www.together.ai/)），并指定了要使用的模型（`"meta-llama/Meta-Llama-3-8B-Instruct"`）。然后，我们提供了一个待补全的消息列表（此处为单个问题），并向 API 传递了一个额外参数（`max_token=100`）。输出是一个遵循 OpenAI 规范的 `ChatCompletionOutput` 对象。可以通过 `output.choices[0].message.content` 访问生成的内容。更多详细信息，请参阅 [chat_completion()](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) 文档。

> [!WARNING]
> 该 API 的设计力求简洁。并非所有参数和选项都面向最终用户提供或加以说明。如果您希望深入了解每项任务可用的所有参数，请参阅[此页面](https://huggingface.co/docs/api-inference/detailed_parameters)。

### 使用特定提供商

如果你想使用特定的提供商，可以在初始化客户端时指定。默认值为 "auto"，它将根据用户在 https://hf.co/settings/inference-providers 中的排序，选择该模型可用的第一个提供商。支持的提供商列表请参阅 [支持的提供商和任务](#supported-providers-and-tasks) 部分。

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

### 使用特定模型

如果你想使用特定的模型怎么办？你可以将其作为参数指定，也可以直接在实例级别指定：

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

> [!TIP]
> 使用 "hf-inference" 提供商时，每个任务都会附带一个来自 Hub 上 100 多万可用模型的推荐模型。不过，该推荐可能会随时间变化，因此一旦确定要使用哪个模型，最好显式地设置该模型。对于第三方提供商，您必须始终指定一个与该提供商兼容的模型。
>
> 访问 Hub 上的 [Models](https://huggingface.co/models?inference=warm) 页面，以探索通过 Inference Providers 提供的模型。

### 使用推理端点

上述示例使用的是推理提供商。虽然它们在快速原型设计和测试中非常有用，但当你准备将模型部署到生产环境时，就需要使用专用的基础设施。这正是[Inference Endpoints](https://huggingface.co/docs/inference-endpoints/index)发挥作用的地方。它允许你部署任意模型，并将其作为私有 API 暴露出来。部署完成后，你将获得一个 URL，可以使用与之前完全相同的代码进行连接，只需更改`model`参数即可：

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

请注意，您不能同时指定 URL 和 provider，二者互斥。URL 用于直接连接到已部署的端点。

### 使用本地端点

您可以使用 [InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 在本地推理服务器（llama.cpp、vllm、litellm server、TGI、mlx 等）上运行聊天补全，这些服务器运行在您自己的机器上。该 API 应与 OpenAI API 兼容。

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

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

> [!TIP]
> 与 OpenAI Python 客户端类似，[InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 可用于在任何兼容 OpenAI REST API 的端点上运行 Chat Completion 推理。

### 身份验证

身份验证可以通过以下两种方式进行：

**通过 Hugging Face 路由**：使用 Hugging Face 作为代理来访问第三方提供商。调用将通过 Hugging Face 的基础设施进行路由，并使用我们的提供商密钥，相关用量将直接计入您的 Hugging Face 账户。

您可以使用 [用户访问令牌](https://huggingface.co/docs/hub/security-tokens) 进行身份验证。您可以使用 `api_key` 参数直接提供您的 Hugging Face 令牌：

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

如果 *未* 传入 `api_key`，客户端将尝试查找并使用本地存储的令牌。这通常发生在你之前已登录的情况下。有关登录的详细信息，请参阅 [身份验证指南](https://huggingface.co/docs/huggingface_hub/quick-start#authentication)。

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

**直接访问提供商**：使用您自己的 API 密钥直接与提供商的服务进行交互：
```python
>>> client = InferenceClient(
    provider="replicate",
    api_key="r8_****"  # Your Replicate API key
)
```

有关更多详细信息，请参阅[Inference Providers 定价文档](https://huggingface.co/docs/inference-providers/pricing#routed-requests-vs-direct-calls)。

## 支持的提供商和任务

[InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 旨在提供最简单的接口，以便在任何提供商上运行 Hugging Face 模型的推理。它拥有一个简单的 API，支持最常见的任务。下表展示了各提供商支持的任务：

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

> [!TIP]
> 查看 [Tasks](https://huggingface.co/tasks) 页面以了解有关每个任务的更多信息。

## OpenAI 兼容性

`chat_completion` 任务遵循 [OpenAI 的 Python 客户端](https://github.com/openai/openai-python) 语法。这对您意味着什么？这意味着，如果您习惯使用 `OpenAI` 的 API，只需更新 2 行代码，即可切换到 `huggingface_hub.InferenceClient` 来使用开源模型！

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

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

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

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

就是这样！唯一需要做的更改是将 `from openai import OpenAI` 替换为 `from huggingface_hub import InferenceClient`，并将 `client = OpenAI(...)` 替换为 `client = InferenceClient(...)`。您可以通过将模型 id 作为 `model` 参数传入，从 Hugging Face Hub 中选择任意 LLM 模型。[此处列出了](https://huggingface.co/models?pipeline_tag=text-generation&other=conversational,text-generation-inference&sort=trending)受支持的模型。对于身份验证，您应传入有效的 [User Access Token](https://huggingface.co/settings/tokens) 作为 `api_key`，或使用 `huggingface_hub` 进行身份验证（参见[身份验证指南](https://huggingface.co/docs/huggingface_hub/quick-start#authentication)）。

所有输入参数和输出格式完全相同。特别是，您可以传入 `stream=True` 以在生成时接收 token。您还可以使用 [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.AsyncInferenceClient) 通过 `asyncio` 运行推理：

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

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

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

asyncio.run(main())
```

你可能会问，为什么使用 [InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 而不是 OpenAI 的客户端？原因有以下几点：
1. [InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 已针对 Hugging Face 服务进行配置。使用 Inference Providers 运行模型时，无需提供 `base_url`。如果当前机器已正确登录，也无需提供 `token` 或 `api_key`。
2. [InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 专为 Text-Generation-Inference (TGI) 和 `transformers` 框架打造，因此您可以放心，它始终与最新更新保持同步。
3. [InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 与我们的 Inference Endpoints 服务集成，可更轻松地启动 Inference Endpoint、检查其状态并在其上运行推理。有关更多详细信息，请参阅 [Inference Endpoints](./inference_endpoints) 指南。

> [!TIP]
> `InferenceClient.chat.completions.create` 只是 `InferenceClient.chat_completion` 的别名。有关更多详细信息，请参阅 [chat_completion()](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient.chat_completion) 的包参考。实例化客户端时的 `base_url` 和 `api_key` 参数也是 `model` 和 `token` 的别名。定义这些别名是为了减少从 `OpenAI` 切换到 `InferenceClient` 时的摩擦。

## 函数调用

函数调用（Function calling）允许 LLM 与外部工具（例如已定义的函数或 API）进行交互。这使得用户能够轻松构建针对特定用例和实际任务定制的应用程序。`InferenceClient` 实现了与 OpenAI Chat Completions API 相同的工具调用接口。下面是一个使用 [Novita](https://novita.ai/) 作为推理提供商的简单工具调用示例：

```python
from huggingface_hub import InferenceClient

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

client = InferenceClient(provider="novita")

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

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

```

> [!TIP]
> 请参阅提供商的文档，以确认哪些模型支持 Function/Tool Calling。

## 结构化输出 & JSON 模式

InferenceClient 支持 JSON 模式，用于生成语法有效的 JSON 响应；同时支持 Structured Outputs，用于生成符合模式约束的响应。JSON 模式提供机器可读的数据，但不强制严格的结构；而 Structured Outputs 则保证响应既是有效的 JSON，又遵循预定义的模式，从而确保下游处理的可靠性。

我们遵循 OpenAI API 规范，同时支持 JSON 模式和 Structured Outputs。您可以通过 `response_format` 参数启用它们。以下是一个使用 [Cerebras](https://www.cerebras.ai/) 作为推理提供商的 Structured Outputs 示例：

```python
from huggingface_hub import InferenceClient

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

client = InferenceClient(provider="cerebras")

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

print(completion.choices[0].message)
```
> [!TIP]
> 请参阅各提供商的文档，以确认它们对 Structured Outputs 和 JSON Mode 支持哪些模型。

## 异步客户端

我们还提供了一个基于 `asyncio` 和 `httpx2` 的客户端异步版本。所有异步 API 端点均可通过 [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.AsyncInferenceClient) 访问。其初始化和 API 与仅支持同步的版本完全相同。

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

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

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

有关 `asyncio` 模块的更多信息，请参阅[官方文档](https://docs.python.org/3/library/asyncio.html)。

## MCP 客户端

`huggingface_hub` 库现在包含一个实验性的 [MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient)，旨在通过 [Model Context Protocol](https://modelcontextprotocol.io)（MCP）赋予大型语言模型（LLM）与外部工具交互的能力。该客户端扩展了 [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.AsyncInferenceClient)，以无缝集成工具的使用。

[MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient) 连接到暴露工具的 MCP 服务器（本地 `stdio` 脚本或远程 `http`/`sse` 服务）。它将这些工具提供给 LLM（通过 [AsyncInferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.AsyncInferenceClient)）。如果 LLM 决定使用某个工具，[MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient) 会管理向 MCP 服务器发出的执行请求，并将该工具的输出传回给 LLM，通常以实时流式方式返回结果。

在下面的示例中，我们通过 [Novita](https://novita.ai/) 推理提供商使用 [Qwen/Qwen2.5-72B-Instruct](https://huggingface.co/Qwen/Qwen2.5-72B-Instruct) 模型。然后，我们添加一个远程 MCP 服务器，在本例中是一个 SSE 服务器，它使 Flux 图像生成工具可供 LLM 使用。

```python
import os

from huggingface_hub import ChatCompletionInputMessage, ChatCompletionStreamOutput, MCPClient

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

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

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

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

if __name__ == "__main__":
    import asyncio

    asyncio.run(main())
```

为了更简单的开发，我们提供了一个更高级的 [Agent](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.Agent) 类。这个“Tiny Agent”通过管理聊天循环和状态，简化了创建对话式 Agent 的过程，本质上是对 [MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient) 的封装。它被设计为直接构建在 [MCPClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/mcp#huggingface_hub.MCPClient) 之上的简单 while 循环。您可以直接从命令行运行这些 Agent：

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

```

启动后，Agent 会加载并列出其从已连接的 MCP 服务器中发现的 Tools，随后即可接收您的提示词！

## 高级技巧

在上一节中，我们了解了[InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient)的主要方面。接下来，让我们深入探讨一些更高级的技巧。

### 账单

作为 HF 用户，您每月会获得一定额度的积分，用于通过 Hub 上的各个提供商运行推理。您获得的积分数量取决于您的账户类型（Free、PRO 或 Enterprise Hub）。每次推理请求都会根据提供商的定价表进行计费。默认情况下，请求费用将计入您的个人账户。不过，您也可以通过向 `InferenceClient` 传入 `bill_to="<your_org_name>"`，将计费设置为您所属的组织，从而使请求费用由该组织承担。要实现此功能，您的组织必须已订阅 Enterprise Hub。有关计费的更多详细信息，请参阅[此指南](https://huggingface.co/docs/api-inference/pricing#features-using-inference-providers)。

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

请注意，您无法向不属于您的其他用户或组织进行充值。如果您希望向他人赠送一些额度，必须与他们共同创建一个联合组织。

### 超时

推理调用可能会花费大量时间。默认情况下，[InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 会“无限期”等待，直到推理完成。如果您希望在工作流程中获得更多控制，可以将 `timeout` 参数设置为特定的秒数。如果超时延迟到期，则会引发 [InferenceTimeoutError](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceTimeoutError)，您可以在代码中捕获该异常：

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

### 二进制输入

某些任务需要二进制输入，例如处理图像或音频文件时。在这种情况下，[InferenceClient](/docs/huggingface_hub/v2.4.0/zh/package_reference/inference_client#huggingface_hub.InferenceClient) 会尽可能宽松地接受不同类型的输入：
- 原始 `bytes`
- 一个文件类对象，以二进制模式打开（`with open("audio.flac", "rb") as f: ...`）
- 指向本地文件的路径（`str` 或 `Path`）
- 一个指向远程文件的 URL（`str`）（例如 `https://...`）。在这种情况下，文件将先下载到本地
被发送到 API。

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

