Hub Python 庫文件

推理

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

推理

推理是指使用訓練好的模型對新資料進行預測的過程。由於此過程可能計算量很大,因此在專用或外部服務上執行可能是一個不錯的選擇。huggingface_hub 庫提供了統一的介面,用於在 Hugging Face Hub 上託管的模型的多個服務之間進行推理

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

可以使用 InferenceClient 物件呼叫這些服務。有關如何使用它的更多資訊,請參閱本指南

推理客戶端

class huggingface_hub.InferenceClient

< >

( model: typing.Optional[str] = None provider: typing.Union[typing.Literal['black-forest-labs', 'cerebras', 'clarifai', 'cohere', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'hyperbolic', 'nebius', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'sambanova', 'scaleway', 'together', 'wavespeed', 'zai-org'], typing.Literal['auto'], NoneType] = None token: typing.Optional[str] = None timeout: typing.Optional[float] = None headers: typing.Optional[dict[str, str]] = None cookies: typing.Optional[dict[str, str]] = None bill_to: typing.Optional[str] = None base_url: typing.Optional[str] = None api_key: typing.Optional[str] = None )

引數

  • model (str, optional) — 用於進行推理的模型。可以是 Hugging Face Hub 上託管的模型 ID,也可以是已部署推理端點的 URL。預設為 None,在這種情況下,將自動為任務選擇推薦模型。注意:為了更好地與 OpenAI 的客戶端相容,model 已別名為 base_url。這兩個引數是互斥的。如果將 URL 作為 modelbase_url 傳遞用於聊天完成,則會在 URL 後面附加 (/v1)/chat/completions 路徑。
  • provider (str, optional) — 要用於推理的提供商的名稱。可以是 "black-forest-labs""cerebras""clarifai""cohere""fal-ai""featherless-ai""fireworks-ai""groq""hf-inference""hyperbolic""nebius""novita""nscale""openai""ovhcloud""publicai""replicate""sambanova""scaleway""together""wavespeed""zai-org"。預設為“auto”,即模型可用的提供商中的第一個,按照使用者在 https://huggingface.co/settings/inference-providers 中的順序排序。如果模型是 URL 或傳遞了 base_url,則不使用 provider
  • token (str, optional) — Hugging Face 令牌。如果未提供,則預設為本地儲存的令牌。注意:為了更好地與 OpenAI 的客戶端相容,token 已別名為 api_key。這兩個引數是互斥的,並且行為完全相同。
  • timeout (float, optional) — 等待伺服器響應的最大秒數。預設為 None,表示將一直迴圈直到伺服器可用。
  • headers (dict[str, str], optional) — 傳送到伺服器的其他標頭。預設情況下,僅傳送授權和使用者代理標頭。此字典中的值將覆蓋預設值。
  • bill_to (str, optional) — 用於請求的賬單帳戶。預設情況下,請求將在使用者帳戶上計費。請求只能計費到使用者所屬的組織,並且該組織已訂閱 Enterprise Hub。
  • cookies (dict[str, str], optional) — 傳送到伺服器的其他 cookie。
  • base_url (str, optional) — 用於進行推理的基礎 URL。這是 model 引數的重複引數,旨在使 InferenceClient 遵循與 openai.OpenAI 客戶端相同的模式。如果設定了 model,則不能使用此引數。預設為 None。
  • api_key (str, optional) — 用於身份驗證的令牌。這是 token 引數的重複引數,旨在使 InferenceClient 遵循與 openai.OpenAI 客戶端相同的模式。如果設定了 token,則不能使用此引數。預設為 None。

初始化一個新的推理客戶端。

InferenceClient 旨在提供統一的推理體驗。該客戶端可以無縫地與(免費的)推理 API、自託管的推理端點或第三方推理提供商一起使用。

音訊分類

< >

( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None top_k: typing.Optional[int] = 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 列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

對提供的音訊內容執行音訊分類。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.audio_classification("audio.flac")
[
    AudioClassificationOutputElement(score=0.4976358711719513, label='hap'),
    AudioClassificationOutputElement(score=0.3677836060523987, label='neu'),
    ...
]

音訊到音訊

< >

( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None ) list[AudioToAudioOutputElement]

引數

  • audio (Union[str, Path, bytes, BinaryIO]) — 模型的音訊內容。它可以是原始音訊位元組、本地音訊檔案或指向音訊檔案的 URL。
  • model (str, optional) — 可以是任何接受音訊檔案並返回另一個音訊檔案的模型。可以是 Hugging Face Hub 上託管的模型 ID,也可以是已部署推理端點的 URL。如果未提供,將使用預設推薦的 audio_to_audio 模型。

返回

list[AudioToAudioOutputElement]

包含音訊標籤、內容型別和音訊內容的 AudioToAudioOutputElement 列表(以 blob 形式)。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

執行與音訊到音訊相關的多個任務,具體取決於模型(例如:語音增強、源分離)。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> audio_output = client.audio_to_audio("audio.flac")
>>> for i, item in enumerate(audio_output):
>>>     with open(f"output_{i}.flac", "wb") as f:
            f.write(item.blob)

自動語音識別

< >

( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None extra_body: typing.Optional[dict] = None ) AutomaticSpeechRecognitionOutput

引數

  • audio (Union[str, Path, bytes, BinaryIO]) — 要轉錄的內容。它可以是原始音訊位元組、本地音訊檔案或指向音訊檔案的 URL。
  • model (str, optional) — 用於 ASR 的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用 ASR 的預設推薦模型。
  • extra_body (dict, optional) — 傳遞給模型的其他提供商特定引數。請參閱提供商的文件以瞭解支援的引數。

返回

AutomaticSpeechRecognitionOutput

一個包含轉錄文字和可選的時間戳塊的專案。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

對給定的音訊內容執行自動語音識別(ASR 或音訊到文字)。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.automatic_speech_recognition("hello_world.flac").text
"hello world"

chat_completion

< >

( messages: list model: typing.Optional[str] = None stream: bool = False frequency_penalty: typing.Optional[float] = None logit_bias: typing.Optional[list[float]] = None logprobs: typing.Optional[bool] = None max_tokens: typing.Optional[int] = None n: typing.Optional[int] = None presence_penalty: typing.Optional[float] = 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: typing.Optional[int] = None stop: typing.Optional[list[str]] = None stream_options: typing.Optional[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions] = None temperature: typing.Optional[float] = None tool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None tool_prompt: typing.Optional[str] = None tools: typing.Optional[list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool]] = None top_logprobs: typing.Optional[int] = None top_p: typing.Optional[float] = None extra_body: typing.Optional[dict] = None ) ChatCompletionOutputChatCompletionStreamOutput 的可迭代物件

引數

  • messages (List of 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) — 根據現有頻率對新詞進行懲罰。範圍:[-2.0, 2.0]。預設為 0.0。
  • logit_bias (list[float], optional) — 調整生成輸出中特定標記出現的可能性。
  • logprobs (bool, optional) — 是否返回輸出標記的 log 機率。如果為 true,則返回訊息內容中返回的每個輸出標記的 log 機率。
  • max_tokens (int, optional) — 響應中允許的最大標記數。預設為 100。
  • n (int, optional) — 為每個提示生成的補全數量。
  • presence_penalty (float, optional) — -2.0 到 2.0 之間的數字。正值會根據新標記在文字中已出現的情況進行懲罰,增加模型討論新主題的可能性。
  • response_format (ChatCompletionInputGrammarType(), optional) — 語法約束。可以是 JSONSchema 或 regex。
  • seed (Optionalint, optional) — 可復現控制流的種子。預設為 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 都附有相應的 log 機率。如果使用此引數,則必須將 logprobs 設定為 true。
  • top_p (float, optional) — 要從中最有可能的下一個單詞中取樣的比例。必須介於 0 和 1 之間。預設為 1.0。
  • tool_choice (ChatCompletionInputToolChoiceClassChatCompletionInputToolChoiceEnum(), optional) — 要用於補全的工具。預設為“auto”。
  • tool_prompt (str, optional) — 要附加在工具之前的提示。
  • tools (List of ChatCompletionInputTool, optional) — 模型可以呼叫的工具列表。目前,只有函式支援作為工具。使用此引數為模型可以生成 JSON 輸入的函式提供列表。
  • extra_body (dict, optional) — 傳遞給模型的其他提供商特定引數。請參閱提供商的文件以瞭解支援的引數。

返回

ChatCompletionOutputChatCompletionStreamOutput 的可迭代物件

從伺服器生成的文字

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

