Hub Python Library documentation

推理

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

推理

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

  1. 推理服务提供商:通过我们的无服务器推理合作伙伴,提供对数百个机器学习模型的简化、统一访问。这种新方法基于我们之前的 Serverless Inference API,得益于世界级的服务提供商,提供了更多的模型、更好的性能和更高的可靠性。有关支持的服务提供商列表,请参阅文档。
  2. Inference Endpoints:一款可轻松将模型部署到生产环境的产品。推理由 Hugging Face 在您选择的云服务商上,通过专用的全托管基础设施运行。
  3. 本地端点:你还可以通过将客户端连接到这些本地端点,使用 llama.cpp、Ollama、vLLM、LiteLLM 或 Text Generation Inference (TGI) 等本地推理服务器来运行推理。

这些服务可以通过 InferenceClient 对象进行调用。有关如何使用它的更多信息,请参阅此指南。

推理客户端

类 huggingface_hub.InferenceClient

< >

( model: str | None = Noneprovider: typing.Union[typing.Literal['baseten', 'cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], typing.Literal['auto'], NoneType] = Nonetoken: str | None = Nonetimeout: float | None = Noneheaders: dict[str, str] | None = Nonecookies: dict[str, str] | None = Nonebill_to: str | None = Nonebase_url: str | None = Noneapi_key: str | None = None )

参数

  • model (str, optional) — 用于运行推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,例如 meta-llama/Meta-Llama-3-8B-Instruct, 也可以是已部署的 Inference Endpoint 的 URL。默认为 None,此时会自动为任务选择一个推荐的模型。 注意:为了与 OpenAI 的客户端更好地兼容,model 已被别名为 base_url。这两个参数互斥。如果将 URL 作为 model 或 base_url 传入以进行聊天补全,则会在该 URL 后追加 (/v1)/chat/completions 后缀路径。
  • provider (str, 可选) — 用于推理的提供商名称。可以是 "baseten"、"cerebras"、"cohere"、"deepinfra"、"fal-ai"、"featherless-ai"、"fireworks-ai"、"groq"、"hf-inference"、"novita"、"nscale"、"openai"、"ovhcloud"、"publicai"、"replicate"、"scaleway"、"together"、"wavespeed" 或 "zai-org"。 默认为 “auto”:自动路由,默认选择 “fastest” 提供商;您可以在 https://hf.co/settings/inference-providers 切换为 “cheapest” 或 “preferred” 提供商顺序。 如果 model 是 URL 或传入了 base_url,则不会使用 provider。
  • token (str, 可选) — 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) — 要发送到服务器的附加 cookies。
  • base_url (str, optional) — 用于运行推理的基础 URL。这是从 model 复制过来的参数,以便 InferenceClient 遵循与 openai.OpenAI 客户端相同的模式。如果设置了 model,则不能使用此参数。默认为 None。
  • api_key (str, optional) — 用于身份验证的 Token。这是从 token 复制而来的参数,旨在让 InferenceClient 遵循与 openai.OpenAI 客户端相同的模式。如果已设置 token,则不能使用此参数。默认值为 None。

初始化一个新的 Inference Client。

InferenceClient 旨在提供统一的推理体验。该客户端可与(免费的)Inference API、自托管的 Inference Endpoints 或第三方 Inference Providers 无缝配合使用。

音频分类

< >

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

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

对提供的音频内容执行音频分类。

示例:

>>> 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: str | None = 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 形式存储的音频内容。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

根据模型的不同,执行与音频到音频相关的多项任务(例如:语音增强、声源分离)。

示例:

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

automatic_speech_recognition

< >

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

参数

  • audio (Union[str, Path, bytes, BinaryIO]) — 要转录的内容。可以是原始音频字节、本地音频文件或指向音频文件的 URL。
  • model (str, 可选) — 用于 ASR 的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用 ASR 的默认推荐模型。
  • extra_body (dict, 可选) — 传递给模型的额外提供商特定参数。请参阅提供商文档以了解支持的参数。

包含转录文本以及可选的时间戳分块的项。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

对给定的音频内容执行自动语音识别(ASR 或音频转文本)。

示例:

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

chat_completion

< >

( messages: listmodel: str | None = Nonestream: bool = Falsefrequency_penalty: float | None = Nonelogit_bias: list[float] | None = Nonelogprobs: bool | None = Nonemax_tokens: int | None = Nonen: int | None = Nonepresence_penalty: float | None = Noneresponse_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] = Noneseed: int | None = Nonestop: list[str] | None = Nonestream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = Nonetemperature: float | None = Nonetool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = Nonetool_prompt: str | None = Nonetools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = Nonetop_logprobs: int | None = Nonetop_p: float | None = Noneextra_body: dict | None = None ) → ChatCompletionOutput or Iterable of ChatCompletionStreamOutput

参数

  • messages(ChatCompletionInputMessage 列表)— 由角色和内容对组成的对话历史记录。
  • model (str, 可选) — 用于聊天补全的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认的推荐聊天文本生成模型。 有关更多详细信息,请参阅 https://huggingface.co/tasks/text-generation。 如果 model 是模型 ID,它将作为 model 参数传递给服务器。如果要在请求负载中设置 model 的同时定义自定义 URL,则必须在初始化 InferenceClient 时设置 base_url。
  • frequency_penalty (float, 可选) — 根据新标记在现有文本中出现的频率对其进行惩罚。取值范围:[-2.0, 2.0]。默认值为 0.0。
  • logit_bias (list[float],可选) — 调整特定标记在生成输出中出现的概率。
  • logprobs (bool, 可选) — 是否返回输出 token 的对数概率。如果为 true,则返回消息内容中每个输出 token 的对数概率。
  • max_tokens (int, 可选) — 响应中允许的最大 token 数。默认值为 100。
  • n (int, 可选) — 为每个提示词生成的补全数量。
  • presence_penalty (float, 可选) — -2.0 到 2.0 之间的数值。正值会根据新 token 是否已出现在当前文本中对其进行惩罚,从而增加模型讨论新话题的可能性。
  • response_format (ChatCompletionInputGrammarType(),可选) — 语法约束。可以是 JSONSchema 或正则表达式。
  • seed(可选的int,optional)— 用于可复现控制流的随机种子。默认值为 None。
  • stop (list[str],可选) — 最多四个用于触发响应结束的字符串。 默认为 None。
  • stream (bool,可选) — 启用响应的实时流式传输。默认值为 False。
  • stream_options (ChatCompletionInputStreamOptions,可选) — 流式补全的选项。
  • temperature (float, 可选) — 控制生成的随机性。值越低,生成的补全越不随机。取值范围:[0, 2]。默认值为 1.0。
  • top_logprobs (int, 可选) — 一个介于 0 和 5 之间的整数,指定在每个 token 位置返回的最可能 token 的数量,每个 token 都附带一个相关的对数概率。如果使用此参数,则必须将 logprobs 设置为 true。
  • top_p (float, 可选) — 用于采样的最可能下一个词的比例。 必须在 0 和 1 之间。默认值为 1.0。
  • tool_choice(ChatCompletionInputToolChoiceClass 或 ChatCompletionInputToolChoiceEnum(),可选) — 用于补全的工具。默认值为 “auto”。
  • tool_prompt (str, 可选) — 在工具之前追加的提示词。
  • tools(ChatCompletionInputTool 列表,可选)— 模型可以调用的工具列表。目前,仅支持将函数作为工具。使用此参数提供模型可以生成 JSON 输入的函数列表。
  • extra_body (dict, 可选) — 传递给模型的额外提供商特定参数。请参阅提供商文档以了解支持的参数。

返回值

ChatCompletionOutput 或 ChatCompletionStreamOutput 的可迭代对象

从服务器返回的生成文本:

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

一种使用指定语言模型完成对话的方法。

client.chat_completion 方法被别名为 client.chat.completions.create,以兼容 OpenAI 的客户端。 输入和输出完全相同,使用任一语法都会得到相同的结果。 有关 OpenAI 兼容性的更多详细信息,请参阅 推理指南。

您可以通过使用 extra_body 参数向模型传递特定于提供商的参数。

示例:

>>> from huggingface_hub import InferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> client.chat_completion(messages, max_tokens=100)
ChatCompletionOutput(
    choices=[
        ChatCompletionOutputComplete(
            finish_reason='eos_token',
            index=0,
            message=ChatCompletionOutputMessage(
                role='assistant',
                content='The capital of France is Paris.',
                name=None,
                tool_calls=None
            ),
            logprobs=None
        )
    ],
    created=1719907176,
    id='',
    model='meta-llama/Meta-Llama-3-8B-Instruct',
    object='text_completion',
    system_fingerprint='2.0.4-sha-f426a33',
    usage=ChatCompletionOutputUsage(
        completion_tokens=8,
        prompt_tokens=17,
        total_tokens=25
    )
)

使用流式处理的示例:

>>> from huggingface_hub import InferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> for token in client.chat_completion(messages, max_tokens=10, stream=True):
...     print(token)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content='The', role='assistant'), index=0, finish_reason=None)], created=1710498504)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' capital', role='assistant'), index=0, finish_reason=None)], created=1710498504)
(...)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' may', role='assistant'), index=0, finish_reason=None)], created=1710498504)

使用 OpenAI 语法的示例:

# instead of `from openai import OpenAI`
from huggingface_hub import InferenceClient

# instead of `client = OpenAI(...)`
client = InferenceClient(
    base_url=...,
    api_key=...,
)

output = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Count to 10"},
    ],
    stream=True,
    max_tokens=1024,
)

for chunk in output:
    print(chunk.choices[0].delta.content)

使用第三方提供商并直接传入额外(提供商特定)参数的示例。使用费用将从您的 Together AI 账户中扣除。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="together",  # Use Together AI provider
...     api_key="<together_api_key>",  # Pass your Together API key directly
... )
>>> client.chat_completion(
...     model="meta-llama/Meta-Llama-3-8B-Instruct",
...     messages=[{"role": "user", "content": "What is the capital of France?"}],
...     extra_body={"safety_model": "Meta-Llama/Llama-Guard-7b"},
... )

