Hub Python 庫文件

在伺服器上執行推理

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

在伺服器上執行推理

推理是使用訓練好的模型對新資料進行預測的過程。由於這個過程可能計算密集,在專用或外部服務上執行可能是一個有趣的選擇。huggingface_hub 庫提供了一個統一的介面,可以跨多個服務對託管在 Hugging Face Hub 上的模型執行推理。

  1. 推理提供者:透過我們的無伺服器推理合作伙伴,可以對數百個機器學習模型進行統一、簡化的訪問。這種新方法建立在我們之前的無伺服器推理 API 的基礎上,由於世界一流的提供者,提供了更多的模型、改進的效能和更高的可靠性。有關支援的提供者列表,請參閱文件
  2. 推理端點:一個輕鬆將模型部署到生產環境的產品。推理由 Hugging Face 在您選擇的雲提供商的專用、完全託管的基礎設施上執行。
  3. 本地端點:您還可以使用本地推理伺服器執行推理,例如 llama.cppOllamavLLMLiteLLMText Generation Inference (TGI),方法是將客戶端連線到這些本地端點。

[!TIP] [InferenceClient](/docs/huggingface_hub/v1.4.0/en/package_reference/inference_client#huggingface_hub.InferenceClient) 是一個向我們的 API 發出 HTTP 請求的 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")。然後,我們提供了一個要完成的訊息列表(這裡是一個問題),並將一個附加引數(max_token=100)傳遞給了 API。輸出是一個符合 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 上 100 萬+ 模型的推薦模型。但是,此推薦可能隨時間而變化,因此最好在決定使用哪個模型後顯式設定它。對於第三方提供者,您必須始終指定一個與該提供者相容的模型。

請訪問 Hub 上的模型頁面,探索可透過推理提供者使用的模型。

使用推理端點

我們上面看到的示例使用了推理提供者。雖然這些對於快速原型開發和測試非常有用。一旦您準備好將模型部署到生產環境,您就需要使用專用基礎設施。這就是 推理端點 發揮作用的地方。它允許您部署任何模型並將其公開為私有 API。部署後,您將獲得一個 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 server、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。下表顯示了哪些提供者支援哪些任務

任務 Black Forest Labs Cerebras Clarifai Cohere fal-ai Featherless AI Fireworks AI Groq HF 推理 Hyperbolic Nebius AI Studio Novita AI Nscale OVHcloud AI 端點 Public AI Replicate Sambanova Scaleway Together Wavespeed Zai
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,您只需更新 2 行程式碼,就可以切換到 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 即可使用推理提供者執行模型。如果您的計算機已正確登入,也無需提供 tokenapi_key
  2. InferenceClient 專為 Text-Generation-Inference (TGI) 和 transformers 框架量身定製,這意味著您可以確信它將始終與最新更新保持一致。
  3. InferenceClient 集成了我們的推理端點服務,使其更容易啟動推理端點、檢查其狀態並在其上執行推理。有關更多詳細資訊,請參閱推理端點指南。

InferenceClient.chat.completions.create 只是 InferenceClient.chat_completion 的別名。有關更多詳細資訊,請參閱chat_completion() 的包引用。例項化客戶端時的 base_urlapi_key 引數也是 modeltoken 的別名。這些別名已被定義,以減少從 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 模式。

非同步客戶端

還提供了一個基於 asynciohttpx 的非同步客戶端版本。所有非同步 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,旨在使大型語言模型 (LLM) 能夠透過 Model Context Protocol (MCP) 與外部工具進行互動。此客戶端擴充套件了 AsyncInferenceClient,以無縫整合工具使用。

MCPClient 連線到公開工具的 MCP 伺服器(本地 stdio 指令碼或遠端 http/sse 服務)。它透過 AsyncInferenceClient 將這些工具提供給 LLM。如果 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 類。這個“微型 Agent”透過管理聊天迴圈和狀態來簡化對話 Agent 的建立,本質上充當 MCPClient 的包裝器。它被設計為直接構建在 MCPClient 之上的一個簡單的 while 迴圈。您可以直接從命令列執行這些 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

啟動後,Agent 將載入,列出從其連線的 MCP 伺服器發現的工具,然後就可以接收您的提示了!

高階技巧

在上一節中,我們瞭解了 InferenceClient 的主要方面。現在讓我們深入探討一些更高階的技巧。

賬單

作為 HF 使用者,您每月可獲得積分,用於透過 Hub 上的各種提供商執行推理。您獲得的積分數量取決於您的賬戶型別(免費、PRO 或 Enterprise Hub)。每次推理請求都會根據提供商的定價表向您收費。預設情況下,請求會記入您的個人賬戶。但是,可以透過將 bill_to="<your_org_name>" 傳遞給 InferenceClient 來設定賬單,以便請求記入您所屬的組織。要使此功能生效,您的組織必須訂閱 Enterprise 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: ...
  • 一個指向本地檔案的路徑(strPath
  • 一個指向遠端檔案的 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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.