用於使用指定語言模型完成對話的方法。

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: typing.Optional[str] = None doc_stride: typing.Optional[int] = None handle_impossible_answer: typing.Optional[bool] = None lang: typing.Optional[str] = None max_answer_len: typing.Optional[int] = None max_question_len: typing.Optional[int] = None max_seq_len: typing.Optional[int] = None top_k: typing.Optional[int] = None word_boxes: typing.Optional[list[typing.Union[list[float], str]]] = 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, optional) — 執行 OCR 時使用的語言。預設為英語。
  • max_answer_len (int, optional) — 預測答案的最大長度(例如,只考慮更短長度的答案)。
  • max_question_len (int, optional) — 分詞後問題的最大長度。如果需要,將對其進行截斷。
  • max_seq_len (int, optional) — 傳遞給模型的每個塊(文字+問題)的最大長度(以 token 為單位)。如果需要,上下文將被分割成多個塊(使用 doc_stride 作為重疊)。
  • top_k (int, optional) — 返回的答案數量(將按可能性順序選擇)。如果上下文中沒有足夠的可用選項,則可能返回少於 top_k 個答案。
  • word_boxes (list[Union[list[float], str, optional) — 單詞和邊界框的列表(歸一化 0-1000)。如果提供,推理將跳過 OCR 步驟並使用提供的邊界框。

返回

list[DocumentQuestionAnsweringOutputElement]

包含預測標籤、關聯機率、單詞 ID 和頁面編號的 `DocumentQuestionAnsweringOutputElement` 項列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

回答文件影像上的問題。

示例

>>> 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 normalize: typing.Optional[bool] = None prompt_name: typing.Optional[str] = None truncate: typing.Optional[bool] = None truncation_direction: typing.Optional[typing.Literal['left', 'right']] = None dimensions: typing.Optional[int] = None encoding_format: typing.Optional[typing.Literal['float', 'base64']] = None model: typing.Optional[str] = None ) np.ndarray

引數

  • text (str) — 要嵌入的文字。
  • model (str, optional) — 用於特徵提取任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的特徵提取模型。預設為 None。
  • normalize (bool, optional) — 是否對嵌入進行歸一化。僅在由 Text-Embedding-Inference 提供支援的伺服器上可用。
  • prompt_name (str, optional) — 應由編碼使用的提示名稱。如果未設定,則不應用任何提示。必須是 *Sentence Transformers* 配置的 *prompts* 字典中的一個鍵。例如,如果 `prompt_name` 是“query”,並且 `prompts` 是 {“query”: “query: ”,…},那麼句子“What is the capital of France?”將被編碼為“query: What is the capital of France?”,因為提示文字將在要編碼的文字之前新增。
  • truncate (bool, optional) — 是否截斷嵌入。僅在由 Text-Embedding-Inference 提供支援的伺服器上可用。
  • truncation_direction (Literal[“left”, “right”], optional) — 當傳入 truncate=True 時,應截斷輸入的哪一側。
  • dimensions (int, optional) — 結果嵌入應具有的維度數。僅在 OpenAI 相容的嵌入端點上可用。
  • encoding_format (Literal[“float”, “base64”], optional) — 輸出嵌入的格式。可以是“float”或“base64”。僅在 OpenAI 相容的嵌入端點上可用。

返回

np.ndarray

將輸入文字表示為 float32 numpy 陣列的嵌入。

引發

[InferenceTimeoutError] 或 [HfHubHTTPError]

  • [InferenceTimeoutError] — 如果模型不可用或請求超時。
  • [HfHubHTTPError] — 如果請求以除 HTTP 503 之外的 HTTP 錯誤狀態碼失敗。

為給定的文字生成嵌入。

示例

>>> 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: typing.Optional[str] = None targets: typing.Optional[list[str]] = None top_k: typing.Optional[int] = None ) list[FillMaskOutputElement]

引數

  • text (str) — 要填充的字串,必須包含 [MASK] 標記(請檢查模型卡以獲取掩碼的確切名稱)。
  • model (str, optional) — 用於填充掩碼任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的填充掩碼模型。
  • targets (list[str, optional) — 當傳入時,模型將把分數限制在傳入的目標上,而不是在整個詞彙表中查詢。如果提供的目標不在模型詞彙表中,它們將被標記化,並使用第一個生成的 token(併發出警告,這可能會變慢)。
  • top_k (int, optional) — 當指定時,覆蓋返回的預測數量。

返回

list[FillMaskOutputElement]

一個包含預測標籤、關聯機率、令牌引用和完成文字的 FillMaskOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

填充一個帶有缺失詞(準確地說是令牌)的空缺。

示例

>>> 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: typing.Optional[str] = None ) dict[str, Any]

引數

  • model (str, optional) — 要使用的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數會覆蓋例項級別定義的模型。預設為 None。

返回

dict[str, Any]

有關端點的資訊。

獲取已部署端點的資訊。

此端點僅在由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 提供的端點上可用。由 transformers 提供的端點將返回空負載。

示例

>>> 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: typing.Optional[str] = None ) bool

引數

  • model (str, optional) — 推理端點的 URL。此引數會覆蓋例項級別定義的模型。預設為 None。

返回

布林值

如果一切正常,則為 True。

檢查已部署端點的執行狀況。

健康檢查僅適用於由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 提供的推理端點。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient("https://jzgu0buei5.us-east-1.aws.endpoints.huggingface.cloud")
>>> client.health_check()
True

image_classification

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None function_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = None top_k: typing.Optional[int] = None ) list[ImageClassificationOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分類的影像。可以是原始位元組、影像檔案、線上影像的 URL 或 PIL 影像。
  • model (str, optional) — 要用於影像分類的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的影像分類模型。
  • function_to_apply ("ImageClassificationOutputTransform", optional) — 應用於模型輸出以檢索分數的函式。
  • top_k (int, optional) — 指定時,限制輸出為最可能的 K 個類別。

返回

list[ImageClassificationOutputElement]

一個包含預測標籤和關聯機率的 ImageClassificationOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

使用指定模型對給定影像執行影像分類。

示例

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

image_segmentation

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None mask_threshold: typing.Optional[float] = None overlap_mask_area_threshold: typing.Optional[float] = None subtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = None threshold: typing.Optional[float] = None ) list[ImageSegmentationOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分割的影像。可以是原始位元組、影像檔案、線上影像的 URL 或 PIL 影像。
  • model (str, optional) — 要用於影像分割的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的影像分割模型。
  • mask_threshold (float, optional) — 用於將預測的掩碼轉換為二進位制值的閾值。
  • overlap_mask_area_threshold (float, optional) — 掩碼重疊閾值,用於消除小型、不連通的區域。
  • subtask ("ImageSegmentationSubtask", optional) — 分割任務,取決於模型的效能。
  • threshold (float, optional) — 用於過濾預測掩碼的機率閾值。

返回

list[ImageSegmentationOutputElement]

包含分割掩碼和相關屬性的 ImageSegmentationOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

使用指定模型對給定影像執行影像分割。

如果您想處理影像,則必須安裝 PIL (pip install Pillow)。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> 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: typing.Optional[str] = None negative_prompt: typing.Optional[str] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None model: typing.Optional[str] = None target_size: typing.Optional[huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize] = None **kwargs ) Image

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 轉換的輸入影像。它可以是原始位元組、影像檔案、線上影像的 URL 或 PIL 影像。
  • prompt (str, optional) — 用於指導影像生成的文字提示。
  • negative_prompt (str, optional) — 一個用於指導不應包含在影像生成中的內容的提示。
  • num_inference_steps (int, optional) — 對於擴散模型。去噪步驟的數量。更多的去噪步驟通常會以犧牲較慢的推理速度為代價來獲得更高質量的影像。
  • guidance_scale (float, optional) — 對於擴散模型。更高的引導比例值會促使模型生成與文字提示更緊密相關的影像,但會以較低的影像質量為代價。
  • model (str, optional) — 要使用的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數會覆蓋例項級別定義的模型。預設為 None。
  • target_size (ImageToImageTargetSize, optional) — 輸出影像的大小(畫素)。此引數僅受某些提供商和特定模型的支援。在不支援時將被忽略。

返回

影像

轉換後的影像。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

使用指定的模型執行影像到影像的轉換。

如果您想處理影像,則必須安裝 PIL (pip install Pillow)。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> image = client.image_to_image("cat.jpg", prompt="turn the cat into a tiger")
>>> image.save("tiger.jpg")

image_to_text

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None ) ImageToTextOutput

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要進行字幕生成的輸入影像。它可以是原始位元組、影像檔案、線上影像的 URL 或 PIL 影像。
  • model (str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數會覆蓋例項級別定義的模型。預設為 None。

返回

ImageToTextOutput

生成的文字。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

接收輸入影像並返回文字。

模型可能因您的用例(影像字幕、光學字元識別 (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: typing.Optional[str] = None prompt: typing.Optional[str] = None negative_prompt: typing.Optional[str] = None num_frames: typing.Optional[float] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None seed: typing.Optional[int] = None target_size: typing.Optional[huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize] = None **kwargs ) bytes

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用於生成影片的輸入影像。它可以是原始位元組、影像檔案、線上影像的 URL 或 PIL 影像。
  • model (str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數會覆蓋例項級別定義的模型。預設為 None。
  • prompt (str, optional) — 用於指導影片生成的文字提示。
  • negative_prompt (str, optional) — 一個用於指導影片生成中不應包含的內容的提示。
  • num_frames (float, optional) — num_frames 引數決定了生成多少個影片幀。
  • num_inference_steps (int, optional) — 對於擴散模型。去噪步驟的數量。更多的去噪步驟通常會以犧牲較慢的推理速度為代價,來獲得更高質量的影像。
  • guidance_scale (float, optional) — 對於擴散模型。更高的指導尺度值會鼓勵模型生成與文字提示緊密相關的影片,但會降低影像質量。
  • seed (int, optional) — 用於影片生成的種子。
  • target_size (ImageToVideoTargetSize, optional) — 輸出影片幀的畫素大小。
  • num_inference_steps (int, optional) — 去噪步驟的數量。更多的去噪步驟通常會以犧牲較慢的推理速度為代價,來獲得更高質量的影片。
  • seed (int, optional) — 隨機數生成器的種子。

返回

位元組

生成的影片。

從輸入影像生成影片。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> video = 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: typing.Optional[str] = None threshold: typing.Optional[float] = None ) list[ObjectDetectionOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要在其上進行物件檢測的影像。它可以是原始位元組、影像檔案、線上影像的 URL 或 PIL 影像。
  • model (str, optional) — 用於物件檢測的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的物件檢測模型 (DETR)。
  • threshold (float, optional) — 用於進行預測的機率閾值。

返回

list[ObjectDetectionOutputElement]

包含邊界框和相關屬性的 ObjectDetectionOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPErrorValueError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。
  • ValueError — 如果請求輸出不是 List。

使用指定的模型對給定影像執行物件檢測。

如果您想處理影像,則必須安裝 PIL (pip install Pillow)。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> 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: typing.Optional[str] = None align_to_words: typing.Optional[bool] = None doc_stride: typing.Optional[int] = None handle_impossible_answer: typing.Optional[bool] = None max_answer_len: typing.Optional[int] = None max_question_len: typing.Optional[int] = None max_seq_len: typing.Optional[int] = None top_k: typing.Optional[int] = None ) Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]

引數

  • question (str) — 要回答的問題。
  • context (str) — 問題的上下文。
  • model (str) — 用於問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。
  • align_to_words (bool, optional) — 嘗試將答案與實際單詞對齊。在具有空格分隔語言的場景中可以提高質量。在沒有空格分隔的語言(如日語或中文)上可能會降低質量。
  • doc_stride (int, 可選) — 如果上下文太長,無法與模型的問題一起裝入,它將被分成幾個帶有重疊的塊。此引數控制重疊的大小。
  • handle_impossible_answer (bool, 可選) — 是否接受不可能的答案。
  • max_answer_len (int, 可選) — 預測答案的最大長度(例如,只考慮較短長度的答案)。
  • max_question_len (int, 可選) — 分詞後的問題最大長度。如有需要將截斷。
  • max_seq_len (int, 可選) — 模型分塊處理時,上下文+問題的最大序列長度(以token計)。如果需要,上下文將被分成幾個塊(使用docStride作為重疊)。
  • top_k (int, 可選) — 要返回的答案數量(將按可能性順序選擇)。請注意,如果沒有足夠的可用選項,我們將返回少於 topk 個答案。

返回

Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]