通过 Hugging Face Routing 使用第三方提供商的示例。相关用量将从您的 Hugging Face 账户中计费。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="novita",  # Use Novita 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: strmodel: str | None = Nonedoc_stride: int | None = Nonehandle_impossible_answer: bool | None = Nonelang: str | None = Nonemax_answer_len: int | None = Nonemax_question_len: int | None = Nonemax_seq_len: int | None = Nonetop_k: int | None = Noneword_boxes: list[list[float] | str] | None = None ) → list[DocumentQuestionAnsweringOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO]) — 上下文的输入图像。可以是原始字节、图像文件或指向在线图像的 URL。
  • question (str) — 要回答的问题。
  • model (str, 可选) — 用于文档问答任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文档问答模型。默认为 None。
  • doc_stride (int, 可选) — 如果文档中的单词过长,无法与问题一起放入模型,则会被拆分为多个带有一定重叠的块。此参数用于控制该重叠的大小。
  • handle_impossible_answer (bool, 可选) — 是否接受“不可能”作为答案
  • lang (str, 可选) — 运行 OCR 时使用的语言。默认为 english。
  • max_answer_len (int, 可选) — 预测答案的最大长度(例如,仅考虑长度较短的答案)。
  • max_question_len (int,可选) — 问题经过分词后的最大长度。如有必要,将被截断。
  • max_seq_len (int, 可选) — 传递给模型的每个块中,完整句子(上下文 + 问题)的最大 token 长度。如有需要,上下文将被拆分为多个块(使用 doc_stride 作为重叠部分)。
  • top_k (int, 可选) — 要返回的答案数量(按可能性顺序选择)。如果上下文中可用的选项不足,返回的答案数量可能少于 top_k。
  • word_boxes (list[Union[list[float], str, 可选) — 单词及其边界框(归一化 0->1000)的列表。如果提供,推理将跳过 OCR 步骤,并直接使用提供的边界框。

返回值

list[DocumentQuestionAnsweringOutputElement]

一个包含 DocumentQuestionAnsweringOutputElement 项的列表,其中包含预测标签、相关概率、词 id 和页码。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

回答有关文档图像的问题。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?")
[DocumentQuestionAnsweringOutputElement(answer='us-001', end=16, score=0.9999666213989258, start=16)]

特征提取

< >

( text: str | list[str]normalize: bool | None = Noneprompt_name: str | None = Nonetruncate: bool | None = Nonetruncation_direction: typing.Optional[typing.Literal['left', 'right']] = Nonedimensions: int | None = Noneencoding_format: typing.Optional[typing.Literal['float', 'base64']] = Nonemodel: str | None = None ) → np.ndarray

参数

  • text (str 或 list[str]) — 要嵌入的文本或文本列表。
  • model (str, 可选) — 用于特征提取任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的特征提取模型。默认为 None。
  • normalize (bool, optional) — 是否对嵌入进行归一化。 仅在由 Text-Embedding-Inference 提供支持的服务端上可用。
  • prompt_name (str, optional) — The name of the prompt that should be used by for encoding. If not set, no prompt will be applied. Must be a key in the Sentence Transformers configuration prompts dictionary. For example if prompt_name is “query” and the prompts is {“query”: “query: ”,…}, then the sentence “What is the capital of France?” will be encoded as “query: What is the capital of France?” because the prompt text will be prepended before any text to encode.
  • truncate (bool, 可选) — 是否截断嵌入。 仅在由 Text-Embedding-Inference 提供支持的服务端上可用。
  • truncation_direction (Literal[“left”, “right”], optional) — 当传入 truncate=True 时,应对输入的哪一侧进行截断。
  • dimensions (int, 可选) — 输出嵌入应具有的维度数。 仅在 OpenAI 兼容的嵌入端点上可用。
  • encoding_format (Literal[“float”, “base64”], 可选) — 输出嵌入的格式。可以是 “float” 或 “base64”。 仅在 OpenAI 兼容的嵌入端点上可用。

返回值

np.ndarray

表示输入文本的 float32 numpy 数组形式的嵌入。

引发

[InferenceTimeoutError] 或 [HfHubHTTPError]

  • [InferenceTimeoutError] — 如果模型不可用或请求超时。
  • [HfHubHTTPError] — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

为给定的文本或文本批次生成嵌入。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.feature_extraction("Hi, who are you?")
array([[ 2.424802  ,  2.93384   ,  1.1750331 , ...,  1.240499, -0.13776633, -0.7889173 ],
[-0.42943227, -0.6364878 , -1.693462  , ...,  0.41978157, -2.4336355 ,  0.6162071 ],
...,
[ 0.28552425, -0.928395  , -1.2077185 , ...,  0.76810825, -2.1069427 ,  0.6236161 ]], dtype=float32)

fill_mask

< >

( text: strmodel: str | None = Nonetargets: list[str] | None = Nonetop_k: int | None = None ) → list[FillMaskOutputElement]

参数

  • text (str) — 用于填充的字符串,必须包含 [MASK] 标记(请查看模型卡片以获取掩码的确切名称)。
  • model (str, 可选) — 用于填充掩码任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的填充掩码模型。
  • targets (list[str, 可选) — 如果传入此参数,模型将把分数限制在传入的目标范围内,而不是在整个词汇表中查找。如果提供的目标不在模型词汇表中,它们将被分词,并使用第一个生成的 token(会发出警告,且速度可能更慢)。
  • top_k (int,可选) — 如果传入,将覆盖要返回的预测数量。

返回值

list[FillMaskOutputElement]

一个包含 FillMaskOutputElement 项的列表,其中包含预测标签、相关概率、token 引用以及补全后的文本。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

用缺失的单词(更准确地说,是 token)来填补空缺。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.fill_mask("The goal of life is <mask>.")
[
    FillMaskOutputElement(score=0.06897063553333282, token=11098, token_str=' happiness', sequence='The goal of life is happiness.'),
    FillMaskOutputElement(score=0.06554922461509705, token=45075, token_str=' immortality', sequence='The goal of life is immortality.')
]

get_endpoint_info

< >

( model: str | None = None ) → dict[str, Any]

参数

  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 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'
}

健康检查

< >

( model: str | None = None ) → bool

参数

  • model (str, 可选) — Inference Endpoint 的 URL。此参数会覆盖实例级别定义的 model。默认值为 None。

返回值

bool

如果一切正常,则为 True。

检查已部署端点的健康状况。

健康检查功能仅适用于由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 驱动的 Inference Endpoints。

示例:

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

图像分类

< >

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

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分类的图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于图像分类的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用图像分类的默认推荐模型。
  • function_to_apply ("ImageClassificationOutputTransform", 可选) — 应用于模型输出以获取分数的函数。
  • top_k (int, 可选) — 指定时,将输出限制为概率最高的前 K 个类别。

返回值

list[ImageClassificationOutputElement]

一个包含 ImageClassificationOutputElement 项的列表,其中包含预测标签及其对应的概率。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定的模型对给定图像执行图像分类。

示例:

>>> 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: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonemask_threshold: float | None = Noneoverlap_mask_area_threshold: float | None = Nonesubtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = Nonethreshold: float | None = None ) → list[ImageSegmentationOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分割的图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于图像分割的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用图像分割的默认推荐模型。
  • mask_threshold (float, 可选) — 将预测掩码转换为二值时使用的阈值。
  • overlap_mask_area_threshold (float, 可选) — 用于消除小型、不连续区域的掩码重叠阈值。
  • subtask ("ImageSegmentationSubtask", 可选) — 根据模型能力,要执行的分割任务。
  • threshold (float, 可选) — 用于过滤预测掩码的概率阈值。

返回值

list[ImageSegmentationOutputElement]

一个包含分割掩码及其相关属性的 ImageSegmentationOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定的模型对给定图像执行图像分割。

如果要处理图像,必须安装 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: str | None = Nonenegative_prompt: str | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Nonemodel: str | None = Nonetarget_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None**kwargs ) → Image

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用于翻译的输入图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • prompt (str, 可选) — 用于引导图像生成的文本提示。
  • negative_prompt (str, 可选) — 用于指导图像生成中不应包含内容的提示。
  • num_inference_steps (int, 可选) — 适用于扩散模型。去噪步数。更多的去噪步数通常能生成更高质量的图像,但会牺牲推理速度。
  • guidance_scale (float, 可选) — 适用于扩散模型。较高的 guidance scale 值会促使模型生成与文本提示紧密相关的图像,但代价是图像质量降低。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。默认为 None。
  • target_size (ImageToImageTargetSize,可选) — 输出图像的像素尺寸。此参数仅受部分提供商和特定模型支持。在不支持的情况下将被忽略。

返回值

Image

翻译后的图像。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定模型执行图像到图像的转换。

如果要处理图像,必须安装 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: str | None = None ) → ImageToTextOutput

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用于生成说明的输入图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。默认为 None。

生成的文本。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

接收输入图像并返回文本。

模型根据具体用例(如图像描述、光学字符识别(OCR)、Pix2Struct 等)可能产生截然不同的输出。请查阅模型卡片以了解该模型的具体特性。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.image_to_text("cat.jpg")
'a cat standing in a grassy field '
>>> client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
'a dog laying on the grass next to a flower pot '

image_to_video

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Noneprompt: str | None = Nonenegative_prompt: str | None = Nonenum_frames: float | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Noneseed: int | None = Nonetarget_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None**kwargs ) → bytes

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用于生成视频的输入图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。默认为 None。
  • prompt (str, 可选) — 用于引导视频生成的文本提示。
  • negative_prompt (str, 可选) — 用于指导视频生成中不应包含内容的提示。
  • num_frames (float, 可选) — num_frames 参数决定生成多少视频帧。
  • num_inference_steps (int, 可选) — 适用于扩散模型。去噪步数。更多的去噪步数通常能生成更高质量的图像,但会牺牲推理速度。
  • guidance_scale (float, 可选) — 适用于扩散模型。较高的 guidance scale 值会促使模型生成与文本提示紧密相关的视频,但代价是图像质量降低。
  • seed (int, 可选) — 用于视频生成的随机种子。
  • target_size (ImageToVideoTargetSize,可选) — 输出视频帧的像素尺寸。
  • num_inference_steps (int, 可选) — 去噪步数。更多的去噪步数通常能带来更高质量的视频,但代价是推理速度变慢。
  • seed (int, 可选) — 随机数生成器的种子。

返回值

bytes

生成的视频。

根据输入图像生成视频。

示例:

>>> 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: str | None = Nonethreshold: float | None = None ) → list[ObjectDetectionOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要检测对象的图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于目标检测的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用目标检测的默认推荐模型(DETR)。
  • threshold (float, 可选) — 做出预测所需的概率。

返回值

list[ObjectDetectionOutputElement]

一个包含边界框及其相关属性的 ObjectDetectionOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError 或 ValueError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。
  • 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: strcontext: strmodel: str | None = Nonealign_to_words: bool | None = Nonedoc_stride: int | None = Nonehandle_impossible_answer: bool | None = Nonemax_answer_len: int | None = Nonemax_question_len: int | None = Nonemax_seq_len: int | None = Nonetop_k: int | None = None ) → Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]

参数

  • question (str) — 要回答的问题。
  • context (str) — 问题的上下文。
  • model (str) — 用于问答任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。
  • align_to_words (bool, 可选) — 尝试将答案对齐到实际的单词。可提高空格分隔语言的质量。可能会损害非空格分隔语言(如日语或中文)的质量
  • 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 列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

从给定文本中检索问题的答案。

示例:

>>> 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: strother_sentences: listmodel: str | None = None ) → list[float]

参数

  • sentence (str) — 用于与其他句子进行比较的主要句子。
  • other_sentences (list[str]) — 要与之比较的句子列表。
  • model (str, 可选) — 用于句子相似度任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的句子相似度模型。默认为 None。

返回值

list[float]

表示输入文本的嵌入。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

通过比较它们的嵌入来计算一个句子与其他句子列表之间的语义相似度。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.sentence_similarity(
...     "Machine learning is so easy.",
...     other_sentences=[
...         "Deep learning is so straightforward.",
...         "This is so difficult, like rocket science.",
...         "I can't believe how much I struggled with this.",
...     ],
... )
[0.7785726189613342, 0.45876261591911316, 0.2906220555305481]

摘要

< >

( text: strmodel: str | None = Noneclean_up_tokenization_spaces: bool | None = Nonegenerate_parameters: dict[str, typing.Any] | None = Nonetruncation: 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",可选) — 要使用的截断策略。

生成的摘要文本。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定模型生成给定文本的摘要。

示例:

>>> 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: dictquery: strmodel: str | None = Nonepadding: typing.Optional[ForwardRef('Padding')] = Nonesequential: bool | None = Nonetruncation: bool | None = None ) → TableQuestionAnsweringOutputElement

参数

  • table (str) — 以列表字典形式表示的数据表,其中键为表头,值为所有数据项,所有列表的长度必须相同。
  • query (str) — 您想要向表格查询的纯文本查询。
  • model (str) — 用于表格问答任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。
  • padding ("Padding",可选) — 启用并控制填充。
  • sequential (bool, 可选) — 是否按顺序执行推理,还是作为批次执行。批次推理速度更快,但像 SQA 这样的模型需要按顺序执行推理,才能从序列中提取关系,因为它们具有对话性质。
  • truncation (bool,可选) — 启用并控制截断。

一个表格问答输出,包含答案、坐标、单元格以及所使用的聚合器。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

从表格中提供的信息中检索问题的答案。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> query = "How many stars does the transformers repository have?"
>>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]}
>>> client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq")
TableQuestionAnsweringOutputElement(answer='36542', coordinates=[[0, 1]], cells=['36542'], aggregator='AVERAGE')

表格分类

< >

( table: dictmodel: str | None = None ) → List

参数

  • table (dict[str, Any]) — 要分类的属性集合。
  • model (str, 可选) — 用于表格分类任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的表格分类模型。默认为 None。

返回值

List

标签列表,初始表格中的每一行对应一个标签。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

