Hub Python 函式庫文件
推論
並獲得增強的文件體驗
開始使用
推論
推論是使用訓練好的模型對新數據進行預測的過程。由於此過程可能需要大量計算,因此在專用或外部服務上執行可能是一個不錯的選擇。huggingface_hub 程式庫提供了一個統一的介面,可用於為託管在 Hugging Face Hub 上的模型在多種服務上執行推論。
- 推論供應商 (Inference Providers):提供一種精簡且統一的方式來存取數百種機器學習模型,由我們的無伺服器推論合作夥伴提供支援。這種新方法建立在我們之前的無伺服器推論 API 之上,得益於世界級的供應商,它提供了更多模型、改進的效能以及更高的可靠性。請參閱說明文件以獲取支援的供應商清單。
- 推論端點 (Inference Endpoints):一種讓您輕鬆將模型部署到生產環境的產品。推論由 Hugging Face 在您選擇的雲端供應商上提供的專用、完全託管的基礎設施中執行。
- 本地端點:您也可以透過將客戶端連接到本地端點,使用諸如 llama.cpp、Ollama、vLLM、LiteLLM 或 Text Generation Inference (TGI) 等本地推論伺服器來執行推論。
這些服務可以使用 InferenceClient 物件進行呼叫。請參閱本指南以獲取更多關於如何使用它的資訊。
推論客戶端 (Inference Client)
class huggingface_hub.InferenceClient
< 原始碼 >( model: str | None = None provider: typing.Union[typing.Literal['black-forest-labs', 'cerebras', 'clarifai', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'hyperbolic', 'nebius', 'novita', 'nscale', 'nvidia', 'openai', 'ovhcloud', 'publicai', 'replicate', 'sambanova', '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 )
參數
- model (
str,optional) — 用於執行推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID(例如meta-llama/Meta-Llama-3-8B-Instruct)或部署的推論端點 URL。預設為 None,此時會自動為該任務選擇推薦模型。注意:為了與 OpenAI 客戶端有更好的相容性,model已被別名為base_url。這兩個參數互斥。如果將 URL 作為model或base_url傳遞給聊天補全,(/v1)/chat/completions後綴路徑將會附加到 URL 後。 - provider (
str, optional) — 用於推論的供應商名稱。可以是"black-forest-labs"、"cerebras"、"clarifai"、"cohere"、"deepinfra"、"fal-ai"、"featherless-ai"、"fireworks-ai"、"groq"、"hf-inference"、"hyperbolic"、"nebius"、"novita"、"nscale"、"nvidia"、"openai"、"ovhcloud"、"publicai"、"replicate"、"sambanova"、"scaleway"、"together"、"wavespeed"或"zai-org"。預設為 “auto”:自動路由,預設為“最快”供應商;您可以在 https://huggingface.co/settings/inference-providers 切換為“最便宜”或“偏好”的供應商順序。如果 model 是 URL 或傳遞了base_url,則不會使用provider。 - token (
str, optional) — Hugging Face 權杖 (token)。如果未提供,將預設使用本地儲存的權杖。注意:為了與 OpenAI 客戶端有更好的相容性,token已被別名為api_key。這兩個參數互斥且行為完全相同。 - timeout (
float,optional) — 等待伺服器回應的最長秒數。預設為 None,表示會持續輪詢直到伺服器可用為止。 - headers (
dict[str, str],optional) — 發送到伺服器的額外標頭。預設情況下,僅發送驗證和 user-agent 標頭。此字典中的值將覆蓋預設值。 - bill_to (
str,optional) — 用於請求的計費帳戶。預設情況下,請求會計入使用者的帳戶。請求只能計入使用者所屬且已訂閱 Enterprise Hub 的組織。 - cookies (
dict[str, str],optional) — 發送到伺服器的額外 cookies。 - base_url (
str,optional) — 用於執行推論的基礎 URL。這是與model重複的參數,旨在使 InferenceClient 遵循與openai.OpenAI客戶端相同的模式。如果設定了model,則無法使用此參數。預設為 None。 - api_key (
str,optional) — 用於驗證的權杖。這是與token重複的參數,旨在使 InferenceClient 遵循與openai.OpenAI客戶端相同的模式。如果設定了token,則無法使用此參數。預設為 None。
初始化新的推論客戶端。
InferenceClient 旨在提供統一的推論執行體驗。該客戶端可以與(免費的)Inference API、自託管的 Inference Endpoints 或第三方推論供應商無縫整合使用。
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 ) → list[AudioClassificationOutputElement]
參數
- audio (Union[str, Path, bytes, BinaryIO]) — 要分類的音訊內容。可以是原始音訊位元組、本地音訊檔案,或是指向音訊檔案的 URL。
- model (
str, optional) — 用於音訊分類的模型。可以是託管在 Hugging Face Hub 上的模型 ID 或部署的推論端點 URL。如果未提供,將使用預設的音訊分類推薦模型。 - top_k (
int, optional) — 指定時,將輸出限制為最有可能的前 K 個類別。 - function_to_apply (
"AudioClassificationOutputTransform", optional) — 用於模型輸出的函式,以便檢索分數。
返回
list[AudioClassificationOutputElement]
包含預測標籤及其置信度的 AudioClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
對提供的音訊內容執行音訊分類。
audio_to_audio (音訊轉音訊)
< 原始碼 >( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: str | None = None ) → list[AudioToAudioOutputElement]
參數
- audio (Union[str, Path, bytes, BinaryIO]) — 模型所需的音訊內容。可以是原始音訊位元組、本地音訊檔案,或是指向音訊檔案的 URL。
- model (
str, optional) — 模型可以是任何接受音訊檔案並返回另一個音訊檔案的模型。可以是託管在 Hugging Face Hub 上的模型 ID 或部署的推論端點 URL。如果未提供,將使用預設的 audio_to_audio 推薦模型。
返回
list[AudioToAudioOutputElement]
包含音訊標籤、內容類型以及 Blob 格式音訊內容的 AudioToAudioOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
InferenceTimeoutError— 如果模型不可用或請求逾時。HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
根據模型執行與音訊轉音訊相關的多種任務(例如:語音增強、音源分離)。
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 ) → AutomaticSpeechRecognitionOutput
參數
- audio (Union[str, Path, bytes, BinaryIO]) — 要轉錄的內容。可以是原始音訊位元組、本地音訊檔案,或指向音訊檔案的 URL。
- model (
str, optional) — 用於 ASR 的模型。可以是託管在 Hugging Face Hub 上的模型 ID 或部署的推論端點 URL。如果未提供,將使用預設的 ASR 推薦模型。 - extra_body (
dict, optional) — 要傳遞給模型的其他供應商特定參數。請參閱供應商的說明文件以了解支援的參數。
包含轉錄文本以及(可選)時間戳區塊的項目。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
對給定的音訊內容執行自動語音辨識(ASR 或音訊轉文本)。
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 ) → ChatCompletionOutput 或 ChatCompletionStreamOutput 的迭代器
參數
- messages (
ChatCompletionInputMessage列表) — 由角色和內容對組成的對話歷史記錄。 - model (
str, optional) — 用於聊天補全的模型。可以是託管在 Hugging Face Hub 上的模型 ID 或部署的推論端點 URL。如果未提供,將使用預設的聊天型文本生成推薦模型。詳情請參閱 https://huggingface.co/tasks/text-generation。如果model是模型 ID,它會作為model參數傳遞給伺服器。如果您想定義自訂 URL 同時在請求負載中設定model,則必須在初始化 InferenceClient 時設定base_url。 - frequency_penalty (
float, optional) — 根據 Token 到目前為止在文本中出現的頻率對新 Token 進行懲罰。範圍:[-2.0, 2.0]。預設為 0.0。 - logit_bias (
list[float], optional) — 調整特定 Token 在生成輸出中出現的可能性。 - logprobs (
bool, optional) — 是否返回輸出 Token 的對數機率。如果為 true,則返回訊息內容中每個輸出 Token 的對數機率。 - max_tokens (
int, optional) — 回應中允許的最大 Token 數量。預設為 100。 - n (
int, optional) — 每個提示要生成的補全數量。 - presence_penalty (
float, optional) — -2.0 到 2.0 之間的數字。正值根據新 Token 目前在文本中是否已出現來對其進行懲罰,從而增加模型談論新主題的可能性。 - response_format (
ChatCompletionInputGrammarType(), optional) — 語法約束。可以是 JSONSchema 或正規表示式。 - seed (Optional
int, optional) — 用於可重現控制流的 Seed。預設為 None。 - stop (
list[str], optional) — 最多四個字串,用以觸發回應的結束。預設為 None。 - stream (
bool, optional) — 啟用回應的即時串流。預設為 False。 - stream_options (
ChatCompletionInputStreamOptions, optional) — 串流補全的選項。 - temperature (
float, optional) — 控制生成的隨機性。較低的值可確保較不隨機的補全。範圍:[0, 2]。預設為 1.0。 - top_logprobs (
int, optional) — 介於 0 到 5 之間的整數,指定在每個 Token 位置要返回的最可能 Token 的數量,每個 Token 都帶有相關的對數機率。如果使用此參數,必須將 logprobs 設定為 true。 - top_p (
float, optional) — 從最可能的下一個字詞中進行取樣的分數。必須介於 0 到 1 之間。預設為 1.0。 - tool_choice (
ChatCompletionInputToolChoiceClass或ChatCompletionInputToolChoiceEnum(), optional) — 用於補全的工具。預設為 “auto”。 - tool_prompt (
str, optional) — 在工具之前附加的提示詞。 - tools (
ChatCompletionInputTool列表, optional) — 模型可以呼叫的工具列表。目前,僅支援函數作為工具。使用此參數提供一個函數列表,模型可以為其生成 JSON 輸入。 - extra_body (
dict, optional) — 要傳遞給模型的其他供應商特定參數。請參閱供應商的說明文件以了解支援的參數。
從伺服器返回的生成文本
- 如果
stream=False,則生成的文本將作為 ChatCompletionOutput 返回(預設)。 - 如果
stream=True,則生成的文本將以 Token 為單位作為 ChatCompletionStreamOutput 的序列返回。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
一種使用特定語言模型完成對話的方法。
client.chat_completion方法被別名為client.chat.completions.create,以便與 OpenAI 的客戶端相容。輸入和輸出完全相同,使用任一語法都會產生相同的結果。請查看 推論指南 以獲取有關 OpenAI 相容性的更多詳細資訊。
您可以使用
extra_body參數將特定於供應商的參數傳遞給模型。
範例
>>> 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
)
)使用串流的範例
>>> 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 語法的範例
# 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 帳戶。
>>> 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 路由使用第三方供應商的範例。使用費用將計入您的 Hugging Face 帳戶。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="sambanova", # Use Sambanova 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?"}],
... )使用圖像 + 文本作為輸入的範例
>>> 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.使用工具的範例
>>> 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 的範例
>>> 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 (文件問答)
< 原始碼 >( 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 ) → list[DocumentQuestionAnsweringOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO]) — 作為上下文的輸入圖像。可以是原始位元組、圖像檔案,或指向線上圖像的 URL。 - question (
str) — 要回答的問題。 - model (
str, optional) — 用於文件問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID 或部署的推論端點 URL。如果未提供,將使用預設的文件問答推薦模型。預設為 None。 - doc_stride (
int, optional) — 如果文件中的字詞太長而無法與問題一起放入模型中,它將被分成幾個區塊並有部分重疊。此參數控制該重疊的大小。 - handle_impossible_answer (
bool, optional) — 是否接受“不可能”作為答案。 - lang (
str, 選填) — 執行 OCR 時使用的語言。預設為英文 (english)。 - max_answer_len (
int, 選填) — 預測答案的最大長度(例如:僅考慮長度較短的答案)。 - max_question_len (
int, 選填) — 經過標記化 (tokenization) 後問題的最大長度。必要時將會截斷。 - max_seq_len (
int, 選填) — 傳遞給模型的每個區塊的總句子(上下文 + 問題)標記總長度上限。必要時,上下文將被拆分為多個區塊(使用 doc_stride 進行重疊)。 - top_k (
int, 選填) — 要回傳的答案數量(將按可能性排序)。若上下文中的可用選項不足,回傳的數量可能會少於 top_k。 - word_boxes (
list[Union[list[float], str, 選填) — 單詞和邊界框 (bounding box) 的列表(正規化至 0->1000)。若提供此參數,推論過程將跳過 OCR 步驟,並改用提供的邊界框。
返回
list[DocumentQuestionAnsweringOutputElement]
包含預測標籤、相關機率、單詞 ID 和頁碼的 DocumentQuestionAnsweringOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
針對文件圖像回答問題。
範例
>>> 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
< 來源 >( 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 ) → np.ndarray
參數
- text (str 或 list[str]) — 要嵌入的文字或文字列表。
- model (str, 選填) — 用於特徵提取任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推論端點 (Inference Endpoint) 的 URL。若未提供,將使用預設推薦的特徵提取模型。預設為 None。
- normalize (bool, 選填) — 是否對嵌入向量進行正規化。僅適用於由 Text-Embedding-Inference 驅動的伺服器。
- prompt_name (str, 選填) — 用於編碼的提示詞名稱。若未設定,則不套用任何提示詞。必須是 Sentence Transformers 設定 prompts 字典中的鍵。例如,如果
prompt_name為 “query” 且prompts為 {“query”: “query: ”,…},則句子 “What is the capital of France?” 將被編碼為 “query: What is the capital of France?”,因為提示詞文字會被置於任何要編碼的文字之前。 - truncate (bool, 選填) — 是否截斷嵌入向量。僅適用於由 Text-Embedding-Inference 驅動的伺服器。
- truncation_direction (Literal[“left”, “right”], 選填) — 當傳遞 truncate=True 時,輸入的哪一側應該被截斷。
- dimensions (int, 選填) — 產生的輸出嵌入向量應具有的維度數量。僅適用於相容 OpenAI 的嵌入端點。
- encoding_format (Literal[“float”, “base64”], 選填) — 輸出嵌入向量的格式。可以是 “float” 或 “base64”。僅適用於相容 OpenAI 的嵌入端點。
返回
np.ndarray
表示輸入文字的嵌入向量,格式為 float32 numpy 陣列。
引發
[InferenceTimeoutError] 或 [HfHubHTTPError]
- [InferenceTimeoutError] — 若模型無法使用或請求逾時。
- [HfHubHTTPError] — 若請求失敗,且 HTTP 錯誤狀態碼非 503。
為給定的文字或一批文字產生嵌入向量。
範例
>>> 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
< 來源 >( text: str model: str | None = None targets: list[str] | None = None top_k: int | None = None ) → list[FillMaskOutputElement]
參數
- text (
str) — 要填空的字串,必須包含 [MASK] 標記(請查看模型卡以確認遮罩的確切名稱)。 - model (
str, 選填) — 用於填空任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推論端點的 URL。若未提供,將使用預設推薦的填空模型。 - targets (
list[str, 選填) — 若傳入此參數,模型會將分數限制在指定的目標範圍內,而非在整個詞彙表中搜尋。若提供的目標不在模型詞彙表中,它們將會被標記化,並使用第一個產生的標記(會產生警告,且速度可能較慢)。 - top_k (
int, 選填) — 若傳入此參數,將覆寫回傳的預測數量。
返回
list[FillMaskOutputElement]
包含預測標籤、相關機率、標記參考和完成後文字的 FillMaskOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
填補缺少單詞(更準確地說是標記)的空缺。
範例
>>> 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
< 來源 >( model: str | None = None ) → dict[str, Any]
取得關於已部署端點的資訊。
此端點僅適用於由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 驅動的端點。由 transformers 驅動的端點將回傳空酬載 (payload)。
範例
>>> 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
< 來源 >( model: str | None = None ) → bool
檢查已部署端點的運作狀態。
健康檢查僅適用於由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 驅動的推論端點。
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 ) → list[ImageClassificationOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分類的圖像。可以是原始位元組、圖像檔案、線上圖像的 URL 或 PIL 圖像。 - model (
str, 選填) — 用於圖像分類的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推論端點的 URL。若未提供,將使用預設推薦的圖像分類模型。 - function_to_apply (
"ImageClassificationOutputTransform", 選填) — 用於處理模型輸出以檢索分數的函數。 - top_k (
int, 選填) — 指定時,將輸出限制為機率最高的 K 個類別。
返回
list[ImageClassificationOutputElement]
包含預測標籤和相關機率的 ImageClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定的模型對給定圖像執行圖像分類。
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 ) → list[ImageSegmentationOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分割的圖像。可以是原始位元組、圖像檔案、線上圖像的 URL 或 PIL 圖像。 - model (
str, 選填) — 用於圖像分割的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推論端點的 URL。若未提供,將使用預設推薦的圖像分割模型。 - mask_threshold (
float, 選填) — 將預測的遮罩轉為二進位值時使用的門檻。 - overlap_mask_area_threshold (
float, 選填) — 用於消除小型、斷開區段的遮罩重疊門檻。 - subtask (
"ImageSegmentationSubtask", 選填) — 根據模型能力所執行的分割子任務。 - threshold (
float, 選填) — 過濾掉預測遮罩的機率門檻。
返回
list[ImageSegmentationOutputElement]
包含分割遮罩和相關屬性的 ImageSegmentationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定的模型對給定圖像執行圖像分割。
若要處理圖像,必須安裝
PIL(pip install Pillow)。
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 ) → Image
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 轉換用的輸入圖像。可以是原始位元組、圖像檔案、線上圖像的 URL 或 PIL 圖像。 - prompt (
str, 選填) — 引導圖像生成的文字提示詞。 - negative_prompt (
str, 選填) — 用於引導在圖像生成中排除哪些內容的提示詞。 - num_inference_steps (
int, 選填) — 用於擴散模型 (diffusion models)。去噪步驟的數量。較多的去噪步驟通常會產生更高品質的圖像,但推論速度會變慢。 - guidance_scale (
float, 選填) — 用於擴散模型。較高的引導比例值會鼓勵模型產生與文字提示詞高度相關的圖像,但可能會犧牲圖像品質。 - model (
str, 選填) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推論端點的 URL。此參數會覆寫執行個體層級定義的模型。預設為 None。 - target_size (
ImageToImageTargetSize, 選填) — 輸出圖像的尺寸(像素)。此參數僅由部分供應商和特定模型支援。若不支援,將會被忽略。
返回
影像
轉換後的圖像。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定的模型執行圖像到圖像的轉換。
若要處理圖像,必須安裝
PIL(pip install Pillow)。
image_to_text
< 來源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: str | None = None ) → ImageToTextOutput
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要進行標註的輸入圖像。可以是原始位元組、圖像檔案、線上圖像的 URL 或 PIL 圖像。 - model (
str, 選填) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推論端點的 URL。此參數會覆寫執行個體層級定義的模型。預設為 None。
生成的文字。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
輸入圖像並回傳文字。
根據您的使用案例(圖像標註、光學字元識別 (OCR)、Pix2Struct 等),模型的輸出可能會非常不同。請查看模型卡以進一步了解該模型的特性。
範例
>>> 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
< 原始碼 >( 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 ) → bytes
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用於生成影片的輸入圖像。可以是原始位元組 (bytes)、圖像檔案、線上圖像的 URL 或 PIL 圖像。 - model (
str, 選填) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署的推論端點 (Inference Endpoint) URL。此參數會覆蓋實例層級定義的模型。預設為 None。 - prompt (
str, 選填) — 引導影片生成的文字提示詞。 - negative_prompt (
str, 選填) — 用於引導影片生成中「不」包含哪些內容的提示詞。 - num_frames (
float, 選填) — num_frames 參數決定了生成影片的影格數量。 - num_inference_steps (
int, 選填) — 針對擴散模型 (diffusion models)。去雜訊步驟的數量。通常更多的步驟會產生更高品質的圖像,但代價是推論速度較慢。 - guidance_scale (
float, 選填) — 針對擴散模型。較高的引導尺度數值會鼓勵模型生成與文字提示更緊密相關的影片,但代價是較低的圖像品質。 - seed (
int, 選填) — 用於影片生成的種子數 (seed)。 - target_size (
ImageToVideoTargetSize, 選填) — 輸出影片影格的大小(以像素為單位)。 - num_inference_steps (
int, 選填) — 去雜訊步驟的數量。通常更多的去雜訊步驟會產生更高品質的影片,但代價是推論速度較慢。 - seed (
int, 選填) — 隨機數產生器的種子數。
返回
bytes
生成的影片。
根據輸入圖像生成影片。
object_detection
< 原始碼 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: str | None = None threshold: float | None = None ) → list[ObjectDetectionOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用於偵測物件的圖像。可以是原始位元組 (bytes)、圖像檔案、線上圖像的 URL 或 PIL 圖像。 - model (
str, 選填) — 用於物件偵測的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署的推論端點 URL。若未提供,將使用預設推薦的物件偵測模型 (DETR)。 - threshold (
float, 選填) — 進行預測所需的機率閥值。
返回
list[ObjectDetectionOutputElement]
包含邊界框 (bounding boxes) 與相關屬性的 ObjectDetectionOutputElement 項目清單。
引發
InferenceTimeoutError 或 HfHubHTTPError 或 ValueError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。ValueError— 若請求輸出不是清單 (List) 時發生。
使用指定模型對給定圖像執行物件偵測。
若要處理圖像,必須安裝
PIL(pip install Pillow)。
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 ) → Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]
參數
- question (
str) — 要回答的問題。 - context (
str) — 問題的背景內容。 - model (
str) — 用於問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署的推論端點 URL。 - align_to_words (
bool, 選填) — 嘗試將答案對齊到真實單詞。能提升以空格分隔語言的品質。對於非以空格分隔的語言(如日文或中文)可能會降低效果。 - doc_stride (
int, 選填) — 如果背景內容太長而無法與問題一起放入模型中,它將被分成幾個重疊的區塊。此參數控制該重疊的大小。 - handle_impossible_answer (
bool, 選填) — 是否接受「不可能 (impossible)」作為答案。 - max_answer_len (
int, 選填) — 預測答案的最大長度(例如,僅考慮長度較短的答案)。 - max_question_len (
int, 選填) — Token 化後問題的最大長度。必要時會進行截斷。 - max_seq_len (
int, 選填) — 傳遞給模型的每個區塊之總句子的最大長度(背景 + 問題,以 Token 為單位)。必要時,背景內容將被分成多個區塊(使用 docStride 作為重疊)。 - top_k (
int, 選填) — 要返回的答案數量(將按可能性順序選出)。請注意,如果背景內容中可用的選項不足,我們返回的答案數量可能會小於 top_k。
返回
Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]
當 top_k 為 1 或未提供時,返回單一的 QuestionAnsweringOutputElement。當 top_k 大於 1 時,返回 QuestionAnsweringOutputElement 的清單。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
從給定的文字中檢索問題的答案。
sentence_similarity
< 原始碼 >( sentence: str other_sentences: list model: str | None = None ) → list[float]
參數
- sentence (
str) — 用於與其他句子比較的基準句子。 - other_sentences (
list[str]) — 要進行比較的句子清單。 - model (
str, 選填) — 用於句子相似度任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署的推論端點 URL。若未提供,將使用預設推薦的句子相似度模型。預設為 None。
返回
list[float]
代表輸入文字的嵌入向量 (embedding)。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
透過比較嵌入向量,計算一個句子與一系列其他句子之間的語義相似度。
範例
>>> 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]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 ) → SummarizationOutput
參數
- text (
str) — 要摘要的輸入文字。 - model (
str, 選填) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署的推論端點 URL。若未提供,將使用預設推薦的摘要模型。 - clean_up_tokenization_spaces (
bool, 選填) — 是否清除文字輸出中可能多餘的空格。 - generate_parameters (
dict[str, Any], 選填) — 文字生成演算法的額外參數設定。 - truncation (
"SummarizationTruncationStrategy", 選填) — 使用的截斷策略。
生成的摘要文字。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定模型生成給定文字的摘要。
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 ) → TableQuestionAnsweringOutputElement
參數
- table (
str) — 資料表,表示為鍵值清單字典 (dict of lists),其中鍵為標題,列表則為所有值。所有列表的大小必須相同。 - query (
str) — 您想對表格提出的純文字查詢。 - model (
str) — 用於表格問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署的推論端點 URL。 - padding (
"Padding", 選填) — 啟用並控制填充 (padding)。 - sequential (
bool, 選填) — 是否循序進行推論或以批次 (batch) 進行。批次處理速度較快,但像 SQA 這類模型由於其對話性質,需要以循序方式執行推論以提取序列內的關係。 - truncation (
bool, 選填) — 啟用並控制截斷。
包含答案、座標、單元格以及使用的聚合器 (aggregator) 之表格問答輸出。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
從表格中的資訊檢索問題的答案。
範例
>>> 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
< 原始碼 >( table: dict model: str | None = None ) → List
參數
- table (
dict[str, Any]) — 要分類的屬性集。 - model (
str, 選填) — 用於表格分類任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署的推論端點 URL。若未提供,將使用預設推薦的表格分類模型。預設為 None。
返回
List
標籤清單,初始表格中每一列一個標籤。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
根據一組屬性對目標類別(群組)進行分類。
範例
>>> 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
< 原始碼 >( table: dict model: str | None = None ) → List
參數
- table (
dict[str, Any]) — 儲存在表格中的屬性集。用於預測目標的屬性可以是數值型或類別型。 - model (
str, optional) — 用於表格迴歸任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推理端點 (Inference Endpoint) 的 URL。若未提供,將使用預設推薦的表格迴歸模型。預設值為 None。
返回
List
預測數值目標值的列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
在給定表格中一組屬性/特徵的情況下,預測數值目標值。
範例
>>> 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: str model: str | None = None top_k: int | None = None function_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None ) → list[TextClassificationOutputElement]
參數
- text (
str) — 要進行分類的字串。 - model (
str, optional) — 用於文字分類任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推理端點的 URL。若未提供,將使用預設推薦的文字分類模型。預設值為 None。 - top_k (
int, optional) — 若有指定,將輸出限制為機率最高的 K 個類別。 - function_to_apply (
"TextClassificationOutputTransform", optional) — 用於對模型輸出進行處理以獲取分數的函數。
返回
list[TextClassificationOutputElement]
一個包含 TextClassificationOutputElement 項目的列表,其中包含預測標籤與相關機率。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
對給定文字執行文字分類(例如:情感分析)。
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 stop_sequences: 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 ) → Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]
參數
- prompt (
str) — 輸入文字。 - details (
bool, optional) — 預設情況下,text_generation 會回傳一個字串。若需要詳細輸出(token、機率、seed、結束原因等),請傳入details=True。僅適用於在text-generation-inference後端上執行的模型。 - stream (
bool, optional) — 預設情況下,text_generation 會回傳完整的生成文字。若需要串流回傳 token,請傳入stream=True。僅適用於在text-generation-inference後端上執行的模型。 - model (
str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推理端點的 URL。此參數會覆蓋實例層級定義的模型。預設值為 None。 - adapter_id (
str, optional) — Lora 適配器 ID。 - best_of (
int, optional) — 生成 best_of 個序列,並回傳其中 token 對數機率 (logprobs) 最高的一個。 - decoder_input_details (
bool, optional) — 回傳解碼器輸入 token 的 logprobs 與 ID。若要生效,必須同時設定details=True。預設值為False。 - do_sample (
bool, optional) — 啟動 Logits 取樣。 - frequency_penalty (
float, optional) — -2.0 到 2.0 之間的數字。正值會根據新 token 在目前文字中已出現的頻率進行懲罰,降低模型逐字重複相同句子的可能性。 - grammar (TextGenerationInputGrammarType, optional) — 文法限制。可以是 JSONSchema 或正規表示式 (regex)。
- max_new_tokens (
int, optional) — 生成的最大 token 數量。預設值為 100。 - repetition_penalty (
float, optional) — 重複懲罰參數。1.0 代表無懲罰。詳情請參考此論文。 - return_full_text (
bool, optional) — 是否將 prompt 加入到生成文字的前方。 - seed (
int, optional) — 隨機取樣種子。 - stop (
list[str], optional) — 若生成了stop中的成員,則停止生成 token。 - stop_sequences (
list[str], optional) — 已棄用的參數。請改用stop。 - temperature (
float, optional) — 用於調整 Logits 分佈的數值。 - top_n_tokens (
int, optional) — 在每個生成步驟中,回傳最有可能的top_n_tokens個 token 的相關資訊,而不僅僅是已取樣的 token。 - top_k (
int, optional) — 用於 top-k 過濾的最高機率詞彙 token 數量。 - top_p (
float, optional) — 若設定為 < 1,則僅保留機率加總等於或高於top_p的最小一組機率最高 token。 - truncate (
int, optional) — 將輸入 token 截斷至指定大小。 - typical_p (
float, optional) — Typical Decoding 機率質量。更多資訊請參閱用於自然語言生成的 Typical Decoding。 - watermark (
bool, optional) — 使用大型語言模型浮水印進行浮水印標記。
返回
Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]
從伺服器返回的生成文本
- 若
stream=False且details=False,則生成的文字將以str形式回傳(預設值) - 若
stream=True且details=False,則生成的文字將以逐 token 的Iterable[str]形式回傳 - 若
stream=False且details=True,則生成的文字將以包含更多詳細資訊的 TextGenerationOutput 形式回傳 - 若
details=True且stream=True,則生成的文字將以逐 token 的 TextGenerationStreamOutput 可迭代物件形式回傳
引發
ValidationError 或 InferenceTimeoutError 或 HfHubHTTPError
ValidationError— 若輸入數值無效。此時不會向伺服器發送任何 HTTP 呼叫。- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
給定一個提示詞 (prompt),生成後續文字。
若您想從對話訊息生成回應,應使用 InferenceClient.chat_completion() 方法。它接受訊息列表而非單一文字提示,並會為您處理對話模板。
範例
>>> 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
< 原始碼 >( 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 ) → Image
參數
- prompt (
str) — 用於生成圖像的提示詞。 - negative_prompt (
str, optional) — 用於指導在圖像生成中「不要」包含什麼的提示詞。 - height (
int, optional) — 輸出圖像的高度(以像素為單位)。 - width (
int, optional) — 輸出圖像的寬度(以像素為單位)。 - num_inference_steps (
int, optional) — 去噪步驟的數量。較多的去噪步驟通常會產生更高品質的圖像,但推理速度會變慢。 - guidance_scale (
float, optional) — 較高的引導比例數值會鼓勵模型生成與文字提示詞更緊密連結的圖像,但數值過高可能會導致飽和與其他偽影。 - model (
str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推理端點的 URL。若未提供,將使用預設推薦的文生圖模型。預設值為 None。 - scheduler (
str, optional) — 使用相容的排程器 (scheduler) 覆蓋預設值。 - seed (
int, optional) — 隨機數生成器的種子。 - extra_body (
dict[str, Any], optional) — 要傳遞給模型的額外供應商特定參數。有關支援的參數,請參閱供應商的說明文件。
返回
影像
生成的圖像。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定模型根據給定文字生成圖像。
若要處理圖像,必須安裝
PIL(pip install Pillow)。
您可以使用
extra_body參數將特定於供應商的參數傳遞給模型。
範例
>>> 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")>>> 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 路由使用第三方供應商的範例。使用費用將計入您的 Hugging Face 帳戶。
>>> 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 供應商並附加額外參數的範例
>>> 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
< 原始碼 >( 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 ) → bytes
參數
- text (
str) — 要合成的文字。 - model (
str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署推理端點的 URL。若未提供,將使用預設推薦的語音合成模型。預設值為 None。 - do_sample (
bool, optional) — 在生成新 token 時,是否使用取樣 (sampling) 而非貪婪解碼 (greedy decoding)。 - early_stopping (
Union[bool, "TextToSpeechEarlyStoppingEnum"], 選填) — 控制基於束搜尋(beam-based)方法的停止條件。 - epsilon_cutoff (
float, 選填) — 若設定為嚴格介於 0 與 1 之間的浮點數,則僅會對條件機率大於 epsilon_cutoff 的 token 進行採樣。在論文中,建議值範圍為 3e-4 至 9e-4,視模型大小而定。詳情請參閱 截斷採樣作為語言模型去平滑化(Truncation Sampling as Language Model Desmoothing)。 - eta_cutoff (
float, 選填) — Eta 採樣是局部典型採樣(locally typical sampling)與 epsilon 採樣的混合體。若設定為嚴格介於 0 與 1 之間的浮點數,則僅在 token 大於 eta_cutoff 或 sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))) 時才納入考量。後者直觀上為期望的下一個 token 機率,並由 sqrt(eta_cutoff) 進行縮放。在論文中,建議值範圍為 3e-4 至 2e-3,視模型大小而定。詳情請參閱 截斷採樣作為語言模型去平滑化(Truncation Sampling as Language Model Desmoothing)。 - max_length (
int, 選填) — 生成文字的最大長度(以 token 計算),包含輸入部分。 - max_new_tokens (
int, 選填) — 生成 token 的最大數量。其優先級高於 max_length。 - min_length (
int, 選填) — 生成文字的最小長度(以 token 計算),包含輸入部分。 - min_new_tokens (
int, 選填) — 生成 token 的最小數量。其優先級高於 min_length。 - num_beam_groups (
int, 選填) — 將 num_beams 分成的組數,以確保不同束組(beam groups)之間的多樣性。詳情請參閱 這篇論文。 - num_beams (
int, 選填) — 束搜尋(beam search)所使用的束數。 - penalty_alpha (
float, 選填) — 該數值用於平衡對比搜尋解碼(contrastive search decoding)中的模型置信度與退化懲罰(degeneration penalty)。 - temperature (
float, 選填) — 用於調節下一個 token 機率的數值。 - top_k (
int, 選填) — 為了 top-k 過濾而保留的最高機率詞彙 token 數量。 - top_p (
float, 選填) — 若設定為小於 1 的浮點數,則僅保留機率累加起來達到 top_p 或更高的最小機率 token 集合用於生成。 - typical_p (
float, 選填) — 局部典型性(local typicality)衡量了在已生成的局部文字前提下,預測下一個目標 token 的條件機率與預測下一個隨機 token 的預期條件機率之間的相似程度。若設定為小於 1 的浮點數,則保留機率累加起來達到 typical_p 或更高的最小局部典型 token 集合用於生成。詳情請參閱 這篇論文。 - use_cache (
bool, 選填) — 模型是否應使用過去的 key/values 注意力快取來加速解碼。 - extra_body (
dict[str, Any], 選填) — 傳遞給模型的額外供應商特定參數。請參閱供應商文件以取得支援的參數資訊。
返回
bytes
生成的音訊。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
合成一段朗讀給定文字的音訊。
您可以使用
extra_body參數將特定於供應商的參數傳遞給模型。
範例
>>> 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 帳戶。
>>> 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 路由使用第三方供應商的範例。使用費用將計入您的 Hugging Face 帳戶。
>>> 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)>>> 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」的 music-gen 範例
>>> 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
< 原始碼 >( 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 ) → bytes
參數
- prompt (
str) — 用於生成影片的提示詞。 - model (
str, 選填) — 用於推論的模型。可以是託管於 Hugging Face Hub 上的模型 ID,或是已部署推論端點(Inference Endpoint)的 URL。若未提供,將使用預設推薦的文生影片模型。預設值為 None。 - guidance_scale (
float, 選填) — 較高的 guidance scale 數值會鼓勵模型生成與文字提示詞連結更緊密的影片,但數值過高可能會導致飽和及其他異常現象。 - negative_prompt (
list[str], 選填) — 一個或多個提示詞,用於指導影片生成中不應包含的內容。 - num_frames (
float, 選填) — num_frames 參數決定了生成多少影格的影片。 - num_inference_steps (
int, 選填) — 去噪步數。通常更多的去噪步數會帶來更高品質的影片,但推論速度會變慢。 - seed (
int, 選填) — 隨機數產生器的種子(seed)。 - extra_body (
dict[str, Any], 選填) — 傳遞給模型的額外供應商特定參數。請參閱供應商文件以取得支援的參數資訊。
返回
bytes
生成的影片。
根據給定的文字生成一段影片。
您可以使用
extra_body參數將特定於供應商的參數傳遞給模型。
範例
直接使用第三方供應商的範例。使用量將計入您的 fal.ai 帳戶。
>>> 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 路由使用第三方供應商的範例。使用費用將計入您的 Hugging Face 帳戶。
>>> 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
< 原始碼 >( text: str model: str | None = None aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None ignore_labels: list[str] | None = None stride: int | None = None ) → list[TokenClassificationOutputElement]
參數
- text (
str) — 要進行分類的字串。 - model (
str, 選填) — 用於 token 分類任務的模型。可以是託管於 Hugging Face Hub 上的模型 ID,或是已部署推論端點的 URL。若未提供,將使用預設推薦的 token 分類模型。預設值為 None。 - aggregation_strategy (
"TokenClassificationAggregationStrategy", 選填) — 用於根據模型預測結果聚合(合併)token 的策略。 - ignore_labels (
list[str], 選填) — 要忽略的標籤列表。 - stride (
int, 選填) — 切分輸入文字為區塊(chunks)時,區塊間重疊的 token 數量。
返回
list[TokenClassificationOutputElement]
包含實體群組、置信度分數、詞彙、起始與結束索引的 TokenClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
對給定文字執行 token 分類。通常用於句法分析(如文法結構),或命名實體識別(NER)以理解文字內包含的關鍵字。
範例
>>> 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,
)
]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 ) → TranslationOutput
參數
- text (
str) — 要進行翻譯的字串。 - model (
str, 選填) — 用於翻譯任務的模型。可以是託管於 Hugging Face Hub 上的模型 ID,或是已部署推論端點的 URL。若未提供,將使用預設推薦的翻譯模型。預設值為 None。 - src_lang (
str, 選填) — 文字的來源語言。對於可從多種語言進行翻譯的模型是必要的。 - tgt_lang (
str, 選填) — 要翻譯成的目標語言。對於可翻譯成多種語言的模型是必要的。 - clean_up_tokenization_spaces (
bool, 選填) — 是否清理文字輸出中可能多餘的空格。 - truncation (
"TranslationTruncationStrategy", 選填) — 使用的截斷策略。 - generate_parameters (
dict[str, Any], 選填) — 文字生成演算法的額外參數設定。
生成的翻譯文字。
引發
InferenceTimeoutError 或 HfHubHTTPError 或 ValueError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。ValueError— 若僅提供了src_lang和tgt_lang引數中的其中一個。
將文字從一種語言轉換為另一種語言。
請參閱 https://huggingface.co/tasks/translation 以取得如何針對您的特定用例選擇最佳模型的更多資訊。來源和目標語言通常取決於模型。不過,某些模型可以指定來源和目標語言。如果您使用的是其中一種模型,可以使用 src_lang 和 tgt_lang 引數來傳遞相關資訊。
範例
>>> 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.')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 ) → list[VisualQuestionAnsweringOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用於上下文的輸入影像。可以是原始 bytes、影像檔案、線上影像的 URL 或 PIL Image。 - question (
str) — 要回答的問題。 - model (
str, 選填) — 用於視覺問答任務的模型。可以是託管於 Hugging Face Hub 上的模型 ID,或是已部署推論端點的 URL。若未提供,將使用預設推薦的視覺問答模型。預設值為 None。 - top_k (
int, 選填) — 要返回的答案數量(將按可能性排序選擇)。請注意,如果上下文內沒有足夠的可用選項,返回的答案數量會少於 topk。
返回
list[VisualQuestionAnsweringOutputElement]
包含預測標籤及其關聯機率的 VisualQuestionAnsweringOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
InferenceTimeoutError— 如果模型不可用或請求逾時。HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
根據影像回答開放式問題。
範例
>>> 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
< 原始碼 >( text: str candidate_labels: list multi_label: bool | None = False hypothesis_template: str | None = None model: str | None = None ) → list[ZeroShotClassificationOutputElement]
參數
- text (
str) — 要進行分類的輸入文字。 - candidate_labels (
list[str]) — 用於將文字分類的一組可能類別標籤。 - labels (
list[str], 選填) — (已棄用)字串列表。每個字串皆為輸入文字的一種可能標籤的口語化表示。 - multi_label (
bool, 選填) — 是否可以同時符合多個候選標籤。若為 false,則分數會進行正規化,使得每個序列的標籤可能性總和為 1。若為 true,則標籤被視為獨立的,機率會針對每個候選者進行正規化。 - hypothesis_template (
str, 選填) — 用於與candidate_labels結合的句子,透過將其中的預留位置替換為候選標籤,嘗試進行文字分類。 - model (
str, 選填) — 用於推論的模型。可以是託管於 Hugging Face Hub 上的模型 ID,或是已部署推論端點的 URL。此參數會覆寫實例層級定義的模型。若未提供,將使用預設推薦的零樣本分類模型。
返回
list[ZeroShotClassificationOutputElement]
包含預測標籤及其置信度的 ZeroShotClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
提供文字和一組候選標籤作為輸入,以對輸入文字進行分類。
multi_label=False 的範例
>>> 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 的範例
>>> 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.",
... 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
< 原始碼 >( 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 labels: list = None ) → list[ZeroShotImageClassificationOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要進行標註的輸入圖像。它可以是原始二進位資料(bytes)、圖像檔案、線上圖像的 URL 或 PIL 圖像。 - candidate_labels (
list[str]) — 此圖像的候選標籤。 - labels (
list[str], 選擇性參數) — (已棄用) 可能的標籤字串列表。必須至少包含 2 個標籤。 - model (
str, 選擇性參數) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點(Inference Endpoint)URL。此參數會覆寫實例層級定義的模型。若未提供,將使用預設建議的零樣本圖像分類模型。 - hypothesis_template (
str, 選擇性參數) — 與candidate_labels結合使用的語句,透過將佔位符替換為候選標籤來嘗試圖像分類。
返回
list[ZeroShotImageClassificationOutputElement]
包含預測標籤及其信賴度的 ZeroShotImageClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
提供輸入圖像和文字標籤,以預測圖像的文字標籤。
範例
>>> 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",
... labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]非同步推論用戶端 (Async Inference Client)
亦提供一個基於 asyncio 與 httpx 的非同步版本用戶端。
class huggingface_hub.AsyncInferenceClient
< 原始碼 >( model: str | None = None provider: typing.Union[typing.Literal['black-forest-labs', 'cerebras', 'clarifai', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'hyperbolic', 'nebius', 'novita', 'nscale', 'nvidia', 'openai', 'ovhcloud', 'publicai', 'replicate', 'sambanova', '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 )
參數
- model (
str, 選擇性參數) — 用於執行推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID(例如meta-llama/Meta-Llama-3-8B-Instruct)或是已部署的推論端點 URL。預設為 None,此情況下將自動為任務選擇推薦的模型。注意:為了與 OpenAI 用戶端更好地相容,model已別名為base_url。這兩個參數是互斥的。如果以model或base_url的形式傳入 URL 進行聊天補全,將會自動在 URL 後補上(/v1)/chat/completions路徑後綴。 - provider (
str, 選擇性參數) — 用於推論的提供者名稱。可以是"black-forest-labs","cerebras","clarifai","cohere","deepinfra","fal-ai","featherless-ai","fireworks-ai","groq","hf-inference","hyperbolic","nebius","novita","nscale","nvidia","openai","ovhcloud","publicai","replicate","sambanova","scaleway","together","wavespeed"或"zai-org"。預設為 “auto”:自動路由,預設選擇“最快 (fastest)”的提供者;您可以在 https://huggingface.co/settings/inference-providers 切換為“最便宜 (cheapest)”或“首選 (preferred)”的提供者順序。若傳入的是 URL 或使用了base_url,則不會使用provider參數。 - token (
str, 選擇性參數) — Hugging Face 權杖(token)。若未提供,將預設使用本地儲存的權杖。注意:為了與 OpenAI 用戶端更好地相容,token已別名為api_key。這兩個參數是互斥的,且行為完全相同。 - timeout (
float, 選擇性參數) — 等待伺服器回應的最長秒數。預設為 None,表示將無限期循環直到伺服器可用。 - headers (
dict[str, str], 選擇性參數) — 要發送給伺服器的額外標頭(headers)。預設僅發送授權與 user-agent 標頭。此字典中的值將覆寫預設值。 - bill_to (
str, 選擇性參數) — 用於請求的計費帳戶。預設情況下,請求會計入使用者的帳戶。請求僅能計入使用者所屬且已訂閱 Enterprise Hub 的組織。 - cookies (
dict[str, str], 選擇性參數) — 要發送給伺服器的額外 Cookie。 - base_url (
str, 選擇性參數) — 用於執行推論的基礎 URL。這是來自model的重複參數,目的是讓 InferenceClient 遵循與openai.OpenAI用戶端相同的模式。若已設定model,則此參數不可使用。預設為 None。 - api_key (
str, 選擇性參數) — 用於驗證的權杖。這是來自token的重複參數,目的是讓 InferenceClient 遵循與openai.OpenAI用戶端相同的模式。若已設定token,則此參數不可使用。預設為 None。
初始化新的推論客戶端。
InferenceClient 旨在提供統一的推論執行體驗。該客戶端可以與(免費的)Inference API、自託管的 Inference Endpoints 或第三方推論供應商無縫整合使用。
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 ) → list[AudioClassificationOutputElement]
參數
- audio (Union[str, Path, bytes, BinaryIO]) — 要分類的音訊內容。它可以是原始音訊二進位資料、本地音訊檔案或指向音訊檔案的 URL。
- model (
str, 選擇性參數) — 用於音訊分類的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。若未提供,將使用預設推薦的音訊分類模型。 - top_k (
int, 選擇性參數) — 若有指定,將輸出限制為機率最高的前 K 個類別。 - function_to_apply (
"AudioClassificationOutputTransform", 選擇性參數) — 用於對模型輸出進行運算以取得分數的函式。
返回
list[AudioClassificationOutputElement]
包含預測標籤及其置信度的 AudioClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
對提供的音訊內容執行音訊分類。
範例
# 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 (音訊轉音訊)
< 原始碼 >( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: str | None = None ) → list[AudioToAudioOutputElement]
參數
- audio (Union[str, Path, bytes, BinaryIO]) — 傳給模型的音訊內容。它可以是原始音訊二進位資料、本地音訊檔案或指向音訊檔案的 URL。
- model (
str, 選擇性參數) — 模型可以是任何接收音訊檔案並回傳另一個音訊檔案的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。若未提供,將使用預設推薦用於 audio_to_audio 的模型。
返回
list[AudioToAudioOutputElement]
包含音訊標籤、內容類型以及 Blob 格式音訊內容的 AudioToAudioOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
InferenceTimeoutError— 如果模型不可用或請求逾時。HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
根據模型執行與音訊轉音訊相關的多種任務(例如:語音增強、音源分離)。
範例
# 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 (自動語音辨識)
< 原始碼 >( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: str | None = None extra_body: dict | None = None ) → AutomaticSpeechRecognitionOutput
參數
- audio (Union[str, Path, bytes, BinaryIO]) — 要轉錄的內容。它可以是原始音訊二進位資料、本地音訊檔案或指向音訊檔案的 URL。
- model (
str, 選擇性參數) — 用於 ASR 的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。若未提供,將使用預設推薦用於 ASR 的模型。 - extra_body (
dict, 選擇性參數) — 傳遞給模型的額外提供者特定參數。請參閱提供者的文件以了解支援的參數。
包含轉錄文本以及(可選)時間戳區塊的項目。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
對給定的音訊內容執行自動語音辨識(ASR 或音訊轉文本)。
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 ) → ChatCompletionOutput 或 ChatCompletionStreamOutput 的迭代器
參數
- messages (List of ChatCompletionInputMessage) — 由角色與內容對組成的對話記錄。
- model (
str, 選擇性參數) — 用於聊天補全的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。若未提供,將使用預設推薦用於聊天文字生成的模型。詳情請參閱 https://huggingface.co/tasks/text-generation。如果model是模型 ID,它會作為model參數傳遞給伺服器。如果您希望在請求內容中設定model的同時定義自訂 URL,則在初始化 InferenceClient 時必須設定base_url。 - frequency_penalty (
float, 選擇性參數) — 根據權杖在目前文字中已出現的頻率對新權杖進行懲罰。範圍:[-2.0, 2.0]。預設為 0.0。 - logit_bias (
list[float], 選擇性參數) — 調整特定權杖出現在產生輸出中的可能性。 - logprobs (
bool, 選擇性參數) — 是否回傳輸出權杖的對數機率(log probabilities)。若為 true,將回傳訊息內容中回傳的每個輸出權杖的對數機率。 - max_tokens (
int, 選擇性參數) — 回應中允許的最大權杖數。預設為 100。 - n (
int, 選擇性參數) — 針對每個提示詞(prompt)要生成的補全次數。 - presence_penalty (
float, 選擇性參數) — 介於 -2.0 到 2.0 之間的數值。正值會根據新權杖在目前文字中是否出現進行懲罰,增加模型談論新主題的可能性。 - response_format (
ChatCompletionInputGrammarType(), 選擇性參數) — 文法約束。可以是 JSONSchema 或正規表示式(regex)。 - seed (Optional
int, 選擇性參數) — 用於可重現控制流的種子。預設為 None。 - stop (
list[str], 選擇性參數) — 最多四個會觸發回應結束的字串。預設為 None。 - stream (
bool, 選擇性參數) — 啟用回應的即時串流。預設為 False。 - stream_options (ChatCompletionInputStreamOptions, 選擇性參數) — 串流補全的選項。
- temperature (
float, 選擇性參數) — 控制生成內容的隨機性。數值較低可確保較少的隨機補全。範圍:[0, 2]。預設為 1.0。 - top_logprobs (
int, 選擇性參數) — 介於 0 到 5 之間的整數,指定在每個權杖位置要回傳的最可能權杖數量,每個權杖皆帶有相關聯的對數機率。若要使用此參數,必須將 logprobs 設定為 true。 - top_p (
float, 選擇性參數) — 從最可能的下一個單詞中採樣的比例。必須介於 0 到 1 之間。預設為 1.0。 - tool_choice (ChatCompletionInputToolChoiceClass 或
ChatCompletionInputToolChoiceEnum(), 選擇性參數) — 用於補全的工具。預設為 “auto”。 - tool_prompt (
str, 選擇性參數) — 要附加在工具之前的提示詞。 - tools (List of ChatCompletionInputTool, 選擇性參數) — 模型可以呼叫的工具列表。目前僅支援以函式作為工具。請使用此項來提供模型可以為其生成 JSON 輸入的函式列表。
- extra_body (
dict, 選擇性參數) — 傳遞給模型的額外提供者特定參數。請參閱提供者的文件以了解支援的參數。
從伺服器返回的生成文本
- 如果
stream=False,則生成的文本將作為 ChatCompletionOutput 返回(預設)。 - 如果
stream=True,則生成的文本將以 Token 為單位作為 ChatCompletionStreamOutput 的序列返回。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
一種使用特定語言模型完成對話的方法。
client.chat_completion方法被別名為client.chat.completions.create,以便與 OpenAI 的客戶端相容。輸入和輸出完全相同,使用任一語法都會產生相同的結果。請查看 推論指南 以獲取有關 OpenAI 相容性的更多詳細資訊。
您可以使用
extra_body參數將特定於供應商的參數傳遞給模型。
範例
# 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
)
)使用串流的範例
# 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 語法的範例
# 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 帳戶。
>>> 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 路由使用第三方供應商的範例。使用費用將計入您的 Hugging Face 帳戶。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="sambanova", # Use Sambanova 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?"}],
... )使用圖像 + 文本作為輸入的範例
# 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.使用工具的範例
# 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 的範例
# 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"}'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 ) → list[DocumentQuestionAnsweringOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO]) — 用作上下文的輸入圖像。可以是原始位元組、圖像文件或線上圖像的 URL。 - question (
str) — 要回答的問題。 - model (
str, 選填) — 用於文件問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署好的推論端點(Inference Endpoint)URL。若未提供,將使用預設推薦的文件問答模型。預設為 None。 - doc_stride (
int, 選填) — 如果文件中的單字對於模型來說太長而無法與問題一起放入,它將被分成幾個塊(chunk),並帶有一些重疊。此參數控制該重疊的大小。 - handle_impossible_answer (
bool, 選填) — 是否接受「不可能」(impossible)作為答案。 - lang (
str, 選填) — 執行 OCR 時使用的語言。預設為英文。 - max_answer_len (
int, 選填) — 預測答案的最大長度(例如,僅考慮長度較短的答案)。 - max_question_len (
int, 選填) — 標記化(tokenization)後問題的最大長度。如有必要,將會進行截斷。 - max_seq_len (
int, 選填) — 傳遞給模型的每個塊中,總句子(上下文 + 問題)標記的最大長度。如有必要,上下文將被拆分成多個塊(使用 doc_stride 作為重疊)。 - top_k (
int, 選填) — 要回傳的答案數量(將按可能性排序)。如果上下文中沒有足夠的可用選項,回傳的答案數量可能會少於 top_k。 - word_boxes (
list[Union[list[float], str], 選填) — 單字和邊界框(bounding boxes)的列表(正規化為 0->1000)。如果提供,推論將跳過 OCR 步驟並改用提供的邊界框。
返回
list[DocumentQuestionAnsweringOutputElement]
包含預測標籤、相關機率、單詞 ID 和頁碼的 DocumentQuestionAnsweringOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
針對文件圖像回答問題。
範例
# 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
< 原始碼 >( 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 ) → np.ndarray
參數
- text (str 或 list[str]) — 要嵌入的文字或文字列表。
- model (str, 選填) — 用於特徵提取任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署好的推論端點 URL。若未提供,將使用預設推薦的特徵提取模型。預設為 None。
- normalize (bool, 選填) — 是否對嵌入向量(embeddings)進行標準化。僅適用於由 Text-Embedding-Inference 驅動的伺服器。
- prompt_name (str, 選填) — 應由編碼使用的提示詞名稱。如果未設定,則不會應用任何提示詞。必須是 Sentence Transformers 設定 prompts 字典中的一個鍵。例如,如果
prompt_name是「query」且prompts為 {“query”: “query: ”,…},則句子「What is the capital of France?」將被編碼為「query: What is the capital of France?」,因為提示詞文字會被添加到任何要編碼的文字之前。 - truncate (bool, 選填) — 是否對嵌入向量進行截斷。僅適用於由 Text-Embedding-Inference 驅動的伺服器。
- truncation_direction (Literal[“left”, “right”], 選填) — 當傳入 truncate=True 時,應該從輸入的哪一側進行截斷。
- dimensions (int, 選填) — 產生的輸出嵌入向量應具有的維度數。僅適用於與 OpenAI 相容的嵌入端點。
- encoding_format (Literal[“float”, “base64”], 選填) — 輸出嵌入向量的格式。可以是「float」或「base64」。僅適用於與 OpenAI 相容的嵌入端點。
返回
np.ndarray
表示輸入文字的嵌入向量,格式為 float32 numpy 陣列。
引發
[InferenceTimeoutError] 或 [HfHubHTTPError]
- [InferenceTimeoutError] — 若模型無法使用或請求逾時。
- [HfHubHTTPError] — 若請求失敗,且 HTTP 錯誤狀態碼非 503。
為給定的文字或一批文字產生嵌入向量。
範例
# 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
< 原始碼 >( text: str model: str | None = None targets: list[str] | None = None top_k: int | None = None ) → list[FillMaskOutputElement]
參數
- text (
str) — 要填入的字串,必須包含 [MASK] 標記(請檢查模型卡以確認遮罩的確切名稱)。 - model (
str, 選填) — 用於填補遮罩任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署好的推論端點 URL。若未提供,將使用預設推薦的填補遮罩模型。 - targets (
list[str], 選填) — 傳遞時,模型將限制評分於傳遞的目標,而不是在整個詞彙表中查找。如果提供的目標不在模型詞彙表中,它們將會被標記化,並使用第一個產生的標記(會有警告,且可能較慢)。 - top_k (
int, 選填) — 傳遞時,覆蓋要回傳的預測數量。
返回
list[FillMaskOutputElement]
包含預測標籤、相關機率、標記參考和完成後文字的 FillMaskOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
填補缺少單詞(更準確地說是標記)的空缺。
範例
# 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
< 原始碼 >( model: str | None = None ) → dict[str, Any]
取得關於已部署端點的資訊。
此端點僅適用於由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 驅動的端點。由 transformers 驅動的端點將回傳空酬載 (payload)。
範例
# 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
< 原始碼 >( model: str | None = None ) → bool
檢查已部署端點的運作狀態。
健康檢查僅適用於由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 驅動的推論端點。
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 ) → list[ImageClassificationOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分類的圖像。可以是原始位元組、圖像文件、線上圖像的 URL 或 PIL 圖像。 - model (
str, 選填) — 用於圖像分類的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署好的推論端點 URL。若未提供,將使用預設推薦的圖像分類模型。 - function_to_apply (
"ImageClassificationOutputTransform", 選填) — 為了檢索分數而應用於模型輸出的函數。 - top_k (
int, 選填) — 指定時,將輸出限制為機率最高的前 K 個類別。
返回
list[ImageClassificationOutputElement]
包含預測標籤和相關機率的 ImageClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定的模型對給定圖像執行圖像分類。
範例
# 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
< 原始碼 >( 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 ) → list[ImageSegmentationOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分割的圖像。可以是原始位元組、圖像文件、線上圖像的 URL 或 PIL 圖像。 - model (
str, 選填) — 用於圖像分割的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署好的推論端點 URL。若未提供,將使用預設推薦的圖像分割模型。 - mask_threshold (
float, 選填) — 將預測的遮罩轉換為二值時使用的閾值。 - overlap_mask_area_threshold (
float, 選填) — 用於消除小型、斷開的區段之遮罩重疊閾值。 - subtask (
"ImageSegmentationSubtask", 選填) — 要執行的分割任務,取決於模型能力。 - threshold (
float, 選填) — 用於篩選預測遮罩的機率閾值。
返回
list[ImageSegmentationOutputElement]
包含分割遮罩和相關屬性的 ImageSegmentationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定的模型對給定圖像執行圖像分割。
若要處理圖像,必須安裝
PIL(pip install Pillow)。
範例
# 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
< 原始碼 >( 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 ) → Image
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用於轉換的輸入圖像。可以是原始位元組、圖像文件、線上圖像的 URL 或 PIL 圖像。 - prompt (
str, 選填) — 用於指導圖像生成的文字提示詞。 - negative_prompt (
str, 選填) — 用於指導圖像生成中「不應」包含內容的提示詞。 - num_inference_steps (
int, 選填) — 針對擴散模型(diffusion models)。去噪步驟的數量。較多的去噪步驟通常會產生更高品質的圖像,但會以較慢的推論速度為代價。 - guidance_scale (
float, 選填) — 針對擴散模型。較高的指導比例值會鼓勵模型生成與文字提示詞緊密相關的圖像,但會以降低圖像品質為代價。 - model (
str, 選填) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署好的推論端點 URL。此參數會覆蓋在實例層級定義的模型。預設為 None。 - target_size (
ImageToImageTargetSize, 選填) — 輸出圖像的大小(以像素為單位)。此參數僅由部分提供者和特定模型支援。當不支援時,將會被忽略。
返回
影像
轉換後的圖像。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定的模型執行圖像到圖像的轉換。
若要處理圖像,必須安裝
PIL(pip install Pillow)。
image_to_text
< 原始碼 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: str | None = None ) → ImageToTextOutput
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要進行字幕生成的輸入圖像。可以是原始位元組、圖像文件、線上圖像的 URL 或 PIL 圖像。 - model (
str, 選填) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署好的推論端點 URL。此參數會覆蓋在實例層級定義的模型。預設為 None。
生成的文字。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
輸入圖像並回傳文字。
根據您的使用案例(圖像標註、光學字元識別 (OCR)、Pix2Struct 等),模型的輸出可能會非常不同。請查看模型卡以進一步了解該模型的特性。
範例
# 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
< 原始碼 >( 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 ) → bytes
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用於生成影片的輸入圖像。可以是原始位元組、圖像文件、線上圖像的 URL 或 PIL 圖像。 - model (
str, 選填) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是部署好的推論端點 URL。此參數會覆蓋在實例層級定義的模型。預設為 None。 - prompt (
str, 選填) — 用於指導影片生成的文字提示詞。 - negative_prompt (
str, 選填) — 用於指導影片生成中「不應」包含內容的提示詞。 - num_frames (
float, 選填) — num_frames 參數決定了生成多少影格的影片。 - num_inference_steps (
int, 選填) — 用於擴散模型(diffusion models)。去噪(denoising)步驟的數量。較多的去噪步驟通常會產生更高品質的影像,但代價是推論速度較慢。 - guidance_scale (
float, 選填) — 用於擴散模型。較高的導引尺度(guidance scale)值會促使模型生成與文字提示更緊密相關的影片,但代價是影像品質可能會下降。 - seed (
int, 選填) — 用於影片生成的種子數(seed)。 - target_size (
ImageToVideoTargetSize, 選填) — 輸出影片影格的尺寸(以像素為單位)。 - num_inference_steps (
int, 選填) — 去噪步驟的數量。較多的去噪步驟通常會產生更高品質的影片,但代價是推論速度較慢。 - seed (
int, 選填) — 亂數產生器的種子數。
返回
bytes
生成的影片。
根據輸入圖像生成影片。
範例
# 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
< 原始碼 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: str | None = None threshold: float | None = None ) → list[ObjectDetectionOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要進行物件偵測的影像。可以是原始位元組(raw bytes)、影像檔案、線上影像的 URL,或是一個 PIL 影像物件。 - model (
str, 選填) — 用於物件偵測的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點(Inference Endpoint)URL。若未提供,將使用物件偵測的預設推薦模型(DETR)。 - threshold (
float, 選填) — 進行預測所需的機率閾值。
返回
list[ObjectDetectionOutputElement]
包含邊界框 (bounding boxes) 與相關屬性的 ObjectDetectionOutputElement 項目清單。
引發
InferenceTimeoutError 或 HfHubHTTPError 或 ValueError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。ValueError— 若請求輸出不是清單 (List) 時發生。
使用指定模型對給定圖像執行物件偵測。
若要處理圖像,必須安裝
PIL(pip install Pillow)。
範例
# 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
< 原始碼 >( 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 ) → Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]
參數
- question (
str) — 要回答的問題。 - context (
str) — 问题的上下文內容。 - model (
str) — 用於問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。 - align_to_words (
bool, 選填) — 嘗試將答案對齊到真實單字。在以空格分隔的語言中可以提升品質。但在非空格分隔的語言(如日文或中文)中可能會造成負面影響。 - doc_stride (
int, 選填) — 如果上下文太長而無法與問題一同交給模型,它將會被分割成數個具有部分重疊的區塊。此參數控制該重疊的大小。 - handle_impossible_answer (
bool, 選填) — 是否接受「不可能」(impossible)作為一個答案。 - max_answer_len (
int, 選填) — 預測答案的最大長度(例如,僅考慮長度較短的答案)。 - max_question_len (
int, 選填) — 標記化(tokenization)後問題的最大長度。若有需要將會進行截斷。 - max_seq_len (
int, 選填) — 傳遞給模型的每個區塊之總句子的最大長度(以 token 計算,包含上下文+問題)。若有需要,上下文將會被分割成數個區塊(使用 docStride 作為重疊部分)。 - top_k (
int, 選填) — 要返回的答案數量(將按可能性順序選擇)。請注意,如果上下文中沒有足夠的可用選項,我們返回的答案數量會少於 topk。
返回
Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]
當 top_k 為 1 或未提供時,返回單一的 QuestionAnsweringOutputElement。當 top_k 大於 1 時,返回 QuestionAnsweringOutputElement 的清單。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
從給定的文字中檢索問題的答案。
範例
# 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
< 原始碼 >( sentence: str other_sentences: list model: str | None = None ) → list[float]
參數
- sentence (
str) — 用於與其他句子進行比較的主要句子。 - other_sentences (
list[str]) — 要進行比較的句子列表。 - model (
str, 選填) — 用於句子相似度任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。若未提供,將使用預設推薦的句子相似度模型。預設值為 None。
返回
list[float]
代表輸入文字的嵌入向量 (embedding)。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
透過比較嵌入向量,計算一個句子與一系列其他句子之間的語義相似度。
範例
# 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]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 ) → SummarizationOutput
參數
- text (
str) — 要進行摘要的輸入文字。 - model (
str, 選填) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。若未提供,將使用摘要任務的預設推薦模型。 - clean_up_tokenization_spaces (
bool, 選填) — 是否清理輸出文字中可能多出的空格。 - generate_parameters (
dict[str, Any], 選填) — 文字生成演算法的額外參數設定。 - truncation (
"SummarizationTruncationStrategy", 選填) — 要使用的截斷策略。
生成的摘要文字。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定模型生成給定文字的摘要。
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 ) → TableQuestionAnsweringOutputElement
參數
- table (
str) — 資料表格,以列表字典(dict of lists)形式表示,其中鍵為標題(headers),值為包含所有數據的列表;所有列表必須具有相同的大小。 - query (
str) — 您想要針對表格進行查詢的純文字問題。 - model (
str) — 用於表格問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。 - padding (
"Padding", 選填) — 啟動並控制填充(padding)。 - sequential (
bool, 選填) — 是否循序(sequentially)進行推論或以批次(batch)方式進行。批次處理速度較快,但像 SQA 這類模型由於其對話性質,需要進行循序推論以提取序列內的關係。 - truncation (
bool, 選填) — 啟動並控制截斷(truncation)。
包含答案、座標、單元格以及使用的聚合器 (aggregator) 之表格問答輸出。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
從表格中的資訊檢索問題的答案。
範例
# 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
< 原始碼 >( table: dict model: str | None = None ) → List
參數
- table (
dict[str, Any]) — 要進行分類的屬性集合。 - model (
str, 選填) — 用於表格分類任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。若未提供,將使用預設推薦的表格分類模型。預設值為 None。
返回
List
標籤清單,初始表格中每一列一個標籤。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
根據一組屬性對目標類別(群組)進行分類。
範例
# 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
< 原始碼 >( table: dict model: str | None = None ) → List
參數
- table (
dict[str, Any]) — 儲存在表格中的屬性集合。用於預測目標的屬性可以是數值型或類別型。 - model (
str, 選填) — 用於表格迴歸任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。若未提供,將使用預設推薦的表格迴歸模型。預設值為 None。
返回
List
預測數值目標值的列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
在給定表格中一組屬性/特徵的情況下,預測數值目標值。
範例
# 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: str model: str | None = None top_k: int | None = None function_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None ) → list[TextClassificationOutputElement]
參數
- text (
str) — 要進行分類的字串。 - model (
str, 選填) — 用於文字分類任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。若未提供,將使用預設推薦的文字分類模型。預設值為 None。 - top_k (
int, 選填) — 若有指定,則將輸出限制為機率最高的前 K 個類別。 - function_to_apply (
"TextClassificationOutputTransform", 選填) — 用於處理模型輸出以取得分數的函數。
返回
list[TextClassificationOutputElement]
一個包含 TextClassificationOutputElement 項目的列表,其中包含預測標籤與相關機率。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
對給定文字執行文字分類(例如:情感分析)。
範例
# 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
< 原始碼 >( 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 stop_sequences: 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 ) → Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]
參數
- prompt (
str) — 輸入文字。 - details (
bool, 選填) — 預設情況下,text_generation 回傳一個字串。若您需要詳細輸出(包含 token、機率、種子、完成原因等),請傳入details=True。此功能僅適用於使用text-generation-inference後端的模型。 - stream (
bool, 選填) — 預設情況下,text_generation 回傳完整的生成文字。若您希望以串流方式取得 token,請傳入stream=True。此功能僅適用於使用text-generation-inference後端的模型。 - model (
str, 選填) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點 URL。此參數會覆寫實例層級(instance level)定義的模型。預設值為 None。 - adapter_id (
str, 選填) — Lora adapter ID。 - best_of (
int, 選填) — 生成 best_of 個序列,並回傳具有最高 token 機率對數(logprobs)的那一個。 - decoder_input_details (
bool, 選填) — 回傳解碼器輸入的 token 機率對數與 ID。您必須同時設定details=True才會生效。預設值為False。 - do_sample (
bool, 選填) — 啟動 logits 取樣(sampling)。 - frequency_penalty (
float, 選填) — 介於 -2.0 到 2.0 之間的數值。正值會根據 token 在文字中已出現的頻率進行懲罰,從而降低模型逐字重複相同內容的可能性。 - grammar (TextGenerationInputGrammarType, 選填) — 文法限制。可以是 JSONSchema 或正規表達式(regex)。
- max_new_tokens (
int, 選用) — 生成的 Token 最大數量。預設為 100。 - repetition_penalty (
float, 選用) — 用於重複懲罰的參數。1.0 代表無懲罰。更多詳情請參閱此篇論文。 - return_full_text (
bool, 選用) — 是否將提示詞(prompt)附加在生成的文字之前。 - seed (
int, 選用) — 隨機取樣的種子(seed)。 - stop (
list[str], 選用) — 若生成內容包含stop中的成員,則停止生成 Token。 - stop_sequences (
list[str], 選用) — 已棄用的參數,請改用stop。 - temperature (
float, 選用) — 用於調整 Logits 分佈的數值。 - top_n_tokens (
int, 選用) — 在每個生成步驟中,回傳機率最高的top_n_tokens個 Token 的相關資訊,而不僅僅是取樣出的那個 Token。 - top_k (
int, 選用) — 用於 top-k 過濾的最高機率詞彙 Token 數量。 - top_p (
float, 選用) — 若設定為小於 1 的數值,生成時將僅保留機率累加達top_p或以上的最小機率 Token 集合。 - truncate (
int, 選用) — 將輸入 Token 截斷至給定長度。 - typical_p (
float, 選用) — 典型解碼(Typical Decoding)質量。更多資訊請參閱自然語言生成的典型解碼 (Typical Decoding for Natural Language Generation)。 - watermark (
bool, 選用) — 使用大型語言模型浮水印 (A Watermark for Large Language Models) 進行浮水印標記。
返回
Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]
從伺服器返回的生成文本
- 若
stream=False且details=False,則生成的文字將以str形式回傳(預設值) - 若
stream=True且details=False,則生成的文字將以AsyncIterable[str]的形式逐個 Token 回傳。 - 若
stream=False且details=True,則生成的文字將以包含更多詳細資訊的 TextGenerationOutput 形式回傳 - 若
details=True且stream=True,則生成的文字將以逐 token 的 TextGenerationStreamOutput 可迭代物件形式回傳
引發
ValidationError 或 InferenceTimeoutError 或 HfHubHTTPError
ValidationError— 若輸入數值無效。此時不會向伺服器發送任何 HTTP 呼叫。- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
給定一個提示詞 (prompt),生成後續文字。
若您想從對話訊息生成回應,應使用 InferenceClient.chat_completion() 方法。它接受訊息列表而非單一文字提示,並會為您處理對話模板。
範例
# 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
< 原始碼 >( 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 ) → Image
參數
- prompt (
str) — 用於生成影像的提示詞(prompt)。 - negative_prompt (
str, 選用) — 一個用以引導在影像生成中「不要」包含什麼的提示詞。 - height (
int, 選用) — 輸出影像的高度(像素)。 - width (
int, 選用) — 輸出影像的寬度(像素)。 - num_inference_steps (
int, 選用) — 去噪步驟的數量。較多的去噪步驟通常能帶來較高品質的影像,但代價是推論速度較慢。 - guidance_scale (
float, 選用) — 較高的指引尺度(guidance scale)數值會鼓勵模型生成與提示詞關聯性更緊密的影像,但數值過高可能會導致飽和及其他偽影。 - model (
str, 選用) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點(Inference Endpoint)URL。若未提供,則會使用預設建議的文生圖(text-to-image)模型。預設為 None。 - scheduler (
str, 選用) — 使用相容的排程器(scheduler)來覆寫預設值。 - seed (
int, 選用) — 隨機數生成器的種子。 - extra_body (
dict[str, Any], 選用) — 傳遞給模型的額外供應商特定參數。請參閱供應商的相關說明文件以獲取支援的參數列表。
返回
影像
生成的圖像。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
使用指定模型根據給定文字生成圖像。
若要處理圖像,必須安裝
PIL(pip install Pillow)。
您可以使用
extra_body參數將特定於供應商的參數傳遞給模型。
範例
# 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")>>> 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 路由使用第三方供應商的範例。使用費用將計入您的 Hugging Face 帳戶。
>>> 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 供應商並附加額外參數的範例
>>> 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
< 原始碼 >( 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 ) → bytes
參數
- text (
str) — 要合成的文字。 - model (
str, 選用) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點(Inference Endpoint)URL。若未提供,則會使用預設建議的語音合成(text-to-speech)模型。預設為 None。 - do_sample (
bool, 選用) — 生成新 Token 時,是否使用取樣(sampling)而非貪婪解碼(greedy decoding)。 - early_stopping (
Union[bool, "TextToSpeechEarlyStoppingEnum"], 選用) — 控制基於束搜尋(beam-based)方法的停止條件。 - epsilon_cutoff (
float, 選用) — 若設定為嚴格介於 0 與 1 之間的浮點數,則僅會對條件機率大於 epsilon_cutoff 的 Token 進行取樣。在論文中,建議數值範圍為 3e-4 至 9e-4,具體取決於模型大小。更多詳情請參閱作為語言模型去平滑的截斷取樣 (Truncation Sampling as Language Model Desmoothing)。 - eta_cutoff (
float, 選用) — Eta 取樣是局部典型取樣(locally typical sampling)與 Epsilon 取樣的混合體。若設定為嚴格介於 0 與 1 之間的浮點數,則僅在 Token 機率大於 eta_cutoff 或 sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))) 時才會被考慮。後一項直覺上代表預期下一個 Token 的機率,並由 sqrt(eta_cutoff) 進行縮放。在論文中,建議數值範圍為 3e-4 至 2e-3,具體取決於模型大小。更多詳情請參閱作為語言模型去平滑的截斷取樣 (Truncation Sampling as Language Model Desmoothing)。 - max_length (
int, 選用) — 生成文字的最大長度(以 Token 為單位),包含輸入內容。 - max_new_tokens (
int, 選用) — 生成的最大 Token 數量。優先順序高於 max_length。 - min_length (
int, 選用) — 生成文字的最小長度(以 Token 為單位),包含輸入內容。 - min_new_tokens (
int, 選用) — 生成的最小 Token 數量。優先順序高於 min_length。 - num_beam_groups (
int, 選用) — 將 num_beams 分組的數量,以確保不同組別之間的束(beam)具有多樣性。更多詳情請參閱此篇論文。 - num_beams (
int, 選用) — 用於束搜尋(beam search)的束數量。 - penalty_alpha (
float, 選用) — 該數值用於平衡對比搜尋解碼(contrastive search decoding)中的模型信心與退化懲罰(degeneration penalty)。 - temperature (
float, 選用) — 用於調節下一個 Token 機率的數值。 - top_k (
int, 選用) — 用於 top-k 過濾的最高機率詞彙 Token 數量。 - top_p (
float, 選用) — 若設定為小於 1 的數值,生成時將僅保留機率累加達top_p或以上的最小機率 Token 集合。 - typical_p (
float, 選用) — 局部典型性(Local typicality)衡量目標 Token 的條件預測機率與基於已生成的文本片段預測隨機 Token 的預期條件機率之間的相似度。若設定為小於 1 的數值,生成時將僅保留機率累加達typical_p或以上的局部最典型 Token 的最小集合。更多詳情請參閱此篇論文。 - use_cache (
bool, 選用) — 模型是否應使用過去的最後 Key/Values 注意力來加速解碼。 - extra_body (
dict[str, Any], 選用) — 傳遞給模型的額外供應商特定參數。請參閱供應商的相關說明文件以獲取支援的參數列表。
返回
bytes
生成的音訊。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
合成一段朗讀給定文字的音訊。
您可以使用
extra_body參數將特定於供應商的參數傳遞給模型。
範例
# 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 帳戶。
>>> 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 路由使用第三方供應商的範例。使用費用將計入您的 Hugging Face 帳戶。
>>> 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)>>> 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」的 music-gen 範例
>>> 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
< 原始碼 >( 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 ) → bytes
參數
- prompt (
str) — 用於生成影片的提示詞(prompt)。 - model (
str, 選用) — 用於推論的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點(Inference Endpoint)URL。若未提供,則會使用預設建議的文生影片(text-to-video)模型。預設為 None。 - guidance_scale (
float, 選用) — 較高的指引尺度(guidance scale)數值會鼓勵模型生成與提示詞關聯性更緊密的影片,但數值過高可能會導致飽和及其他偽影。 - negative_prompt (
list[str], 選用) — 一個或多個用以引導在影片生成中「不要」包含什麼的提示詞。 - num_frames (
float, 選用) — num_frames 參數決定了生成多少影格的影片。 - num_inference_steps (
int, 選用) — 去噪步驟的數量。較多的去噪步驟通常能帶來較高品質的影片,但代價是推論速度較慢。 - seed (
int, 選用) — 隨機數生成器的種子。 - extra_body (
dict[str, Any], 選用) — 傳遞給模型的額外供應商特定參數。請參閱供應商的相關說明文件以獲取支援的參數列表。
返回
bytes
生成的影片。
根據給定的文字生成一段影片。
您可以使用
extra_body參數將特定於供應商的參數傳遞給模型。
範例
直接使用第三方供應商的範例。使用量將計入您的 fal.ai 帳戶。
>>> 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 路由使用第三方供應商的範例。使用費用將計入您的 Hugging Face 帳戶。
>>> 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
< 原始碼 >( text: str model: str | None = None aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None ignore_labels: list[str] | None = None stride: int | None = None ) → list[TokenClassificationOutputElement]
參數
- text (
str) — 要進行分類的字串。 - model (
str, 選用) — 用於 Token 分類任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,或是已部署的推論端點(Inference Endpoint)URL。若未提供,則會使用預設建議的 Token 分類模型。預設為 None。 - aggregation_strategy (
"TokenClassificationAggregationStrategy", 選用) — 基於模型預測結果聚合 Token 所使用的策略。 - ignore_labels (
list[str, 選用) — 要忽略的標籤列表。 - stride (
int, 選用) — 切分輸入文字時,區塊間重疊的 Token 數量。
返回
list[TokenClassificationOutputElement]
包含實體群組、置信度分數、詞彙、起始與結束索引的 TokenClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
對給定文字執行 token 分類。通常用於句法分析(如文法結構),或命名實體識別(NER)以理解文字內包含的關鍵字。
範例
# 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,
)
]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 ) → TranslationOutput
參數
- 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], 選填) — 文字生成演算法的額外參數設定。
生成的翻譯文字。
引發
InferenceTimeoutError 或 HfHubHTTPError 或 ValueError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。ValueError— 若僅提供了src_lang和tgt_lang引數中的其中一個。
將文字從一種語言轉換為另一種語言。
請參閱 https://huggingface.co/tasks/translation 以取得如何針對您的特定用例選擇最佳模型的更多資訊。來源和目標語言通常取決於模型。不過,某些模型可以指定來源和目標語言。如果您使用的是其中一種模型,可以使用 src_lang 和 tgt_lang 引數來傳遞相關資訊。
範例
# 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.')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 ) → list[VisualQuestionAnsweringOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 作為上下文輸入的圖片。可以是原始位元組、圖片檔案、線上圖片網址或 PIL 圖片物件。 - question (
str) — 要回答的問題。 - model (
str, 選填) — 用於視覺問答任務的模型。可以是託管於 Hugging Face Hub 上的模型 ID,或是已部署推理端點的 URL。若未提供,將使用預設推薦的視覺問答模型。預設為 None。 - top_k (
int, 選填) — 要回傳的答案數量(按可能性高低排序)。請注意,如果上下文中可用的選項不足,回傳的數量可能會少於 top_k。
返回
list[VisualQuestionAnsweringOutputElement]
包含預測標籤及其關聯機率的 VisualQuestionAnsweringOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
InferenceTimeoutError— 如果模型不可用或請求逾時。HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
根據影像回答開放式問題。
範例
# 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
< 原始碼 >( text: str candidate_labels: list multi_label: bool | None = False hypothesis_template: str | None = None model: str | None = None ) → list[ZeroShotClassificationOutputElement]
參數
- text (
str) — 要分類的輸入文字。 - candidate_labels (
list[str]) — 用於將文字分類的一組可能的類別標籤。 - labels (
list[str], 選填) — (已棄用) 字串列表。每個字串為輸入文字的一個可能標籤的描述(verbalization)。 - multi_label (
bool, 選填) — 是否允許多個候選標籤同時為真。若為 false,分數將進行標準化,使每個序列的標籤可能性總和為 1。若為 true,則標籤被視為獨立的,並針對每個候選者進行機率標準化。 - hypothesis_template (
str, 選填) — 與candidate_labels結合使用的句子,透過將佔位符替換為候選標籤來嘗試進行文字分類。 - model (
str, 選填) — 用於推理的模型。可以是託管於 Hugging Face Hub 上的模型 ID,或是已部署推理端點的 URL。此參數會覆寫在執行個體(instance)層級定義的模型。若未提供,將使用預設推薦的零樣本分類模型。
返回
list[ZeroShotClassificationOutputElement]
包含預測標籤及其置信度的 ZeroShotClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
提供文字和一組候選標籤作為輸入,以對輸入文字進行分類。
multi_label=False 的範例
# 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 的範例
# 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.",
... 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
< 原始碼 >( 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 labels: list = None ) → list[ZeroShotImageClassificationOutputElement]
參數
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要進行標註(caption)的輸入圖片。可以是原始位元組、圖片檔案、線上圖片網址或 PIL 圖片物件。 - candidate_labels (
list[str]) — 此圖片的候選標籤。 - labels (
list[str], 選填) — (已棄用) 可能標籤的字串列表。至少必須有 2 個標籤。 - model (
str, 選填) — 用於推理的模型。可以是託管於 Hugging Face Hub 上的模型 ID,或是已部署推理端點的 URL。此參數會覆寫在執行個體層級定義的模型。若未提供,將使用預設推薦的零樣本圖片分類模型。 - hypothesis_template (
str, 選填) — 與candidate_labels結合使用的句子,透過將佔位符替換為候選標籤來嘗試進行圖片分類。
返回
list[ZeroShotImageClassificationOutputElement]
包含預測標籤及其信賴度的 ZeroShotImageClassificationOutputElement 項目列表。
引發
InferenceTimeoutError 或 HfHubHTTPError
- InferenceTimeoutError — 如果模型不可用或請求逾時。
HfHubHTTPError— 如果請求失敗,且 HTTP 錯誤狀態碼不為 503。
提供輸入圖像和文字標籤,以預測圖像的文字標籤。
範例
# 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",
... labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]InferenceTimeoutError
當模型不可用或請求逾時時所引發的錯誤。