當 top_k 為 1 或未提供時,它返回單個 QuestionAnsweringOutputElement。當 top_k 大於 1 時,它返回一個 QuestionAnsweringOutputElement 列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

從給定文字中檢索問題的答案。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> 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: typing.Optional[str] = None ) list[float]

引數

  • sentence (str) — 用於與其他句子進行比較的主要句子。
  • other_sentences (list[str]) — 要比較的句子列表。
  • model (str, 可選) — 用於句子相似度任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,則將使用預設推薦的句子相似度模型。預設為 None。

返回

list[float]

表示輸入文字的嵌入。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

透過比較句子的嵌入來計算一個句子與一組其他句子之間的語義相似度。

示例

>>> 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]

摘要

< >

( text: str model: typing.Optional[str] = None clean_up_tokenization_spaces: typing.Optional[bool] = None generate_parameters: typing.Optional[dict[str, typing.Any]] = None truncation: typing.Optional[ForwardRef('SummarizationTruncationStrategy')] = None ) SummarizationOutput

引數

  • text (str) — 要摘要的輸入文字。
  • model (str, 可選) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,則將使用預設推薦的摘要模型。
  • clean_up_tokenization_spaces (bool, 可選) — 是否清理文字輸出中可能存在的額外空格。
  • generate_parameters (dict[str, Any], 可選) — 文字生成演算法的附加引數化。
  • truncation ("SummarizationTruncationStrategy", 可選) — 要使用的截斷策略。

返回

SummarizationOutput

生成的摘要文字。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

使用指定的模型生成給定文字的摘要。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.summarization("The Eiffel tower...")
SummarizationOutput(generated_text="The Eiffel tower is one of the most famous landmarks in the world....")

table_question_answering

< >

( table: dict query: str model: typing.Optional[str] = None padding: typing.Optional[ForwardRef('Padding')] = None sequential: typing.Optional[bool] = None truncation: typing.Optional[bool] = None ) TableQuestionAnsweringOutputElement

引數

  • table (str) — 一個由列表組成的字典表示的資料表,條目是標題,列表是所有值,所有列表必須具有相同的大小。
  • query (str) — 您想向表格提出的純文字查詢。
  • model (str) — 用於表格問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。
  • padding ("Padding", 可選) — 啟用並控制填充。
  • sequential (bool, 可選) — 是順序執行推理還是批次執行推理。批次處理速度更快,但像 SQA 這樣的模型需要順序執行推理才能提取序列中的關係,因為它們是對話性質的。
  • truncation (bool, 可選) — 啟用並控制截斷。

返回

TableQuestionAnsweringOutputElement

一個表格問答輸出,包含答案、座標、單元格和使用的聚合器。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

從表格中提供的資訊中檢索問題的答案。

示例

>>> 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: typing.Optional[str] = None ) List

引數

  • table (dict[str, Any]) — 要分類的屬性集。
  • model (str, optional) — 用於表格分類任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的表格分類模型。預設為 None。

返回

列表

表格初始行數的一系列標籤。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

根據一組屬性對目標類別(一組)進行分類。

示例

>>> 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: typing.Optional[str] = None ) List

引數

  • table (dict[str, Any]) — 表格中儲存的屬性集。用於預測目標的屬性可以是數值型和類別型。
  • model (str, optional) — 用於表格迴歸任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的表格迴歸模型。預設為 None。

返回

列表

一組預測的數值目標值。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

給定表格中的一組屬性/特徵,預測數值目標值。

示例

>>> 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_classification

< >

( text: str model: typing.Optional[str] = None top_k: typing.Optional[int] = 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 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

對給定文字執行文字分類(例如,情感分析)。

示例

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.text_classification("I like you")
[
    TextClassificationOutputElement(label='POSITIVE', score=0.9998695850372314),
    TextClassificationOutputElement(label='NEGATIVE', score=0.0001304351753788069),
]

text_generation

< >

( prompt: str details: typing.Optional[bool] = None stream: typing.Optional[bool] = None model: typing.Optional[str] = None adapter_id: typing.Optional[str] = None best_of: typing.Optional[int] = None decoder_input_details: typing.Optional[bool] = None do_sample: typing.Optional[bool] = None frequency_penalty: typing.Optional[float] = None grammar: typing.Optional[huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType] = None max_new_tokens: typing.Optional[int] = None repetition_penalty: typing.Optional[float] = None return_full_text: typing.Optional[bool] = None seed: typing.Optional[int] = None stop: typing.Optional[list[str]] = None stop_sequences: typing.Optional[list[str]] = None temperature: typing.Optional[float] = None top_k: typing.Optional[int] = None top_n_tokens: typing.Optional[int] = None top_p: typing.Optional[float] = None truncate: typing.Optional[int] = None typical_p: typing.Optional[float] = None watermark: typing.Optional[bool] = None ) Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]

引數

  • prompt (str) — 輸入文字。
  • details (bool, optional) — 預設情況下,text_generation 返回一個字串。如果需要詳細輸出(tokens、機率、seed、finish reason 等),請傳遞 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 adapter id。
  • best_of (int, optional) — 生成 best_of 個序列並返回具有最高 token logprob 的序列。
  • decoder_input_details (bool, optional) — 返回解碼器輸入 token logprobs 和 ids。必須同時設定 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, 可選) — 重複懲罰引數。1.0 表示無懲罰。更多細節請參閱本文件
  • return_full_text (bool, 可選) — 是否將提示新增到生成的文字前面
  • seed (int, 可選) — 隨機取樣種子
  • stop (list[str], 可選) — 生成停止詞。
  • stop_sequences (list[str], 可選) — 已棄用引數。請改用 stop
  • temperature (float, 可選) — 用於調整 logits 分佈的值。
  • top_n_tokens (int, 可選) — 在每個生成步驟中返回 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 for Natural Language Generation 以瞭解更多資訊
  • watermark (bool, 可選) -- 使用 A Watermark for Large Language Models 進行水印處理

返回

Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]

從伺服器生成的文字

  • 如果 stream=Falsedetails=False,則生成的文字將作為 str 返回(預設)
  • 如果 stream=Truedetails=False,則生成的文字將逐 token 返回為 Iterable[str]
  • 如果 stream=Falsedetails=True,則生成的文字將包含更多詳細資訊,並作為 TextGenerationOutput 返回
  • 如果 details=Truestream=True,則生成的文字將逐 token 返回為 TextGenerationStreamOutput 的可迭代物件

引發

ValidationErrorInferenceTimeoutErrorHfHubHTTPError

  • ValidationError -- 如果輸入值無效。不會向伺服器發出 HTTP 呼叫。
  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

給定一個提示,生成以下文字。

如果您想從聊天訊息生成響應,您應該使用 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: typing.Optional[str] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None model: typing.Optional[str] = None scheduler: typing.Optional[str] = None seed: typing.Optional[int] = None extra_body: typing.Optional[dict[str, typing.Any]] = None ) Image

引數

  • prompt (str) — 用於生成影像的提示。
  • negative_prompt (str, 可選) — 指導影像生成時不應包含的內容的提示。
  • height (int, 可選) — 輸出影像的畫素高度
  • width (int, 可選) — 輸出影像的畫素寬度
  • num_inference_steps (int, 可選) — 去噪步驟的數量。更多的去噪步驟通常可以提高影像質量,但會降低推理速度。
  • guidance_scale (float, 可選) — 更高的引導尺度值會鼓勵模型生成與文字提示更緊密相關的影像,但值過高可能會導致飽和和其他偽影。
  • model (str, 可選) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,將使用預設推薦的文字到影像模型。預設為 None。
  • scheduler (str, 可選) — 覆蓋排程器,使用相容的排程器。
  • seed (int, 可選) — 隨機數生成器的種子。
  • extra_body (dict[str, Any], 可選) — 傳遞給模型的其他特定於提供商的引數。有關支援的引數,請參閱提供商的文件。

返回

影像

生成的影像。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

根據給定文字和指定模型生成影像。

如果您想處理影像,則必須安裝 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")
直接使用第三方提供商的示例。使用量將在您的 fal.ai 賬戶上計費。
>>> 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: typing.Optional[str] = None do_sample: typing.Optional[bool] = None early_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None epsilon_cutoff: typing.Optional[float] = None eta_cutoff: typing.Optional[float] = None max_length: typing.Optional[int] = None max_new_tokens: typing.Optional[int] = None min_length: typing.Optional[int] = None min_new_tokens: typing.Optional[int] = None num_beam_groups: typing.Optional[int] = None num_beams: typing.Optional[int] = None penalty_alpha: typing.Optional[float] = None temperature: typing.Optional[float] = None top_k: typing.Optional[int] = None top_p: typing.Optional[float] = None typical_p: typing.Optional[float] = None use_cache: typing.Optional[bool] = None extra_body: typing.Optional[dict[str, typing.Any]] = None ) bytes