根据一组属性对目标类别(组)进行分类。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> table = {
...     "fixed_acidity": ["7.4", "7.8", "10.3"],
...     "volatile_acidity": ["0.7", "0.88", "0.32"],
...     "citric_acid": ["0", "0", "0.45"],
...     "residual_sugar": ["1.9", "2.6", "6.4"],
...     "chlorides": ["0.076", "0.098", "0.073"],
...     "free_sulfur_dioxide": ["11", "25", "5"],
...     "total_sulfur_dioxide": ["34", "67", "13"],
...     "density": ["0.9978", "0.9968", "0.9976"],
...     "pH": ["3.51", "3.2", "3.23"],
...     "sulphates": ["0.56", "0.68", "0.82"],
...     "alcohol": ["9.4", "9.8", "12.6"],
... }
>>> client.tabular_classification(table=table, model="julien-c/wine-quality")
["5", "5", "5"]

表格回归

< >

( table: dictmodel: str | None = None ) → List

参数

  • table (dict[str, Any]) — 存储在表中的一组属性。用于预测目标的属性可以是数值型,也可以是类别型。
  • model (str, 可选) — 用于表格回归任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的表格回归模型。默认为 None。

返回值

List

预测数值目标值的列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

给定表格中的一组属性/特征,预测一个数值目标值。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> table = {
...     "Height": ["11.52", "12.48", "12.3778"],
...     "Length1": ["23.2", "24", "23.9"],
...     "Length2": ["25.4", "26.3", "26.5"],
...     "Length3": ["30", "31.2", "31.1"],
...     "Species": ["Bream", "Bream", "Bream"],
...     "Width": ["4.02", "4.3056", "4.6961"],
... }
>>> client.tabular_regression(table, model="scikit-learn/Fish-Weight")
[110, 120, 130]

文本分类

< >

( text: strmodel: str | None = Nonetop_k: int | None = Nonefunction_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None ) → list[TextClassificationOutputElement]

参数

  • text (str) — 要分类的字符串。
  • model (str, 可选) — 用于文本分类任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文本分类模型。默认为 None。
  • top_k (int, 可选) — 指定时,将输出限制为概率最高的前 K 个类别。
  • function_to_apply ("TextClassificationOutputTransform", 可选) — 应用于模型输出以获取分数的函数。

返回值

list[TextClassificationOutputElement]

一个包含 TextClassificationOutputElement 项的列表,其中包含预测标签及其对应的概率。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

对给定文本执行文本分类(例如情感分析)。

示例:

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

文本生成

< >

( prompt: strdetails: bool | None = Nonestream: bool | None = Nonemodel: str | None = Noneadapter_id: str | None = Nonebest_of: int | None = Nonedecoder_input_details: bool | None = Nonedo_sample: bool | None = Nonefrequency_penalty: float | None = Nonegrammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = Nonemax_new_tokens: int | None = Nonerepetition_penalty: float | None = Nonereturn_full_text: bool | None = Noneseed: int | None = Nonestop: list[str] | None = Nonetemperature: float | None = Nonetop_k: int | None = Nonetop_n_tokens: int | None = Nonetop_p: float | None = Nonetruncate: int | None = Nonetypical_p: float | None = Nonewatermark: bool | None = None ) → Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]

参数

  • prompt (str) — 输入文本。
  • details (bool, 可选) — 默认情况下,text_generation 返回一个字符串。如果您需要详细的输出(tokens、概率、seed、finish reason 等),请传入 details=True。仅适用于使用 text-generation-inference 后端运行的模型。
  • stream (bool,可选) — 默认情况下,text_generation 会返回完整的生成文本。如果您希望以流的形式返回 token,请传入 stream=True。此功能仅适用于使用 text-generation-inference 后端运行的模型。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。默认为 None。
  • adapter_id (str, 可选) — Lora 适配器 ID。
  • best_of (int,可选) — 生成 best_of 个序列,并返回其中 token 对数概率最高的一个。
  • decoder_input_details (bool,可选) — 返回解码器输入 token 的 logprobs 和 ids。必须同时设置 details=True 才会生效。默认为 False。
  • do_sample (bool,可选) — 启用 logits 采样
  • frequency_penalty (float, 可选) — 介于 -2.0 和 2.0 之间的数值。正值会根据新标记在现有文本中出现的频率对其进行惩罚,从而降低模型逐字重复相同内容的概率。
  • 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。
  • temperature (float,可选) — 用于调节 logits 分布的值。
  • top_n_tokens (int, 可选) — 返回每个生成步骤中 top_n_tokens 个最可能 token 的信息,而不仅仅是采样到的 token。
  • top_k (int, *可选`) — 用于 top-k 过滤时保留的最高概率词汇标记的数量。
  • top_p (float, *optional) -- If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p` or higher are kept for generation.
  • truncate (int, *可选`) — 将输入标记截断为指定大小。
  • typical_p (float, *可选`) — 典型解码质量 有关更多信息,请参阅 用于自然语言生成的典型解码
  • watermark (bool, 可选) — 使用 大型语言模型的水印 进行水印处理

返回值

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

从服务器返回的生成文本:

  • 如果 stream=False 且 details=False,则生成的文本将以 str 形式返回(默认值)
  • 如果 stream=True 且 details=False,生成的文本将以 Iterable[str] 的形式逐 token 返回。
  • 如果 stream=False 且 details=True,生成的文本将作为 TextGenerationOutput 返回,并包含更多详细信息
  • 如果 details=True 且 stream=True,生成的文本将以 TextGenerationStreamOutput 的可迭代对象形式逐 token 返回。

引发

ValidationError 或 InferenceTimeoutError 或 HfHubHTTPError

  • ValidationError — 如果输入值无效。不会向服务器发起 HTTP 调用。
  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

给定一个提示,生成以下文本。

如果您想根据聊天消息生成回复,应使用 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: strnegative_prompt: str | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Nonemodel: str | None = Nonescheduler: str | None = Noneseed: int | None = Noneextra_body: dict[str, typing.Any] | None = None ) → Image

参数

  • prompt (str) — 用于生成图像的提示词。
  • negative_prompt (str, 可选) — 用于指导图像生成中不应包含内容的提示。
  • height (int, 可选) — 输出图像的高度(以像素为单位)
  • width (int, 可选) — 输出图像的宽度(以像素为单位)
  • num_inference_steps (int, 可选) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但会牺牲推理速度。
  • guidance_scale (float, 可选) — 较高的 guidance scale 值会促使模型生成与文本提示紧密相关的图像,但数值过高可能导致饱和及其他伪影。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文本生成图像模型。默认为 None。
  • scheduler (str, 可选) — 使用兼容的调度器覆盖默认的调度器。
  • seed (int, 可选) — 随机数生成器的种子。
  • extra_body (dict[str, Any],可选) — 传递给模型的额外提供商特定参数。有关支持的参数,请参阅提供商的文档。

返回值

Image

生成的图像。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定模型根据给定文本生成图像。

如果要处理图像,必须安装 PIL(pip install Pillow)。

您可以通过使用 extra_body 参数向模型传递特定于提供商的参数。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()

>>> image = client.text_to_image("An astronaut riding a horse on the moon.")
>>> image.save("astronaut.png")

>>> image = client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     negative_prompt="low resolution, blurry",
...     model="stabilityai/stable-diffusion-2-1",
... )
>>> image.save("better_astronaut.png")
Example using a third-party provider directly. Usage will be billed on your fal.ai account.
>>> 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 Routing 使用第三方提供商的示例。相关用量将从您的 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: strmodel: str | None = Nonedo_sample: bool | None = Noneearly_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = Noneepsilon_cutoff: float | None = Noneeta_cutoff: float | None = Nonemax_length: int | None = Nonemax_new_tokens: int | None = Nonemin_length: int | None = Nonemin_new_tokens: int | None = Nonenum_beam_groups: int | None = Nonenum_beams: int | None = Nonepenalty_alpha: float | None = Nonetemperature: float | None = Nonetop_k: int | None = Nonetop_p: float | None = Nonetypical_p: float | None = Noneuse_cache: bool | None = Noneextra_body: dict[str, typing.Any] | None = None ) → bytes

参数

  • text (str) — 要合成的文本。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文本转语音模型。默认为 None。
  • do_sample (bool, 可选) — 在生成新 token 时,是否使用采样而非贪心解码。
  • early_stopping (Union[bool, "TextToSpeechEarlyStoppingEnum"],可选) — 控制基于束搜索方法的停止条件。
  • epsilon_cutoff (float, 可选) — 如果设置为严格介于 0 和 1 之间的浮点数,则仅会采样条件概率大于 epsilon_cutoff 的 token。在论文中,建议值根据模型大小在 3e-4 到 9e-4 之间。有关更多详细信息,请参阅 Truncation Sampling as Language Model Desmoothing。
  • eta_cutoff (float, 可选) — Eta 采样是局部典型采样和 epsilon 采样的混合。如果设置为严格介于 0 和 1 之间的 float,则仅当 token 大于 eta_cutoff 或 sqrt(eta_cutoff)
    • exp(-entropy(softmax(next_token_logits)))。后一项直观上是期望的下一个 token 概率,并按 sqrt(eta_cutoff) 进行缩放。在论文中,建议的取值范围从 3e-4 到 2e-3,具体取决于模型的大小。有关更多详细信息,请参阅 Truncation Sampling as Language Model Desmoothing。
  • max_length (int, 可选) — 生成文本的最大长度(以 token 计),包括输入部分。
  • max_new_tokens (int, 可选) — 要生成的最大 token 数量。优先于 max_length。
  • min_length (int,可选) — 生成文本的最小长度(以 token 计),包括输入。
  • min_new_tokens (int, 可选) — 要生成的最小 token 数量。优先于 min_length。
  • num_beam_groups (int, 可选) — 将 num_beams 划分为若干组,以确保不同 beam 组之间的多样性。 有关更多详细信息,请参阅 这篇论文。
  • num_beams (int, 可选) — 用于束搜索的束数量。
  • penalty_alpha (float, 可选) — 该值用于在对比搜索解码中平衡模型置信度与退化惩罚。
  • temperature (float, 可选) — 用于调节下一个 token 概率的值。
  • top_k (int, 可选) — 用于 top-k 过滤时保留的最高概率词汇表 token 数量。
  • top_p (float, 可选) — 如果设置为小于 1 的浮点数,则仅保留概率之和达到或超过 top_p 的最小最可能 token 集合用于生成。
  • typical_p (float, 可选) — 局部典型性衡量了在已生成部分文本的条件下,预测下一个目标 token 的条件概率与预测下一个随机 token 的期望条件概率之间的相似程度。如果设置为小于 1 的 float 值,则仅保留概率之和达到 typical_p 或更高的、局部典型性最高的最小 token 集合用于生成。有关更多详细信息,请参阅这篇论文。
  • use_cache (bool, 可选) — 模型是否应使用过去最后的关键值注意力来加速解码
  • extra_body (dict[str, Any],可选) — 传递给模型的额外提供商特定参数。有关支持的参数,请参阅提供商的文档。

返回值

bytes

生成的音频。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

合成一段语音,用于朗读给定的文本。

您可以通过使用 extra_body 参数向模型传递特定于提供商的参数。

示例:

>>> from pathlib import Path
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()

>>> audio = client.text_to_speech("Hello world")
>>> Path("hello_world.flac").write_bytes(audio)

直接使用第三方提供商的示例。使用量将从您的 Replicate 账户中扣除。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",
...     api_key="your-replicate-api-key",  # Pass your Replicate API key directly
... )
>>> audio = client.text_to_speech(
...     text="Hello world",
...     model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)

通过 Hugging Face Routing 使用第三方提供商的示例。相关用量将从您的 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)
Example using Replicate provider with extra parameters
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Use replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> audio = client.text_to_speech(
...     "Hello, my name is Kororo, an awesome text-to-speech model.",
...     model="hexgrad/Kokoro-82M",
...     extra_body={"voice": "af_nicole"},
... )
>>> Path("hello.flac").write_bytes(audio)

在 fal.ai 上使用“YuE-s1-7B-anneal-en-cot”的音乐生成示例

>>> 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: strmodel: str | None = Noneguidance_scale: float | None = Nonenegative_prompt: list[str] | None = Nonenum_frames: float | None = Nonenum_inference_steps: int | None = Noneseed: int | None = Noneextra_body: dict[str, typing.Any] | None = None ) → bytes

