Hub Python 库文档

在服务器上运行推理

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

在服务器上运行推理

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

  1. 推理提供商:由我们的无服务器推理合作伙伴提供支持,对数百个机器学习模型进行简化、统一的访问。这种新方法建立在我们之前的无服务器推理 API 的基础上, благодаря世界一流的提供商,提供了更多的模型、改进的性能和更高的可靠性。请参阅文档以获取受支持的提供商列表。
  2. 推理端点:一种用于轻松将模型部署到生产环境的产品。推理由 Hugging Face 在您选择的云提供商的专用、完全托管的基础设施中运行。
  3. 本地端点:您还可以通过将客户端连接到本地端点,使用本地推理服务器(如 llama.cppOllamavLLMLiteLLMText Generation Inference (TGI))运行推理。

这些服务都可以通过 InferenceClient 对象调用。它替代了旧版 InferenceApi 客户端,增加了对任务和第三方提供商的特定支持。在旧版 InferenceAPI 客户端部分了解如何迁移到新客户端。

InferenceClient 是一个发出 HTTP 调用到我们 API 的 Python 客户端。如果您想使用您喜欢的工具(curl、postman 等)直接进行 HTTP 调用,请参阅推理提供商文档或推理端点文档页面。

对于 Web 开发,已发布了一个 JS 客户端。如果您对游戏开发感兴趣,可以看看我们的 C# 项目

入门

让我们从文本到图像任务开始

>>> 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 初始化了一个 InferenceClient。使用提供商时,您必须指定要使用的模型。模型 ID 必须是 Hugging Face Hub 上的模型 ID,而不是第三方提供商的模型 ID。在我们的示例中,我们从文本提示生成了一个图像。返回值是一个可以保存到文件的 `PIL.Image` 对象。有关更多详细信息,请查看 text_to_image() 文档。

现在我们来看一个使用 chat_completion() API 的示例。此任务使用 LLM 从消息列表生成响应

>>> 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),并指定了我们要使用的模型 (`"meta-llama/Meta-Llama-3-8B-Instruct"`)。然后我们提供了一个要完成的消息列表(这里是一个单独的问题),并向 API 传递了一个额外的参数 (`max_token=100`)。输出是一个遵循 OpenAI 规范的 `ChatCompletionOutput` 对象。生成的内容可以通过 `output.choices[0].message.content` 访问。有关更多详细信息,请查看 chat_completion() 文档。

该 API 设计得简单易用。并非所有参数和选项都对最终用户可用或进行了描述。如果您有兴趣了解每个任务的所有可用参数,请查看此页面

使用特定提供商

如果您想使用特定的提供商,可以在初始化客户端时指定。默认值为“auto”,它将根据用户在 https://huggingface.co/settings/inference-providers 中的排序选择模型可用的第一个提供商。有关支持的提供商列表,请参阅支持的提供商和任务部分。

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

使用特定模型

如果你想使用特定的模型怎么办?你可以将其指定为参数,或者直接在实例级别指定

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

当使用“hf-inference”提供商时,每个任务都会附带一个来自 Hub 上 1M+ 模型中的推荐模型。然而,这个推荐模型可能会随着时间而改变,因此最好在您决定使用哪个模型后明确设置模型。对于第三方提供商,您必须始终指定一个与该提供商兼容的模型。

访问 Hub 上的模型页面,探索通过推理提供商提供的模型。

使用推理端点

我们上面看到的示例使用推理提供商。虽然这些在快速原型设计和测试方面非常有用。一旦您准备好将模型部署到生产环境,您将需要使用专用的基础设施。这就是 推理端点发挥作用的地方。它允许您部署任何模型并将其作为私有 API 公开。部署后,您将获得一个 URL,您可以使用与之前完全相同的代码连接到该 URL,只需更改 `model` 参数

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

请注意,您不能同时指定 URL 和提供商——它们是互斥的。URL 用于直接连接到已部署的端点。

使用本地端点