引數

  • text (str) — 要合成的文字。
  • model (str, 可選) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,將使用預設推薦的文字到語音模型。預設為 None。
  • do_sample (bool, optional) — 是否在生成新 token 時使用取樣而不是貪婪解碼。
  • early_stopping (Union[bool, "TextToSpeechEarlyStoppingEnum"], optional) — 控制基於束(beam-based)方法的停止條件。
  • epsilon_cutoff (float, optional) — 如果設定為嚴格在0到1之間的浮點數,則只採樣條件機率大於 epsilon_cutoff 的 token。在論文中,建議值範圍為 3e-4 到 9e-4,具體取決於模型的大小。有關更多詳細資訊,請參閱 Truncation Sampling as Language Model Desmoothing
  • eta_cutoff (float, optional) — Eta 取樣是區域性典型取樣和 epsilon 取樣的混合。如果設定為嚴格在 0 到 1 之間的浮點數,則僅考慮條件機率大於 eta_cutoff 或 sqrt(eta_cutoff) 的 token
    • exp(-entropy(softmax(next_token_logits)))。後者直觀上是預期的下一個 token 機率,乘以 sqrt(eta_cutoff)。在論文中,建議值範圍為 3e-4 到 2e-3,具體取決於模型的大小。有關更多詳細資訊,請參閱 Truncation Sampling as Language Model Desmoothing
  • max_length (int, optional) — 生成文字的最大長度(以 token 為單位),包括輸入。
  • max_new_tokens (int, optional) — 要生成的 token 的最大數量。優先於 max_length。
  • min_length (int, optional) — 生成文字的最小長度(以 token 為單位),包括輸入。
  • min_new_tokens (int, optional) — 要生成的 token 的最小數量。優先於 min_length。
  • num_beam_groups (int, optional) — 將 num_beams 分組的數量,以確保不同 beam 組之間的多樣性。有關更多詳細資訊,請參閱 this paper
  • num_beams (int, optional) — 用於束搜尋的 beam 數量。
  • penalty_alpha (float, optional) — 該值用於平衡對比搜尋解碼中的模型置信度和退化懲罰。
  • temperature (float, optional) — 用於調節下一個 token 機率的值。
  • top_k (int, optional) — 用於 top-k 過濾的最高機率詞彙 token 的數量。
  • top_p (float, optional) — 如果設定為小於 1 的浮點數,則只保留機率累加到 top_p 或更高的最小一組最可能 token 進行生成。
  • typical_p (float, optional) — 區域性典型性衡量了預測下一個 token 的條件機率與給定已生成文字後預測隨機 token 的預期條件機率的相似程度。如果設定為小於 1 的浮點數,則會保留機率累加到 typical_p 或更高的最小一組區域性典型 token 以進行生成。有關更多詳細資訊,請參閱 this paper
  • use_cache (bool, optional) — 模型是否應使用過去的鍵/值注意力來加速解碼
  • extra_body (dict[str, Any], optional) — 傳遞給模型的附加提供者特定引數。有關支援的引數,請參閱提供者的文件。

返回

位元組

生成的音訊。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

合成一個由語音朗讀給定文字的音訊。

您可以透過使用 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)
使用 Replicate 提供商並帶有額外引數的示例
>>> 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)

示例 music-gen 使用 fal.ai 上的 “YuE-s1-7B-anneal-en-cot”

>>> 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: typing.Optional[str] = None guidance_scale: typing.Optional[float] = None negative_prompt: typing.Optional[list[str]] = None num_frames: typing.Optional[float] = None num_inference_steps: typing.Optional[int] = None seed: typing.Optional[int] = None extra_body: typing.Optional[dict[str, typing.Any]] = None ) bytes

引數

  • prompt (str) — 用於生成影片的提示。
  • model (str, optional) — 要用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,將使用預設推薦的文字到影片模型。預設為 None。
  • guidance_scale (float, optional) — 更高的引導尺度值會鼓勵模型生成與文字提示更緊密相關的影片,但過高的值可能會導致飽和和其他偽影。
  • negative_prompt (list[str], optional) — 用於引導影片生成中不包含的內容的提示。
  • num_frames (float, optional) — num_frames 引數決定生成多少影片幀。
  • num_inference_steps (int, optional) — 去噪步數。更多的去噪步數通常可以帶來更高質量的影片,但會以犧牲推理速度為代價。
  • seed (int, optional) — 隨機數生成器的種子。
  • extra_body (dict[str, Any], optional) — 傳遞給模型的附加提供者特定引數。有關支援的引數,請參閱提供者的文件。

返回

位元組

生成的影片。

根據給定的文字生成影片。

您可以透過使用 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: typing.Optional[str] = None aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None ignore_labels: typing.Optional[list[str]] = None stride: typing.Optional[int] = None ) list[TokenClassificationOutputElement]

引數

  • text (str) — 要分類的字串。
  • model (str, optional) — 用於令牌分類任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的令牌分類模型。預設為 None。
  • aggregation_strategy ("TokenClassificationAggregationStrategy", optional) — 用於基於模型預測融合令牌的策略
  • ignore_labels (list[str, optional) — 要忽略的標籤列表
  • stride (int, optional) — 分割輸入文字時塊之間的重疊令牌數。

返回

list[TokenClassificationOutputElement]

包含實體組、置信度得分、單詞、開始和結束索引的 TokenClassificationOutputElement 項列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

對給定文字執行令牌分類。通常用於語法分析或命名實體識別 (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,
    )
]

翻譯

< >

( text: str model: typing.Optional[str] = None src_lang: typing.Optional[str] = None tgt_lang: typing.Optional[str] = None clean_up_tokenization_spaces: typing.Optional[bool] = None truncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = None generate_parameters: typing.Optional[dict[str, typing.Any]] = None ) TranslationOutput

引數

  • text (str) — 要翻譯的字串。
  • model (str, optional) — 用於翻譯任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的翻譯模型。預設為 None。
  • src_lang (str, optional) — 文字的源語言。對於可以從多種語言進行翻譯的模型是必需的。
  • tgt_lang (str, optional) — 要翻譯成的目標語言。對於可以翻譯成多種語言的模型是必需的。
  • clean_up_tokenization_spaces (bool, optional) — 是否清理文字輸出中可能存在的額外空格。
  • truncation ("TranslationTruncationStrategy", optional) — 要使用的截斷策略。
  • generate_parameters (dict[str, Any], optional) — 文字生成演算法的附加引數化。

返回

TranslationOutput

生成的翻譯文字。

引發

InferenceTimeoutErrorHfHubHTTPErrorValueError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。
  • ValueError — 如果只提供 src_langtgt_lang 引數中的一個。

將文字從一種語言翻譯成另一種語言。

請檢視 https://huggingface.co/tasks/translation,瞭解更多關於如何為您的具體用例選擇最佳模型的資訊。源語言和目標語言通常取決於模型。但是,可以為某些模型指定源語言和目標語言。如果您使用的是這些模型之一,則可以使用 src_langtgt_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.')

指定語言

>>> client.translation("My name is Sarah Jessica Parker but you can call me Jessica", model="facebook/mbart-large-50-many-to-many-mmt", src_lang="en_XX", tgt_lang="fr_XX")
"Mon nom est Sarah Jessica Parker mais vous pouvez m'appeler Jessica"

visual_question_answering

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] question: str model: typing.Optional[str] = None top_k: typing.Optional[int] = None ) list[VisualQuestionAnsweringOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 輸入影像用於上下文。可以是原始位元組、影像檔案、線上影像的 URL,或是 PIL 影像。
  • question (str) — 要回答的問題。
  • model (str, optional) — 用於視覺問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的視覺問答模型。預設為 None。
  • top_k (int, optional) — 要返回的答案數量(將按可能性順序選擇)。請注意,如果沒有足夠的上下文選項,我們將返回少於 topk 個答案。

返回

list[VisualQuestionAnsweringOutputElement]

包含預測標籤和相關機率的 VisualQuestionAnsweringOutputElement 項列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

基於影像回答開放式問題。

示例

>>> 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: typing.Optional[bool] = False hypothesis_template: typing.Optional[str] = None model: typing.Optional[str] = None ) list[ZeroShotClassificationOutputElement]

引數

  • text (str) — 要分類的輸入文字。
  • candidate_labels (list[str]) — 將文字分類到的可能類標籤集。
  • labels (list[str], optional) — (已棄用) 字串列表。每個字串是輸入文字可能標籤的口頭表達。
  • multi_label (bool, 可選) — 是否允許多個候選標籤為真。如果為 False,則對分數進行歸一化,使得每個序列的標籤似然之和為 1。如果為 True,則將標籤視為獨立,併為每個候選者歸一化機率。
  • hypothesis_template (str, 可選) — 與 candidate_labels 一起使用的句子,透過用候選標籤替換佔位符來嘗試進行文字分類。
  • model (str, 可選) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此引數將覆蓋例項級別的模型。如果未提供,將使用預設推薦的零樣本分類模型。

返回

list[ZeroShotClassificationOutputElement]

包含預測標籤及其置信度的 ZeroShotClassificationOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

提供文字和一組候選標籤來對輸入文字進行分類。

使用 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: typing.Optional[str] = None hypothesis_template: typing.Optional[str] = None labels: list = None ) list[ZeroShotImageClassificationOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要進行題詞的輸入影像。它可以是原始位元組、影像檔案、線上影像的 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 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

提供輸入影像和文字標籤,以預測影像的文字標籤。

示例

>>> 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),...]

非同步推理客戶端

還提供了一個非同步版本客戶端,基於 asynciohttpx

class huggingface_hub.AsyncInferenceClient

< >

( model: typing.Optional[str] = None provider: typing.Union[typing.Literal['black-forest-labs', 'cerebras', 'clarifai', 'cohere', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'hyperbolic', 'nebius', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'sambanova', 'scaleway', 'together', 'wavespeed', 'zai-org'], typing.Literal['auto'], NoneType] = None token: typing.Optional[str] = None timeout: typing.Optional[float] = None headers: typing.Optional[dict[str, str]] = None cookies: typing.Optional[dict[str, str]] = None bill_to: typing.Optional[str] = None base_url: typing.Optional[str] = None api_key: typing.Optional[str] = None )