参数

  • prompt (str) — 用于生成视频的提示词。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文本生成视频模型。默认为 None。
  • guidance_scale (float, 可选) — 较高的 guidance scale 值会促使模型生成与文本提示紧密相关的视频,但数值过高可能导致饱和及其他伪影。
  • negative_prompt (list[str],可选) — 一个或多个提示词,用于指导视频生成中不应包含的内容。
  • num_frames (float, 可选) — num_frames 参数决定生成多少视频帧。
  • num_inference_steps (int, 可选) — 去噪步数。更多的去噪步数通常能带来更高质量的视频,但代价是推理速度变慢。
  • seed (int, 可选) — 随机数生成器的种子。
  • extra_body (dict[str, Any],可选) — 传递给模型的额外提供商特定参数。有关支持的参数,请参阅提供商的文档。

返回值

bytes

生成的视频。

根据给定的文本生成视频。

您可以通过使用 extra_body 参数向模型传递特定于提供商的参数。

示例:

直接使用第三方提供商的示例。使用费用将从您的 fal.ai 账户中扣除。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="fal-ai",  # Using fal.ai provider
...     api_key="fal-ai-api-key",  # Pass your fal.ai API key
... )
>>> video = client.text_to_video(
...     "A majestic lion running in a fantasy forest",
...     model="tencent/HunyuanVideo",
... )
>>> with open("lion.mp4", "wb") as file:
...     file.write(video)

通过 Hugging Face Routing 使用第三方提供商的示例。相关用量将从您的 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: strmodel: str | None = Noneaggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = Noneignore_labels: list[str] | None = Nonestride: int | None = None ) → list[TokenClassificationOutputElement]

参数

  • text (str) — 要分类的字符串。
  • model (str, 可选) — 用于 token classification 任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的 token classification 模型。默认为 None。
  • aggregation_strategy ("TokenClassificationAggregationStrategy",可选) — 用于根据模型预测结果融合 token 的策略
  • ignore_labels (list[str, 可选) — 要忽略的标签列表
  • stride (int, 可选) — 在拆分输入文本时,相邻块之间重叠的 token 数量。

返回值

list[TokenClassificationOutputElement]

包含实体组、置信度分数、单词、起始和结束索引的 TokenClassificationOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

对给定文本执行 token 分类。 通常用于句子解析,包括语法分析或命名实体识别(NER),以理解文本中包含的关键词。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica")
[
    TokenClassificationOutputElement(
        entity_group='PER',
        score=0.9971321225166321,
        word='Sarah Jessica Parker',
        start=11,
        end=31,
    ),
    TokenClassificationOutputElement(
        entity_group='PER',
        score=0.9773476123809814,
        word='Jessica',
        start=52,
        end=59,
    )
]

翻译

< >

( text: strmodel: str | None = Nonesrc_lang: str | None = Nonetgt_lang: str | None = Noneclean_up_tokenization_spaces: bool | None = Nonetruncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = Nonegenerate_parameters: dict[str, typing.Any] | None = None ) → TranslationOutput

参数

  • text (str) — 要翻译的字符串。
  • model (str, 可选) — 用于翻译任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的翻译模型。默认为 None。
  • src_lang (str, 可选) — 文本的源语言。对于支持从多种语言进行翻译的模型,此参数为必填项。
  • tgt_lang (str, 可选) — 要翻译到的目标语言。对于可以翻译到多种语言的模型,此参数为必填项。
  • clean_up_tokenization_spaces (bool, 可选) — 是否清理文本输出中可能存在的多余空格。
  • truncation("TranslationTruncationStrategy",可选)— 要使用的截断策略。
  • generate_parameters (dict[str, Any],可选) — 文本生成算法的额外参数配置。

生成的翻译文本。

引发

InferenceTimeoutError 或 HfHubHTTPError 或 ValueError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。
  • ValueError — 如果只提供了 src_lang 和 tgt_lang 参数中的一个。

将文本从一种语言转换为另一种语言。

请访问 https://huggingface.co/tasks/translation 了解如何为特定用例选择最佳模型的更多信息。源语言和目标语言通常取决于模型。 不过,对于某些模型,可以指定源语言和目标语言。如果你正在使用这些模型之一, 可以使用 src_lang 和 tgt_lang 参数来传递相关信息。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.translation("My name is Wolfgang and I live in Berlin")
'Mein Name ist Wolfgang und ich lebe in Berlin.'
>>> client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr")
TranslationOutput(translation_text='Je m'appelle Wolfgang et je vis à Berlin.')

指定语言:

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

视觉问答

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]question: strmodel: str | None = Nonetop_k: int | None = None ) → list[VisualQuestionAnsweringOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 上下文的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • question (str) — 要回答的问题。
  • model (str, 可选) — 用于视觉问答任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认的推荐视觉问答模型。默认为 None。
  • top_k (int, 可选) — 要返回的答案数量(按可能性顺序选择)。请注意,如果上下文中可用的选项不足,我们将返回少于 topk 个答案。

返回值

list[VisualQuestionAnsweringOutputElement]

一个包含 VisualQuestionAnsweringOutputElement 项的列表,其中包含预测标签及其对应的概率。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

基于图像回答开放式问题。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.visual_question_answering(
...     image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg",
...     question="What is the animal doing?"
... )
[
    VisualQuestionAnsweringOutputElement(score=0.778609573841095, answer='laying down'),
    VisualQuestionAnsweringOutputElement(score=0.6957435607910156, answer='sitting'),
]

zero_shot_classification

< >

( text: strcandidate_labels: listmulti_label: bool | None = Falsehypothesis_template: str | None = Nonemodel: str | None = None ) → list[ZeroShotClassificationOutputElement]

参数

  • text (str) — 要分类的输入文本。
  • candidate_labels (list[str]) — 用于对文本进行分类的可能类别标签集合。
  • multi_label (bool, 可选) — 是否允许多个候选标签同时为真。如果为 false,则对分数进行归一化,使得每个序列的标签似然之和为 1。如果为 true,则标签被视为相互独立,并对每个候选标签的概率进行归一化。
  • hypothesis_template (str, 可选) — 与 candidate_labels 配合使用的句子,通过将占位符替换为候选标签来尝试进行文本分类。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。如果未提供,将使用默认推荐的零样本分类模型。

返回值

list[ZeroShotClassificationOutputElement]

包含预测标签及其置信度的 ZeroShotClassificationOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

提供一段文本和一组候选标签作为输入,用于对输入文本进行分类。

multi_label=False 的示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> text = (
...     "A new model offers an explanation for how the Galilean satellites formed around the solar system's"
...     "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling"
...     " mysteries when he went for a run up a hill in Nice, France."
... )
>>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"]
>>> client.zero_shot_classification(text, labels)
[
    ZeroShotClassificationOutputElement(label='scientific discovery', score=0.7961668968200684),
    ZeroShotClassificationOutputElement(label='space & cosmos', score=0.18570658564567566),
    ZeroShotClassificationOutputElement(label='microbiology', score=0.00730885099619627),
    ZeroShotClassificationOutputElement(label='archeology', score=0.006258360575884581),
    ZeroShotClassificationOutputElement(label='robots', score=0.004559356719255447),
]
>>> client.zero_shot_classification(text, labels, multi_label=True)
[
    ZeroShotClassificationOutputElement(label='scientific discovery', score=0.9829297661781311),
    ZeroShotClassificationOutputElement(label='space & cosmos', score=0.755190908908844),
    ZeroShotClassificationOutputElement(label='microbiology', score=0.0005462635890580714),
    ZeroShotClassificationOutputElement(label='archeology', score=0.00047131875180639327),
    ZeroShotClassificationOutputElement(label='robots', score=0.00030448526376858354),
]

使用 multi_label=True 和自定义 hypothesis_template 的示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.zero_shot_classification(
...    text="I really like our dinner and I'm very happy. I don't like the weather though.",
...    candidate_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: listmodel: str | None = Nonehypothesis_template: str | None = None ) → list[ZeroShotImageClassificationOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用于生成说明的输入图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • candidate_labels (list[str]) — 此图像的候选标签
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。如果未提供,将使用默认推荐的零样本图像分类模型。
  • hypothesis_template (str, 可选) — 与 candidate_labels 配合使用的句子,通过将占位符替换为候选标签来尝试进行图像分类。

返回值

list[ZeroShotImageClassificationOutputElement]

包含预测标签及其置信度的 ZeroShotImageClassificationOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

提供输入图像和文本标签,以预测该图像的文本标签。

示例:

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()

>>> client.zero_shot_image_classification(
...     "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg",
...     candidate_labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]

异步推理客户端

还提供了基于 asyncio 和 httpx2 的客户端异步版本。

类 huggingface_hub.AsyncInferenceClient

< >

( model: str | None = Noneprovider: typing.Union[typing.Literal['baseten', 'cerebras', 'cohere', 'deepinfra', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'novita', 'nscale', 'openai', 'ovhcloud', 'publicai', 'replicate', 'scaleway', 'together', 'wavespeed', 'zai-org'], typing.Literal['auto'], NoneType] = Nonetoken: str | None = Nonetimeout: float | None = Noneheaders: dict[str, str] | None = Nonecookies: dict[str, str] | None = Nonebill_to: str | None = Nonebase_url: str | None = Noneapi_key: str | None = None )

参数

  • model (str, optional) — 用于运行推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,例如 meta-llama/Meta-Llama-3-8B-Instruct, 也可以是已部署的 Inference Endpoint 的 URL。默认为 None,此时会自动为任务选择一个推荐的模型。 注意:为了与 OpenAI 的客户端更好地兼容,model 已被别名为 base_url。这两个参数互斥。如果将 URL 作为 model 或 base_url 传入以进行聊天补全,则会在该 URL 后追加 (/v1)/chat/completions 后缀路径。
  • provider (str, 可选) — 用于推理的提供商名称。可以是 "baseten"、"cerebras"、"cohere"、"deepinfra"、"fal-ai"、"featherless-ai"、"fireworks-ai"、"groq"、"hf-inference"、"novita"、"nscale"、"openai"、"ovhcloud"、"publicai"、"replicate"、"scaleway"、"together"、"wavespeed" 或 "zai-org"。 默认为 “auto”:自动路由,默认选择 “fastest” 提供商;您可以在 https://hf.co/settings/inference-providers 切换为 “cheapest” 或 “preferred” 提供商顺序。 如果 model 是 URL 或传入了 base_url,则不会使用 provider。
  • token (str, 可选) — 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) — 要发送到服务器的附加 cookies。
  • base_url (str, optional) — 用于运行推理的基础 URL。这是从 model 复制过来的参数,以便 InferenceClient 遵循与 openai.OpenAI 客户端相同的模式。如果设置了 model,则不能使用此参数。默认为 None。
  • api_key (str, optional) — 用于身份验证的 Token。这是从 token 复制而来的参数,旨在让 InferenceClient 遵循与 openai.OpenAI 客户端相同的模式。如果已设置 token,则不能使用此参数。默认值为 None。

初始化一个新的 Inference Client。

InferenceClient 旨在提供统一的推理体验。该客户端可与(免费的)Inference API、自托管的 Inference Endpoints 或第三方 Inference Providers 无缝配合使用。

音频分类

< >

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

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

对提供的音频内容执行音频分类。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.audio_classification("audio.flac")
[
    AudioClassificationOutputElement(score=0.4976358711719513, label='hap'),
    AudioClassificationOutputElement(score=0.3677836060523987, label='neu'),
    ...
]

音频到音频

< >

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

参数

  • audio (Union[str, Path, bytes, BinaryIO]) — 模型的音频内容。可以是原始音频字节、本地音频文件,或指向音频文件的 URL。
  • model (str, 可选) — 该模型可以是任何接收音频文件并返回另一个音频文件的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用 audio_to_audio 的默认推荐模型。

返回值

list[AudioToAudioOutputElement]

一个包含 AudioToAudioOutputElement 项的列表,其中包含音频标签、内容类型以及以 blob 形式存储的音频内容。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

根据模型的不同,执行与音频到音频相关的多项任务(例如:语音增强、声源分离)。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> audio_output = await client.audio_to_audio("audio.flac")
>>> async for i, item in enumerate(audio_output):
>>>     with open(f"output_{i}.flac", "wb") as f:
            f.write(item.blob)

automatic_speech_recognition

< >

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

参数

  • audio (Union[str, Path, bytes, BinaryIO]) — 要转录的内容。可以是原始音频字节、本地音频文件或指向音频文件的 URL。
  • model (str, 可选) — 用于 ASR 的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用 ASR 的默认推荐模型。
  • extra_body (dict, 可选) — 传递给模型的额外提供商特定参数。请参阅提供商文档以了解支持的参数。

包含转录文本以及可选的时间戳分块的项。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

对给定的音频内容执行自动语音识别(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: listmodel: str | None = Nonestream: bool = Falsefrequency_penalty: float | None = Nonelogit_bias: list[float] | None = Nonelogprobs: bool | None = Nonemax_tokens: int | None = Nonen: int | None = Nonepresence_penalty: float | None = Noneresponse_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] = Noneseed: int | None = Nonestop: list[str] | None = Nonestream_options: huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions | None = Nonetemperature: float | None = Nonetool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = Nonetool_prompt: str | None = Nonetools: list[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool] | None = Nonetop_logprobs: int | None = Nonetop_p: float | None = Noneextra_body: dict | None = None ) → ChatCompletionOutput or Iterable of ChatCompletionStreamOutput