您可以使用 InferenceClient 在您自己的机器上运行本地推理服务器(llama.cpp、vllm、litellm 服务器、TGI、mlx 等)进行聊天补全。API 应该与 OpenAI API 兼容。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(model="https://: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)

与 OpenAI Python 客户端类似,InferenceClient 可以用于与任何与 OpenAI REST API 兼容的端点运行聊天补全推理。

身份验证

身份验证可以通过两种方式完成

通过 Hugging Face 路由:使用 Hugging Face 作为代理访问第三方提供商。调用将通过 Hugging Face 的基础设施使用我们的提供商密钥进行路由,使用费用将直接计入您的 Hugging Face 账户。

您可以使用用户访问令牌进行身份验证。您可以直接通过 `api_key` 参数提供您的 Hugging Face 令牌

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

如果您**不**传递`api_key`,客户端将尝试查找并使用本地存储在您机器上的令牌。这通常发生在您之前已登录的情况下。有关登录的详细信息,请参阅身份验证指南

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

直接访问提供商:使用您自己的 API 密钥直接与提供商的服务交互

>>> client = InferenceClient(
    provider="replicate",
    api_key="r8_****"  # Your Replicate API key
)

更多详情请参考推理提供商定价文档

支持的提供商和任务

InferenceClient 的目标是提供最简单的接口,以便在任何提供商上运行 Hugging Face 模型上的推理。它具有支持最常见任务的简单 API。下表显示了哪些提供商支持哪些任务

任务 黑森林实验室 Cerebras Cohere fal-ai 无羽毛AI 焰火人工智能 Groq HF 推理 双曲线 Nebius AI Studio 诺维塔人工智能 Replicate Sambanova Together
audio_classification()
audio_to_audio()
automatic_speech_recognition()
chat_completion()
document_question_answering()
feature_extraction()
fill_mask()
image_classification()
image_segmentation()
image_to_image()
image_to_video()
image_to_text()
object_detection()
question_answering()
sentence_similarity()
summarization()
table_question_answering()
text_classification()
text_generation()
text_to_image()
text_to_speech()
text_to_video()
tabular_classification()
tabular_regression()
token_classification()
translation()
visual_question_answering()
zero_shot_image_classification()
zero_shot_classification()

请查看任务页面以了解每个任务的更多信息。

OpenAI 兼容性

`chat_completion` 任务遵循 OpenAI 的 Python 客户端语法。这对您意味着什么?这意味着如果您习惯于使用 `OpenAI` 的 API,您可以通过更新两行代码来切换到 `huggingface_hub.InferenceClient` 以使用开源模型!

- 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 模型。这里是支持的模型列表。对于身份验证,您应该将有效的用户访问令牌作为 `api_key` 传递,或者使用 `huggingface_hub` 进行身份验证(参见身份验证指南)。

所有输入参数和输出格式都严格相同。特别是,您可以传递 `stream=True` 以在生成令牌时接收它们。您还可以使用 AsyncInferenceClient 使用 `asyncio` 运行推理

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 而不是 OpenAI 的客户端?有以下几个原因

  1. InferenceClient 已为 Hugging Face 服务配置。您无需提供 `base_url` 即可使用推理提供商运行模型。如果您的机器已正确登录,您也无需提供 `token` 或 `api_key`。
  2. InferenceClient 专为 Text-Generation-Inference (TGI) 和 `transformers` 框架量身定制,这意味着您能确保它始终与最新更新保持同步。
  3. InferenceClient 集成了我们的推理端点服务,使得启动推理端点、检查其状态并在其上运行推理变得更加容易。有关更多详细信息,请查看推理端点指南。

`InferenceClient.chat.completions.create` 只是 `InferenceClient.chat_completion` 的一个别名。有关更多详细信息,请查看 chat_completion() 的包参考。实例化客户端时的 `base_url` 和 `api_key` 参数也是 `model` 和 `token` 的别名。这些别名是为了减少从 `OpenAI` 切换到 `InferenceClient` 时的摩擦而定义的。

函数调用

函数调用允许 LLM 与外部工具(例如已定义的函数或 API)交互。这使用户能够轻松构建针对特定用例和实际任务定制的应用程序。`InferenceClient` 实现了与 OpenAI Chat Completions API 相同的工具调用接口。以下是使用 Nebius 作为推理提供商的工具调用简单示例

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="nebius")

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)