引數

  • model (str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,例如 meta-llama/Meta-Llama-3-8B-Instruct,也可以是已部署的 Inference Endpoint 的 URL。預設為 None,在這種情況下,將自動為該任務選擇推薦的模型。注意:為了更好地與 OpenAI 的客戶端相容,model 已被別名為 base_url。這兩個引數是互斥的。如果將 URL 作為 modelbase_url 傳遞用於聊天補全,則會在 URL 後面附加 (/v1)/chat/completions 路徑。
  • provider (str, 可選) — 用於推理的提供商名稱。可以是 "black-forest-labs""cerebras""clarifai""cohere""fal-ai""featherless-ai""fireworks-ai""groq""hf-inference""hyperbolic""nebius""novita""nscale""openai""ovhcloud""publicai""replicate""sambanova""scaleway""together""wavespeed""zai-org"。預設為“auto”,即按使用者在 https://huggingface.co/settings/inference-providers 中設定的順序,可用模型的第一順位提供商。如果模型是 URL 或傳遞了 base_url,則不使用 provider
  • token (str, 可選) — Hugging Face token。如果未提供,則預設為本地儲存的 token。注意:為了更好地與 OpenAI 的客戶端相容,token 已被別名為 api_key。這兩個引數是互斥的,並且具有完全相同的行為。
  • timeout (float, optional) — 等待伺服器響應的最長時間(秒)。預設為 None,表示會一直迴圈直到伺服器可用。
  • headers (dict[str, str], optional) — 傳送到伺服器的附加標頭。預設情況下,僅傳送授權和使用者代理標頭。此字典中的值將覆蓋預設值。
  • bill_to (str, optional) — 用於請求的賬單賬戶。預設情況下,請求會向用戶賬戶收費。請求只能向用戶所屬的組織收費,並且該組織已訂閱 Enterprise Hub。
  • cookies (dict[str, str], optional) — 傳送到伺服器的附加 cookie。
  • base_url (str, optional) — 用於進行推理的基礎 URL。這是 model 引數的重複引數,用於使 InferenceClient 遵循與 openai.OpenAI 客戶端相同的模式。不能與 model 引數一起使用。預設為 None。
  • api_key (str, optional) — 用於身份驗證的 token。這是 token 引數的重複引數,用於使 InferenceClient 遵循與 openai.OpenAI 客戶端相同的模式。不能與 token 引數一起使用。預設為 None。

初始化一個新的推理客戶端。

InferenceClient 旨在提供統一的推理體驗。該客戶端可以無縫地與(免費的)推理 API、自託管的推理端點或第三方推理提供商一起使用。

音訊分類

< >

( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None top_k: typing.Optional[int] = None function_to_apply: typing.Optional[ForwardRef('AudioClassificationOutputTransform')] = None ) list[AudioClassificationOutputElement]

引數

  • audio (Union[str, Path, bytes, BinaryIO]) — 要分類的音訊內容。它可以是原始音訊位元組、本地音訊檔案或指向音訊檔案的 URL。
  • model (str, 可選) — 用於音訊分類的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,將使用預設推薦的音訊分類模型。
  • top_k (int, 可選) — 指定時,將輸出限制為最可能的 K 個類別。
  • function_to_apply ("AudioClassificationOutputTransform", 可選) — 要應用於模型輸出以檢索分數的函式。

返回

list[AudioClassificationOutputElement]

包含預測標籤及其置信度的 AudioClassificationOutputElement 列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

對提供的音訊內容執行音訊分類。

示例

# 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: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None ) list[AudioToAudioOutputElement]

引數

  • audio (Union[str, Path, bytes, BinaryIO]) — 模型音訊內容。它可以是原始音訊位元組、本地音訊檔案或指向音訊檔案的 URL。
  • model (str, 可選) — 可以是任何接受音訊檔案並返回另一個音訊檔案的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,將使用推薦的預設 audio_to_audio 模型。

返回

list[AudioToAudioOutputElement]

包含音訊標籤、內容型別和音訊內容的 AudioToAudioOutputElement 列表(以 blob 形式)。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

執行與音訊到音訊相關的多個任務,具體取決於模型(例如:語音增強、源分離)。

示例

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

自動語音識別

< >

( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None extra_body: typing.Optional[dict] = None ) AutomaticSpeechRecognitionOutput

引數

  • audio (Union[str, Path, bytes, BinaryIO]) — 要轉錄的內容。它可以是原始音訊位元組、本地音訊檔案或指向音訊檔案的 URL。
  • model (str, 可選) — 用於 ASR 的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,將使用推薦的預設 ASR 模型。
  • extra_body (dict, 可選) — 傳遞給模型的其他提供商特定引數。有關支援的引數,請參閱提供商的文件。

返回

AutomaticSpeechRecognitionOutput

一個包含轉錄文字和可選的時間戳塊的專案。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

對給定的音訊內容執行自動語音識別(ASR 或音訊到文字)。

示例

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.automatic_speech_recognition("hello_world.flac").text
"hello world"

chat_completion

< >

( messages: list model: typing.Optional[str] = None stream: bool = False frequency_penalty: typing.Optional[float] = None logit_bias: typing.Optional[list[float]] = None logprobs: typing.Optional[bool] = None max_tokens: typing.Optional[int] = None n: typing.Optional[int] = None presence_penalty: typing.Optional[float] = 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: typing.Optional[int] = None stop: typing.Optional[list[str]] = None stream_options: typing.Optional[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions] = None temperature: typing.Optional[float] = None tool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None tool_prompt: typing.Optional[str] = None tools: typing.Optional[list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool]] = None top_logprobs: typing.Optional[int] = None top_p: typing.Optional[float] = None extra_body: typing.Optional[dict] = None ) ChatCompletionOutputChatCompletionStreamOutput 的可迭代物件

引數

  • messages (List of ChatCompletionInputMessage) — 對話歷史,包含角色和內容對。
  • model (str, 可選) — 用於聊天的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,將使用推薦的預設基於聊天的文字生成模型。有關更多詳細資訊,請參閱 https://huggingface.co/tasks/text-generation。如果 model 是模型 ID,則會作為 model 引數傳遞給伺服器。如果您想在請求負載中定義自定義 URL 並設定 model,則必須在初始化 InferenceClient 時設定 base_url
  • frequency_penalty (float, 可選) — 根據文字中已有的頻率對新標記進行懲罰。範圍:[-2.0, 2.0]。預設為 0.0。
  • logit_bias (list[float], 可選) — 調整特定標記在生成輸出中出現的可能性。
  • logprobs (bool, 可選) — 是否返回輸出標記的 log 機率。如果為 true,則返回訊息內容中返回的每個輸出標記的 log 機率。
  • max_tokens (int, 可選) — 響應允許的最大標記數。預設為 100。
  • n (int, 可選) — 為每個提示生成的完成次數。
  • presence_penalty (float, 可選) — 介於 -2.0 和 2.0 之間的數字。正值會根據新標記是否已出現在文字中進行懲罰,從而增加模型討論新主題的可能性。
  • response_format (ChatCompletionInputGrammarType(), 可選) — 語法約束。可以是 JSONSchema 或 regex。
  • seed (Optionalint, 可選) — 可復現的控制流的種子。預設為 None。
  • stop (list[str], 可選) — 最多四個字串,用於觸發響應的結束。預設為 None。
  • stream (bool, 可選) — 啟用響應的即時流式傳輸。預設為 False。
  • stream_options (ChatCompletionInputStreamOptions, 可選) — 流式完成選項。
  • temperature (float, 可選) — 控制生成的隨機性。較低的值可確保生成結果不太隨機。範圍:[0, 2]。預設為 1.0。
  • top_logprobs (int, 可選) — 一個介於 0 和 5 之間的整數,指定要返回的每個標記位置的最有可能的標記數量,每個標記都有一個相關的 log 機率。如果使用此引數,則必須將 logprobs 設定為 true。
  • top_p (float, 可選) — 要從中取樣最有可能的下一個詞的分數。必須介於 0 和 1 之間。預設為 1.0。
  • tool_choice (ChatCompletionInputToolChoiceClass or ChatCompletionInputToolChoiceEnum(), 可選) — 要使用的工具。預設為“auto”。
  • tool_prompt (str, 可選) — 在工具之前附加的提示。
  • tools (List of ChatCompletionInputTool, 可選) — 模型可能呼叫的工具列表。目前,只有函式支援作為工具。使用此功能為模型可以生成 JSON 輸入的函式列表。
  • extra_body (dict, 可選) — 傳遞給模型的其他提供商特定引數。有關支援的引數,請參閱提供商的文件。

返回

ChatCompletionOutputChatCompletionStreamOutput 的可迭代物件

從伺服器生成的文字

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

用於使用指定語言模型完成對話的方法。

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"}'

close

< >

( )

關閉客戶端。

當客戶端作為上下文管理器使用時,此方法會自動呼叫。