参数

  • messages(ChatCompletionInputMessage 列表)— 由角色和内容对组成的对话历史记录。
  • model (str, 可选) — 用于聊天补全的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认的推荐聊天文本生成模型。 有关更多详细信息,请参阅 https://huggingface.co/tasks/text-generation。 如果 model 是模型 ID,它将作为 model 参数传递给服务器。如果要在请求负载中设置 model 的同时定义自定义 URL,则必须在初始化 InferenceClient 时设置 base_url。
  • frequency_penalty (float, 可选) — 根据新标记在现有文本中出现的频率对其进行惩罚。取值范围:[-2.0, 2.0]。默认值为 0.0。
  • logit_bias (list[float],可选) — 调整特定标记在生成输出中出现的概率。
  • logprobs (bool, 可选) — 是否返回输出 token 的对数概率。如果为 true,则返回消息内容中每个输出 token 的对数概率。
  • max_tokens (int, 可选) — 响应中允许的最大 token 数。默认值为 100。
  • n (int, 可选) — 为每个提示词生成的补全数量。
  • presence_penalty (float, 可选) — -2.0 到 2.0 之间的数值。正值会根据新 token 是否已出现在当前文本中对其进行惩罚,从而增加模型讨论新话题的可能性。
  • response_format (ChatCompletionInputGrammarType(),可选) — 语法约束。可以是 JSONSchema 或正则表达式。
  • seed(可选的int,optional)— 用于可复现控制流的随机种子。默认值为 None。
  • stop (list[str],可选) — 最多四个用于触发响应结束的字符串。 默认为 None。
  • stream (bool,可选) — 启用响应的实时流式传输。默认值为 False。
  • stream_options (ChatCompletionInputStreamOptions,可选) — 流式补全的选项。
  • temperature (float, 可选) — 控制生成的随机性。值越低,生成的补全越不随机。取值范围:[0, 2]。默认值为 1.0。
  • top_logprobs (int, 可选) — 一个介于 0 和 5 之间的整数,指定在每个 token 位置返回的最可能 token 的数量,每个 token 都附带一个相关的对数概率。如果使用此参数,则必须将 logprobs 设置为 true。
  • top_p (float, 可选) — 用于采样的最可能下一个词的比例。 必须在 0 和 1 之间。默认值为 1.0。
  • tool_choice(ChatCompletionInputToolChoiceClass 或 ChatCompletionInputToolChoiceEnum(),可选) — 用于补全的工具。默认值为 “auto”。
  • tool_prompt (str, 可选) — 在工具之前追加的提示词。
  • tools(ChatCompletionInputTool 列表,可选)— 模型可以调用的工具列表。目前,仅支持将函数作为工具。使用此参数提供模型可以生成 JSON 输入的函数列表。
  • extra_body (dict, 可选) — 传递给模型的额外提供商特定参数。请参阅提供商文档以了解支持的参数。

返回值

ChatCompletionOutput 或 ChatCompletionStreamOutput 的可迭代对象

从服务器返回的生成文本:

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

一种使用指定语言模型完成对话的方法。

client.chat_completion 方法被别名为 client.chat.completions.create,以兼容 OpenAI 的客户端。 输入和输出完全相同,使用任一语法都会得到相同的结果。 有关 OpenAI 兼容性的更多详细信息,请参阅 推理指南。

您可以通过使用 extra_body 参数向模型传递特定于提供商的参数。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> await client.chat_completion(messages, max_tokens=100)
ChatCompletionOutput(
    choices=[
        ChatCompletionOutputComplete(
            finish_reason='eos_token',
            index=0,
            message=ChatCompletionOutputMessage(
                role='assistant',
                content='The capital of France is Paris.',
                name=None,
                tool_calls=None
            ),
            logprobs=None
        )
    ],
    created=1719907176,
    id='',
    model='meta-llama/Meta-Llama-3-8B-Instruct',
    object='text_completion',
    system_fingerprint='2.0.4-sha-f426a33',
    usage=ChatCompletionOutputUsage(
        completion_tokens=8,
        prompt_tokens=17,
        total_tokens=25
    )
)

使用流式处理的示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> async for token in await client.chat_completion(messages, max_tokens=10, stream=True):
...     print(token)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content='The', role='assistant'), index=0, finish_reason=None)], created=1710498504)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' capital', role='assistant'), index=0, finish_reason=None)], created=1710498504)
(...)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' may', role='assistant'), index=0, finish_reason=None)], created=1710498504)

使用 OpenAI 语法的示例:

# Must be run in an async context
# instead of `from openai import OpenAI`
from huggingface_hub import AsyncInferenceClient

# instead of `client = OpenAI(...)`
client = AsyncInferenceClient(
    base_url=...,
    api_key=...,
)

output = await client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Count to 10"},
    ],
    stream=True,
    max_tokens=1024,
)

for chunk in output:
    print(chunk.choices[0].delta.content)

使用第三方提供商并直接传入额外(提供商特定)参数的示例。使用费用将从您的 Together AI 账户中扣除。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="together",  # Use Together AI provider
...     api_key="<together_api_key>",  # Pass your Together API key directly
... )
>>> client.chat_completion(
...     model="meta-llama/Meta-Llama-3-8B-Instruct",
...     messages=[{"role": "user", "content": "What is the capital of France?"}],
...     extra_body={"safety_model": "Meta-Llama/Llama-Guard-7b"},
... )

通过 Hugging Face Routing 使用第三方提供商的示例。相关用量将从您的 Hugging Face 账户中计费。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="novita",  # Use Novita provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> client.chat_completion(
...     model="meta-llama/Meta-Llama-3-8B-Instruct",
...     messages=[{"role": "user", "content": "What is the capital of France?"}],
... )

使用图像 + 文本作为输入的示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient

# provide a remote URL
>>> image_url ="https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
# or a base64-encoded image
>>> image_path = "/path/to/image.jpeg"
>>> with open(image_path, "rb") as f:
...     base64_image = base64.b64encode(f.read()).decode("utf-8")
>>> image_url = f"data:image/jpeg;base64,{base64_image}"

>>> client = AsyncInferenceClient("meta-llama/Llama-3.2-11B-Vision-Instruct")
>>> output = await client.chat.completions.create(
...     messages=[
...         {
...             "role": "user",
...             "content": [
...                 {
...                     "type": "image_url",
...                     "image_url": {"url": image_url},
...                 },
...                 {
...                     "type": "text",
...                     "text": "Describe this image in one sentence.",
...                 },
...             ],
...         },
...     ],
... )
>>> output
The image depicts the iconic Statue of Liberty situated in New York Harbor, New York, on a clear day.

使用工具的示例:

# Must be run in an async context
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
...     {
...         "role": "system",
...         "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
...     },
...     {
...         "role": "user",
...         "content": "What's the weather like the next 3 days in San Francisco, CA?",
...     },
... ]
>>> tools = [
...     {
...         "type": "function",
...         "function": {
...             "name": "get_current_weather",
...             "description": "Get the current weather",
...             "parameters": {
...                 "type": "object",
...                 "properties": {
...                     "location": {
...                         "type": "string",
...                         "description": "The city and state, e.g. San Francisco, CA",
...                     },
...                     "format": {
...                         "type": "string",
...                         "enum": ["celsius", "fahrenheit"],
...                         "description": "The temperature unit to use. Infer this from the users location.",
...                     },
...                 },
...                 "required": ["location", "format"],
...             },
...         },
...     },
...     {
...         "type": "function",
...         "function": {
...             "name": "get_n_day_weather_forecast",
...             "description": "Get an N-day weather forecast",
...             "parameters": {
...                 "type": "object",
...                 "properties": {
...                     "location": {
...                         "type": "string",
...                         "description": "The city and state, e.g. San Francisco, CA",
...                     },
...                     "format": {
...                         "type": "string",
...                         "enum": ["celsius", "fahrenheit"],
...                         "description": "The temperature unit to use. Infer this from the users location.",
...                     },
...                     "num_days": {
...                         "type": "integer",
...                         "description": "The number of days to forecast",
...                     },
...                 },
...                 "required": ["location", "format", "num_days"],
...             },
...         },
...     },
... ]

>>> response = await client.chat_completion(
...     model="meta-llama/Meta-Llama-3-70B-Instruct",
...     messages=messages,
...     tools=tools,
...     tool_choice="auto",
...     max_tokens=500,
... )
>>> response.choices[0].message.tool_calls[0].function
ChatCompletionOutputFunctionDefinition(
    arguments={
        'location': 'San Francisco, CA',
        'format': 'fahrenheit',
        'num_days': 3
    },
    name='get_n_day_weather_forecast',
    description=None
)

使用 response_format 的示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
...     {
...         "role": "user",
...         "content": "I saw a puppy a cat and a raccoon during my bike ride in the park. What did I see and when?",
...     },
... ]
>>> response_format = {
...     "type": "json",
...     "value": {
...         "properties": {
...             "location": {"type": "string"},
...             "activity": {"type": "string"},
...             "animals_seen": {"type": "integer", "minimum": 1, "maximum": 5},
...             "animals": {"type": "array", "items": {"type": "string"}},
...         },
...         "required": ["location", "activity", "animals_seen", "animals"],
...     },
... }
>>> response = await client.chat_completion(
...     messages=messages,
...     response_format=response_format,
...     max_tokens=500,
... )
>>> response.choices[0].message.content
'{

y": "bike ride",
": ["puppy", "cat", "raccoon"],
_seen": 3,
n": "park"}'

关闭

< >

( )

关闭客户端。

使用客户端作为上下文管理器时,会自动调用此方法。

