Hub Python 库文档
推理
并获得增强的文档体验
开始使用
推理
推理是使用经过训练的模型对新数据进行预测的过程。由于此过程可能需要大量计算,因此在专用或外部服务上运行可能是一个有趣的选择。`huggingface_hub` 库提供了一个统一的接口,用于对托管在 Hugging Face Hub 上的模型执行跨多个服务的推理。
- 推理提供商:通过我们的无服务器推理合作伙伴提供对数百种机器学习模型的简化统一访问。这种新方法建立在我们之前的无服务器推理 API 的基础上,得益于世界级的提供商,提供了更多的模型、改进的性能和更高的可靠性。有关受支持提供商的列表,请参阅文档。
- 推理端点:一种用于轻松将模型部署到生产环境的产品。推理由 Hugging Face 在您选择的云提供商上专用的完全托管的基础设施中运行。
- 本地端点:您还可以使用本地推理服务器(如 llama.cpp、Ollama、vLLM、LiteLLM 或 文本生成推理 (TGI))通过将客户端连接到这些本地端点来运行推理。
可以使用 InferenceClient 对象调用这些服务。有关如何使用它的更多信息,请参阅本指南。
推理客户端
class huggingface_hub.InferenceClient
< 源代码 >( model: typing.Optional[str] = None provider: typing.Union[typing.Literal['black-forest-labs', 'cerebras', 'cohere', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'hyperbolic', 'nebius', 'novita', 'nscale', 'openai', 'replicate', 'sambanova', 'together'], typing.Literal['auto'], NoneType] = None token: typing.Optional[str] = None timeout: typing.Optional[float] = None headers: typing.Optional[typing.Dict[str, str]] = None cookies: typing.Optional[typing.Dict[str, str]] = None proxies: typing.Optional[typing.Any] = None bill_to: typing.Optional[str] = None base_url: typing.Optional[str] = None api_key: typing.Optional[str] = None )
参数
- model (
str
,可选
) — 用于运行推理的模型。可以是托管在 Hugging Face Hub 上的模型 ID,例如meta-llama/Meta-Llama-3-8B-Instruct
,也可以是已部署的推理端点的 URL。默认为 None,在这种情况下,将自动为任务选择推荐的模型。注意:为了更好地兼容 OpenAI 的客户端,model
已被别名为base_url
。这两个参数是互斥的。如果将 URL 作为model
或base_url
传递给聊天补全,则(/v1)/chat/completions
后缀路径将附加到 URL。 - provider (
str
, 可选) — 用于推理的提供商名称。可以是"black-forest-labs"
,"cerebras"
,"cohere"
,"fal-ai"
,"featherless-ai"
,"fireworks-ai"
,"groq"
,"hf-inference"
,"hyperbolic"
,"nebius"
,"novita"
,"nscale"
,"openai"
,"replicate"
, “sambanova” 或 “together”。默认为 "auto",即模型可用提供商中的第一个,按用户在 https://huggingface.co/settings/inference-providers 中的顺序排序。如果 model 是 URL 或base_url
已传递,则不使用provider
。 - token (
str
, 可选) — Hugging Face token。如果未提供,将默认为本地保存的 token。注意:为了更好地兼容 OpenAI 的客户端,token
已被别名为api_key
。这两个参数互斥,且行为完全相同。 - timeout (
float
,可选
) — 等待服务器响应的最大秒数。默认为 None,这意味着它将一直循环直到服务器可用。 - headers (
Dict[str, str]
,可选
) — 发送到服务器的附加标头。默认情况下,只发送授权和用户代理标头。此字典中的值将覆盖默认值。 - bill_to (
str
,可选
) — 用于请求的计费账户。默认情况下,请求将计费到用户的账户。请求只能计费到用户是其成员且已订阅企业中心 (Enterprise Hub) 的组织。 - cookies (
Dict[str, str]
,可选
) — 发送到服务器的附加 cookie。 - proxies (
Any
,可选
) — 用于请求的代理。 - base_url (
str
,可选
) — 运行推理的基础 URL。这是从model
复制的参数,以使 InferenceClient 遵循与openai.OpenAI
客户端相同的模式。如果设置了model
,则不能使用此参数。默认为 None。 - api_key (
str
,可选
) — 用于身份验证的 token。这是从token
复制的参数,以使 InferenceClient 遵循与openai.OpenAI
客户端相同的模式。如果设置了token
,则不能使用此参数。默认为 None。
初始化新的推理客户端。
InferenceClient 旨在提供统一的推理体验。客户端可以无缝地与(免费的)推理 API、自托管推理端点或第三方推理提供商一起使用。
音频分类
< 源代码 >( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None top_k: typing.Optional[int] = None function_to_apply: typing.Optional[ForwardRef('AudioClassificationOutputTransform')] = None ) → List[AudioClassificationOutputElement]
参数
- audio (Union[str, Path, bytes, BinaryIO]) — 要分类的音频内容。可以是原始音频字节、本地音频文件或指向音频文件的 URL。
- model (
str
, 可选) — 用于音频分类的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用音频分类的默认推荐模型。 - top_k (
int
, 可选) — 指定后,将输出限制为最可能的 K 个类别。 - function_to_apply (
"AudioClassificationOutputTransform"
, 可选) — 应用于模型输出以检索分数的功能。
返回
List[AudioClassificationOutputElement]
包含预测标签及其置信度的 AudioClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
对提供的音频内容执行音频分类。
音频到音频
< 源代码 >( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None ) → List[AudioToAudioOutputElement]
参数
- audio (Union[str, Path, bytes, BinaryIO]) — 用于模型的音频内容。可以是原始音频字节、本地音频文件或指向音频文件的 URL。
- model (
str
, 可选) — 该模型可以是任何接受音频文件并返回另一个音频文件的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用 audio_to_audio 的默认推荐模型。
返回
List[AudioToAudioOutputElement]
包含音频标签、内容类型和 blob 中的音频内容的 AudioToAudioOutputElement 项列表。
引发
InferenceTimeoutError
或 HTTPError
InferenceTimeoutError
— 如果模型不可用或请求超时。HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
根据模型执行与音频到音频相关的多项任务(例如:语音增强、源分离)。
自动语音识别
< 源代码 >( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None extra_body: typing.Optional[typing.Dict] = None ) → AutomaticSpeechRecognitionOutput
参数
- audio (Union[str, Path, bytes, BinaryIO]) — 要转录的内容。可以是原始音频字节、本地音频文件或音频文件的 URL。
- model (
str
, 可选) — 用于 ASR 的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用 ASR 的默认推荐模型。 - extra_body (
Dict
, 可选) — 传递给模型的额外提供商特定参数。有关支持的参数,请参阅提供商的文档。
包含转录文本和可选时间戳块的项。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
对给定的音频内容执行自动语音识别(ASR 或音频转文本)。
聊天补全
< 源代码 >( messages: typing.List[typing.Union[typing.Dict, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage]] model: typing.Optional[str] = None stream: bool = False frequency_penalty: typing.Optional[float] = None logit_bias: typing.Optional[typing.List[float]] = None logprobs: typing.Optional[bool] = None max_tokens: typing.Optional[int] = None n: typing.Optional[int] = None presence_penalty: typing.Optional[float] = None response_format: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatText, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONSchema, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONObject, NoneType] = None seed: typing.Optional[int] = None stop: typing.Optional[typing.List[str]] = None stream_options: typing.Optional[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions] = None temperature: typing.Optional[float] = None tool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None tool_prompt: typing.Optional[str] = None tools: typing.Optional[typing.List[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool]] = None top_logprobs: typing.Optional[int] = None top_p: typing.Optional[float] = None extra_body: typing.Optional[typing.Dict] = None ) → ChatCompletionOutput 或 Iterable of ChatCompletionStreamOutput
参数
- messages (ChatCompletionInputMessage 列表) — 由角色和内容对组成的对话历史。
- model (
str
, 可选) — 用于聊天补全的模型。可以是托管在 Hugging Face Hub 上的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用基于聊天的文本生成的默认推荐模型。有关更多详细信息,请参阅 https://huggingface.co/tasks/text-generation。如果model
是模型 ID,它将作为model
参数传递给服务器。如果要在设置请求负载中的model
时定义自定义 URL,则必须在初始化 InferenceClient 时设置base_url
。 - frequency_penalty (
float
, 可选) — 根据新 token 在文本中已有的频率对其进行惩罚。范围:[-2.0, 2.0]。默认为 0.0。 - logit_bias (
List[float]
, 可选) — 调整特定 token 出现在生成输出中的可能性。 - 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
, 可选) — 可复现控制流的种子。默认为 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 (List of ChatCompletionInputTool, 可选) — 模型可能调用的工具列表。目前,只支持函数作为工具。使用此参数提供模型可能生成 JSON 输入的函数列表。
- extra_body (
Dict
, 可选) — 要传递给模型的额外提供方特定参数。有关支持的参数,请参阅提供方的文档。
返回
服务器返回的生成文本
- 如果
stream=False
,则生成文本作为 ChatCompletionOutput 返回(默认)。 - 如果
stream=True
,则生成文本以 token 为单位作为 ChatCompletionStreamOutput 序列返回。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
使用指定的语言模型完成对话的方法。
client.chat_completion
方法被别名为 client.chat.completions.create
,以与 OpenAI 的客户端兼容。输入和输出严格相同,使用任一语法都将产生相同的结果。有关 OpenAI 兼容性的更多详细信息,请查看 推理指南。
示例
>>> from huggingface_hub import InferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> client.chat_completion(messages, max_tokens=100)
ChatCompletionOutput(
choices=[
ChatCompletionOutputComplete(
finish_reason='eos_token',
index=0,
message=ChatCompletionOutputMessage(
role='assistant',
content='The capital of France is Paris.',
name=None,
tool_calls=None
),
logprobs=None
)
],
created=1719907176,
id='',
model='meta-llama/Meta-Llama-3-8B-Instruct',
object='text_completion',
system_fingerprint='2.0.4-sha-f426a33',
usage=ChatCompletionOutputUsage(
completion_tokens=8,
prompt_tokens=17,
total_tokens=25
)
)
使用流式传输的示例
>>> from huggingface_hub import InferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> for token in client.chat_completion(messages, max_tokens=10, stream=True):
... print(token)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content='The', role='assistant'), index=0, finish_reason=None)], created=1710498504)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' capital', role='assistant'), index=0, finish_reason=None)], created=1710498504)
(...)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' may', role='assistant'), index=0, finish_reason=None)], created=1710498504)
使用 OpenAI 语法的示例
# instead of `from openai import OpenAI`
from huggingface_hub import InferenceClient
# instead of `client = OpenAI(...)`
client = InferenceClient(
base_url=...,
api_key=...,
)
output = client.chat.completions.create(
model="meta-llama/Meta-Llama-3-8B-Instruct",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Count to 10"},
],
stream=True,
max_tokens=1024,
)
for chunk in output:
print(chunk.choices[0].delta.content)
直接使用额外(提供方特定)参数的第三方提供方示例。使用费用将计入您的 Together AI 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="together", # Use Together AI provider
... api_key="<together_api_key>", # Pass your Together API key directly
... )
>>> client.chat_completion(
... model="meta-llama/Meta-Llama-3-8B-Instruct",
... messages=[{"role": "user", "content": "What is the capital of France?"}],
... extra_body={"safety_model": "Meta-Llama/Llama-Guard-7b"},
... )
通过 Hugging Face 路由使用第三方提供方的示例。使用费用将计入您的 Hugging Face 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="sambanova", # Use Sambanova provider
... api_key="hf_...", # Pass your HF token
... )
>>> client.chat_completion(
... model="meta-llama/Meta-Llama-3-8B-Instruct",
... messages=[{"role": "user", "content": "What is the capital of France?"}],
... )
使用图像 + 文本作为输入的示例
>>> from huggingface_hub import InferenceClient
# provide a remote URL
>>> image_url ="https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
# or a base64-encoded image
>>> image_path = "/path/to/image.jpeg"
>>> with open(image_path, "rb") as f:
... base64_image = base64.b64encode(f.read()).decode("utf-8")
>>> image_url = f"data:image/jpeg;base64,{base64_image}"
>>> client = InferenceClient("meta-llama/Llama-3.2-11B-Vision-Instruct")
>>> output = client.chat.completions.create(
... messages=[
... {
... "role": "user",
... "content": [
... {
... "type": "image_url",
... "image_url": {"url": image_url},
... },
... {
... "type": "text",
... "text": "Describe this image in one sentence.",
... },
... ],
... },
... ],
... )
>>> output
The image depicts the iconic Statue of Liberty situated in New York Harbor, New York, on a clear day.
使用工具的示例
>>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
... {
... "role": "system",
... "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
... },
... {
... "role": "user",
... "content": "What's the weather like the next 3 days in San Francisco, CA?",
... },
... ]
>>> tools = [
... {
... "type": "function",
... "function": {
... "name": "get_current_weather",
... "description": "Get the current weather",
... "parameters": {
... "type": "object",
... "properties": {
... "location": {
... "type": "string",
... "description": "The city and state, e.g. San Francisco, CA",
... },
... "format": {
... "type": "string",
... "enum": ["celsius", "fahrenheit"],
... "description": "The temperature unit to use. Infer this from the users location.",
... },
... },
... "required": ["location", "format"],
... },
... },
... },
... {
... "type": "function",
... "function": {
... "name": "get_n_day_weather_forecast",
... "description": "Get an N-day weather forecast",
... "parameters": {
... "type": "object",
... "properties": {
... "location": {
... "type": "string",
... "description": "The city and state, e.g. San Francisco, CA",
... },
... "format": {
... "type": "string",
... "enum": ["celsius", "fahrenheit"],
... "description": "The temperature unit to use. Infer this from the users location.",
... },
... "num_days": {
... "type": "integer",
... "description": "The number of days to forecast",
... },
... },
... "required": ["location", "format", "num_days"],
... },
... },
... },
... ]
>>> response = client.chat_completion(
... model="meta-llama/Meta-Llama-3-70B-Instruct",
... messages=messages,
... tools=tools,
... tool_choice="auto",
... max_tokens=500,
... )
>>> response.choices[0].message.tool_calls[0].function
ChatCompletionOutputFunctionDefinition(
arguments={
'location': 'San Francisco, CA',
'format': 'fahrenheit',
'num_days': 3
},
name='get_n_day_weather_forecast',
description=None
)
使用 response_format 的示例
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
... {
... "role": "user",
... "content": "I saw a puppy a cat and a raccoon during my bike ride in the park. What did I saw 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"}'
文档问答
< 来源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] question: str model: typing.Optional[str] = None doc_stride: typing.Optional[int] = None handle_impossible_answer: typing.Optional[bool] = None lang: typing.Optional[str] = None max_answer_len: typing.Optional[int] = None max_question_len: typing.Optional[int] = None max_seq_len: typing.Optional[int] = None top_k: typing.Optional[int] = None word_boxes: typing.Optional[typing.List[typing.Union[typing.List[float], str]]] = None ) → List[DocumentQuestionAnsweringOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO]
) — 上下文的输入图像。可以是原始字节、图像文件或在线图像的 URL。 - question (
str
) — 要回答的问题。 - model (
str
, 可选) — 用于文档问答任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的文档问答模型。默认为 None。 - doc_stride (
int
, 可选) — 如果文档中的单词太长,无法与模型的问题一起容纳,它将被分割成几个带有重叠的块。此参数控制重叠的大小。 - handle_impossible_answer (
bool
, 可选) — 是否接受“不可能”作为答案。 - lang (
str
, 可选) — 运行 OCR 时使用的语言。默认为英语。 - 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]
包含预测标签、相关概率、单词 ID 和页码的 DocumentQuestionAnsweringOutputElement 项列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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 normalize: typing.Optional[bool] = None prompt_name: typing.Optional[str] = None truncate: typing.Optional[bool] = None truncation_direction: typing.Optional[typing.Literal['Left', 'Right']] = None model: typing.Optional[str] = None ) → np.ndarray
参数
- text (str) — 要嵌入的文本。
- model (str, 可选) — 用于特征提取任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的特征提取模型。默认为 None。
- normalize (bool, 可选) — 是否对嵌入进行归一化。仅适用于由 Text-Embedding-Inference 提供支持的服务器。
- prompt_name (str, 可选) — 编码时应使用的提示名称。如果未设置,将不应用任何提示。必须是 *Sentence Transformers* 配置 *prompts* 字典中的键。例如,如果
prompt_name
是“query”且prompts
是 {“query”: “query: ”,…},则句子“What is the capital of France?” 将被编码为“query: What is the capital of France?”,因为提示文本将预先添加到要编码的任何文本之前。 - truncate (bool, 可选) — 是否截断嵌入。仅适用于由 Text-Embedding-Inference 提供支持的服务器。
- truncation_direction (Literal[“Left”, “Right”], 可选) — 当传入 *truncate=True* 时,输入的哪一侧应被截断。
返回
np.ndarray
表示输入文本的嵌入,为 float32 numpy 数组。
引发
[InferenceTimeoutError] 或 HTTPError
- [InferenceTimeoutError] — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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)
填补掩码
< 源 >( text: str model: typing.Optional[str] = None targets: typing.Optional[typing.List[str]] = None top_k: typing.Optional[int] = None ) → List[FillMaskOutputElement]
参数
- text (
str
) — 要填充的字符串,必须包含 [MASK] 标记(检查模型卡以获取掩码的确切名称)。 - model (
str
, 可选) — 用于填补掩码任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的填补掩码模型。 - targets (
List[str
, 可选) — 传入时,模型将分数限制在传入的目标上,而不是在整个词汇表中查找。如果提供的目标不在模型词汇表中,它们将被分词,并将使用第一个生成的 token(带有警告,并且可能会较慢)。 - top_k (
int
, 可选) — 传入时,覆盖要返回的预测数量。
返回
List[FillMaskOutputElement]
包含预测标签、相关概率、token 引用和完成文本的 FillMaskOutputElement 项列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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.')
]
获取端点信息
< 源 >( model: typing.Optional[str] = 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: typing.Optional[str] = None ) → ModelStatus
参数
- model (
str
, 可选) — 要检查其状态的模型标识符。如果未提供模型,将使用与此 InferenceClient 实例关联的模型。只能检查 HF Inference API 服务,因此标识符不能是 URL。
返回
ModelStatus
ModelStatus 数据类的一个实例,包含模型状态信息:加载、状态、计算类型和框架。
获取托管在 HF Inference API 上的模型的状态。
此端点主要在您已经知道要使用的模型并想检查其可用性时有用。如果您想发现已部署的模型,则应使用 list_deployed_models()。
健康检查
< 源 >( model: typing.Optional[str] = None ) → bool
检查已部署端点的健康状况。
健康检查仅适用于由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 提供支持的推理端点。对于推理 API,请改用 InferenceClient.get_model_status()。
图像分类
< 源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None function_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = None top_k: typing.Optional[int] = None ) → List[ImageClassificationOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要分类的图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
, 可选) — 用于图像分类的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的图像分类模型。 - function_to_apply (
"ImageClassificationOutputTransform"
, 可选) — 要应用于模型输出以检索分数的函数。 - top_k (
int
, 可选) — 指定时,将输出限制为最有可能的前 K 个类别。
返回
List[ImageClassificationOutputElement]
包含预测标签和相关概率的 ImageClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
使用指定模型对给定图像执行图像分类。
图像分割
< 源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None mask_threshold: typing.Optional[float] = None overlap_mask_area_threshold: typing.Optional[float] = None subtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = None threshold: typing.Optional[float] = None ) → List[ImageSegmentationOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要分割的图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
, optional) — 用于图像分割的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用图像分割的默认推荐模型。 - mask_threshold (
float
, optional) — 将预测的掩码转换为二进制值时使用的阈值。 - overlap_mask_area_threshold (
float
, optional) — 用于消除小而不连贯的分割区域的掩码重叠阈值。 - subtask (
"ImageSegmentationSubtask"
, optional) — 要执行的分割任务,取决于模型功能。 - threshold (
float
, optional) — 用于过滤预测掩码的概率阈值。
返回
List[ImageSegmentationOutputElement]
包含分割掩码和相关属性的 ImageSegmentationOutputElement 列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
使用指定的模型对给定图像执行图像分割。
如果您想处理图像,必须安装 `PIL` (`pip install Pillow`)。
图像到图像
< 源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] prompt: typing.Optional[str] = None negative_prompt: typing.Optional[str] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None model: typing.Optional[str] = None target_size: typing.Optional[huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize] = None **kwargs ) → Image
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 用于转换的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - prompt (
str
, optional) — 用于指导图像生成的文本提示。 - negative_prompt (
str
, optional) — 一个提示,用于指导图像生成中不应包含的内容。 - num_inference_steps (
int
, optional) — 对于扩散模型。去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - guidance_scale (
float
, optional) — 对于扩散模型。更高的指导尺度值会鼓励模型生成与文本提示紧密相关的图像,但图像质量会降低。 - model (
str
, optional) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数会覆盖实例级别定义_的_模型。默认为 None。 - target_size (
ImageToImageTargetSize
, optional) — 输出图像的像素大小。
返回
图像
转换后的图像。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
使用指定模型执行图像到图像的转换。
如果您想处理图像,必须安装 `PIL` (`pip install Pillow`)。
图像到文本
< 源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None ) → ImageToTextOutput
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要添加字幕的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
, optional) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数会覆盖实例级别定义_的_模型。默认为 None。
生成的文本。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None prompt: typing.Optional[str] = None negative_prompt: typing.Optional[str] = None num_frames: typing.Optional[float] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None seed: typing.Optional[int] = None target_size: typing.Optional[huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize] = None **kwargs ) → bytes
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 用于生成视频的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
, optional) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数会覆盖实例级别定义_的_模型。默认为 None。 - prompt (
str
, optional) — 用于指导视频生成的文本提示。 - negative_prompt (
str
, optional) — 一个提示,用于指导视频生成中不应包含的内容。 - num_frames (
float
, optional) — `num_frames` 参数决定生成多少视频帧。 - num_inference_steps (
int
, optional) — 对于扩散模型。去噪步数。更多的去噪步数通常会带来更高质量的视频,但推理速度会变慢。 - guidance_scale (
float
, optional) — 对于扩散模型。更高的指导尺度值会鼓励模型生成与文本提示紧密相关的视频,但图像质量会降低。 - seed (
int
, optional) — 用于视频生成的种子。 - target_size (
ImageToVideoTargetSize
, optional) — 输出视频帧的像素大小。 - num_inference_steps (
int
, optional) — 去噪步数。更多的去噪步数通常会带来更高质量的视频,但推理速度会变慢。 - seed (
int
, optional) — 随机数生成器的种子。
返回
字节
生成的视频。
从输入图像生成视频。
列出已部署的模型
< 源 >( frameworks: typing.Union[NoneType, str, typing.Literal['all'], typing.List[str]] = None ) → Dict[str, List[str]]
列出部署在 HF Serverless Inference API 服务上的模型。
此帮助程序逐框架检查已部署的模型。默认情况下,它将检查支持的 4 个主要框架,这些框架占托管模型的 95%。但是,如果您想要一个完整的模型列表,可以将 `frameworks` 设置为“all”作为输入。或者,如果您事先知道您对哪个框架感兴趣,您也可以将搜索限制在该框架(例如 `frameworks="text-generation-inference"`)。检查的框架越多,所需时间就越长。
此端点方法不返回 HF Inference API 服务可用的所有模型的实时列表。它搜索最近可用的模型缓存列表,该列表可能不是最新的。如果您想了解特定模型的实时状态,请使用 get_model_status()。
此端点方法主要用于发现。如果您已经知道要使用的模型并想检查其可用性,可以直接使用 get_model_status()。
示例
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
# Discover zero-shot-classification models currently deployed
>>> models = client.list_deployed_models()
>>> models["zero-shot-classification"]
['Narsil/deberta-large-mnli-zero-cls', 'facebook/bart-large-mnli', ...]
# List from only 1 framework
>>> client.list_deployed_models("text-generation-inference")
{'text-generation': ['bigcode/starcoder', 'meta-llama/Llama-2-70b-chat-hf', ...], ...}
对象检测
< 源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None threshold: typing.Optional[float] = None ) → List[ObjectDetectionOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要检测对象的图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
, optional) — 用于对象检测的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的对象检测模型(DETR)。 - threshold (
float
, optional) — 进行预测所需的概率。
返回
List[ObjectDetectionOutputElement]
包含边界框和相关属性的 ObjectDetectionOutputElement 列表。
引发
InferenceTimeoutError 或 HTTPError
或 ValueError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。ValueError
— 如果请求输出不是列表。
使用指定的模型对给定图像执行对象检测。
如果您想处理图像,必须安装 `PIL` (`pip install Pillow`)。
问答
< 源 >( question: str context: str model: typing.Optional[str] = None align_to_words: typing.Optional[bool] = None doc_stride: typing.Optional[int] = None handle_impossible_answer: typing.Optional[bool] = None max_answer_len: typing.Optional[int] = None max_question_len: typing.Optional[int] = None max_seq_len: typing.Optional[int] = None top_k: typing.Optional[int] = None ) → Union[QuestionAnsweringOutputElement
, ListQuestionAnsweringOutputElement]
参数
- question (
str
) — 要回答的问题。 - context (
str
) — 问题的上下文。 - model (
str
) — 用于问答任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。 - align_to_words (
bool
, optional) — 尝试将答案与实际单词对齐。可提高空格分隔语言的质量。可能会损害非空格分隔语言(如日语或中文)的质量。 - doc_stride (
int
, optional) — 如果上下文太长,无法与模型的问题匹配,它将被分成几个有重叠的块。此参数控制重叠的大小。 - handle_impossible_answer (
bool
, optional) — 是否接受不可能的答案。 - max_answer_len (
int
, optional) — 预测答案的最大长度(例如,只考虑较短长度的答案)。 - max_question_len (
int
, optional) — 分词后问题的最大长度。如果需要,将被截断。 - max_seq_len (
int
, optional) — 传递给模型的每个块中总句子(上下文 + 问题)的最大标记长度。如果需要,上下文将分为几个块(使用 docStride 作为重叠)。 - top_k (
int
, optional) — 要返回的答案数量(将按可能性顺序选择)。请注意,如果上下文内没有足够的可用选项,我们将返回少于 topk 的答案。
返回
Union[QuestionAnsweringOutputElement
, ListQuestionAnsweringOutputElement]
当 top_k 为 1 或未提供时,返回单个 QuestionAnsweringOutputElement
。当 top_k 大于 1 时,返回 QuestionAnsweringOutputElement
列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
从给定文本中检索问题的答案。
句子相似度
< 源 >( sentence: str other_sentences: typing.List[str] model: typing.Optional[str] = None ) → List[float]
参数
- sentence (
str
) — 要与其他句子进行比较的主要句子。 - other_sentences (
List[str]
) — 要比较的句子列表。 - model (
str
, optional) — 用于句子相似度任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的句子相似度模型。默认为 None。
返回
List[float]
表示输入文本的嵌入。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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: str model: typing.Optional[str] = None clean_up_tokenization_spaces: typing.Optional[bool] = None generate_parameters: typing.Optional[typing.Dict[str, typing.Any]] = None truncation: typing.Optional[ForwardRef('SummarizationTruncationStrategy')] = None ) → SummarizationOutput
参数
- text (
str
) — 要总结的输入文本。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的摘要模型。 - clean_up_tokenization_spaces (
bool
, 可选) — 是否清除文本输出中可能存在的额外空格。 - generate_parameters (
Dict[str, Any]
, 可选) — 文本生成算法的额外参数设置。 - truncation (
"SummarizationTruncationStrategy"
, 可选) — 要使用的截断策略。
生成的摘要文本。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
使用指定模型生成给定文本的摘要。
table_question_answering
< 来源 >( table: typing.Dict[str, typing.Any] query: str model: typing.Optional[str] = None padding: typing.Optional[ForwardRef('Padding')] = None sequential: typing.Optional[bool] = None truncation: typing.Optional[bool] = None ) → TableQuestionAnsweringOutputElement
参数
- table (
str
) — 以列表字典表示的数据表,其中条目是标题,列表是所有值,所有列表必须具有相同的大小。 - query (
str
) — 你想向表格提出的纯文本查询。 - model (
str
) — 用于表格问答任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。 - padding (
"Padding"
, 可选) — 激活和控制填充。 - sequential (
bool
, 可选) — 是顺序推理还是批量推理。批量推理更快,但像 SQA 这样的模型需要顺序推理才能在序列中提取关系,因为它们具有对话性质。 - truncation (
bool
, 可选) — 激活和控制截断。
一个表格问答输出,包含答案、坐标、单元格和使用的聚合器。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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')
tabular_classification
< 来源 >( table: typing.Dict[str, typing.Any] model: typing.Optional[str] = None ) → List
参数
- table (
Dict[str, Any]
) — 要分类的属性集。 - model (
str
, 可选) — 用于表格分类任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的表格分类模型。默认为 None。
返回
List
标签列表,每行一个,与初始表格中的行对应。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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"]
tabular_regression
< 来源 >( table: typing.Dict[str, typing.Any] model: typing.Optional[str] = None ) → List
参数
- table (
Dict[str, Any]
) — 存储在表格中的属性集。用于预测目标的属性可以是数值型和类别型。 - model (
str
, 可选) — 用于表格回归任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的表格回归模型。默认为 None。
返回
List
预测的数值目标值列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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_classification
< 来源 >( text: str model: typing.Optional[str] = None top_k: typing.Optional[int] = None function_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None ) → List[TextClassificationOutputElement]
参数
- text (
str
) — 要分类的字符串。 - model (
str
, 可选) — 用于文本分类任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的文本分类模型。默认为 None。 - top_k (
int
, 可选) — 指定时,将输出限制为最有可能的前 K 个类别。 - function_to_apply (
"TextClassificationOutputTransform"
, 可选) — 应用于模型输出以检索分数的函数。
返回
List[TextClassificationOutputElement]
包含预测标签和相关概率的 TextClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
对给定文本执行文本分类(例如情感分析)。
text_generation
< 来源 >( prompt: str details: typing.Optional[bool] = None stream: typing.Optional[bool] = None model: typing.Optional[str] = None adapter_id: typing.Optional[str] = None best_of: typing.Optional[int] = None decoder_input_details: typing.Optional[bool] = None do_sample: typing.Optional[bool] = None frequency_penalty: typing.Optional[float] = None grammar: typing.Optional[huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType] = None max_new_tokens: typing.Optional[int] = None repetition_penalty: typing.Optional[float] = None return_full_text: typing.Optional[bool] = None seed: typing.Optional[int] = None stop: typing.Optional[typing.List[str]] = None stop_sequences: typing.Optional[typing.List[str]] = None temperature: typing.Optional[float] = None top_k: typing.Optional[int] = None top_n_tokens: typing.Optional[int] = None top_p: typing.Optional[float] = None truncate: typing.Optional[int] = None typical_p: typing.Optional[float] = None watermark: typing.Optional[bool] = None ) → Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]
参数
- prompt (
str
) — 输入文本。 - details (
bool
, 可选) — 默认情况下,text_generation 返回一个字符串。如果您想要详细输出(标记、概率、种子、结束原因等),请传递details=True
。仅适用于运行text-generation-inference
后端的模型。 - stream (
bool
, 可选) — 默认情况下,text_generation 返回完整的生成文本。如果您希望以流式方式返回标记,请传递stream=True
。仅适用于运行text-generation-inference
后端的模型。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数会覆盖实例级别定义的模型。默认为 None。 - adapter_id (
str
, 可选) — Lora 适配器 ID。 - best_of (
int
, 可选) — 生成最佳序列,并返回具有最高标记对数概率的序列。 - decoder_input_details (
bool
, 可选) — 返回解码器输入标记的对数概率和 ID。您还必须将details=True
设置为才能考虑在内。默认为False
。 - do_sample (
bool
, 可选) — 激活 logits 采样 - frequency_penalty (
float
, 可选) — 介于 -2.0 和 2.0 之间的数字。正值根据新标记在文本中已有的频率对其进行惩罚,从而降低模型逐字重复相同行的可能性。 - grammar (TextGenerationInputGrammarType, 可选) — 语法约束。可以是 JSONSchema 或正则表达式。
- max_new_tokens (
int
, 可选) — 生成的最大标记数。默认为 100。 - repetition_penalty (
float
, 可选) — 重复惩罚的参数。1.0 表示无惩罚。有关更多详细信息,请参阅这篇论文。 - return_full_text (
bool
, 可选) — 是否在生成文本前加上提示。 - seed (
int
, 可选) — 随机采样种子 - stop (
List[str]
, 可选) — 如果生成了stop
中的成员,则停止生成标记。 - stop_sequences (
List[str]
, 可选) — 已弃用的参数。请改用stop
。 - temperature (
float
, 可选) — 用于调整 logits 分布的值。 - top_n_tokens (
int
, 可选) — 返回每个生成步骤中最有可能的top_n_tokens
个标记的信息,而不是仅仅采样标记。 - top_k (
int
, *可选`) — 用于 top-k 过滤的最高概率词汇标记数。 - top_p (
float
, *可选`) -- 如果设置为 < 1,则仅保留最小的、概率总和为top_p
或更高的最可能标记集用于生成。 - 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]
形式逐个标记返回 - 如果
stream=False
且details=True
,则生成文本以 TextGenerationOutput 形式返回更多详细信息 - 如果
details=True
且stream=True
,则生成文本以 TextGenerationStreamOutput 的可迭代形式逐个标记返回
引发
ValidationError
或 InferenceTimeoutError 或 HTTPError
ValidationError
— 如果输入值无效。不对服务器进行 HTTP 调用。- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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: str negative_prompt: typing.Optional[str] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None model: typing.Optional[str] = None scheduler: typing.Optional[str] = None seed: typing.Optional[int] = None extra_body: typing.Optional[typing.Dict[str, typing.Any]] = None ) → Image
参数
- prompt (
str
) — 用于生成图像的提示语。 - negative_prompt (
str
, 可选) — 用于指导图像生成中不应包含内容的提示语。 - height (
int
, 可选) — 输出图像的高度(像素)。 - width (
int
, 可选) — 输出图像的宽度(像素)。 - num_inference_steps (
int
, 可选) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但推理速度会变慢。 - guidance_scale (
float
, 可选) — 较高的指导尺度值鼓励模型生成与文本提示紧密相关的图像,但过高的值可能会导致饱和和其他伪影。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的文本到图像模型。默认为 None。 - scheduler (
str
, 可选) — 用兼容的调度器覆盖。 - seed (
int
, 可选) — 随机数生成器的种子。 - extra_body (
Dict[str, Any]
, 可选) — 要传递给模型的其他提供商特定参数。有关支持的参数,请参阅提供商的文档。
返回
图像
生成的图像。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
根据给定文本使用指定模型生成图像。
如果您想处理图像,必须安装 `PIL` (`pip install Pillow`)。
示例
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> image = client.text_to_image("An astronaut riding a horse on the moon.")
>>> image.save("astronaut.png")
>>> image = client.text_to_image(
... "An astronaut riding a horse on the moon.",
... negative_prompt="low resolution, blurry",
... model="stabilityai/stable-diffusion-2-1",
... )
>>> image.save("better_astronaut.png")
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="fal-ai", # Use fal.ai provider
... api_key="fal-ai-api-key", # Pass your fal.ai API key
... )
>>> image = client.text_to_image(
... "A majestic lion in a fantasy forest",
... model="black-forest-labs/FLUX.1-schnell",
... )
>>> image.save("lion.png")
通过 Hugging Face 路由使用第三方提供方的示例。使用费用将计入您的 Hugging Face 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate", # Use replicate provider
... api_key="hf_...", # Pass your HF token
... )
>>> image = client.text_to_image(
... "An astronaut riding a horse on the moon.",
... model="black-forest-labs/FLUX.1-dev",
... )
>>> image.save("astronaut.png")
使用 Replicate 提供商和额外参数的示例
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate", # Use replicate provider
... api_key="hf_...", # Pass your HF token
... )
>>> image = client.text_to_image(
... "An astronaut riding a horse on the moon.",
... model="black-forest-labs/FLUX.1-schnell",
... extra_body={"output_quality": 100},
... )
>>> image.save("astronaut.png")
文本转语音
< 来源 >( text: str model: typing.Optional[str] = None do_sample: typing.Optional[bool] = None early_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None epsilon_cutoff: typing.Optional[float] = None eta_cutoff: typing.Optional[float] = None max_length: typing.Optional[int] = None max_new_tokens: typing.Optional[int] = None min_length: typing.Optional[int] = None min_new_tokens: typing.Optional[int] = None num_beam_groups: typing.Optional[int] = None num_beams: typing.Optional[int] = None penalty_alpha: typing.Optional[float] = None temperature: typing.Optional[float] = None top_k: typing.Optional[int] = None top_p: typing.Optional[float] = None typical_p: typing.Optional[float] = None use_cache: typing.Optional[bool] = None extra_body: typing.Optional[typing.Dict[str, typing.Any]] = None ) → bytes
参数
- text (
str
) — 要合成的文本。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的文本到语音模型。默认为 None。 - do_sample (
bool
, 可选) — 生成新令牌时是否使用采样而不是贪婪解码。 - early_stopping (
Union[bool, "TextToSpeechEarlyStoppingEnum"]
, 可选) — 控制基于束的方法的停止条件。 - epsilon_cutoff (
float
, 可选) — 如果设置为严格介于 0 和 1 之间的浮点数,则仅对条件概率大于 epsilon_cutoff 的令牌进行采样。在论文中,建议的值范围为 3e-4 到 9e-4,具体取决于模型的大小。有关更多详细信息,请参阅 截断采样作为语言模型去平滑。 - eta_cutoff (
float
, 可选) — Eta 采样是局部典型采样和 epsilon 采样的混合。如果设置为严格介于 0 和 1 之间的浮点数,则仅当令牌大于 eta_cutoff 或 sqrt(eta_cutoff)- exp(-entropy(softmax(next_token_logits))) 时才考虑该令牌。后一项直观地讲是预期下一个令牌的概率,由 sqrt(eta_cutoff) 缩放。在论文中,建议的值范围为 3e-4 到 2e-3,具体取决于模型的大小。有关更多详细信息,请参阅 截断采样作为语言模型去平滑。
- max_length (
int
, 可选) — 生成文本的最大长度(以令牌为单位),包括输入。 - max_new_tokens (
int
, 可选) — 要生成的最大令牌数。优先于 max_length。 - min_length (
int
, 可选) — 生成文本的最小长度(以令牌为单位),包括输入。 - min_new_tokens (
int
, 可选) — 要生成的最小令牌数。优先于 min_length。 - num_beam_groups (
int
, 可选) — 将 num_beams 分组的数量,以确保不同束组之间的多样性。有关更多详细信息,请参阅 此论文。 - num_beams (
int
, 可选) — 用于束搜索的束数。 - penalty_alpha (
float
, 可选) — 该值平衡了模型置信度和对比搜索解码中的退化惩罚。 - temperature (
float
, 可选) — 用于调整下一个令牌概率的值。 - top_k (
int
, 可选) — 保留用于 top-k 过滤的最高概率词汇令牌的数量。 - top_p (
float
, 可选) — 如果设置为小于 1 的浮点数,则仅保留概率总和达到或超过 top_p 的最小概率最高令牌集用于生成。 - typical_p (
float
, 可选) — 局部典型性衡量了在给定已生成的部分文本的情况下,预测下一个目标令牌的条件概率与预测下一个随机令牌的预期条件概率的相似程度。如果设置为小于 1 的浮点数,则保留局部最典型的令牌的最小集合,其概率总和达到或超过 typical_p 用于生成。有关更多详细信息,请参阅 此论文。 - use_cache (
bool
, 可选) — 模型是否应使用过去的最后键/值注意力来加速解码。 - extra_body (
Dict[str, Any]
, 可选) — 要传递给模型的其他提供商特定参数。有关支持的参数,请参阅提供商的文档。
返回
字节
生成的音频。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
合成给定文本的语音音频。
示例
>>> from pathlib import Path
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> audio = client.text_to_speech("Hello world")
>>> Path("hello_world.flac").write_bytes(audio)
直接使用第三方提供商的示例。使用费用将在您的 Replicate 账户中扣除。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate",
... api_key="your-replicate-api-key", # Pass your Replicate API key directly
... )
>>> audio = client.text_to_speech(
... text="Hello world",
... model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
通过 Hugging Face 路由使用第三方提供方的示例。使用费用将计入您的 Hugging Face 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate",
... api_key="hf_...", # Pass your HF token
... )
>>> audio =client.text_to_speech(
... text="Hello world",
... model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate", # Use replicate provider
... api_key="hf_...", # Pass your HF token
... )
>>> audio = client.text_to_speech(
... "Hello, my name is Kororo, an awesome text-to-speech model.",
... model="hexgrad/Kokoro-82M",
... extra_body={"voice": "af_nicole"},
... )
>>> Path("hello.flac").write_bytes(audio)
在 fal.ai 上使用“YuE-s1-7B-anneal-en-cot”生成音乐的示例
>>> 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)
文本转视频
< 来源 >( prompt: str model: typing.Optional[str] = None guidance_scale: typing.Optional[float] = None negative_prompt: typing.Optional[typing.List[str]] = None num_frames: typing.Optional[float] = None num_inference_steps: typing.Optional[int] = None seed: typing.Optional[int] = None extra_body: typing.Optional[typing.Dict[str, typing.Any]] = None ) → bytes
参数
- prompt (
str
) — 用于从文本生成视频的提示。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的文本到视频模型。默认为 None。 - guidance_scale (
float
, 可选) — 较高的指导尺度值鼓励模型生成与文本提示紧密相关的视频,但过高的值可能会导致饱和和其他伪影。 - negative_prompt (
List[str]
, 可选) — 用于指导视频生成中不应包含内容的一个或多个提示。 - num_frames (
float
, 可选) — num_frames 参数决定生成多少视频帧。 - num_inference_steps (
int
, 可选) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的视频,但推理速度会变慢。 - seed (
int
, 可选) — 随机数生成器的种子。 - extra_body (
Dict[str, Any]
, 可选) — 要传递给模型的其他提供商特定参数。有关支持的参数,请参阅提供商的文档。
返回
字节
生成的视频。
根据给定文本生成视频。
示例
直接使用第三方提供商的示例。使用费用将在您的 fal.ai 账户中扣除。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="fal-ai", # Using fal.ai provider
... api_key="fal-ai-api-key", # Pass your fal.ai API key
... )
>>> video = client.text_to_video(
... "A majestic lion running in a fantasy forest",
... model="tencent/HunyuanVideo",
... )
>>> with open("lion.mp4", "wb") as file:
... file.write(video)
通过 Hugging Face 路由使用第三方提供方的示例。使用费用将计入您的 Hugging Face 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate", # Using replicate provider
... api_key="hf_...", # Pass your HF token
... )
>>> video = client.text_to_video(
... "A cat running in a park",
... model="genmo/mochi-1-preview",
... )
>>> with open("cat.mp4", "wb") as file:
... file.write(video)
令牌分类
< 来源 >( text: str model: typing.Optional[str] = None aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None ignore_labels: typing.Optional[typing.List[str]] = None stride: typing.Optional[int] = None ) → List[TokenClassificationOutputElement]
参数
- text (
str
) — 要分类的字符串。 - model (
str
, 可选) — 用于令牌分类任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的令牌分类模型。默认为 None。 - aggregation_strategy (
"TokenClassificationAggregationStrategy"
, 可选) — 根据模型预测合并令牌的策略 - ignore_labels (
List[str
, 可选) — 要忽略的标签列表 - stride (
int
, 可选) — 分割输入文本时块之间的重叠令牌数。
返回
列表[TokenClassificationOutputElement]
包含实体组、置信度分数、单词、开始和结束索引的 TokenClassificationOutputElement 列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 HTTP 错误状态代码(HTTP 503 除外)。
对给定文本执行令牌分类。通常用于句子解析,无论是语法解析,还是命名实体识别 (NER) 以理解文本中包含的关键词。
示例
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.token_classification("My name is Sarah Jessica Parker but you can call me Jessica")
[
TokenClassificationOutputElement(
entity_group='PER',
score=0.9971321225166321,
word='Sarah Jessica Parker',
start=11,
end=31,
),
TokenClassificationOutputElement(
entity_group='PER',
score=0.9773476123809814,
word='Jessica',
start=52,
end=59,
)
]
翻译
< 来源 >( text: str model: typing.Optional[str] = None src_lang: typing.Optional[str] = None tgt_lang: typing.Optional[str] = None clean_up_tokenization_spaces: typing.Optional[bool] = None truncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = None generate_parameters: typing.Optional[typing.Dict[str, typing.Any]] = None ) → TranslationOutput
参数
- text (
str
) — 要翻译的字符串。 - model (
str
, 可选) — 用于翻译任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的翻译模型。默认为 None。 - src_lang (
str
, 可选) — 文本的源语言。对于可以从多种语言翻译的模型是必需的。 - tgt_lang (
str
, 可选) — 目标翻译语言。对于可以翻译成多种语言的模型是必需的。 - clean_up_tokenization_spaces (
bool
, 可选) — 是否清除文本输出中可能存在的额外空格。 - truncation (
"TranslationTruncationStrategy"
, 可选) — 要使用的截断策略。 - generate_parameters (
Dict[str, Any]
, 可选) — 文本生成算法的附加参数。
生成的翻译文本。
引发
InferenceTimeoutError 或 HTTPError
或 ValueError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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.')
视觉问答
< 来源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] question: str model: typing.Optional[str] = None top_k: typing.Optional[int] = None ) → List[VisualQuestionAnsweringOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 上下文的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - question (
str
) — 要回答的问题。 - model (
str
, 可选) — 用于视觉问答任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的视觉问答模型。默认为 None。 - top_k (
int
, 可选) — 返回的答案数量(将按可能性顺序选择)。请注意,如果上下文中没有足够的选项,我们将返回少于 topk 的答案。
返回
List[VisualQuestionAnsweringOutputElement]
包含预测标签和相关概率的 VisualQuestionAnsweringOutputElement 项目列表。
引发
InferenceTimeoutError
或 HTTPError
InferenceTimeoutError
— 如果模型不可用或请求超时。HTTPError
— 如果请求失败并返回 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'),
]
零样本分类
< source 来源 >( text: str candidate_labels: typing.List[str] multi_label: typing.Optional[bool] = False hypothesis_template: typing.Optional[str] = None model: typing.Optional[str] = None ) → List[ZeroShotClassificationOutputElement]
参数
- text (
str
) — 要分类的输入文本。 - candidate_labels (
List[str]
) — 用于将文本分类为可能的类别标签集。 - labels (
List[str]
, 可选) — (已弃用) 字符串列表。每个字符串都是输入文本可能标签的口语化表达。 - multi_label (
bool
, 可选) — 多个候选标签是否可以为真。如果为 false,则分数将被归一化,使得每个序列的标签可能性之和为 1。如果为 true,则标签被认为是独立的,并且每个候选的概率都被归一化。 - hypothesis_template (
str
, 可选) — 与candidate_labels
结合使用的句子,通过将占位符替换为候选标签来尝试文本分类。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。此参数会覆盖实例级别定义的模型。如果未提供,将使用默认推荐的零样本分类模型。
返回
List[ZeroShotClassificationOutputElement]
包含预测标签及其置信度的 ZeroShotClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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.",
... 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)
]
零样本图像分类
< source 来源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] candidate_labels: typing.List[str] model: typing.Optional[str] = None hypothesis_template: typing.Optional[str] = None labels: typing.List[str] = None ) → List[ZeroShotImageClassificationOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要添加字幕的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - candidate_labels (
List[str]
) — 此图像的候选标签 - labels (
List[str]
, 可选) — (已弃用) 字符串列表,每个字符串都是可能的标签。必须至少有 2 个标签。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。此参数会覆盖实例级别定义的模型。如果未提供,将使用默认推荐的零样本图像分类模型。 - hypothesis_template (
str
, 可选) — 与candidate_labels
结合使用的句子,通过将占位符替换为候选标签来尝试图像分类。
返回
List[ZeroShotImageClassificationOutputElement]
包含预测标签及其置信度的 ZeroShotImageClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 HTTPError
- InferenceTimeoutError — 如果模型不可用或请求超时。
HTTPError
— 如果请求失败并返回 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",
... labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]
异步推理客户端
还提供了一个基于 asyncio
和 aiohttp
的异步客户端版本。要使用它,您可以直接安装 aiohttp
或使用 [inference]
额外包
pip install --upgrade huggingface_hub[inference]
# or
# pip install aiohttp
class huggingface_hub.AsyncInferenceClient
< source 来源 >( model: typing.Optional[str] = None provider: typing.Union[typing.Literal['black-forest-labs', 'cerebras', 'cohere', 'fal-ai', 'featherless-ai', 'fireworks-ai', 'groq', 'hf-inference', 'hyperbolic', 'nebius', 'novita', 'nscale', 'openai', 'replicate', 'sambanova', 'together'], typing.Literal['auto'], NoneType] = None token: typing.Optional[str] = None timeout: typing.Optional[float] = None headers: typing.Optional[typing.Dict[str, str]] = None cookies: typing.Optional[typing.Dict[str, str]] = None trust_env: bool = False proxies: typing.Optional[typing.Any] = None bill_to: typing.Optional[str] = None base_url: typing.Optional[str] = None api_key: typing.Optional[str] = None )
参数
- model (
str
,可选
) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,例如meta-llama/Meta-Llama-3-8B-Instruct
,也可以是已部署推理端点的 URL。默认为 None,在这种情况下,将自动为任务选择推荐的模型。注意:为了更好地与 OpenAI 的客户端兼容,model
已被别名为base_url
。这两个参数是互斥的。如果将 URL 作为model
或base_url
传递给聊天完成,则(/v1)/chat/completions
后缀路径将附加到 URL。 - provider (
str
, 可选) — 用于推理的提供商名称。可以是"black-forest-labs"
,"cerebras"
,"cohere"
,"fal-ai"
,"featherless-ai"
,"fireworks-ai"
,"groq"
,"hf-inference"
,"hyperbolic"
,"nebius"
,"novita"
,"nscale"
,"openai"
,"replicate"
, “sambanova” 或 “together” 。默认为 “auto”,即模型可用提供商中的第一个,按用户在 https://huggingface.co/settings/inference-providers 中的顺序排序。如果 model 是 URL 或base_url
已传递,则不使用provider
。 - token (
str
, 可选) — Hugging Face 令牌。如果未提供,将默认为本地保存的令牌。注意:为了更好地与 OpenAI 的客户端兼容,token
已被别名为api_key
。这两个参数是互斥的,并且具有完全相同的行为。 - timeout (
float
,可选
) — 等待服务器响应的最大秒数。默认为 None,表示将循环直到服务器可用。 - headers (
Dict[str, str]
,可选
) — 发送到服务器的附加标头。默认情况下,只发送授权和用户代理标头。此字典中的值将覆盖默认值。 - bill_to (
str
,可选
) — 用于请求的计费账户。默认情况下,请求计费到用户的账户。请求只能计费到用户是其成员的组织,并且该组织已订阅企业中心。 - cookies (
Dict[str, str]
,可选
) — 发送到服务器的附加 Cookie。 - trust_env (
bool
,可选
) — 如果参数为True
(默认为False
),则信任代理配置的环境设置。 - proxies (
Any
,可选
) — 用于请求的代理。 - base_url (
str
,可选
) — 用于推理的基础 URL。这是model
的重复参数,旨在使 InferenceClient 遵循与openai.OpenAI
客户端相同的模式。不能与model
同时设置。默认为 None。 - api_key (
str
,可选
) — 用于身份验证的令牌。这是token
的重复参数,旨在使 InferenceClient 遵循与openai.OpenAI
客户端相同的模式。不能与token
同时设置。默认为 None。
初始化新的推理客户端。
InferenceClient 旨在提供统一的推理体验。客户端可以无缝地与(免费的)推理 API、自托管推理端点或第三方推理提供商一起使用。
音频分类
< source 来源 >( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None top_k: typing.Optional[int] = None function_to_apply: typing.Optional[ForwardRef('AudioClassificationOutputTransform')] = None ) → List[AudioClassificationOutputElement]
参数
- audio (Union[str, Path, bytes, BinaryIO]) — 要分类的音频内容。可以是原始音频字节、本地音频文件或指向音频文件的 URL。
- model (
str
, 可选) — 用于音频分类的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的音频分类模型。 - top_k (
int
, 可选) — 指定时,将输出限制为最有可能的前 K 个类别。 - function_to_apply (
"AudioClassificationOutputTransform"
, 可选) — 应用于模型输出以检索分数的功能。
返回
List[AudioClassificationOutputElement]
包含预测标签及其置信度的 AudioClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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'),
...
]
音频到音频
< source 来源 >( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None ) → List[AudioToAudioOutputElement]
参数
- audio (Union[str, Path, bytes, BinaryIO]) — 模型的音频内容。可以是原始音频字节、本地音频文件或指向音频文件的 URL。
- model (
str
, 可选) — 该模型可以是任何接受音频文件并返回另一个音频文件的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的 audio_to_audio 模型。
返回
List[AudioToAudioOutputElement]
包含音频标签、内容类型和 blob 中的音频内容的 AudioToAudioOutputElement 项列表。
引发
InferenceTimeoutError
或 aiohttp.ClientResponseError
InferenceTimeoutError
— 如果模型不可用或请求超时。aiohttp.ClientResponseError
— 如果请求失败并返回 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)
自动语音识别
< source 来源 >( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None extra_body: typing.Optional[typing.Dict] = None ) → AutomaticSpeechRecognitionOutput
参数
- audio (Union[str, Path, bytes, BinaryIO]) — 要转录的内容。可以是原始音频字节、本地音频文件或指向音频文件的 URL。
- model (
str
, 可选) — 用于 ASR 的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的 ASR 模型。 - extra_body (
Dict
, 可选) — 传递给模型的其他提供商特定参数。有关支持的参数,请参阅提供商文档。
包含转录文本和可选时间戳块的项。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 HTTP 错误状态码,但不是 HTTP 503。
对给定的音频内容执行自动语音识别(ASR 或音频转文本)。
聊天补全
< source 来源 >( messages: typing.List[typing.Union[typing.Dict, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputMessage]] model: typing.Optional[str] = None stream: bool = False frequency_penalty: typing.Optional[float] = None logit_bias: typing.Optional[typing.List[float]] = None logprobs: typing.Optional[bool] = None max_tokens: typing.Optional[int] = None n: typing.Optional[int] = None presence_penalty: typing.Optional[float] = None response_format: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatText, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONSchema, huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputResponseFormatJSONObject, NoneType] = None seed: typing.Optional[int] = None stop: typing.Optional[typing.List[str]] = None stream_options: typing.Optional[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputStreamOptions] = None temperature: typing.Optional[float] = None tool_choice: typing.Union[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputToolChoiceClass, ForwardRef('ChatCompletionInputToolChoiceEnum'), NoneType] = None tool_prompt: typing.Optional[str] = None tools: typing.Optional[typing.List[huggingface_hub.inference._generated.types.chat_completion.ChatCompletionInputTool]] = None top_logprobs: typing.Optional[int] = None top_p: typing.Optional[float] = None extra_body: typing.Optional[typing.Dict] = None ) → ChatCompletionOutput 或 Iterable of ChatCompletionStreamOutput
参数
- messages (List of ChatCompletionInputMessage) — 由角色和内容对组成的对话历史。
- model (
str
, 可选) — 用于聊天完成的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署推理端点的 URL。如果未提供,将使用默认推荐的基于聊天的文本生成模型。有关详细信息,请参阅 https://huggingface.co/tasks/text-generation。如果model
是模型 ID,它将作为model
参数传递给服务器。如果您想在请求有效负载中设置model
的同时定义自定义 URL,则必须在初始化 InferenceClient 时设置base_url
。 - frequency_penalty (
float
, 可选) — 根据新词在文本中出现的频率对其进行惩罚。范围:[-2.0, 2.0]。默认为 0.0。 - logit_bias (
List[float]
, 可选) — 调整特定词元在生成输出中出现的可能性。 - logprobs (
bool
, 可选) — 是否返回输出词元的对数概率。如果为 true,则返回消息内容中每个输出词元的对数概率。 - max_tokens (
int
, 可选) — 响应中允许的最大词元数。默认为 100。 - n (
int
, 可选) — 为每个提示生成完成的数量。 - presence_penalty (
float
, 可选) — 介于 -2.0 和 2.0 之间的数字。正值根据新词是否出现在文本中对其进行惩罚,从而增加模型谈论新主题的可能性。 - response_format (
ChatCompletionInputGrammarType()
, 可选) — 语法约束。可以是 JSONSchema 或正则表达式。 - seed (可选
int
,可选) — 用于可重现控制流的种子。默认为 None。 - stop (
List[str]
,可选) — 最多四个字符串,用于触发响应结束。默认为 None。 - stream (
bool
,可选) — 启用实时流式响应。默认为 False。 - stream_options (ChatCompletionInputStreamOptions,可选) — 流式完成的选项。
- temperature (
float
,可选) — 控制生成的随机性。较低的值可确保较少的随机完成。范围:[0, 2]。默认为 1.0。 - top_logprobs (
int
,可选) — 一个介于 0 到 5 之间的整数,指定在每个令牌位置返回最有可能的令牌数量,每个令牌都带有一个关联的对数概率。如果使用此参数,logprobs 必须设置为 true。 - top_p (
float
,可选) — 从最有可能的下一个词中采样的分数。必须介于 0 和 1 之间。默认为 1.0。 - tool_choice (ChatCompletionInputToolChoiceClass 或
ChatCompletionInputToolChoiceEnum()
,可选) — 用于完成的工具。默认为“auto”。 - tool_prompt (
str
,可选) — 在工具之前附加的提示。 - tools (List of ChatCompletionInputTool,可选) — 模型可能调用的工具列表。目前,只支持函数作为工具。使用此参数可提供模型可能生成 JSON 输入的函数列表。
- extra_body (
Dict
,可选) — 传递给模型的额外提供程序特定参数。请参阅提供程序的文档以获取支持的参数。
返回
服务器返回的生成文本
- 如果
stream=False
,则生成文本作为 ChatCompletionOutput 返回(默认)。 - 如果
stream=True
,则生成文本以 token 为单位作为 ChatCompletionStreamOutput 序列返回。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 HTTP 错误状态码,但不是 HTTP 503。
使用指定的语言模型完成对话的方法。
client.chat_completion
方法被别名为 client.chat.completions.create
,以与 OpenAI 的客户端兼容。输入和输出严格相同,使用任一语法都将产生相同的结果。有关 OpenAI 兼容性的更多详细信息,请查看 推理指南。
示例
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> await client.chat_completion(messages, max_tokens=100)
ChatCompletionOutput(
choices=[
ChatCompletionOutputComplete(
finish_reason='eos_token',
index=0,
message=ChatCompletionOutputMessage(
role='assistant',
content='The capital of France is Paris.',
name=None,
tool_calls=None
),
logprobs=None
)
],
created=1719907176,
id='',
model='meta-llama/Meta-Llama-3-8B-Instruct',
object='text_completion',
system_fingerprint='2.0.4-sha-f426a33',
usage=ChatCompletionOutputUsage(
completion_tokens=8,
prompt_tokens=17,
total_tokens=25
)
)
使用流式传输的示例
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
>>> async for token in await client.chat_completion(messages, max_tokens=10, stream=True):
... print(token)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content='The', role='assistant'), index=0, finish_reason=None)], created=1710498504)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' capital', role='assistant'), index=0, finish_reason=None)], created=1710498504)
(...)
ChatCompletionStreamOutput(choices=[ChatCompletionStreamOutputChoice(delta=ChatCompletionStreamOutputDelta(content=' may', role='assistant'), index=0, finish_reason=None)], created=1710498504)
使用 OpenAI 语法的示例
# Must be run in an async context
# instead of `from openai import OpenAI`
from huggingface_hub import AsyncInferenceClient
# instead of `client = OpenAI(...)`
client = AsyncInferenceClient(
base_url=...,
api_key=...,
)
output = await client.chat.completions.create(
model="meta-llama/Meta-Llama-3-8B-Instruct",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Count to 10"},
],
stream=True,
max_tokens=1024,
)
for chunk in output:
print(chunk.choices[0].delta.content)
直接使用额外(提供方特定)参数的第三方提供方示例。使用费用将计入您的 Together AI 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="together", # Use Together AI provider
... api_key="<together_api_key>", # Pass your Together API key directly
... )
>>> client.chat_completion(
... model="meta-llama/Meta-Llama-3-8B-Instruct",
... messages=[{"role": "user", "content": "What is the capital of France?"}],
... extra_body={"safety_model": "Meta-Llama/Llama-Guard-7b"},
... )
通过 Hugging Face 路由使用第三方提供方的示例。使用费用将计入您的 Hugging Face 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="sambanova", # Use Sambanova provider
... api_key="hf_...", # Pass your HF token
... )
>>> client.chat_completion(
... model="meta-llama/Meta-Llama-3-8B-Instruct",
... messages=[{"role": "user", "content": "What is the capital of France?"}],
... )
使用图像 + 文本作为输入的示例
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
# provide a remote URL
>>> image_url ="https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
# or a base64-encoded image
>>> image_path = "/path/to/image.jpeg"
>>> with open(image_path, "rb") as f:
... base64_image = base64.b64encode(f.read()).decode("utf-8")
>>> image_url = f"data:image/jpeg;base64,{base64_image}"
>>> client = AsyncInferenceClient("meta-llama/Llama-3.2-11B-Vision-Instruct")
>>> output = await client.chat.completions.create(
... messages=[
... {
... "role": "user",
... "content": [
... {
... "type": "image_url",
... "image_url": {"url": image_url},
... },
... {
... "type": "text",
... "text": "Describe this image in one sentence.",
... },
... ],
... },
... ],
... )
>>> output
The image depicts the iconic Statue of Liberty situated in New York Harbor, New York, on a clear day.
使用工具的示例
# Must be run in an async context
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
... {
... "role": "system",
... "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
... },
... {
... "role": "user",
... "content": "What's the weather like the next 3 days in San Francisco, CA?",
... },
... ]
>>> tools = [
... {
... "type": "function",
... "function": {
... "name": "get_current_weather",
... "description": "Get the current weather",
... "parameters": {
... "type": "object",
... "properties": {
... "location": {
... "type": "string",
... "description": "The city and state, e.g. San Francisco, CA",
... },
... "format": {
... "type": "string",
... "enum": ["celsius", "fahrenheit"],
... "description": "The temperature unit to use. Infer this from the users location.",
... },
... },
... "required": ["location", "format"],
... },
... },
... },
... {
... "type": "function",
... "function": {
... "name": "get_n_day_weather_forecast",
... "description": "Get an N-day weather forecast",
... "parameters": {
... "type": "object",
... "properties": {
... "location": {
... "type": "string",
... "description": "The city and state, e.g. San Francisco, CA",
... },
... "format": {
... "type": "string",
... "enum": ["celsius", "fahrenheit"],
... "description": "The temperature unit to use. Infer this from the users location.",
... },
... "num_days": {
... "type": "integer",
... "description": "The number of days to forecast",
... },
... },
... "required": ["location", "format", "num_days"],
... },
... },
... },
... ]
>>> response = await client.chat_completion(
... model="meta-llama/Meta-Llama-3-70B-Instruct",
... messages=messages,
... tools=tools,
... tool_choice="auto",
... max_tokens=500,
... )
>>> response.choices[0].message.tool_calls[0].function
ChatCompletionOutputFunctionDefinition(
arguments={
'location': 'San Francisco, CA',
'format': 'fahrenheit',
'num_days': 3
},
name='get_n_day_weather_forecast',
description=None
)
使用 response_format 的示例
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
>>> messages = [
... {
... "role": "user",
... "content": "I saw a puppy a cat and a raccoon during my bike ride in the park. What did I saw 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"}'
关闭所有打开的会话。
默认情况下,在调用完成后,‘aiohttp.ClientSession’ 对象会自动关闭。但是,如果从服务器流式传输数据并在流完成之前停止,则必须调用此方法才能正确关闭会话。
另一种可能性是使用异步上下文(例如 async with AsyncInferenceClient(): ...
)。
文档问答
< 源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] question: str model: typing.Optional[str] = None doc_stride: typing.Optional[int] = None handle_impossible_answer: typing.Optional[bool] = None lang: typing.Optional[str] = None max_answer_len: typing.Optional[int] = None max_question_len: typing.Optional[int] = None max_seq_len: typing.Optional[int] = None top_k: typing.Optional[int] = None word_boxes: typing.Optional[typing.List[typing.Union[typing.List[float], str]]] = None ) → List[DocumentQuestionAnsweringOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO]
) — 上下文的输入图像。可以是原始字节、图像文件或在线图像的 URL。 - question (
str
) — 要回答的问题。 - model (
str
,可选) — 用于文档问答任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的文档问答模型。默认为 None。 - doc_stride (
int
,可选) — 如果文档中的单词太长而无法与模型的问题匹配,它将被分成几个有重叠的块。此参数控制重叠的大小。 - handle_impossible_answer (
bool
,可选) — 是否接受“不可能”作为答案。 - lang (
str
,可选) — 运行 OCR 时使用的语言。默认为英语。 - max_answer_len (
int
,可选) — 预测答案的最大长度(例如,只考虑较短长度的答案)。 - max_question_len (
int
,可选) — 令牌化后问题的最大长度。如果需要,将被截断。 - max_seq_len (
int
,可选) — 传递给模型的每个块中总句子(上下文 + 问题)的最大长度(以令牌为单位)。如果需要,上下文将被分成几个块(使用 doc_stride 作为重叠)。 - top_k (
int
,可选) — 要返回的答案数量(将按可能性顺序选择)。如果上下文中没有足够的选项,可以返回少于 top_k 个答案。 - word_boxes (
List[Union[List[float], str
,可选) — 单词和边界框列表(归一化 0->1000)。如果提供,推理将跳过 OCR 步骤并使用提供的边界框。
返回
List[DocumentQuestionAnsweringOutputElement]
包含预测标签、相关概率、单词 ID 和页码的 DocumentQuestionAnsweringOutputElement 项列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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 normalize: typing.Optional[bool] = None prompt_name: typing.Optional[str] = None truncate: typing.Optional[bool] = None truncation_direction: typing.Optional[typing.Literal['Left', 'Right']] = None model: typing.Optional[str] = None ) → np.ndarray
参数
- text (str) — 要嵌入的文本。
- model (str,可选) — 用于特征提取任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的特征提取模型。默认为 None。
- normalize (bool,可选) — 是否对嵌入进行归一化。仅在由 Text-Embedding-Inference 提供支持的服务器上可用。
- prompt_name (str,可选) — 编码时应使用的提示名称。如果未设置,则不应用提示。必须是 *Sentence Transformers* 配置 *prompts* 字典中的键。例如,如果
prompt_name
是“query”,并且prompts
是 {“query”: “query: ”,…},那么句子“What is the capital of France?” 将被编码为“query: What is the capital of France?”,因为提示文本将在任何要编码的文本之前添加。 - truncate (bool,可选) — 是否截断嵌入。仅在由 Text-Embedding-Inference 提供支持的服务器上可用。
- truncation_direction (Literal[“Left”, “Right”],可选) — 当传递 truncate=True 时,输入应从哪一侧截断。
返回
np.ndarray
表示输入文本的嵌入,为 float32 numpy 数组。
引发
[InferenceTimeoutError] 或 aiohttp.ClientResponseError
- [InferenceTimeoutError] — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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)
填补掩码
< 源 >( text: str model: typing.Optional[str] = None targets: typing.Optional[typing.List[str]] = None top_k: typing.Optional[int] = None ) → List[FillMaskOutputElement]
参数
- text (
str
) — 要填充的字符串,必须包含 [MASK] 令牌(查看模型卡以获取掩码的确切名称)。 - model (
str
,可选) — 用于填充掩码任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的填充掩码模型。 - targets (
List[str
,可选) — 传递时,模型会将分数限制为传递的目标,而不是在整个词汇表中查找。如果提供的目标不在模型的词汇表中,它们将被标记化,并使用第一个结果令牌(有警告,并且可能会较慢)。 - top_k (
int
,可选) — 传递时,覆盖要返回的预测数量。
返回
List[FillMaskOutputElement]
包含预测标签、相关概率、token 引用和完成文本的 FillMaskOutputElement 项列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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.')
]
获取端点信息
< 源 >( model: typing.Optional[str] = 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: typing.Optional[str] = None ) → ModelStatus
参数
- model (
str
,可选) — 要检查状态的模型的标识符。如果未提供模型,将使用此 InferenceClient 实例关联的模型。只能检查 HF Inference API 服务,因此标识符不能是 URL。
返回
ModelStatus
ModelStatus 数据类的一个实例,包含模型状态信息:加载、状态、计算类型和框架。
获取托管在 HF Inference API 上的模型的状态。
此端点主要在您已经知道要使用的模型并想检查其可用性时有用。如果您想发现已部署的模型,则应使用 list_deployed_models()。
健康检查
< 源 >( model: typing.Optional[str] = None ) → bool
检查已部署端点的健康状况。
健康检查仅适用于由 Text-Generation-Inference (TGI) 或 Text-Embedding-Inference (TEI) 提供支持的推理端点。对于推理 API,请改用 InferenceClient.get_model_status()。
图像分类
< 源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None function_to_apply: typing.Optional[ForwardRef('ImageClassificationOutputTransform')] = None top_k: typing.Optional[int] = None ) → List[ImageClassificationOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要分类的图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
,可选) — 用于图像分类的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用图像分类的默认推荐模型。 - function_to_apply (
"ImageClassificationOutputTransform"
,可选) — 应用于模型输出以检索分数的函数。 - top_k (
int
,可选) — 指定时,将输出限制为最有可能的前 K 个类别。
返回
List[ImageClassificationOutputElement]
包含预测标签和相关概率的 ImageClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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')] model: typing.Optional[str] = None mask_threshold: typing.Optional[float] = None overlap_mask_area_threshold: typing.Optional[float] = None subtask: typing.Optional[ForwardRef('ImageSegmentationSubtask')] = None threshold: typing.Optional[float] = None ) → List[ImageSegmentationOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要分割的图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
,可选) — 用于图像分割的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用图像分割的默认推荐模型。 - mask_threshold (
float
,可选) — 将预测掩码转换为二进制值时使用的阈值。 - overlap_mask_area_threshold (
float
,可选) — 掩码重叠阈值,用于消除小的、不连通的片段。 - subtask (
"ImageSegmentationSubtask"
,可选) — 要执行的分割任务,取决于模型能力。 - threshold (
float
,可选) — 过滤预测掩码的概率阈值。
返回
List[ImageSegmentationOutputElement]
包含分割掩码和相关属性的 ImageSegmentationOutputElement 列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] prompt: typing.Optional[str] = None negative_prompt: typing.Optional[str] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None model: typing.Optional[str] = None target_size: typing.Optional[huggingface_hub.inference._generated.types.image_to_image.ImageToImageTargetSize] = None **kwargs ) → Image
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 用于翻译的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - prompt (
str
,可选) — 指导图像生成的文本提示。 - negative_prompt (
str
,可选) — 指导图像生成中不包含的内容的提示。 - num_inference_steps (
int
,可选) — 对于扩散模型。去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但推理速度会变慢。 - guidance_scale (
float
,可选) — 对于扩散模型。较高的指导尺度值会促使模型生成与文本提示紧密关联的图像,但会降低图像质量。 - model (
str
,可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数会覆盖实例级别定义的模型。默认为 None。 - target_size (
ImageToImageTargetSize
,可选) — 输出图像的像素大小。
返回
图像
转换后的图像。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 HTTP 错误状态码,但不是 HTTP 503。
使用指定模型执行图像到图像的转换。
如果您想处理图像,必须安装 `PIL` (`pip install Pillow`)。
图像到文本
< 源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None ) → ImageToTextOutput
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要配字幕的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
,可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数会覆盖实例级别定义的模型。默认为 None。
生成的文本。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None prompt: typing.Optional[str] = None negative_prompt: typing.Optional[str] = None num_frames: typing.Optional[float] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None seed: typing.Optional[int] = None target_size: typing.Optional[huggingface_hub.inference._generated.types.image_to_video.ImageToVideoTargetSize] = None **kwargs ) → bytes
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 用于生成视频的输入图像。它可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数会覆盖实例级别定义的模型。默认为 None。 - prompt (
str
, 可选) — 用于指导视频生成的文本提示。 - negative_prompt (
str
, 可选) — 用于指导视频生成中不应包含内容的提示。 - num_frames (
float
, 可选) —num_frames
参数决定了要生成多少视频帧。 - num_inference_steps (
int
, 可选) — 对于扩散模型。去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - guidance_scale (
float
, 可选) — 对于扩散模型。更高的指导比例值会促使模型生成与文本提示紧密相关的视频,但会牺牲图像质量。 - seed (
int
, 可选) — 用于视频生成的种子。 - target_size (
ImageToVideoTargetSize
, 可选) — 输出视频帧的像素大小。 - num_inference_steps (
int
, 可选) — 去噪步数。更多的去噪步数通常会带来更高质量的视频,但推理速度会变慢。 - seed (
int
, 可选) — 随机数生成器的种子。
返回
字节
生成的视频。
从输入图像生成视频。
示例
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> video = await client.image_to_video("cat.jpg", model="Wan-AI/Wan2.2-I2V-A14B", prompt="turn the cat into a tiger")
>>> with open("tiger.mp4", "wb") as f:
... f.write(video)
列出已部署的模型
< 源 >( frameworks: typing.Union[NoneType, str, typing.Literal['all'], typing.List[str]] = None ) → Dict[str, List[str]]
列出部署在 HF Serverless Inference API 服务上的模型。
此帮助程序逐框架检查已部署的模型。默认情况下,它将检查支持的 4 个主要框架,这些框架占托管模型的 95%。但是,如果您想要一个完整的模型列表,可以将 `frameworks` 设置为“all”作为输入。或者,如果您事先知道您对哪个框架感兴趣,您也可以将搜索限制在该框架(例如 `frameworks="text-generation-inference"`)。检查的框架越多,所需时间就越长。
此端点方法不返回 HF Inference API 服务可用的所有模型的实时列表。它搜索最近可用的模型缓存列表,该列表可能不是最新的。如果您想了解特定模型的实时状态,请使用 get_model_status()。
此端点方法主要用于发现。如果您已经知道要使用的模型并想检查其可用性,可以直接使用 get_model_status()。
示例
# Must be run in an async contextthon
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
# Discover zero-shot-classification models currently deployed
>>> models = await client.list_deployed_models()
>>> models["zero-shot-classification"]
['Narsil/deberta-large-mnli-zero-cls', 'facebook/bart-large-mnli', ...]
# List from only 1 framework
>>> await client.list_deployed_models("text-generation-inference")
{'text-generation': ['bigcode/starcoder', 'meta-llama/Llama-2-70b-chat-hf', ...], ...}
对象检测
< 源 >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] model: typing.Optional[str] = None threshold: typing.Optional[float] = None ) → List[ObjectDetectionOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要检测图像上的对象。它可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - model (
str
, 可选) — 用于对象检测的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用对象检测的默认推荐模型 (DETR)。 - threshold (
float
, 可选) — 进行预测所需的概率。
返回
List[ObjectDetectionOutputElement]
包含边界框和相关属性的 ObjectDetectionOutputElement 列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
或 ValueError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 HTTP 错误状态码,但不是 HTTP 503。ValueError
— 如果请求输出不是列表。
使用指定的模型对给定图像执行对象检测。
如果您想处理图像,必须安装 `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: str context: str model: typing.Optional[str] = None align_to_words: typing.Optional[bool] = None doc_stride: typing.Optional[int] = None handle_impossible_answer: typing.Optional[bool] = None max_answer_len: typing.Optional[int] = None max_question_len: typing.Optional[int] = None max_seq_len: typing.Optional[int] = None top_k: typing.Optional[int] = None ) → Union[QuestionAnsweringOutputElement
, ListQuestionAnsweringOutputElement]
参数
- question (
str
) — 要回答的问题。 - context (
str
) — 问题的上下文。 - model (
str
) — 用于问答任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。 - align_to_words (
bool
, 可选) — 尝试将答案与真实词语对齐。可提高以空格分隔的语言的质量。但可能对不以空格分隔的语言(如日语或中文)造成负面影响。 - doc_stride (
int
, 可选) — 如果上下文太长,无法与模型的问题匹配,则会将其分成几个具有重叠的块。此参数控制重叠的大小。 - handle_impossible_answer (
bool
, 可选) — 是否接受不可能的答案。 - max_answer_len (
int
, 可选) — 预测答案的最大长度(例如,只考虑长度较短的答案)。 - max_question_len (
int
, 可选) — 标记化后问题的最大长度。如果需要,将被截断。 - max_seq_len (
int
, 可选) — 传递给模型的每个块中总句(上下文 + 问题)的最大长度(以标记为单位)。如果需要,上下文将分成几个块(使用 docStride 作为重叠)。 - top_k (
int
, 可选) — 要返回的答案数量(将按可能性顺序选择)。请注意,如果上下文内没有足够的可用选项,我们返回的答案数量将少于 topk。
返回
Union[QuestionAnsweringOutputElement
, ListQuestionAnsweringOutputElement]
当 top_k 为 1 或未提供时,返回单个 QuestionAnsweringOutputElement
。当 top_k 大于 1 时,返回 QuestionAnsweringOutputElement
列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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: str other_sentences: typing.List[str] model: typing.Optional[str] = None ) → List[float]
参数
- sentence (
str
) — 要与其他句子进行比较的主句。 - other_sentences (
List[str]
) — 要比较的句子列表。 - model (
str
, 可选) — 用于句子相似性任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的句子相似性模型。默认为 None。
返回
List[float]
表示输入文本的嵌入。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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: str model: typing.Optional[str] = None clean_up_tokenization_spaces: typing.Optional[bool] = None generate_parameters: typing.Optional[typing.Dict[str, typing.Any]] = None truncation: typing.Optional[ForwardRef('SummarizationTruncationStrategy')] = None ) → SummarizationOutput
参数
- text (
str
) — 要概括的输入文本。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的摘要模型。 - clean_up_tokenization_spaces (
bool
, 可选) — 是否清理文本输出中可能存在的额外空格。 - generate_parameters (
Dict[str, Any]
, 可选) — 文本生成算法的额外参数。 - truncation (
"SummarizationTruncationStrategy"
, 可选) — 要使用的截断策略。
生成的摘要文本。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 HTTP 错误状态码,但不是 HTTP 503。
使用指定模型生成给定文本的摘要。
table_question_answering
< 源 >( table: typing.Dict[str, typing.Any] query: str model: typing.Optional[str] = None padding: typing.Optional[ForwardRef('Padding')] = None sequential: typing.Optional[bool] = None truncation: typing.Optional[bool] = None ) → TableQuestionAnsweringOutputElement
参数
- table (
str
) — 以列表字典表示的数据表,其中条目是标题,列表是所有值,所有列表必须具有相同的大小。 - query (
str
) — 您要向表格提出的纯文本查询。 - model (
str
) — 用于表格问答任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。 - padding (
"Padding"
, 可选) — 激活和控制填充。 - sequential (
bool
, 可选) — 是否按顺序或分批进行推理。分批速度更快,但像 SQA 这样的模型需要按顺序进行推理才能提取序列中的关系,因为它们的对话性质。 - truncation (
bool
, 可选) — 激活和控制截断。
一个表格问答输出,包含答案、坐标、单元格和使用的聚合器。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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')
tabular_classification
< 源 >( table: typing.Dict[str, typing.Any] model: typing.Optional[str] = None ) → List
参数
- table (
Dict[str, Any]
) — 要分类的属性集。 - model (
str
, 可选) — 用于表格分类任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的表格分类模型。默认为 None。
返回
List
标签列表,每行一个,与初始表格中的行对应。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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"]
tabular_regression
< 源 >( table: typing.Dict[str, typing.Any] model: typing.Optional[str] = None ) → List
参数
- table (
Dict[str, Any]
) — 存储在表中的属性集。用于预测目标的属性可以是数值型和类别型。 - model (
str
, 可选) — 用于表格回归任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的表格回归模型。默认为 None。
返回
List
预测的数值目标值列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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_classification
< 源 >( text: str model: typing.Optional[str] = None top_k: typing.Optional[int] = None function_to_apply: typing.Optional[ForwardRef('TextClassificationOutputTransform')] = None ) → List[TextClassificationOutputElement]
参数
- text (
str
) — 要分类的字符串。 - model (
str
, 可选) — 用于文本分类任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的文本分类模型。默认为 None。 - top_k (
int
, 可选) — 指定时,将输出限制为最可能的 K 个类别。 - function_to_apply (
"TextClassificationOutputTransform"
, 可选) — 用于将模型输出转换为分数的功能。
返回
List[TextClassificationOutputElement]
包含预测标签和相关概率的 TextClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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),
]
text_generation
< 源 >( prompt: str details: typing.Optional[bool] = None stream: typing.Optional[bool] = None model: typing.Optional[str] = None adapter_id: typing.Optional[str] = None best_of: typing.Optional[int] = None decoder_input_details: typing.Optional[bool] = None do_sample: typing.Optional[bool] = None frequency_penalty: typing.Optional[float] = None grammar: typing.Optional[huggingface_hub.inference._generated.types.text_generation.TextGenerationInputGrammarType] = None max_new_tokens: typing.Optional[int] = None repetition_penalty: typing.Optional[float] = None return_full_text: typing.Optional[bool] = None seed: typing.Optional[int] = None stop: typing.Optional[typing.List[str]] = None stop_sequences: typing.Optional[typing.List[str]] = None temperature: typing.Optional[float] = None top_k: typing.Optional[int] = None top_n_tokens: typing.Optional[int] = None top_p: typing.Optional[float] = None truncate: typing.Optional[int] = None typical_p: typing.Optional[float] = None watermark: typing.Optional[bool] = None ) → Union[str, TextGenerationOutput, Iterable[str], Iterable[TextGenerationStreamOutput]]
参数
- prompt (
str
) — 输入文本。 - details (
bool
, 可选) — 默认情况下,text_generation
返回完整的生成文本。如果需要详细输出(标记、概率、种子、完成原因等),请传递details=True
。仅适用于使用text-generation-inference
后端运行的模型。 - stream (
bool
, 可选) — 默认情况下,text_generation
返回完整的生成文本。如果需要返回标记流,请传递stream=True
。仅适用于使用text-generation-inference
后端运行的模型。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数会覆盖实例级别定义的模型。默认为 None。 - adapter_id (
str
, 可选) — Lora 适配器 ID。 - best_of (
int
, 可选) — 生成best_of
个序列并返回具有最高标记对数概率的那个。 - decoder_input_details (
bool
, 可选) — 返回解码器输入标记的对数概率和 ID。必须同时设置details=True
才能生效。默认为False
。 - do_sample (
bool
, 可选) — 激活 logits 采样。 - frequency_penalty (
float
, optional) — 介于 -2.0 和 2.0 之间的数字。正值根据新标记在文本中已有的频率进行惩罚,从而降低模型逐字重复相同行的可能性。 - grammar (TextGenerationInputGrammarType, 可选) — 语法约束。可以是 JSONSchema 或正则表达式。
- max_new_tokens (
int
, 可选) — 生成标记的最大数量。默认为 100。 - repetition_penalty (
float
, 可选) — 重复惩罚的参数。1.0 表示没有惩罚。有关更多详细信息,请参阅这篇论文。 - return_full_text (
bool
, 可选) — 是否在生成的文本前加上提示。 - seed (
int
, 可选) — 随机采样种子。 - stop (
List[str]
, 可选) — 如果生成了 `stop` 成员,则停止生成标记。 - stop_sequences (
List[str]
, 可选) — 已弃用的参数。请改用 `stop`。 - temperature (
float
, 可选) — 用于调制对数分布的值。 - top_n_tokens (
int
, 可选) — 返回每个生成步骤中 `top_n_tokens` 最可能标记的信息,而不仅仅是采样的标记。 - top_k (
int
, *可选`) — 用于 top-k 过滤的最高概率词汇标记的数量。 - top_p (
float
, *可选) -- 如果设置为 < 1,则仅保留概率总和达到或高于
top_p` 的最小概率标记集。 - 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]
形式逐个标记返回 - 如果
stream=False
且details=True
,则生成文本以 TextGenerationOutput 形式返回更多详细信息 - 如果
details=True
且stream=True
,则生成文本以 TextGenerationStreamOutput 的可迭代形式逐个标记返回
引发
ValidationError
或 InferenceTimeoutError 或 aiohttp.ClientResponseError
ValidationError
— 如果输入值无效。不对服务器进行 HTTP 调用。- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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: str negative_prompt: typing.Optional[str] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: typing.Optional[int] = None guidance_scale: typing.Optional[float] = None model: typing.Optional[str] = None scheduler: typing.Optional[str] = None seed: typing.Optional[int] = None extra_body: typing.Optional[typing.Dict[str, typing.Any]] = None ) → Image
参数
- prompt (
str
) — 用于生成图像的提示。 - negative_prompt (
str
, 可选) — 一条用于指导图像生成中不应包含哪些内容的提示。 - height (
int
, 可选) — 输出图像的高度(以像素为单位)。 - width (
int
, 可选) — 输出图像的宽度(以像素为单位)。 - num_inference_steps (
int
, 可选) — 去噪步数。更多去噪步数通常会带来更高质量的图像,但推理速度会变慢。 - guidance_scale (
float
, 可选) — 较高的指导尺度值鼓励模型生成与文本提示紧密关联的图像,但过高的值可能导致饱和度和其他伪影。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是部署的推理端点的 URL。如果未提供,将使用默认推荐的文本到图像模型。默认为 None。 - scheduler (
str
, 可选) — 使用兼容的调度器覆盖。 - seed (
int
, 可选) — 随机数生成器的种子。 - extra_body (
Dict[str, Any]
, 可选) — 传递给模型的额外提供者特定参数。有关支持的参数,请参阅提供者的文档。
返回
图像
生成的图像。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 HTTP 错误状态码,但不是 HTTP 503。
根据给定文本使用指定模型生成图像。
如果您想处理图像,必须安装 `PIL` (`pip install Pillow`)。
示例
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> image = await client.text_to_image("An astronaut riding a horse on the moon.")
>>> image.save("astronaut.png")
>>> image = await client.text_to_image(
... "An astronaut riding a horse on the moon.",
... negative_prompt="low resolution, blurry",
... model="stabilityai/stable-diffusion-2-1",
... )
>>> image.save("better_astronaut.png")
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="fal-ai", # Use fal.ai provider
... api_key="fal-ai-api-key", # Pass your fal.ai API key
... )
>>> image = client.text_to_image(
... "A majestic lion in a fantasy forest",
... model="black-forest-labs/FLUX.1-schnell",
... )
>>> image.save("lion.png")
通过 Hugging Face 路由使用第三方提供方的示例。使用费用将计入您的 Hugging Face 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate", # Use replicate provider
... api_key="hf_...", # Pass your HF token
... )
>>> image = client.text_to_image(
... "An astronaut riding a horse on the moon.",
... model="black-forest-labs/FLUX.1-dev",
... )
>>> image.save("astronaut.png")
使用 Replicate 提供商和额外参数的示例
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate", # Use replicate provider
... api_key="hf_...", # Pass your HF token
... )
>>> image = client.text_to_image(
... "An astronaut riding a horse on the moon.",
... model="black-forest-labs/FLUX.1-schnell",
... extra_body={"output_quality": 100},
... )
>>> image.save("astronaut.png")
文本转语音
< 源 >( text: str model: typing.Optional[str] = None do_sample: typing.Optional[bool] = None early_stopping: typing.Union[bool, ForwardRef('TextToSpeechEarlyStoppingEnum'), NoneType] = None epsilon_cutoff: typing.Optional[float] = None eta_cutoff: typing.Optional[float] = None max_length: typing.Optional[int] = None max_new_tokens: typing.Optional[int] = None min_length: typing.Optional[int] = None min_new_tokens: typing.Optional[int] = None num_beam_groups: typing.Optional[int] = None num_beams: typing.Optional[int] = None penalty_alpha: typing.Optional[float] = None temperature: typing.Optional[float] = None top_k: typing.Optional[int] = None top_p: typing.Optional[float] = None typical_p: typing.Optional[float] = None use_cache: typing.Optional[bool] = None extra_body: typing.Optional[typing.Dict[str, typing.Any]] = None ) → bytes
参数
- text (
str
) — 要合成的文本。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是部署的推理端点的 URL。如果未提供,将使用默认推荐的文本到语音模型。默认为 None。 - do_sample (
bool
, 可选) — 生成新标记时是否使用采样而不是贪婪解码。 - early_stopping (
Union[bool, "TextToSpeechEarlyStoppingEnum"]
, 可选) — 控制基于束的方法的停止条件。 - epsilon_cutoff (
float
, 可选) — 如果设置为严格介于 0 和 1 之间的浮点数,则仅对条件概率大于 `epsilon_cutoff` 的标记进行采样。在论文中,建议的值范围为 3e-4 到 9e-4,具体取决于模型的大小。详情请参阅截断采样作为语言模型去平滑。 - eta_cutoff (
float
, 可选) — Eta 采样是局部典型采样和 epsilon 采样的混合。如果设置为严格介于 0 和 1 之间的浮点数,则只有当标记大于 `eta_cutoff` 或 `sqrt(eta_cutoff)`- `exp(-entropy(softmax(next_token_logits)))` 时才会被考虑。后一个项直观上是预期下一个标记概率,由 `sqrt(eta_cutoff)` 缩放。在论文中,建议的值范围为 3e-4 到 2e-3,具体取决于模型的大小。详情请参阅截断采样作为语言模型去平滑。
- max_length (
int
, 可选) — 生成文本的最大长度(以标记为单位),包括输入。 - max_new_tokens (
int
, 可选) — 生成标记的最大数量。优先于 `max_length`。 - min_length (
int
, 可选) — 生成文本的最小长度(以标记为单位),包括输入。 - min_new_tokens (
int
, 可选) — 生成标记的最小数量。优先于 `min_length`。 - num_beam_groups (
int
, 可选) — 将 `num_beams` 分成若干组,以确保不同束组之间的多样性。详情请参阅这篇论文。 - num_beams (
int
, 可选) — 用于束搜索的束数。 - penalty_alpha (
float
, 可选) — 该值平衡了对比搜索解码中的模型置信度和退化惩罚。 - temperature (
float
, 可选) — 用于调节下一个标记概率的值。 - top_k (
int
, 可选) — 用于 top-k 过滤的最高概率词汇标记的数量。 - top_p (
float
, 可选) — 如果设置为浮点数 < 1,则仅保留概率总和达到或高于 `top_p` 的最小概率标记集。 - typical_p (
float
, 可选) — 局部典型性衡量预测目标标记的条件概率与预测随机标记的预期条件概率(给定已生成的部分文本)的相似程度。如果设置为浮点数 < 1,则保留局部典型性最高且概率总和达到或高于 `typical_p` 的最小标记集。详情请参阅这篇论文。 - use_cache (
bool
, 可选) — 模型是否应使用过去的最后键/值注意力来加速解码。 - extra_body (
Dict[str, Any]
, 可选) — 传递给模型的额外提供者特定参数。有关支持的参数,请参阅提供者的文档。
返回
字节
生成的音频。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 HTTP 错误状态码,但不是 HTTP 503。
合成给定文本的语音音频。
示例
# Must be run in an async context
>>> from pathlib import Path
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> audio = await client.text_to_speech("Hello world")
>>> Path("hello_world.flac").write_bytes(audio)
直接使用第三方提供商的示例。使用费用将在您的 Replicate 账户中扣除。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate",
... api_key="your-replicate-api-key", # Pass your Replicate API key directly
... )
>>> audio = client.text_to_speech(
... text="Hello world",
... model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
通过 Hugging Face 路由使用第三方提供方的示例。使用费用将计入您的 Hugging Face 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate",
... api_key="hf_...", # Pass your HF token
... )
>>> audio =client.text_to_speech(
... text="Hello world",
... model="OuteAI/OuteTTS-0.3-500M",
... )
>>> Path("hello_world.flac").write_bytes(audio)
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate", # Use replicate provider
... api_key="hf_...", # Pass your HF token
... )
>>> audio = client.text_to_speech(
... "Hello, my name is Kororo, an awesome text-to-speech model.",
... model="hexgrad/Kokoro-82M",
... extra_body={"voice": "af_nicole"},
... )
>>> Path("hello.flac").write_bytes(audio)
在 fal.ai 上使用“YuE-s1-7B-anneal-en-cot”生成音乐的示例
>>> 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)
文本转视频
< 源 >( prompt: str model: typing.Optional[str] = None guidance_scale: typing.Optional[float] = None negative_prompt: typing.Optional[typing.List[str]] = None num_frames: typing.Optional[float] = None num_inference_steps: typing.Optional[int] = None seed: typing.Optional[int] = None extra_body: typing.Optional[typing.Dict[str, typing.Any]] = None ) → bytes
参数
- prompt (
str
) — 用于生成视频的提示。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是部署的推理端点的 URL。如果未提供,将使用默认推荐的文本到视频模型。默认为 None。 - guidance_scale (
float
, 可选) — 较高的指导尺度值鼓励模型生成与文本提示紧密关联的视频,但过高的值可能导致饱和度和其他伪影。 - negative_prompt (
List[str]
, 可选) — 一条或多条指导视频生成中不应包含哪些内容的提示。 - num_frames (
float
, 可选) — `num_frames` 参数确定生成多少视频帧。 - num_inference_steps (
int
, 可选) — 去噪步数。更多去噪步数通常会带来更高质量的视频,但推理速度会变慢。 - seed (
int
, 可选) — 随机数生成器的种子。 - extra_body (
Dict[str, Any]
, 可选) — 传递给模型的额外提供者特定参数。有关支持的参数,请参阅提供者的文档。
返回
字节
生成的视频。
根据给定文本生成视频。
示例
直接使用第三方提供商的示例。使用费用将在您的 fal.ai 账户中扣除。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="fal-ai", # Using fal.ai provider
... api_key="fal-ai-api-key", # Pass your fal.ai API key
... )
>>> video = client.text_to_video(
... "A majestic lion running in a fantasy forest",
... model="tencent/HunyuanVideo",
... )
>>> with open("lion.mp4", "wb") as file:
... file.write(video)
通过 Hugging Face 路由使用第三方提供方的示例。使用费用将计入您的 Hugging Face 账户。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(
... provider="replicate", # Using replicate provider
... api_key="hf_...", # Pass your HF token
... )
>>> video = client.text_to_video(
... "A cat running in a park",
... model="genmo/mochi-1-preview",
... )
>>> with open("cat.mp4", "wb") as file:
... file.write(video)
令牌分类
< source >( text: str model: typing.Optional[str] = None aggregation_strategy: typing.Optional[ForwardRef('TokenClassificationAggregationStrategy')] = None ignore_labels: typing.Optional[typing.List[str]] = None stride: typing.Optional[int] = None ) → List[TokenClassificationOutputElement]
参数
- text (
str
) — 要分类的字符串。 - model (
str
, 可选) — 用于执行词元分类任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的词元分类模型。默认为 None。 - aggregation_strategy (
"TokenClassificationAggregationStrategy"
, 可选) — 根据模型预测融合词元的策略。 - ignore_labels (
List[str
, 可选) — 要忽略的标签列表。 - stride (
int
, 可选) — 分割输入文本时,块之间重叠词元的数量。
返回
列表[TokenClassificationOutputElement]
包含实体组、置信度分数、单词、开始和结束索引的 TokenClassificationOutputElement 列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 HTTP 错误状态码,但不是 HTTP 503。
对给定文本执行令牌分类。通常用于句子解析,无论是语法解析,还是命名实体识别 (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,
)
]
翻译
< source >( text: str model: typing.Optional[str] = None src_lang: typing.Optional[str] = None tgt_lang: typing.Optional[str] = None clean_up_tokenization_spaces: typing.Optional[bool] = None truncation: typing.Optional[ForwardRef('TranslationTruncationStrategy')] = None generate_parameters: typing.Optional[typing.Dict[str, typing.Any]] = None ) → TranslationOutput
参数
- text (
str
) — 要翻译的字符串。 - model (
str
, 可选) — 用于翻译任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的翻译模型。默认为 None。 - src_lang (
str
, 可选) — 文本的源语言。对于可以从多种语言翻译的模型,此为必需参数。 - tgt_lang (
str
, 可选) — 目标翻译语言。对于可以翻译成多种语言的模型,此为必需参数。 - clean_up_tokenization_spaces (
bool
, 可选) — 是否清理文本输出中可能存在的额外空格。 - truncation (
"TranslationTruncationStrategy"
, 可选) — 要使用的截断策略。 - generate_parameters (
Dict[str, Any]
, 可选) — 文本生成算法的其他参数化。
生成的翻译文本。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
或 ValueError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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.')
视觉问答
< source >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] question: str model: typing.Optional[str] = None top_k: typing.Optional[int] = None ) → List[VisualQuestionAnsweringOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 上下文的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - question (
str
) — 要回答的问题。 - model (
str
, 可选) — 用于视觉问答任务的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。如果未提供,将使用默认推荐的视觉问答模型。默认为 None。 - top_k (
int
, 可选) — 要返回的答案数量(将按可能性顺序选择)。请注意,如果上下文中没有足够的选项,我们将返回少于 topk 的答案。
返回
List[VisualQuestionAnsweringOutputElement]
包含预测标签和相关概率的 VisualQuestionAnsweringOutputElement 项目列表。
引发
InferenceTimeoutError
或 aiohttp.ClientResponseError
InferenceTimeoutError
— 如果模型不可用或请求超时。aiohttp.ClientResponseError
— 如果请求失败并返回 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'),
]
零样本分类
< source >( text: str candidate_labels: typing.List[str] multi_label: typing.Optional[bool] = False hypothesis_template: typing.Optional[str] = None model: typing.Optional[str] = None ) → List[ZeroShotClassificationOutputElement]
参数
- text (
str
) — 要分类的输入文本。 - candidate_labels (
List[str]
) — 用于分类文本的可能类别标签集。 - labels (
List[str]
, 可选) — (已弃用) 字符串列表。每个字符串是输入文本可能标签的口头表达。 - multi_label (
bool
, 可选) — 是否可以有多个候选标签为真。如果为假,分数将归一化,使得每个序列的标签可能性之和为 1。如果为真,标签被认为是独立的,并且概率针对每个候选进行归一化。 - hypothesis_template (
str
, 可选) — 与candidate_labels
结合使用的句子,通过将占位符替换为候选标签来尝试文本分类。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数将覆盖实例级别定义的模型。如果未提供,将使用默认推荐的零样本分类模型。
返回
List[ZeroShotClassificationOutputElement]
包含预测标签及其置信度的 ZeroShotClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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.",
... 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)
]
零样本图像分类
< source >( image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, ForwardRef('Image')] candidate_labels: typing.List[str] model: typing.Optional[str] = None hypothesis_template: typing.Optional[str] = None labels: typing.List[str] = None ) → List[ZeroShotImageClassificationOutputElement]
参数
- image (
Union[str, Path, bytes, BinaryIO, PIL.Image.Image]
) — 要配字幕的输入图像。可以是原始字节、图像文件、在线图像的 URL 或 PIL 图像。 - candidate_labels (
List[str]
) — 此图像的候选标签。 - labels (
List[str]
, 可选) — (已弃用) 字符串列表,表示可能的标签。必须至少有 2 个标签。 - model (
str
, 可选) — 用于推理的模型。可以是 Hugging Face Hub 上托管的模型 ID,也可以是已部署的推理端点的 URL。此参数将覆盖实例级别定义的模型。如果未提供,将使用默认推荐的零样本图像分类模型。 - hypothesis_template (
str
, 可选) — 与candidate_labels
结合使用的句子,通过将占位符替换为候选标签来尝试图像分类。
返回
List[ZeroShotImageClassificationOutputElement]
包含预测标签及其置信度的 ZeroShotImageClassificationOutputElement 项列表。
引发
InferenceTimeoutError 或 aiohttp.ClientResponseError
- InferenceTimeoutError — 如果模型不可用或请求超时。
aiohttp.ClientResponseError
— 如果请求失败并返回 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",
... labels=["dog", "cat", "horse"],
... )
[ZeroShotImageClassificationOutputElement(label='dog', score=0.956),...]
InferenceTimeoutError
模型不可用或请求超时时引发的错误。
ModelStatus
class huggingface_hub.inference._common.ModelStatus
< source >( loaded: bool state: str compute_type: typing.Dict framework: str )
参数
- loaded (
bool
) — 模型是否当前已加载到 HF 的推理 API 中。模型按需加载,导致用户的首次请求需要更长时间。如果模型已加载,可以确保其处于正常状态。 - state (
str
) — 模型的当前状态。可以是“Loaded”(已加载)、“Loadable”(可加载)、“TooBig”(过大)。如果模型状态为“Loadable”,则表示它不过大且具有受支持的后端。当用户首次请求端点上的推理时,可加载模型会自动加载。这意味着用户加载模型是透明的,只是首次调用需要更长时间才能完成。 - compute_type (
Dict
) — 有关模型正在使用或将要使用的计算资源的信息,例如“gpu”类型和副本数量。 - framework (
str
) — 模型构建所使用的框架名称,例如“transformers”或“text-generation-inference”。
此数据类表示 HF 推理 API 中的模型状态。
InferenceAPI
InferenceAPI
是调用推理 API 的传统方式。该接口更为简单,需要了解每个任务的输入参数和输出格式。它还缺乏连接到推理端点或 AWS SageMaker 等其他服务的能力。InferenceAPI
即将弃用,因此建议尽可能使用 InferenceClient。请参阅 此指南,了解如何在脚本中从 InferenceAPI
切换到 InferenceClient。
class huggingface_hub.InferenceApi
< source >( repo_id: str task: typing.Optional[str] = None token: typing.Optional[str] = None gpu: bool = False )
用于配置请求和调用 HuggingFace 推理 API 的客户端。
示例
>>> from huggingface_hub.inference_api import InferenceApi
>>> # Mask-fill example
>>> inference = InferenceApi("bert-base-uncased")
>>> inference(inputs="The goal of life is [MASK].")
[{'sequence': 'the goal of life is life.', 'score': 0.10933292657136917, 'token': 2166, 'token_str': 'life'}]
>>> # Question Answering example
>>> inference = InferenceApi("deepset/roberta-base-squad2")
>>> inputs = {
... "question": "What's my name?",
... "context": "My name is Clara and I live in Berkeley.",
... }
>>> inference(inputs)
{'score': 0.9326569437980652, 'start': 11, 'end': 16, 'answer': 'Clara'}
>>> # Zero-shot example
>>> inference = InferenceApi("typeform/distilbert-base-uncased-mnli")
>>> inputs = "Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!"
>>> params = {"candidate_labels": ["refund", "legal", "faq"]}
>>> inference(inputs, params)
{'sequence': 'Hi, I recently bought a device from your company but it is not working as advertised and I would like to get reimbursed!', 'labels': ['refund', 'faq', 'legal'], 'scores': [0.9378499388694763, 0.04914155602455139, 0.013008488342165947]}
>>> # Overriding configured task
>>> inference = InferenceApi("bert-base-uncased", task="feature-extraction")
>>> # Text-to-image
>>> inference = InferenceApi("stabilityai/stable-diffusion-2-1")
>>> inference("cat")
<PIL.PngImagePlugin.PngImageFile image (...)>
>>> # Return as raw response to parse the output yourself
>>> inference = InferenceApi("mio/amadeus")
>>> response = inference("hello world", raw_response=True)
>>> response.headers
{"Content-Type": "audio/flac", ...}
>>> response.content # raw bytes from server
b'(...)'
__init__
< source >( repo_id: str task: typing.Optional[str] = None token: typing.Optional[str] = None gpu: bool = False )
参数
- repo_id (
str
) — 仓库 ID(例如 user/bert-base-uncased)。 - task (
str
, 可选, 默认为None
) — 是否强制执行任务,而不是使用仓库中指定的任务。 - token (str, 可选) — 用作 HTTP 承载授权的 API 令牌。这不是身份验证令牌。您可以在 https://huggingface.co/settings/token 中找到令牌。或者,您可以使用 HfApi().whoami(token) 找到您的组织和个人 API 令牌。
- gpu (bool, 可选, 默认为 False) — 是否使用 GPU 而非 CPU 进行推理(至少需要 Startup 计划)。
初始化标头和 API 调用信息。
__call__
< source >( inputs: typing.Union[str, typing.Dict, typing.List[str], typing.List[typing.List[str]], NoneType] = None params: typing.Optional[typing.Dict] = None data: typing.Optional[bytes] = None raw_response: bool = False )
调用推理 API。