document_question_answering

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] question: str model: typing.Optional[str] = None doc_stride: typing.Optional[int] = None handle_impossible_answer: typing.Optional[bool] = None lang: typing.Optional[str] = None max_answer_len: typing.Optional[int] = None max_question_len: typing.Optional[int] = None max_seq_len: typing.Optional[int] = None top_k: typing.Optional[int] = None word_boxes: typing.Optional[list[typing.Union[list[float], str]]] = 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, optional) — 執行 OCR 時使用的語言。預設為 "english"。
  • max_answer_len (int, optional) — 預測答案的最大長度(例如,僅考慮長度較短的答案)。
  • max_question_len (int, optional) — 標記化後問題的最大長度。如果需要,將被截斷。
  • max_seq_len (int, optional) — 模型輸入的每個分塊中的總句子(上下文 + 問題)的最大長度(以 token 為單位)。如果需要,上下文將被分割成幾個帶有重疊的分塊(使用 doc_stride 作為重疊)。
  • top_k (int, optional) — 返回答案的數量(將按可能性順序選擇)。如果可用的選項少於 top_k 個,則返回的答案數可能少於 top_k 個。
  • word_boxes (list[Union[list[float], str, optional) — 單詞和邊界框的列表(標準化 0-1000)。如果提供,推理將跳過 OCR 步驟,而是使用提供的邊界框。

返回

list[DocumentQuestionAnsweringOutputElement]

包含預測標籤、關聯機率、單詞 ID 和頁面編號的 `DocumentQuestionAnsweringOutputElement` 項列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

回答文件影像上的問題。

示例

# 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 normalize: typing.Optional[bool] = None prompt_name: typing.Optional[str] = None truncate: typing.Optional[bool] = None truncation_direction: typing.Optional[typing.Literal['left', 'right']] = None dimensions: typing.Optional[int] = None encoding_format: typing.Optional[typing.Literal['float', 'base64']] = None model: typing.Optional[str] = None ) np.ndarray

引數

  • text (str) — 要嵌入的文字。
  • model (str, optional) — 用於特徵提取任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用推薦的預設特徵提取模型。預設為 None。
  • normalize (bool, optional) — 是否對嵌入進行歸一化。僅在由 Text-Embedding-Inference 提供支援的伺服器上可用。
  • prompt_name (str, optional) — 要用於編碼的提示名稱。如果未設定,則不應用提示。必須是 Sentence Transformers 配置 prompts 字典中的一個鍵。例如,如果 prompt_name 為“query”,而 prompts 為 {“query”: “query: ”,…},則句子“What is the capital of France?”將被編碼為“query: What is the capital of France?”,因為提示文字將在要編碼的文字之前新增。
  • truncate (bool, optional) — 是否截斷嵌入。僅在由 Text-Embedding-Inference 提供支援的伺服器上可用。
  • truncation_direction (Literal[“left”, “right”], optional) — 當傳遞 truncate=True 時,應截斷輸入的哪一側。
  • dimensions (int, optional) — 結果嵌入應具有的維度數。僅在 OpenAI 相容的嵌入端點上可用。
  • encoding_format (Literal[“float”, “base64”], optional) — 輸出嵌入的格式。可以是“float”或“base64”。僅在 OpenAI 相容的嵌入端點上可用。

返回

np.ndarray

將輸入文字表示為 float32 numpy 陣列的嵌入。

引發

[InferenceTimeoutError] 或 [HfHubHTTPError]

  • [InferenceTimeoutError] — 如果模型不可用或請求超時。
  • [HfHubHTTPError] — 如果請求以除 HTTP 503 之外的 HTTP 錯誤狀態碼失敗。

為給定的文字生成嵌入。

示例

# 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: typing.Optional[str] = None targets: typing.Optional[list[str]] = None top_k: typing.Optional[int] = None ) list[FillMaskOutputElement]

引數

  • text (str) — 要填充的字串,必須包含 [MASK] token(請檢查模型卡以獲取掩碼的確切名稱)。
  • model (str, optional) — 用於填空任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用推薦的預設填空模型。
  • targets (list[str, optional) — 當傳入時,模型將僅限於目標的分數,而不是查詢整個詞彙表。如果提供的目標不在模型詞彙表中,它們將被標記化,並使用第一個結果標記(併發出警告,這可能會降低速度)。
  • top_k (int, optional) — 當傳入時,覆蓋要返回的預測數量。

返回

list[FillMaskOutputElement]

一個包含預測標籤、關聯機率、令牌引用和完成文字的 FillMaskOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

填充一個帶有缺失詞(準確地說是令牌)的空缺。

示例

# 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: typing.Optional[str] = None ) dict[str, Any]

引數

  • model (str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數將覆蓋例項級別定義的模型。預設為 None。

返回

dict[str, Any]

有關端點的資訊。

獲取已部署端點的資訊。

此端點僅在由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 提供的端點上可用。由 transformers 提供的端點將返回空負載。

示例

# 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: typing.Optional[str] = None ) bool

引數

  • model (str, optional) — 推理端點的 URL。此引數將覆蓋例項級別定義的模型。預設為 None。

返回

布林值

如果一切正常,則為 True。

檢查已部署端點的執行狀況。

健康檢查僅適用於由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 提供的推理端點。

示例

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient("https://jzgu0buei5.us-east-1.aws.endpoints.huggingface.cloud")
>>> await client.health_check()
True

image_classification

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None function_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = None top_k: typing.Optional[int] = None ) list[ImageClassificationOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分類的影像。可以是原始位元組、影像檔案、線上影像的 URL 或 PIL Image。
  • model (str, optional) — 用於影像分類的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的影像分類模型。
  • function_to_apply ("ImageClassificationOutputTransform", optional) — 用於檢索分數的應用到模型輸出的函式。
  • top_k (int, optional) — 指定時,將輸出限制為最可能的前 K 個類。

返回

list[ImageClassificationOutputElement]

一個包含預測標籤和關聯機率的 ImageClassificationOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

使用指定模型對給定影像執行影像分類。

示例

# 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: typing.Optional[str] = None mask_threshold: typing.Optional[float] = None overlap_mask_area_threshold: typing.Optional[float] = None subtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = None threshold: typing.Optional[float] = None ) list[ImageSegmentationOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分割的影像。可以是原始位元組、影像檔案、線上影像的 URL 或 PIL Image。
  • model (str, optional) — 用於影像分割的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的影像分割模型。
  • mask_threshold (float, optional) — 將預測蒙版轉換為二進位制值時使用的閾值。
  • overlap_mask_area_threshold (float, optional) — 消除小而斷開的片段的蒙版重疊閾值。
  • subtask ("ImageSegmentationSubtask", optional) — 根據模型功能執行的分段任務。
  • threshold (float, optional) — 過濾掉預測蒙版的機率閾值。

返回

list[ImageSegmentationOutputElement]

包含分割掩碼和相關屬性的 ImageSegmentationOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

使用指定模型對給定影像執行影像分割。

如果您想處理影像,則必須安裝 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: typing.Optional[str] = None negative_prompt: typing.Optional[str] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None model: typing.Optional[str] = None target_size: typing.Optional[huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize] = None **kwargs ) Image

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 翻譯的輸入影像。可以是原始位元組、影像檔案、線上影像的 URL 或 PIL Image。
  • prompt (str, optional) — 用於指導影像生成的文字提示。
  • negative_prompt (str, optional) — 指導影像生成中不包含的內容的提示。
  • num_inference_steps (int, optional) — 對於擴散模型。去噪步驟的數量。更多的去噪步驟通常會以較慢的推理速度為代價,從而獲得更高質量的影像。
  • guidance_scale (float, optional) — 對於擴散模型。更高的指導尺度值會鼓勵模型生成與文字提示緊密相關的影像,但會以較低的影像質量為代價。
  • model (str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數將覆蓋例項級別設定的模型。預設為 None。
  • target_size (ImageToImageTargetSize, optional) — 輸出影像的畫素大小。此引數僅受某些提供商和特定模型的支援。不支援時將被忽略。

返回

影像

轉換後的影像。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

使用指定的模型執行影像到影像的轉換。

如果您想處理影像,則必須安裝 PIL (pip install Pillow)。

示例

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> image = await client.image_to_image("cat.jpg", prompt="turn the cat into a tiger")
>>> image.save("tiger.jpg")

image_to_text

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] model: typing.Optional[str] = None ) ImageToTextOutput

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要新增說明的輸入影像。可以是原始位元組、影像檔案、線上影像的 URL 或 PIL Image。
  • model (str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數將覆蓋例項級別設定的模型。預設為 None。

返回

ImageToTextOutput

生成的文字。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

接收輸入影像並返回文字。

模型可能因您的用例(影像字幕、光學字元識別 (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: typing.Optional[str] = None prompt: typing.Optional[str] = None negative_prompt: typing.Optional[str] = None num_frames: typing.Optional[float] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None seed: typing.Optional[int] = None target_size: typing.Optional[huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize] = None **kwargs ) bytes

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用於生成影片的輸入影像。可以是原始位元組、影像檔案、線上影像的 URL 或 PIL Image。
  • model (str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數將覆蓋例項級別設定的模型。預設為 None。
  • prompt (str, optional) — 用於指導影片生成的文字提示。
  • negative_prompt (str, optional) — 指導影片生成中不包含的內容的提示。
  • num_frames (float, optional) — num_frames 引數決定生成多少個影片幀。
  • num_inference_steps (int, optional) — 對於擴散模型。去噪步驟的數量。更多的去噪步驟通常會以較慢的推理速度為代價,從而獲得更高質量的影像。
  • guidance_scale (float, 可選) — 對於擴散模型。較高的引導尺度值會促使模型生成與文字提示更緊密相關的影片,但會犧牲影像質量。
  • seed (int, 可選) — 用於影片生成的種子。
  • target_size (ImageToVideoTargetSize, 可選) — 輸出影片幀的畫素大小。
  • num_inference_steps (int, 可選) — 去噪步數。更多的去噪步數通常能帶來更高的影片質量,但推理速度會變慢。
  • seed (int, 可選) — 隨機數生成器的種子。

返回

位元組

生成的影片。

從輸入影像生成影片。

示例

# 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: typing.Optional[str] = None threshold: typing.Optional[float] = None ) list[ObjectDetectionOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要在其上檢測物件的影像。它可以是原始位元組、影像檔案、線上影像的 URL 或 PIL Image。
  • model (str, 可選) — 用於物件檢測的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的物件檢測模型(DETR)。
  • threshold (float, 可選) — 做出預測所需的機率。

返回

list[ObjectDetectionOutputElement]

包含邊界框和相關屬性的 ObjectDetectionOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPErrorValueError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。
  • 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: typing.Optional[str] = None align_to_words: typing.Optional[bool] = None doc_stride: typing.Optional[int] = None handle_impossible_answer: typing.Optional[bool] = None max_answer_len: typing.Optional[int] = None max_question_len: typing.Optional[int] = None max_seq_len: typing.Optional[int] = None top_k: typing.Optional[int] = 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, 可選) — 是否接受不可能的答案。
  • max_answer_len (int, 可選) — 預測答案的最大長度(例如,只考慮長度較短的答案)。
  • max_question_len (int, 可選) — 問題經過 token 化後的最大長度。如果需要,將被截斷。
  • max_seq_len (int, 可選) — 輸入到模型的每個塊的最大序列長度(以 token 為單位)。如果需要,上下文將被分割成多個塊(使用 docStride 作為重疊)。
  • top_k (int, 可選) — 返回的答案數量(將按可能性順序選擇)。請注意,如果沒有足夠的可用選項,則返回的答案少於 topk。

返回

Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]

當 top_k 為 1 或未提供時,它返回單個 QuestionAnsweringOutputElement。當 top_k 大於 1 時,它返回一個 QuestionAnsweringOutputElement 列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

從給定文字中檢索問題的答案。

示例

# 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: typing.Optional[str] = None ) list[float]

引數

  • sentence (str) — 用於與其他句子進行比較的主要句子。
  • other_sentences (list[str]) — 用於比較的句子列表。
  • model (str, 可選) — 用於句子相似性任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,將使用預設推薦的句子相似性模型。預設為 None。

返回

list[float]

表示輸入文字的嵌入。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

透過比較句子的嵌入來計算一個句子與一組其他句子之間的語義相似度。

示例

# 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]

摘要

< >

( text: str model: typing.Optional[str] = None clean_up_tokenization_spaces: typing.Optional[bool] = None generate_parameters: typing.Optional[dict[str, typing.Any]] = 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", optional) — 要使用的截斷策略。

返回

SummarizationOutput

生成的摘要文字。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

使用指定的模型生成給定文字的摘要。

示例

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.summarization("The Eiffel tower...")
SummarizationOutput(generated_text="The Eiffel tower is one of the most famous landmarks in the world....")

table_question_answering

< >

( table: dict query: str model: typing.Optional[str] = None padding: typing.Optional[ForwardRef('Padding')] = None sequential: typing.Optional[bool] = None truncation: typing.Optional[bool] = None ) TableQuestionAnsweringOutputElement

引數

  • table (str) — 一個以字典列表形式表示的資料表,其中條目是標題,列表是所有值,所有列表的大小必須相同。
  • query (str) — 您想詢問表的純文字查詢。
  • model (str) — 用於表格問答任務的模型。可以是 Hugging Face Hub 上託管的模型 ID 或已部署的推理端點的 URL。
  • padding ("Padding", optional) — 啟用並控制填充。
  • sequential (bool, optional) — 是否順序執行或批次執行。批次處理速度更快,但像 SQA 這樣的模型需要順序執行才能在序列中提取關係,因為它們具有對話性質。
  • truncation (bool, optional) — 啟用並控制截斷。

返回

TableQuestionAnsweringOutputElement

一個表格問答輸出,包含答案、座標、單元格和使用的聚合器。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

從表格中提供的資訊中檢索問題的答案。

示例

# 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: typing.Optional[str] = None ) List

引數

  • table (dict[str, Any]) — 要分類的屬性集。
  • model (str, optional) — 用於表格分類任務的模型。可以是 Hugging Face Hub 上託管的模型 ID 或已部署的推理端點的 URL。如果未提供,將使用推薦的預設表格分類模型。預設為 None。

返回

列表

表格初始行數的一系列標籤。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

根據一組屬性對目標類別(一組)進行分類。

示例

# 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: typing.Optional[str] = None ) List

引數

  • table (dict[str, Any]) — 用於預測目標的一組屬性。屬性可以是數值型和類別型的。
  • model (str, optional) — 用於表格迴歸任務的模型。可以是 Hugging Face Hub 上託管的模型 ID 或已部署的推理端點的 URL。如果未提供,將使用推薦的預設表格迴歸模型。預設為 None。

返回

列表

一組預測的數值目標值。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

給定表格中的一組屬性/特徵,預測數值目標值。

示例

# 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_classification

< >

( text: str model: typing.Optional[str] = None top_k: typing.Optional[int] = 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 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

對給定文字執行文字分類(例如,情感分析)。

示例

# 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: typing.Optional[bool] = None stream: typing.Optional[bool] = None model: typing.Optional[str] = None adapter_id: typing.Optional[str] = None best_of: typing.Optional[int] = None decoder_input_details: typing.Optional[bool] = None do_sample: typing.Optional[bool] = None frequency_penalty: typing.Optional[float] = None grammar: typing.Optional[huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType] = None max_new_tokens: typing.Optional[int] = None repetition_penalty: typing.Optional[float] = None return_full_text: typing.Optional[bool] = None seed: typing.Optional[int] = None stop: typing.Optional[list[str]] = None stop_sequences: typing.Optional[list[str]] = None temperature: typing.Optional[float] = None top_k: typing.Optional[int] = None top_n_tokens: typing.Optional[int] = None top_p: typing.Optional[float] = None truncate: typing.Optional[int] = None typical_p: typing.Optional[float] = None watermark: typing.Optional[bool] = None ) Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]

引數

  • prompt (str) — 輸入文字。
  • details (bool, optional) — 預設情況下,text_generation 返回一個字串。如果您想要詳細的輸出(tokens、probabilities、seed、finish reason 等),請傳遞 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 adapter ID。
  • best_of (int, optional) — 生成 best_of 個序列並返回其中具有最高 token logprobs 的那個。
  • decoder_input_details (bool, optional) — 返回 decoder 輸入 token 的 logprobs 和 ids。您必須同時設定 details=True 才能使其生效。預設為 False
  • do_sample (bool, optional) — 啟用 logits 取樣
  • frequency_penalty (float, 可選) — 介於 -2.0 和 2.0 之間的數值。正值會根據文字已有的頻率對新生成的 token 進行懲罰,降低模型逐字重複同一行的可能性。
  • grammar (TextGenerationInputGrammarType, 可選) — 語法約束。可以是 JSONSchema 或正則表示式。
  • max_new_tokens (int, 可選) — 生成的 token 的最大數量。預設為 100。
  • repetition_penalty (float, 可選) — 重複懲罰引數。1.0 表示無懲罰。更多詳情請參閱 本文件
  • return_full_text (bool, 可選) — 是否在生成的文字前加上提示詞。
  • seed (int, 可選) — 隨機取樣種子。
  • stop (list[str], 可選) — 如果生成了 stop 中的成員,則停止生成 token。
  • stop_sequences (list[str], 可選) — 已棄用的引數。請改用 stop
  • temperature (float, 可選) — 用於調整 logits 分佈的值。
  • top_n_tokens (int, 可選) — 返回每個生成步驟中最可能的 top_n_tokens 的資訊,而不是僅返回取樣到的 token。
  • top_k (int, 可選) — 保留用於 top-k 過濾的最高機率詞彙 token 的數量。
  • top_p (float, 可選) -- 如果設定為 < 1,則只保留機率累加到 top_p 或更高的最小一組最有可能的 token 進行生成。
  • truncate (int, 可選) — 將輸入 token 截斷到指定大小。
  • typical_p (float, 可選) -- 典型解碼質量,請參閱 Typical Decoding for Natural Language Generation 以獲取更多資訊。
  • watermark (bool, 可選) — 使用 A Watermark for Large Language Models 進行水印處理。

返回

Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]

從伺服器生成的文字

  • 如果 stream=Falsedetails=False,則生成的文字將作為 str 返回(預設)
  • 如果 stream=Truedetails=False,則生成的文字將逐 token 返回為 AsyncIterable[str]
  • 如果 stream=Falsedetails=True,則生成的文字將包含更多詳細資訊,並作為 TextGenerationOutput 返回
  • 如果 details=Truestream=True,則生成的文字將逐 token 返回為 TextGenerationStreamOutput 的可迭代物件

引發

ValidationErrorInferenceTimeoutErrorHfHubHTTPError

  • ValidationError -- 如果輸入值無效。不會向伺服器發出 HTTP 呼叫。
  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

給定一個提示,生成以下文字。

如果您想從聊天訊息生成響應,您應該使用 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: typing.Optional[str] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None model: typing.Optional[str] = None scheduler: typing.Optional[str] = None seed: typing.Optional[int] = None extra_body: typing.Optional[dict[str, typing.Any]] = None ) Image

引數

  • prompt (str) — 用於生成影像的提示詞。
  • negative_prompt (str, 可選) — 指導影像生成不應包含的內容的提示詞。
  • height (int, 可選) — 輸出影像的畫素高度。
  • width (int, 可選) — 輸出影像的畫素寬度。
  • num_inference_steps (int, 可選) — 去噪步驟的數量。更多的去噪步驟通常會帶來更高質量的影像,但推理速度會變慢。
  • guidance_scale (float, 可選) — 更高的引導比例會鼓勵模型生成與文字提示緊密相關的影像,但過高的值可能會導致飽和和其他偽影。
  • model (str, 可選) — 要用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID 或已部署的推理端點的 URL。如果未提供,將使用預設推薦的文字到影像模型。預設為 None。
  • scheduler (str, 可選) — 使用相容的排程器覆蓋預設排程器。
  • seed (int, 可選) — 隨機數生成器的種子。
  • extra_body (dict[str, Any], 可選) — 傳遞給模型的額外提供商特定引數。有關支援的引數,請參閱提供商的文件。

返回

影像

生成的影像。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

根據給定文字和指定模型生成影像。

如果您想處理影像,則必須安裝 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")
直接使用第三方提供商的示例。使用量將在您的 fal.ai 賬戶上計費。
>>> 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: typing.Optional[str] = None do_sample: typing.Optional[bool] = None early_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None epsilon_cutoff: typing.Optional[float] = None eta_cutoff: typing.Optional[float] = None max_length: typing.Optional[int] = None max_new_tokens: typing.Optional[int] = None min_length: typing.Optional[int] = None min_new_tokens: typing.Optional[int] = None num_beam_groups: typing.Optional[int] = None num_beams: typing.Optional[int] = None penalty_alpha: typing.Optional[float] = None temperature: typing.Optional[float] = None top_k: typing.Optional[int] = None top_p: typing.Optional[float] = None typical_p: typing.Optional[float] = None use_cache: typing.Optional[bool] = None extra_body: typing.Optional[dict[str, typing.Any]] = None ) bytes

引數

  • text (str) — 要合成的文字。
  • model (str, 可選) — 要用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID 或已部署的推理端點的 URL。如果未提供,將使用預設推薦的文字到語音模型。預設為 None。
  • do_sample (bool, 可選) — 在生成新 token 時是否使用取樣而非貪婪解碼。
  • early_stopping (Union[bool, "TextToSpeechEarlyStoppingEnum"], 可選) — 控制基於束的方法的停止條件。
  • epsilon_cutoff (float, optional) — If set to float strictly between 0 and 1, only tokens with a conditional probability greater than epsilon_cutoff will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See Truncation Sampling as Language Model Desmoothing for more details.
  • eta_cutoff (float, optional) — Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either eta_cutoff or sqrt(eta_cutoff)
    • exp(-entropy(softmax(next_token_logits))). The latter term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See Truncation Sampling as Language Model Desmoothing for more details.
  • max_length (int, optional) — The maximum length (in tokens) of the generated text, including the input.
  • max_new_tokens (int, optional) — The maximum number of tokens to generate. Takes precedence over max_length.
  • min_length (int, optional) — The minimum length (in tokens) of the generated text, including the input.
  • min_new_tokens (int, optional) — The minimum number of tokens to generate. Takes precedence over min_length.
  • num_beam_groups (int, optional) — Number of groups to divide num_beams into in order to ensure diversity among different groups of beams. See this paper for more details.
  • num_beams (int, optional) — Number of beams to use for beam search.
  • penalty_alpha (float, optional) — The value balances the model confidence and the degeneration penalty in contrastive search decoding.
  • temperature (float, optional) — The value used to modulate the next token probabilities.
  • top_k (int, optional) — The number of highest probability vocabulary tokens to keep for top-k-filtering.
  • top_p (float, optional) — If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to top_p or higher are kept for generation.
  • typical_p (float, optional) — Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to typical_p or higher are kept for generation. See this paper for more details.
  • use_cache (bool, optional) — Whether the model should use the past last key/values attentions to speed up decoding
  • extra_body (dict[str, Any], optional) — Additional provider-specific parameters to pass to the model. Refer to the provider’s documentation for supported parameters.

返回

位元組

生成的音訊。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

合成一個由語音朗讀給定文字的音訊。

您可以透過使用 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)
使用 Replicate 提供商並帶有額外引數的示例
>>> 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)