document_question_answering

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]question: strmodel: str | None = Nonedoc_stride: int | None = Nonehandle_impossible_answer: bool | None = Nonelang: str | None = Nonemax_answer_len: int | None = Nonemax_question_len: int | None = Nonemax_seq_len: int | None = Nonetop_k: int | None = Noneword_boxes: list[list[float] | str] | None = None ) → list[DocumentQuestionAnsweringOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO]) — 上下文的输入图像。可以是原始字节、图像文件或指向在线图像的 URL。
  • question (str) — 要回答的问题。
  • model (str, 可选) — 用于文档问答任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文档问答模型。默认为 None。
  • doc_stride (int, 可选) — 如果文档中的单词过长,无法与问题一起放入模型,则会被拆分为多个带有一定重叠的块。此参数用于控制该重叠的大小。
  • handle_impossible_answer (bool, 可选) — 是否接受“不可能”作为答案
  • lang (str, 可选) — 运行 OCR 时使用的语言。默认为 english。
  • max_answer_len (int, 可选) — 预测答案的最大长度(例如,仅考虑长度较短的答案)。
  • max_question_len (int,可选) — 问题经过分词后的最大长度。如有必要,将被截断。
  • max_seq_len (int, 可选) — 传递给模型的每个块中,完整句子(上下文 + 问题)的最大 token 长度。如有需要,上下文将被拆分为多个块(使用 doc_stride 作为重叠部分)。
  • top_k (int, 可选) — 要返回的答案数量(按可能性顺序选择)。如果上下文中可用的选项不足,返回的答案数量可能少于 top_k。
  • word_boxes (list[Union[list[float], str, 可选) — 单词及其边界框(归一化 0->1000)的列表。如果提供,推理将跳过 OCR 步骤,并直接使用提供的边界框。

返回值

list[DocumentQuestionAnsweringOutputElement]

一个包含 DocumentQuestionAnsweringOutputElement 项的列表,其中包含预测标签、相关概率、词 id 和页码。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

回答有关文档图像的问题。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.document_question_answering(image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png", question="What is the invoice number?")
[DocumentQuestionAnsweringOutputElement(answer='us-001', end=16, score=0.9999666213989258, start=16)]

特征提取

< >

( text: str | list[str]normalize: bool | None = Noneprompt_name: str | None = Nonetruncate: bool | None = Nonetruncation_direction: typing.Optional[typing.Literal['left', 'right']] = Nonedimensions: int | None = Noneencoding_format: typing.Optional[typing.Literal['float', 'base64']] = Nonemodel: str | None = None ) → np.ndarray

参数

  • text (str 或 list[str]) — 要嵌入的文本或文本列表。
  • model (str, 可选) — 用于特征提取任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的特征提取模型。默认为 None。
  • normalize (bool, optional) — 是否对嵌入进行归一化。 仅在由 Text-Embedding-Inference 提供支持的服务端上可用。
  • prompt_name (str, optional) — The name of the prompt that should be used by for encoding. If not set, no prompt will be applied. Must be a key in the Sentence Transformers configuration prompts dictionary. For example if prompt_name is “query” and the prompts is {“query”: “query: ”,…}, then the sentence “What is the capital of France?” will be encoded as “query: What is the capital of France?” because the prompt text will be prepended before any text to encode.
  • truncate (bool, 可选) — 是否截断嵌入。 仅在由 Text-Embedding-Inference 提供支持的服务端上可用。
  • truncation_direction (Literal[“left”, “right”], optional) — 当传入 truncate=True 时,应对输入的哪一侧进行截断。
  • dimensions (int, 可选) — 输出嵌入应具有的维度数。 仅在 OpenAI 兼容的嵌入端点上可用。
  • encoding_format (Literal[“float”, “base64”], 可选) — 输出嵌入的格式。可以是 “float” 或 “base64”。 仅在 OpenAI 兼容的嵌入端点上可用。

返回值

np.ndarray

表示输入文本的 float32 numpy 数组形式的嵌入。

引发

[InferenceTimeoutError] 或 [HfHubHTTPError]

  • [InferenceTimeoutError] — 如果模型不可用或请求超时。
  • [HfHubHTTPError] — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

为给定的文本或文本批次生成嵌入。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.feature_extraction("Hi, who are you?")
array([[ 2.424802  ,  2.93384   ,  1.1750331 , ...,  1.240499, -0.13776633, -0.7889173 ],
[-0.42943227, -0.6364878 , -1.693462  , ...,  0.41978157, -2.4336355 ,  0.6162071 ],
...,
[ 0.28552425, -0.928395  , -1.2077185 , ...,  0.76810825, -2.1069427 ,  0.6236161 ]], dtype=float32)

fill_mask

< >

( text: strmodel: str | None = Nonetargets: list[str] | None = Nonetop_k: int | None = None ) → list[FillMaskOutputElement]

参数

  • text (str) — 用于填充的字符串,必须包含 [MASK] 标记(请查看模型卡片以获取掩码的确切名称)。
  • model (str, 可选) — 用于填充掩码任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的填充掩码模型。
  • targets (list[str, 可选) — 如果传入此参数,模型将把分数限制在传入的目标范围内,而不是在整个词汇表中查找。如果提供的目标不在模型词汇表中,它们将被分词,并使用第一个生成的 token(会发出警告,且速度可能更慢)。
  • top_k (int,可选) — 如果传入,将覆盖要返回的预测数量。

返回值

list[FillMaskOutputElement]

一个包含 FillMaskOutputElement 项的列表,其中包含预测标签、相关概率、token 引用以及补全后的文本。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

用缺失的单词(更准确地说,是 token)来填补空缺。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.fill_mask("The goal of life is <mask>.")
[
    FillMaskOutputElement(score=0.06897063553333282, token=11098, token_str=' happiness', sequence='The goal of life is happiness.'),
    FillMaskOutputElement(score=0.06554922461509705, token=45075, token_str=' immortality', sequence='The goal of life is immortality.')
]

get_endpoint_info

< >

( model: str | None = None ) → dict[str, Any]

参数

  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 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'
}

健康检查

< >

( model: str | None = None ) → bool

参数

  • model (str, 可选) — Inference Endpoint 的 URL。此参数会覆盖实例级别定义的 model。默认值为 None。

返回值

bool

如果一切正常,则为 True。

检查已部署端点的健康状况。

健康检查功能仅适用于由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 驱动的 Inference Endpoints。

示例:

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

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分类的图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于图像分类的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用图像分类的默认推荐模型。
  • function_to_apply ("ImageClassificationOutputTransform", 可选) — 应用于模型输出以获取分数的函数。
  • top_k (int, 可选) — 指定时,将输出限制为概率最高的前 K 个类别。

返回值

list[ImageClassificationOutputElement]

一个包含 ImageClassificationOutputElement 项的列表,其中包含预测标签及其对应的概率。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定的模型对给定图像执行图像分类。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
[ImageClassificationOutputElement(label='Blenheim spaniel', score=0.9779096841812134), ...]

图像分割

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonemask_threshold: float | None = Noneoverlap_mask_area_threshold: float | None = Nonesubtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = Nonethreshold: float | None = None ) → list[ImageSegmentationOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要分割的图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于图像分割的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用图像分割的默认推荐模型。
  • mask_threshold (float, 可选) — 将预测掩码转换为二值时使用的阈值。
  • overlap_mask_area_threshold (float, 可选) — 用于消除小型、不连续区域的掩码重叠阈值。
  • subtask ("ImageSegmentationSubtask", 可选) — 根据模型能力,要执行的分割任务。
  • threshold (float, 可选) — 用于过滤预测掩码的概率阈值。

返回值

list[ImageSegmentationOutputElement]

一个包含分割掩码及其相关属性的 ImageSegmentationOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定的模型对给定图像执行图像分割。

如果要处理图像,必须安装 PIL(pip install Pillow)。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.image_segmentation("cat.jpg")
[ImageSegmentationOutputElement(score=0.989008, label='LABEL_184', mask=<PIL.PngImagePlugin.PngImageFile image mode=L size=400x300 at 0x7FDD2B129CC0>), ...]

image_to_image

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]prompt: str | None = Nonenegative_prompt: str | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Nonemodel: str | None = Nonetarget_size: huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize | None = None**kwargs ) → Image

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用于翻译的输入图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • prompt (str, 可选) — 用于引导图像生成的文本提示。
  • negative_prompt (str, 可选) — 用于指导图像生成中不应包含内容的提示。
  • num_inference_steps (int, 可选) — 适用于扩散模型。去噪步数。更多的去噪步数通常能生成更高质量的图像,但会牺牲推理速度。
  • guidance_scale (float, 可选) — 适用于扩散模型。较高的 guidance scale 值会促使模型生成与文本提示紧密相关的图像,但代价是图像质量降低。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。默认为 None。
  • target_size (ImageToImageTargetSize,可选) — 输出图像的像素尺寸。此参数仅受部分提供商和特定模型支持。在不支持的情况下将被忽略。

返回值

Image

翻译后的图像。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定模型执行图像到图像的转换。

如果要处理图像,必须安装 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: str | None = None ) → ImageToTextOutput

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用于生成说明的输入图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。默认为 None。

生成的文本。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

接收输入图像并返回文本。

模型根据具体用例(如图像描述、光学字符识别(OCR)、Pix2Struct 等)可能产生截然不同的输出。请查阅模型卡片以了解该模型的具体特性。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.image_to_text("cat.jpg")
'a cat standing in a grassy field '
>>> await client.image_to_text("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
'a dog laying on the grass next to a flower pot '

image_to_video

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Noneprompt: str | None = Nonenegative_prompt: str | None = Nonenum_frames: float | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Noneseed: int | None = Nonetarget_size: huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize | None = None**kwargs ) → bytes

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用于生成视频的输入图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。默认为 None。
  • prompt (str, 可选) — 用于引导视频生成的文本提示。
  • negative_prompt (str, 可选) — 用于指导视频生成中不应包含内容的提示。
  • num_frames (float, 可选) — num_frames 参数决定生成多少视频帧。
  • num_inference_steps (int, 可选) — 适用于扩散模型。去噪步数。更多的去噪步数通常能生成更高质量的图像,但会牺牲推理速度。
  • guidance_scale (float, 可选) — 适用于扩散模型。较高的 guidance scale 值会促使模型生成与文本提示紧密相关的视频,但代价是图像质量降低。
  • seed (int, 可选) — 用于视频生成的随机种子。
  • target_size (ImageToVideoTargetSize,可选) — 输出视频帧的像素尺寸。
  • num_inference_steps (int, 可选) — 去噪步数。更多的去噪步数通常能带来更高质量的视频,但代价是推理速度变慢。
  • seed (int, 可选) — 随机数生成器的种子。

返回值

bytes

生成的视频。

根据输入图像生成视频。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> video = await client.image_to_video("cat.jpg", model="Wan-AI/Wan2.2-I2V-A14B", prompt="turn the cat into a tiger")
>>> with open("tiger.mp4", "wb") as f:
...     f.write(video)

