Hub Python 函式庫文件
在伺服器上執行推論
並獲得增強的文件體驗
開始使用
在伺服器上執行推論
推論是使用訓練好的模型對新數據進行預測的過程。由於此過程可能需要大量計算資源,因此在專用或外部服務上執行是一個很有吸引力的選擇。huggingface_hub 函式庫提供了一個統一的介面,可用於在多個服務上針對託管於 Hugging Face Hub 的模型執行推論。
- 推論供應商 (Inference Providers):提供一種精簡且統一的方式來存取數百種機器學習模型,由我們的無伺服器推論合作夥伴提供支援。這種新方法建立在我們之前的無伺服器推論 API 之上,得益於世界級的供應商,它提供了更多模型、改進的效能以及更高的可靠性。請參閱說明文件以獲取支援的供應商清單。
- 推論端點 (Inference Endpoints):一種讓您輕鬆將模型部署到生產環境的產品。推論由 Hugging Face 在您選擇的雲端供應商上提供的專用、完全託管的基礎設施中執行。
- 本地端點:您也可以透過將客戶端連接到本地端點,使用諸如 llama.cpp、Ollama、vLLM、LiteLLM 或 Text Generation Inference (TGI) 等本地推論伺服器來執行推論。
[!TIP][InferenceClient](/docs/huggingface_hub/v1.16.2/en/package_reference/inference_client#huggingface_hub.InferenceClient) 是一個向我們的 API 發送 HTTP 請求的 Python 客戶端。如果您想直接使用您偏好的工具(curl、postman 等)進行 HTTP 調用,請參考 Inference Providers(推論提供商)文件或 Inference Endpoints(推論終端節點)文件頁面。
入門指南
讓我們從文字轉圖片(text-to-image)任務開始吧
>>> 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 上超過 100 萬個模型的推薦模型。然而,此推薦可能會隨時間改變,因此一旦您決定使用哪一個,最好明確地設定該模型。對於第三方提供商,您必須始終指定與該提供商相容的模型。
造訪 Hub 的 Models(模型)頁面,探索可透過推論提供商使用的模型。
使用推論終端節點 (Inference Endpoints)
我們上面看到的範例使用了推論提供商。雖然這些對於快速建立原型和測試非常有用,但一旦您準備好將模型部署到生產環境,就需要使用專用基礎設施。這正是 Inference Endpoints 發揮作用的地方。它允許您部署任何模型並將其暴露為私人 API。部署後,您將獲得一個網址,您可以使用與以前完全相同的程式碼連接到該網址,只需更改 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")請注意,您不能同時指定網址和提供商——它們是互斥的。網址用於直接連接到已部署的終端節點。
使用本機終端節點
您可以使用 InferenceClient 與您自己機器上運行的本機推論伺服器(llama.cpp, vllm, litellm server, TGI, mlx 等)一起執行對話完成(chat completion)。該 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 帳戶計費。
您可以使用 User Access Token 進行驗證。您可以直接透過 api_key 參數提供您的 Hugging Face 權杖 (token)。
>>> 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 | DeepInfra | fal-ai | Featherless AI | Fireworks AI | Groq | HF Inference | Hyperbolic | Nebius AI Studio | Novita AI | Nscale | NVIDIA | OVHcloud AI Endpoints | 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()(零樣本文本分類) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
造訪 Tasks(任務)頁面以瞭解每個任務的更多資訊。
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 模型。這裡是支援的模型列表。對於身分驗證,您應該傳遞一個有效的 User Access Token 作為 api_key,或者使用 huggingface_hub 進行驗證(參閱 身分驗證指南)。
所有輸入參數和輸出格式都嚴格相同。特別是,您可以傳遞 stream=True 以在 token 生成時接收它們。您還可以使用 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 的客戶端?有幾個原因:
- InferenceClient 是為 Hugging Face 服務配置的。在使用推論提供商執行模型時,您不需要提供
base_url。如果您的機器已經正確登入,您也不需要提供token或api_key。 - InferenceClient 是針對 Text-Generation-Inference (TGI) 和
transformers框架量身定制的,這意味著它將始終與最新更新保持同步。 - InferenceClient 與我們的 Inference Endpoints 服務整合,可以更輕鬆地啟動推論終端節點、檢查其狀態並在其上執行推論。欲了解更多細節,請參閱 Inference Endpoints 指南。
InferenceClient.chat.completions.create只是InferenceClient.chat_completion的別名。欲了解更多細節,請參閱 chat_completion() 的套件參考。實例化客戶端時的base_url和api_key參數也是model和token的別名。定義這些別名是為了減少從OpenAI切換到InferenceClient時的阻力。
函數調用 (Function Calling)
函數調用允許 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 回應)和結構化輸出(用於符合 schema 的回應)。JSON 模式提供機器可讀的數據,而沒有嚴格結構;而結構化輸出則保證既是有效的 JSON,又符合預定義的 schema,以進行可靠的後續處理。
對於 JSON 模式和結構化輸出,我們都遵循 OpenAI API 規格。您可以透過 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 和 httpx。所有非同步 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 服務)。它將這些工具提供給 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」透過管理對話迴圈和狀態來簡化對話型代理的創建,本質上是 MCPClient 的封裝。它被設計成一個建立在 MCPClient 之上的簡單 while 迴圈。您可以直接從命令列執行這些代理:
# 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 的主要方面。現在讓我們深入探討一些更進階的技巧。
計費
作為 Hugging Face 使用者,您每個月都會獲得點數,用於透過 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")請注意,無法向其他使用者或您不屬於的組織計費。如果您想給予他人點數,您必須與他們建立一個聯合組織。
逾時 (Timeout)
推論調用可能會耗費大量時間。預設情況下,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 - 類檔案物件 (file-like object),以二進位模式開啟 (
with open("audio.flac", "rb") as f: ...) - 路徑 (
str或Path),指向本機檔案 - 網址 (
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'}, ...]