请参阅提供商的文档,以验证他们支持哪些模型用于函数/工具调用。

结构化输出与 JSON 模式

InferenceClient 支持 JSON 模式用于语法有效的 JSON 响应,以及结构化输出用于强制执行模式的响应。JSON 模式提供机器可读的数据,但没有严格的结构,而结构化输出则保证了有效的 JSON 和对预定义模式的遵守,以实现可靠的下游处理。

我们遵循 OpenAI API 规范,同时支持 JSON 模式和结构化输出。您可以通过 `response_format` 参数启用它们。以下是使用 Cerebras 作为推理提供商的结构化输出示例

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)

请参阅提供商的文档,以验证他们支持哪些模型用于结构化输出和 JSON 模式。

异步客户端

还提供了基于 `asyncio` 和 `aiohttp` 的客户端异步版本。您可以直接安装 `aiohttp` 或使用 `[inference]` 额外安装

pip install --upgrade huggingface_hub[inference]
# or
# pip install aiohttp

安装完成后,所有异步 API 端点均可通过 AsyncInferenceClient 访问。其初始化和 API 与仅同步版本完全相同。

# 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` 模块的更多信息,请参阅官方文档

MCP 客户端

`huggingface_hub` 库现在包含一个实验性的 MCPClient,旨在通过 模型上下文协议 (MCP) 赋予大型语言模型 (LLM) 与外部工具交互的能力。此客户端扩展了 AsyncInferenceClient,以无缝集成工具使用。

MCPClient 连接到公开工具的 MCP 服务器(本地 `stdio` 脚本或远程 `http` / `sse` 服务)。它将这些工具提供给 LLM(通过 AsyncInferenceClient)。如果 LLM 决定使用某个工具,MCPClient 将管理对 MCP 服务器的执行请求,并将工具的输出中继回 LLM,通常以实时流的形式。

在下面的示例中,我们通过 Nebius 推理提供商使用 Qwen/Qwen2.5-72B-Instruct 模型。然后,我们添加了一个远程 MCP 服务器,在这种情况下,它是一个 SSE 服务器,它使 Flux 图像生成工具可供 LLM 使用。

import os

from huggingface_hub import ChatCompletionInputMessage, ChatCompletionStreamOutput, MCPClient


async def main():
    async with MCPClient(
        provider="nebius",
        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 类。这个“Tiny Agent”通过管理聊天循环和状态来简化对话式 Agent 的创建,本质上充当 MCPClient 的包装器。它旨在成为一个简单的 while 循环,直接构建在 MCPClient 之上。您可以直接从命令行运行这些 Agent

# 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

启动后,代理将加载、列出其从连接的 MCP 服务器发现的工具,然后即可接受您的提示!

高级技巧

在上面一节中,我们了解了 InferenceClient 的主要方面。现在我们深入探讨一些更高级的技巧。

计费

作为 HF 用户,您每月可获得积分,用于通过 Hub 上的各种提供商运行推理。您获得的积分数量取决于您的账户类型(免费、PRO 或企业版 Hub)。每次推理请求都会根据提供商的定价表收费。默认情况下,请求将计入您的个人账户。但是,可以通过简单地将 `bill_to=""` 传递给 `InferenceClient` 来设置计费,以便将请求计入您所属的组织。为此,您的组织必须订阅企业版 Hub。有关计费的更多详细信息,请查看此指南

>>> 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 将“无限期”等待,直到推理完成。如果您想在工作流中进行更多控制,可以将 `timeout` 参数设置为特定的秒值。如果超时延迟到期,则会引发 InferenceTimeoutError,您可以在代码中捕获它

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

二进制输入

某些任务需要二进制输入,例如处理图像或音频文件时。在这种情况下,InferenceClient 尝试尽可能宽松地接受不同类型

  • 原始 `bytes`
  • 以二进制形式打开的文件类对象(`with open("audio.flac", "rb") as f: ...`)
  • 指向本地文件的路径(`str` 或 `Path`)
  • 指向远程文件的 URL(`str`)(例如 `https://...`)。在这种情况下,文件将在发送到 API 之前在本地下载。
>>> 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'}, ...]
< > 在 GitHub 上更新