object_detection

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]model: str | None = Nonethreshold: float | None = None ) → list[ObjectDetectionOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 要检测对象的图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • model (str, 可选) — 用于目标检测的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用目标检测的默认推荐模型(DETR)。
  • threshold (float, 可选) — 做出预测所需的概率。

返回值

list[ObjectDetectionOutputElement]

一个包含边界框及其相关属性的 ObjectDetectionOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError 或 ValueError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。
  • ValueError — 如果请求的输出不是 List。

使用指定的模型对给定图像执行目标检测。

如果要处理图像,必须安装 PIL(pip install Pillow)。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.object_detection("people.jpg")
[ObjectDetectionOutputElement(score=0.9486683011054993, label='person', box=ObjectDetectionBoundingBox(xmin=59, ymin=39, xmax=420, ymax=510)), ...]

question_answering

< >

( question: strcontext: strmodel: str | None = Nonealign_to_words: bool | None = Nonedoc_stride: int | None = Nonehandle_impossible_answer: bool | None = Nonemax_answer_len: int | None = Nonemax_question_len: int | None = Nonemax_seq_len: int | None = Nonetop_k: int | None = None ) → Union[QuestionAnsweringOutputElement, listQuestionAnsweringOutputElement]

参数

  • question (str) — 要回答的问题。
  • context (str) — 问题的上下文。
  • model (str) — 用于问答任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。
  • align_to_words (bool, 可选) — 尝试将答案对齐到实际的单词。可提高空格分隔语言的质量。可能会损害非空格分隔语言(如日语或中文)的质量
  • 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 列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

从给定文本中检索问题的答案。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.question_answering(question="What's my name?", context="My name is Clara and I live in Berkeley.")
QuestionAnsweringOutputElement(answer='Clara', end=16, score=0.9326565265655518, start=11)

sentence_similarity

< >

( sentence: strother_sentences: listmodel: str | None = None ) → list[float]

参数

  • sentence (str) — 用于与其他句子进行比较的主要句子。
  • other_sentences (list[str]) — 要与之比较的句子列表。
  • model (str, 可选) — 用于句子相似度任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的句子相似度模型。默认为 None。

返回值

list[float]

表示输入文本的嵌入。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

通过比较它们的嵌入来计算一个句子与其他句子列表之间的语义相似度。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.sentence_similarity(
...     "Machine learning is so easy.",
...     other_sentences=[
...         "Deep learning is so straightforward.",
...         "This is so difficult, like rocket science.",
...         "I can't believe how much I struggled with this.",
...     ],
... )
[0.7785726189613342, 0.45876261591911316, 0.2906220555305481]

摘要

< >

( text: strmodel: str | None = Noneclean_up_tokenization_spaces: bool | None = Nonegenerate_parameters: dict[str, typing.Any] | None = Nonetruncation: 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",可选) — 要使用的截断策略。

生成的摘要文本。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定模型生成给定文本的摘要。

示例:

# 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: dictquery: strmodel: str | None = Nonepadding: typing.Optional[ForwardRef('Padding')] = Nonesequential: bool | None = Nonetruncation: bool | None = None ) → TableQuestionAnsweringOutputElement

参数

  • table (str) — 以列表字典形式表示的数据表,其中键为表头,值为所有数据项,所有列表的长度必须相同。
  • query (str) — 您想要向表格查询的纯文本查询。
  • model (str) — 用于表格问答任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。
  • padding ("Padding",可选) — 启用并控制填充。
  • sequential (bool, 可选) — 是否按顺序执行推理,还是作为批次执行。批次推理速度更快,但像 SQA 这样的模型需要按顺序执行推理,才能从序列中提取关系,因为它们具有对话性质。
  • truncation (bool,可选) — 启用并控制截断。

一个表格问答输出,包含答案、坐标、单元格以及所使用的聚合器。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

从表格中提供的信息中检索问题的答案。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> query = "How many stars does the transformers repository have?"
>>> table = {"Repository": ["Transformers", "Datasets", "Tokenizers"], "Stars": ["36542", "4512", "3934"]}
>>> await client.table_question_answering(table, query, model="google/tapas-base-finetuned-wtq")
TableQuestionAnsweringOutputElement(answer='36542', coordinates=[[0, 1]], cells=['36542'], aggregator='AVERAGE')

表格分类

< >

( table: dictmodel: str | None = None ) → List

参数

  • table (dict[str, Any]) — 要分类的属性集合。
  • model (str, 可选) — 用于表格分类任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的表格分类模型。默认为 None。

返回值

List

标签列表,初始表格中的每一行对应一个标签。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

根据一组属性对目标类别(组)进行分类。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> table = {
...     "fixed_acidity": ["7.4", "7.8", "10.3"],
...     "volatile_acidity": ["0.7", "0.88", "0.32"],
...     "citric_acid": ["0", "0", "0.45"],
...     "residual_sugar": ["1.9", "2.6", "6.4"],
...     "chlorides": ["0.076", "0.098", "0.073"],
...     "free_sulfur_dioxide": ["11", "25", "5"],
...     "total_sulfur_dioxide": ["34", "67", "13"],
...     "density": ["0.9978", "0.9968", "0.9976"],
...     "pH": ["3.51", "3.2", "3.23"],
...     "sulphates": ["0.56", "0.68", "0.82"],
...     "alcohol": ["9.4", "9.8", "12.6"],
... }
>>> await client.tabular_classification(table=table, model="julien-c/wine-quality")
["5", "5", "5"]

表格回归

< >

( table: dictmodel: str | None = None ) → List

参数

  • table (dict[str, Any]) — 存储在表中的一组属性。用于预测目标的属性可以是数值型,也可以是类别型。
  • model (str, 可选) — 用于表格回归任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的表格回归模型。默认为 None。

返回值

List

预测数值目标值的列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

给定表格中的一组属性/特征,预测一个数值目标值。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> table = {
...     "Height": ["11.52", "12.48", "12.3778"],
...     "Length1": ["23.2", "24", "23.9"],
...     "Length2": ["25.4", "26.3", "26.5"],
...     "Length3": ["30", "31.2", "31.1"],
...     "Species": ["Bream", "Bream", "Bream"],
...     "Width": ["4.02", "4.3056", "4.6961"],
... }
>>> await client.tabular_regression(table, model="scikit-learn/Fish-Weight")
[110, 120, 130]

文本分类

< >

( text: strmodel: str | None = Nonetop_k: int | None = Nonefunction_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None ) → list[TextClassificationOutputElement]

参数

  • text (str) — 要分类的字符串。
  • model (str, 可选) — 用于文本分类任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文本分类模型。默认为 None。
  • top_k (int, 可选) — 指定时,将输出限制为概率最高的前 K 个类别。
  • function_to_apply ("TextClassificationOutputTransform", 可选) — 应用于模型输出以获取分数的函数。

返回值

list[TextClassificationOutputElement]

一个包含 TextClassificationOutputElement 项的列表,其中包含预测标签及其对应的概率。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

对给定文本执行文本分类(例如情感分析)。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.text_classification("I like you")
[
    TextClassificationOutputElement(label='POSITIVE', score=0.9998695850372314),
    TextClassificationOutputElement(label='NEGATIVE', score=0.0001304351753788069),
]

文本生成

< >

( prompt: strdetails: bool | None = Nonestream: bool | None = Nonemodel: str | None = Noneadapter_id: str | None = Nonebest_of: int | None = Nonedecoder_input_details: bool | None = Nonedo_sample: bool | None = Nonefrequency_penalty: float | None = Nonegrammar: huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType | None = Nonemax_new_tokens: int | None = Nonerepetition_penalty: float | None = Nonereturn_full_text: bool | None = Noneseed: int | None = Nonestop: list[str] | None = Nonetemperature: float | None = Nonetop_k: int | None = Nonetop_n_tokens: int | None = Nonetop_p: float | None = Nonetruncate: int | None = Nonetypical_p: float | None = Nonewatermark: bool | None = None ) → Union[str, TextGenerationOutput, AsyncIterable[str], AsyncIterable[TextGenerationStreamOutput]]

参数

  • prompt (str) — 输入文本。
  • details (bool, 可选) — 默认情况下,text_generation 返回一个字符串。如果您需要详细的输出(tokens、概率、seed、finish reason 等),请传入 details=True。仅适用于使用 text-generation-inference 后端运行的模型。
  • stream (bool,可选) — 默认情况下,text_generation 会返回完整的生成文本。如果您希望以流的形式返回 token,请传入 stream=True。此功能仅适用于使用 text-generation-inference 后端运行的模型。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。默认为 None。
  • adapter_id (str, 可选) — Lora 适配器 ID。
  • best_of (int,可选) — 生成 best_of 个序列,并返回其中 token 对数概率最高的一个。
  • decoder_input_details (bool,可选) — 返回解码器输入 token 的 logprobs 和 ids。必须同时设置 details=True 才会生效。默认为 False。
  • do_sample (bool,可选) — 启用 logits 采样
  • frequency_penalty (float, 可选) — 介于 -2.0 和 2.0 之间的数值。正值会根据新标记在现有文本中出现的频率对其进行惩罚,从而降低模型逐字重复相同内容的概率。
  • 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。
  • temperature (float,可选) — 用于调节 logits 分布的值。
  • top_n_tokens (int, 可选) — 返回每个生成步骤中 top_n_tokens 个最可能 token 的信息,而不仅仅是采样到的 token。
  • top_k (int, *可选`) — 用于 top-k 过滤时保留的最高概率词汇标记的数量。
  • top_p (float, *optional) -- If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p` or higher are kept for generation.
  • truncate (int, *可选`) — 将输入标记截断为指定大小。
  • typical_p (float, *可选`) — 典型解码质量 有关更多信息,请参阅 用于自然语言生成的典型解码
  • watermark (bool, 可选) — 使用 大型语言模型的水印 进行水印处理

返回值

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

从服务器返回的生成文本:

  • 如果 stream=False 且 details=False,则生成的文本将以 str 形式返回(默认值)
  • 如果 stream=True 且 details=False,生成的文本将以 AsyncIterable[str] 的形式逐 token 返回。
  • 如果 stream=False 且 details=True,生成的文本将作为 TextGenerationOutput 返回,并包含更多详细信息
  • 如果 details=True 且 stream=True,生成的文本将以 TextGenerationStreamOutput 的可迭代对象形式逐 token 返回。

引发

ValidationError 或 InferenceTimeoutError 或 HfHubHTTPError

  • ValidationError — 如果输入值无效。不会向服务器发起 HTTP 调用。
  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

给定一个提示,生成以下文本。

如果您想根据聊天消息生成回复,应使用 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: strnegative_prompt: str | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int | None = Noneguidance_scale: float | None = Nonemodel: str | None = Nonescheduler: str | None = Noneseed: int | None = Noneextra_body: dict[str, typing.Any] | None = None ) → Image

参数

  • prompt (str) — 用于生成图像的提示词。
  • negative_prompt (str, 可选) — 用于指导图像生成中不应包含内容的提示。
  • height (int, 可选) — 输出图像的高度(以像素为单位)
  • width (int, 可选) — 输出图像的宽度(以像素为单位)
  • num_inference_steps (int, 可选) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但会牺牲推理速度。
  • guidance_scale (float, 可选) — 较高的 guidance scale 值会促使模型生成与文本提示紧密相关的图像,但数值过高可能导致饱和及其他伪影。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文本生成图像模型。默认为 None。
  • scheduler (str, 可选) — 使用兼容的调度器覆盖默认的调度器。
  • seed (int, 可选) — 随机数生成器的种子。
  • extra_body (dict[str, Any],可选) — 传递给模型的额外提供商特定参数。有关支持的参数,请参阅提供商的文档。

返回值

Image

生成的图像。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

使用指定模型根据给定文本生成图像。

如果要处理图像,必须安装 PIL(pip install Pillow)。

您可以通过使用 extra_body 参数向模型传递特定于提供商的参数。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

>>> image = await client.text_to_image("An astronaut riding a horse on the moon.")
>>> image.save("astronaut.png")

>>> image = await client.text_to_image(
...     "An astronaut riding a horse on the moon.",
...     negative_prompt="low resolution, blurry",
...     model="stabilityai/stable-diffusion-2-1",
... )
>>> image.save("better_astronaut.png")
Example using a third-party provider directly. Usage will be billed on your fal.ai account.
>>> 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 Routing 使用第三方提供商的示例。相关用量将从您的 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: strmodel: str | None = Nonedo_sample: bool | None = Noneearly_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = Noneepsilon_cutoff: float | None = Noneeta_cutoff: float | None = Nonemax_length: int | None = Nonemax_new_tokens: int | None = Nonemin_length: int | None = Nonemin_new_tokens: int | None = Nonenum_beam_groups: int | None = Nonenum_beams: int | None = Nonepenalty_alpha: float | None = Nonetemperature: float | None = Nonetop_k: int | None = Nonetop_p: float | None = Nonetypical_p: float | None = Noneuse_cache: bool | None = Noneextra_body: dict[str, typing.Any] | None = None ) → bytes

参数

  • text (str) — 要合成的文本。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文本转语音模型。默认为 None。
  • do_sample (bool, 可选) — 在生成新 token 时,是否使用采样而非贪心解码。
  • early_stopping (Union[bool, "TextToSpeechEarlyStoppingEnum"],可选) — 控制基于束搜索方法的停止条件。
  • epsilon_cutoff (float, 可选) — 如果设置为严格介于 0 和 1 之间的浮点数,则仅会采样条件概率大于 epsilon_cutoff 的 token。在论文中,建议值根据模型大小在 3e-4 到 9e-4 之间。有关更多详细信息,请参阅 Truncation Sampling as Language Model Desmoothing。
  • eta_cutoff (float, 可选) — Eta 采样是局部典型采样和 epsilon 采样的混合。如果设置为严格介于 0 和 1 之间的 float,则仅当 token 大于 eta_cutoff 或 sqrt(eta_cutoff)
    • exp(-entropy(softmax(next_token_logits)))。后一项直观上是期望的下一个 token 概率,并按 sqrt(eta_cutoff) 进行缩放。在论文中,建议的取值范围从 3e-4 到 2e-3,具体取决于模型的大小。有关更多详细信息,请参阅 Truncation Sampling as Language Model Desmoothing。
  • max_length (int, 可选) — 生成文本的最大长度(以 token 计),包括输入部分。
  • max_new_tokens (int, 可选) — 要生成的最大 token 数量。优先于 max_length。
  • min_length (int,可选) — 生成文本的最小长度(以 token 计),包括输入。
  • min_new_tokens (int, 可选) — 要生成的最小 token 数量。优先于 min_length。
  • num_beam_groups (int, 可选) — 将 num_beams 划分为若干组,以确保不同 beam 组之间的多样性。 有关更多详细信息,请参阅 这篇论文。
  • num_beams (int, 可选) — 用于束搜索的束数量。
  • penalty_alpha (float, 可选) — 该值用于在对比搜索解码中平衡模型置信度与退化惩罚。
  • temperature (float, 可选) — 用于调节下一个 token 概率的值。
  • top_k (int, 可选) — 用于 top-k 过滤时保留的最高概率词汇表 token 数量。
  • top_p (float, 可选) — 如果设置为小于 1 的浮点数,则仅保留概率之和达到或超过 top_p 的最小最可能 token 集合用于生成。
  • typical_p (float, 可选) — 局部典型性衡量了在已生成部分文本的条件下,预测下一个目标 token 的条件概率与预测下一个随机 token 的期望条件概率之间的相似程度。如果设置为小于 1 的 float 值,则仅保留概率之和达到 typical_p 或更高的、局部典型性最高的最小 token 集合用于生成。有关更多详细信息,请参阅这篇论文。
  • use_cache (bool, 可选) — 模型是否应使用过去最后的关键值注意力来加速解码
  • extra_body (dict[str, Any],可选) — 传递给模型的额外提供商特定参数。有关支持的参数,请参阅提供商的文档。

返回值

bytes

生成的音频。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

合成一段语音,用于朗读给定的文本。

您可以通过使用 extra_body 参数向模型传递特定于提供商的参数。

示例:

# Must be run in an async context
>>> from pathlib import Path
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

>>> audio = await client.text_to_speech("Hello world")
>>> Path("hello_world.flac").write_bytes(audio)

直接使用第三方提供商的示例。使用量将从您的 Replicate 账户中扣除。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",
...     api_key="your-replicate-api-key",  # Pass your Replicate API key directly
... )
>>> audio = client.text_to_speech(
...     text="Hello world",
...     model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)