示例 music-gen 使用 fal.ai 上的 “YuE-s1-7B-anneal-en-cot”

>>> 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: typing.Optional[str] = None guidance_scale: typing.Optional[float] = None negative_prompt: typing.Optional[list[str]] = None num_frames: typing.Optional[float] = None num_inference_steps: typing.Optional[int] = None seed: typing.Optional[int] = None extra_body: typing.Optional[dict[str, typing.Any]] = None ) bytes

引數

  • prompt (str) — The prompt to generate a video from.
  • model (str, optional) — The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed Inference Endpoint. If not provided, the default recommended text-to-video model will be used. Defaults to None.
  • guidance_scale (float, optional) — A higher guidance scale value encourages the model to generate videos closely linked to the text prompt, but values too high may cause saturation and other artifacts.
  • negative_prompt (list[str], optional) — One or several prompt to guide what NOT to include in video generation.
  • num_frames (float, optional) — The num_frames parameter determines how many video frames are generated.
  • num_inference_steps (int, optional) — The number of denoising steps. More denoising steps usually lead to a higher quality video at the expense of slower inference.
  • seed (int, optional) — Seed for the random number generator.
  • extra_body (dict[str, Any], optional) — Additional provider-specific parameters to pass to the model. Refer to the provider’s documentation for supported parameters.