通过 Hugging Face Routing 使用第三方提供商的示例。相关用量将从您的 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)
Example using Replicate provider with extra parameters
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="replicate",  # Use replicate provider
...     api_key="hf_...",  # Pass your HF token
... )
>>> audio = client.text_to_speech(
...     "Hello, my name is Kororo, an awesome text-to-speech model.",
...     model="hexgrad/Kokoro-82M",
...     extra_body={"voice": "af_nicole"},
... )
>>> Path("hello.flac").write_bytes(audio)

在 fal.ai 上使用“YuE-s1-7B-anneal-en-cot”的音乐生成示例

>>> 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: strmodel: str | None = Noneguidance_scale: float | None = Nonenegative_prompt: list[str] | None = Nonenum_frames: float | None = Nonenum_inference_steps: int | None = Noneseed: int | None = Noneextra_body: dict[str, typing.Any] | None = None ) → bytes

参数

  • prompt (str) — 用于生成视频的提示词。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的文本生成视频模型。默认为 None。
  • guidance_scale (float, 可选) — 较高的 guidance scale 值会促使模型生成与文本提示紧密相关的视频,但数值过高可能导致饱和及其他伪影。
  • negative_prompt (list[str],可选) — 一个或多个提示词,用于指导视频生成中不应包含的内容。
  • num_frames (float, 可选) — num_frames 参数决定生成多少视频帧。
  • num_inference_steps (int, 可选) — 去噪步数。更多的去噪步数通常能带来更高质量的视频,但代价是推理速度变慢。
  • seed (int, 可选) — 随机数生成器的种子。
  • extra_body (dict[str, Any],可选) — 传递给模型的额外提供商特定参数。有关支持的参数,请参阅提供商的文档。

返回值

bytes

生成的视频。

根据给定的文本生成视频。

您可以通过使用 extra_body 参数向模型传递特定于提供商的参数。

示例:

直接使用第三方提供商的示例。使用费用将从您的 fal.ai 账户中扣除。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
...     provider="fal-ai",  # Using fal.ai provider
...     api_key="fal-ai-api-key",  # Pass your fal.ai API key
... )
>>> video = client.text_to_video(
...     "A majestic lion running in a fantasy forest",
...     model="tencent/HunyuanVideo",
... )
>>> with open("lion.mp4", "wb") as file:
...     file.write(video)

通过 Hugging Face Routing 使用第三方提供商的示例。相关用量将从您的 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: strmodel: str | None = Noneaggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = Noneignore_labels: list[str] | None = Nonestride: int | None = None ) → list[TokenClassificationOutputElement]

参数

  • text (str) — 要分类的字符串。
  • model (str, 可选) — 用于 token classification 任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的 token classification 模型。默认为 None。
  • aggregation_strategy ("TokenClassificationAggregationStrategy",可选) — 用于根据模型预测结果融合 token 的策略
  • ignore_labels (list[str, 可选) — 要忽略的标签列表
  • stride (int, 可选) — 在拆分输入文本时,相邻块之间重叠的 token 数量。

返回值

list[TokenClassificationOutputElement]

包含实体组、置信度分数、单词、起始和结束索引的 TokenClassificationOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

对给定文本执行 token 分类。 通常用于句子解析,包括语法分析或命名实体识别(NER),以理解文本中包含的关键词。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica")
[
    TokenClassificationOutputElement(
        entity_group='PER',
        score=0.9971321225166321,
        word='Sarah Jessica Parker',
        start=11,
        end=31,
    ),
    TokenClassificationOutputElement(
        entity_group='PER',
        score=0.9773476123809814,
        word='Jessica',
        start=52,
        end=59,
    )
]

翻译

< >

( text: strmodel: str | None = Nonesrc_lang: str | None = Nonetgt_lang: str | None = Noneclean_up_tokenization_spaces: bool | None = Nonetruncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = Nonegenerate_parameters: dict[str, typing.Any] | None = None ) → TranslationOutput

参数

  • text (str) — 要翻译的字符串。
  • model (str, 可选) — 用于翻译任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认推荐的翻译模型。默认为 None。
  • src_lang (str, 可选) — 文本的源语言。对于支持从多种语言进行翻译的模型,此参数为必填项。
  • tgt_lang (str, 可选) — 要翻译到的目标语言。对于可以翻译到多种语言的模型,此参数为必填项。
  • clean_up_tokenization_spaces (bool, 可选) — 是否清理文本输出中可能存在的多余空格。
  • truncation("TranslationTruncationStrategy",可选)— 要使用的截断策略。
  • generate_parameters (dict[str, Any],可选) — 文本生成算法的额外参数配置。

生成的翻译文本。

引发

InferenceTimeoutError 或 HfHubHTTPError 或 ValueError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。
  • ValueError — 如果只提供了 src_lang 和 tgt_lang 参数中的一个。

将文本从一种语言转换为另一种语言。

请访问 https://huggingface.co/tasks/translation 了解如何为特定用例选择最佳模型的更多信息。源语言和目标语言通常取决于模型。 不过,对于某些模型,可以指定源语言和目标语言。如果你正在使用这些模型之一, 可以使用 src_lang 和 tgt_lang 参数来传递相关信息。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.translation("My name is Wolfgang and I live in Berlin")
'Mein Name ist Wolfgang und ich lebe in Berlin.'
>>> await client.translation("My name is Wolfgang and I live in Berlin", model="Helsinki-NLP/opus-mt-en-fr")
TranslationOutput(translation_text='Je m'appelle Wolfgang et je vis à Berlin.')

指定语言:

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

视觉问答

< >

( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image'), bytearray, memoryview]question: strmodel: str | None = Nonetop_k: int | None = None ) → list[VisualQuestionAnsweringOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 上下文的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • question (str) — 要回答的问题。
  • model (str, 可选) — 用于视觉问答任务的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。如果未提供,将使用默认的推荐视觉问答模型。默认为 None。
  • top_k (int, 可选) — 要返回的答案数量(按可能性顺序选择)。请注意,如果上下文中可用的选项不足,我们将返回少于 topk 个答案。

返回值

list[VisualQuestionAnsweringOutputElement]

一个包含 VisualQuestionAnsweringOutputElement 项的列表,其中包含预测标签及其对应的概率。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

基于图像回答开放式问题。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.visual_question_answering(
...     image="https://huggingface.co/datasets/mishig/sample_images/resolve/main/tiger.jpg",
...     question="What is the animal doing?"
... )
[
    VisualQuestionAnsweringOutputElement(score=0.778609573841095, answer='laying down'),
    VisualQuestionAnsweringOutputElement(score=0.6957435607910156, answer='sitting'),
]

zero_shot_classification

< >

( text: strcandidate_labels: listmulti_label: bool | None = Falsehypothesis_template: str | None = Nonemodel: str | None = None ) → list[ZeroShotClassificationOutputElement]

参数

  • text (str) — 要分类的输入文本。
  • candidate_labels (list[str]) — 用于对文本进行分类的可能类别标签集合。
  • multi_label (bool, 可选) — 是否允许多个候选标签同时为真。如果为 false,则对分数进行归一化,使得每个序列的标签似然之和为 1。如果为 true,则标签被视为相互独立,并对每个候选标签的概率进行归一化。
  • hypothesis_template (str, 可选) — 与 candidate_labels 配合使用的句子,通过将占位符替换为候选标签来尝试进行文本分类。
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。如果未提供,将使用默认推荐的零样本分类模型。

返回值

list[ZeroShotClassificationOutputElement]

包含预测标签及其置信度的 ZeroShotClassificationOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

提供一段文本和一组候选标签作为输入,用于对输入文本进行分类。

multi_label=False 的示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> text = (
...     "A new model offers an explanation for how the Galilean satellites formed around the solar system's"
...     "largest world. Konstantin Batygin did not set out to solve one of the solar system's most puzzling"
...     " mysteries when he went for a run up a hill in Nice, France."
... )
>>> labels = ["space & cosmos", "scientific discovery", "microbiology", "robots", "archeology"]
>>> await client.zero_shot_classification(text, labels)
[
    ZeroShotClassificationOutputElement(label='scientific discovery', score=0.7961668968200684),
    ZeroShotClassificationOutputElement(label='space & cosmos', score=0.18570658564567566),
    ZeroShotClassificationOutputElement(label='microbiology', score=0.00730885099619627),
    ZeroShotClassificationOutputElement(label='archeology', score=0.006258360575884581),
    ZeroShotClassificationOutputElement(label='robots', score=0.004559356719255447),
]
>>> await client.zero_shot_classification(text, labels, multi_label=True)
[
    ZeroShotClassificationOutputElement(label='scientific discovery', score=0.9829297661781311),
    ZeroShotClassificationOutputElement(label='space & cosmos', score=0.755190908908844),
    ZeroShotClassificationOutputElement(label='microbiology', score=0.0005462635890580714),
    ZeroShotClassificationOutputElement(label='archeology', score=0.00047131875180639327),
    ZeroShotClassificationOutputElement(label='robots', score=0.00030448526376858354),
]

使用 multi_label=True 和自定义 hypothesis_template 的示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.zero_shot_classification(
...    text="I really like our dinner and I'm very happy. I don't like the weather though.",
...    candidate_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: listmodel: str | None = Nonehypothesis_template: str | None = None ) → list[ZeroShotImageClassificationOutputElement]

参数

  • image (Union[str, Path, bytes, BinaryIO, PIL.Image.Image]) — 用于生成说明的输入图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL Image。
  • candidate_labels (list[str]) — 此图像的候选标签
  • model (str, 可选) — 用于推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的 Inference Endpoint 的 URL。此参数会覆盖实例级别定义的模型。如果未提供,将使用默认推荐的零样本图像分类模型。
  • hypothesis_template (str, 可选) — 与 candidate_labels 配合使用的句子,通过将占位符替换为候选标签来尝试进行图像分类。

返回值

list[ZeroShotImageClassificationOutputElement]

包含预测标签及其置信度的 ZeroShotImageClassificationOutputElement 项列表。

引发

InferenceTimeoutError 或 HfHubHTTPError

  • InferenceTimeoutError — 如果模型不可用或请求超时。
  • HfHubHTTPError — 如果请求失败且 HTTP 错误状态码不是 HTTP 503。

提供输入图像和文本标签,以预测该图像的文本标签。

示例:

# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

>>> await client.zero_shot_image_classification(
...     "https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg",
...     candidate_labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]

InferenceTimeoutError

类 huggingface_hub.InferenceTimeoutError

< >

( message: str )

当模型不可用或请求超时时引发的错误。

Update on GitHub