返回

位元組

生成的影片。

根據給定的文字生成影片。

您可以透過使用 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: typing.Optional[str] = None aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None ignore_labels: typing.Optional[list[str]] = None stride: typing.Optional[int] = None ) list[TokenClassificationOutputElement]

引數

  • text (str) — A string to be classified.
  • model (str, optional) — The model to use for the token classification task. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed Inference Endpoint. If not provided, the default recommended token classification model will be used. Defaults to None.
  • aggregation_strategy ("TokenClassificationAggregationStrategy", optional) — 用於基於模型預測融合 token 的策略
  • ignore_labels (list[str, optional) — 要忽略的標籤列表
  • stride (int, optional) — 在分割輸入文字時,塊之間的重疊 token 數。

返回

list[TokenClassificationOutputElement]

包含實體組、置信度得分、單詞、開始和結束索引的 TokenClassificationOutputElement 項列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

對給定文字執行令牌分類。通常用於語法分析或命名實體識別 (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,
    )
]

翻譯

< >

( text: str model: typing.Optional[str] = None src_lang: typing.Optional[str] = None tgt_lang: typing.Optional[str] = None clean_up_tokenization_spaces: typing.Optional[bool] = None truncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = None generate_parameters: typing.Optional[dict[str, typing.Any]] = None ) TranslationOutput

引數

  • text (str) — 要翻譯的字串。
  • model (str, optional) — 用於翻譯任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,則將使用預設推薦的翻譯模型。預設為 None。
  • src_lang (str, optional) — 文字的源語言。對於可以從多種語言進行翻譯的模型是必需的。
  • tgt_lang (str, optional) — 要翻譯到的目標語言。對於可以翻譯成多種語言的模型是必需的。
  • clean_up_tokenization_spaces (bool, optional) — 是否清理文字輸出中可能出現的額外空格。
  • truncation ("TranslationTruncationStrategy", optional) — 要使用的截斷策略。
  • generate_parameters (dict[str, Any], optional) — 文字生成演算法的其他引數化。

返回

TranslationOutput

生成的翻譯文字。

引發

InferenceTimeoutErrorHfHubHTTPErrorValueError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。
  • ValueError — 如果只提供 src_langtgt_lang 引數中的一個。

將文字從一種語言翻譯成另一種語言。

請檢視 https://huggingface.co/tasks/translation,瞭解更多關於如何為您的具體用例選擇最佳模型的資訊。源語言和目標語言通常取決於模型。但是,可以為某些模型指定源語言和目標語言。如果您使用的是這些模型之一,則可以使用 src_langtgt_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.')

指定語言

>>> client.translation("My name is Sarah Jessica Parker but you can call me Jessica", model="facebook/mbart-large-50-many-to-many-mmt", src_lang="en_XX", tgt_lang="fr_XX")
"Mon nom est Sarah Jessica Parker mais vous pouvez m'appeler Jessica"

visual_question_answering

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview] question: str model: typing.Optional[str] = None top_k: typing.Optional[int] = None ) list[VisualQuestionAnsweringOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 上下文的輸入影像。可以是原始位元組、影像檔案、線上影像的 URL 或 PIL 影像。
  • question (str) — 要回答的問題。
  • model (str, optional) — 用於視覺問答任務的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。如果未提供,則將使用預設推薦的視覺問答模型。預設為 None。
  • top_k (int, optional) — 要返回的答案數量(將按可能性順序選擇)。請注意,如果上下文中沒有足夠的可用選項,我們將返回少於 topk 個答案。

返回

list[VisualQuestionAnsweringOutputElement]

包含預測標籤和相關機率的 VisualQuestionAnsweringOutputElement 項列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

基於影像回答開放式問題。

示例

# 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: typing.Optional[bool] = False hypothesis_template: typing.Optional[str] = None model: typing.Optional[str] = None ) list[ZeroShotClassificationOutputElement]

引數

  • text (str) — 要分類的輸入文字。
  • candidate_labels (list[str]) — 將文字分類到的可能類別標籤集。
  • labels (list[str], optional) — (已棄用) 字串列表。每個字串都是輸入文字可能標籤的口頭表達。
  • multi_label (bool, optional) — 是否可以有多個候選標籤為真。如果為 false,則對標籤的得分進行歸一化,使每個序列的標籤似然之和為 1。如果為 true,則將標籤視為獨立的,併為每個候選標籤進行機率歸一化。
  • hypothesis_template (str, optional) — 用於將佔位符替換為候選標籤,從而嘗試對文字進行分類的句子。
  • model (str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數會覆蓋例項級別的模型定義。如果未提供,則將使用預設推薦的零樣本分類模型。

返回

list[ZeroShotClassificationOutputElement]

包含預測標籤及其置信度的 ZeroShotClassificationOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

提供文字和一組候選標籤來對輸入文字進行分類。

使用 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: typing.Optional[str] = None hypothesis_template: typing.Optional[str] = None labels: list = None ) list[ZeroShotImageClassificationOutputElement]

引數

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要進行字幕處理的輸入影像。可以是原始位元組、影像檔案、線上影像的 URL 或 PIL 影像。
  • candidate_labels (list[str]) — 此影像的候選標籤
  • labels (list[str], optional) — (已棄用) 字串列表,可以是可能的標籤。至少需要 2 個標籤。
  • model (str, optional) — 用於推理的模型。可以是託管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端點的 URL。此引數會覆蓋例項級別的模型定義。如果未提供,則將使用預設推薦的零樣本影像分類模型。
  • hypothesis_template (str, optional) — 用於將佔位符替換為候選標籤,從而嘗試對影像進行分類的句子。

返回

list[ZeroShotImageClassificationOutputElement]

包含預測標籤及其置信度的 ZeroShotImageClassificationOutputElement 專案列表。

引發

InferenceTimeoutErrorHfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或請求超時。
  • HfHubHTTPError — 如果請求以除 HTTP 503 以外的 HTTP 錯誤狀態碼失敗。

提供輸入影像和文字標籤,以預測影像的文字標籤。

示例

# 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

class huggingface_hub.InferenceTimeoutError

< >

( message: str )

模型不可用或請求超時時引發的錯誤。

在 GitHub 上更新

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