Inference is the process of using a trained model to make predictions on new data. As this process can be compute-intensive,
running on a dedicated server can be an interesting option. The huggingface_hub
library provides an easy way to call a
service that runs inference for hosted models. There are several services you can connect to:
These services can be called with the InferenceClient object. Please refer to this guide for more information on how to use it.
( model: typing.Optional[str] = None token: typing.Union[str, bool, NoneType] = None timeout: typing.Optional[float] = None headers: typing.Union[typing.Dict[str, str], NoneType] = None cookies: typing.Union[typing.Dict[str, str], NoneType] = None )
Parameters
str
, optional
) —
The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. bigcode/starcoder
or a URL to a deployed Inference Endpoint. Defaults to None, in which case a recommended model is
automatically selected for the task.
str
, optional) —
Hugging Face token. Will default to the locally saved token. Pass token=False
if you don’t want to send
your token to the server.
float
, optional
) —
The maximum number of seconds to wait for a response from the server. Loading a new model in Inference
API can take up to several minutes. Defaults to None, meaning it will loop until the server is available.
Dict[str, str]
, optional
) —
Additional headers to send to the server. By default only the authorization and user-agent headers are sent.
Values in this dictionary will override the default values.
Dict[str, str]
, optional
) —
Additional cookies to send to the server.
Initialize a new Inference Client.
InferenceClient aims to provide a unified experience to perform inference. The client can be used seamlessly with either the (free) Inference API or self-hosted Inference Endpoints.
(
audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
model: typing.Optional[str] = None
)
→
List[Dict]
Parameters
str
, optional) —
The model to use for audio classification. Can be a model ID hosted on the Hugging Face Hub
or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for
audio classification will be used.
Returns
List[Dict]
The classification output containing the predicted label and its confidence.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform audio classification on the provided audio content.
( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path] model: typing.Optional[str] = None ) → str
Parameters
str
, optional) —
The model to use for ASR. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. If not provided, the default recommended model for ASR will be used.
Returns
str
The transcribed text.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform automatic speech recognition (ASR or audio-to-text) on the given audio content.
(
text: str
generated_responses: typing.Optional[typing.List[str]] = None
past_user_inputs: typing.Optional[typing.List[str]] = None
parameters: typing.Union[typing.Dict[str, typing.Any], NoneType] = None
model: typing.Optional[str] = None
)
→
Dict
Parameters
str
) —
The last input from the user in the conversation.
List[str]
, optional) —
A list of strings corresponding to the earlier replies from the model. Defaults to None.
List[str]
, optional) —
A list of strings corresponding to the earlier replies from the user. Should be the same length as
generated_responses
. Defaults to None.
Dict[str, Any]
, optional) —
Additional parameters for the conversational task. Defaults to None. For more details about the available
parameters, please refer to this page
str
, optional) —
The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to
a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used.
Defaults to None.
Returns
Dict
The generated conversational output.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Generate conversational responses based on the given input text (i.e. chat with the API).
Example:
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> output = client.conversational("Hi, who are you?")
>>> output
{'generated_text': 'I am the one who knocks.', 'conversation': {'generated_responses': ['I am the one who knocks.'], 'past_user_inputs': ['Hi, who are you?']}, 'warnings': ['Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.']}
>>> client.conversational(
... "Wow, that's scary!",
... generated_responses=output["conversation"]["generated_responses"],
... past_user_inputs=output["conversation"]["past_user_inputs"],
... )
(
text: str
model: typing.Optional[str] = None
)
→
np.ndarray
Parameters
str
) —
The text to embed.
str
, optional) —
The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to
a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used.
Defaults to None.
Returns
np.ndarray
The embedding representing the input text as a float32 numpy array.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Generate embeddings for a given text.
Example:
>>> 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)
(
model: typing.Optional[str] = None
)
→
ModelStatus
Parameters
str
, optional) —
Identifier of the model for witch the status gonna be checked. If model is not provided,
the model associated with this instance of InferenceClient will be used. Only InferenceAPI service can be checked so the
identifier cannot be a URL.
Returns
ModelStatus
An instance of ModelStatus dataclass, containing information, about the state of the model: load, state, compute type and framework.
A function which returns the status of a specific model, from the Inference API.
(
image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
model: typing.Optional[str] = None
)
→
List[Dict]
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The image to classify. It can be raw bytes, an image file, or a URL to an online image.
str
, optional) —
The model to use for image classification. Can be a model ID hosted on the Hugging Face Hub or a URL to a
deployed Inference Endpoint. If not provided, the default recommended model for image classification will be used.
Returns
List[Dict]
a list of dictionaries containing the predicted label and associated probability.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform image classification on the given image using the specified model.
(
image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
model: typing.Optional[str] = None
)
→
List[Dict]
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The image to segment. It can be raw bytes, an image file, or a URL to an online image.
str
, optional) —
The model to use for image segmentation. Can be a model ID hosted on the Hugging Face Hub or a URL to a
deployed Inference Endpoint. If not provided, the default recommended model for image segmentation will be used.
Returns
List[Dict]
A list of dictionaries containing the segmented masks and associated attributes.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform image segmentation on the given image using the specified model.
You must have PIL
installed if you want to work with images (pip install Pillow
).
(
image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
prompt: typing.Optional[str] = None
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
**kwargs
)
→
Image
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The input image for translation. It can be raw bytes, an image file, or a URL to an online image.
str
, optional) —
The text prompt to guide the image generation.
str
, optional) —
A negative prompt to guide the translation process.
int
, optional) —
The height in pixels of the generated image.
int
, optional) —
The width in pixels of the generated image.
int
, optional) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference.
float
, optional) —
Higher guidance scale encourages to generate images that are closely linked to the text prompt
,
usually at the expense of lower image quality.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
Image
The translated image.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform image-to-image translation using a specified model.
You must have PIL
installed if you want to work with images (pip install Pillow
).
(
image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
model: typing.Optional[str] = None
)
→
str
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The input image to caption. It can be raw bytes, an image file, or a URL to an online image..
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
str
The generated text.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Takes an input image and return text.
Models can have very different outputs depending on your use case (image captioning, optical character recognition (OCR), Pix2Struct, etc). Please have a look to the model card to learn more about a model’s specificities.
Example:
>>> 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]
model: typing.Optional[str] = None
)
→
List[ObjectDetectionOutput]
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The image to detect objects on. It can be raw bytes, an image file, or a URL to an online image.
str
, optional) —
The model to use for object detection. Can be a model ID hosted on the Hugging Face Hub or a URL to a
deployed Inference Endpoint. If not provided, the default recommended model for object detection (DETR) will be used.
Returns
List[ObjectDetectionOutput]
A list of dictionaries containing the bounding boxes and associated attributes.
Raises
InferenceTimeoutError or HTTPError
or ValueError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.ValueError
—
If the request output is not a List.Perform object detection on the given image using the specified model.
You must have PIL
installed if you want to work with images (pip install Pillow
).
( json: typing.Union[str, typing.Dict, typing.List, NoneType] = None data: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, NoneType] = None model: typing.Optional[str] = None task: typing.Optional[str] = None stream: bool = False ) → bytes
Parameters
Union[str, Dict, List]
, optional) —
The JSON data to send in the request body. Defaults to None.
Union[str, Path, bytes, BinaryIO]
, optional) —
The content to send in the request body. It can be raw bytes, a pointer to an opened file, a local file
path, or a URL to an online resource (image, audio file,…). If both json
and data
are passed,
data
will take precedence. At least json
or data
must be provided. Defaults to None.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. Will override the model defined at the instance level. Defaults to None.
str
, optional) —
The task to perform on the inference. Used only to default to a recommended model if model
is not
provided. At least model
or task
must be provided. Defaults to None.
bool
, optional) —
Whether to iterate over streaming APIs.
Returns
bytes
The raw bytes returned by the server.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Make a POST request to the inference server.
(
sentence: str
other_sentences: typing.List[str]
model: typing.Optional[str] = None
)
→
List[float]
Parameters
str
) —
The main sentence to compare to others.
List[str]
) —
The list of sentences to compare to.
str
, optional) —
The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to
a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used.
Defaults to None.
Returns
List[float]
The embedding representing the input text.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Compute the semantic similarity between a sentence and a list of other sentences by comparing their embeddings.
Example:
>>> 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
parameters: typing.Union[typing.Dict[str, typing.Any], NoneType] = None
model: typing.Optional[str] = None
)
→
str
Parameters
str
) —
The input text to summarize.
Dict[str, Any]
, optional) —
Additional parameters for summarization. Check out this page
for more details.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
str
The generated summary text.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Generate a summary of a given text using a specified model.
(
prompt: str
details: bool = False
stream: bool = False
model: typing.Optional[str] = None
do_sample: bool = False
max_new_tokens: int = 20
best_of: typing.Optional[int] = None
repetition_penalty: typing.Optional[float] = None
return_full_text: bool = False
seed: typing.Optional[int] = None
stop_sequences: typing.Optional[typing.List[str]] = None
temperature: typing.Optional[float] = None
top_k: typing.Optional[int] = None
top_p: typing.Optional[float] = None
truncate: typing.Optional[int] = None
typical_p: typing.Optional[float] = None
watermark: bool = False
decoder_input_details: bool = False
)
→
Union[str, TextGenerationResponse, Iterable[str], Iterable[TextGenerationStreamResponse]]
Parameters
str
) —
Input text.
bool
, optional) —
By default, text_generation returns a string. Pass details=True
if you want a detailed output (tokens,
probabilities, seed, finish reason, etc.). Only available for models running on with the
text-generation-inference
backend.
bool
, optional) —
By default, text_generation returns the full generated text. Pass stream=True
if you want a stream of
tokens to be returned. Only available for models running on with the text-generation-inference
backend.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
bool
) —
Activate logits sampling
int
) —
Maximum number of generated tokens
int
) —
Generate best_of sequences and return the one if the highest token logprobs
float
) —
The parameter for repetition penalty. 1.0 means no penalty. See this
paper for more details.
bool
) —
Whether to prepend the prompt to the generated text
int
) —
Random sampling seed
List[str]
) —
Stop generating tokens if a member of stop_sequences
is generated
float
) —
The value used to module the logits distribution.
int
) —
The number of highest probability vocabulary tokens to keep for top-k-filtering.
float
) —
If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p
or
higher are kept for generation.
int
) —
Truncate inputs tokens to the given size
float
) —
Typical Decoding mass
See Typical Decoding for Natural Language Generation for more information
bool
) —
Watermarking with A Watermark for Large Language Models
bool
) —
Return the decoder input token logprobs and ids. You must set details=True
as well for it to be taken
into account. Defaults to False
.
Returns
Union[str, TextGenerationResponse, Iterable[str], Iterable[TextGenerationStreamResponse]]
Generated text returned from the server:
stream=False
and details=False
, the generated text is returned as a str
(default)stream=True
and details=False
, the generated text is returned token by token as a Iterable[str]
stream=False
and details=True
, the generated text is returned with more details as a TextGenerationResponsedetails=True
and stream=True
, the generated text is returned token by token as a iterable of TextGenerationStreamResponseRaises
ValidationError
or InferenceTimeoutError or HTTPError
ValidationError
—
If input values are not valid. No HTTP call is made to the server.HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Given a prompt, generate the following text.
It is recommended to have Pydantic installed in order to get inputs validated. This is preferable as it allow early failures.
API endpoint is supposed to run with the text-generation-inference
backend (TGI). This backend is the
go-to solution to run large language models at scale. However, for some smaller models (e.g. “gpt2”) the
default transformers
+ api-inference
solution is still in use. Both approaches have very similar APIs, but
not exactly the same. This method is compatible with both approaches but some parameters are only available for
text-generation-inference
. If some parameters are ignored, a warning message is triggered but the process
continues correctly.
To learn more about the TGI project, please refer to https://github.com/huggingface/text-generation-inference.
Example:
>>> 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)
TextGenerationResponse(
generated_text='100% open source and built to be easy to use.',
details=Details(
finish_reason=<FinishReason.Length: 'length'>,
generated_tokens=12,
seed=None,
prefill=[
InputToken(id=487, text='The', logprob=None),
InputToken(id=53789, text=' hugging', logprob=-13.171875),
(...)
InputToken(id=204, text=' ', logprob=-7.0390625)
],
tokens=[
Token(id=1425, text='100', logprob=-1.0175781, special=False),
Token(id=16, text='%', logprob=-0.0463562, special=False),
(...)
Token(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)
...
TextGenerationStreamResponse(token=Token(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(
id=25,
text='.',
logprob=-0.5703125,
special=False),
generated_text='100% open source and built to be easy to use.',
details=StreamDetails(finish_reason=<FinishReason.Length: 'length'>, generated_tokens=12, seed=None)
)
(
prompt: str
negative_prompt: typing.Optional[str] = None
height: typing.Optional[float] = None
width: typing.Optional[float] = None
num_inference_steps: typing.Optional[float] = None
guidance_scale: typing.Optional[float] = None
model: typing.Optional[str] = None
**kwargs
)
→
Image
Parameters
str
) —
The prompt to generate an image from.
str
, optional) —
An optional negative prompt for the image generation.
float
, optional) —
The height in pixels of the image to generate.
float
, optional) —
The width in pixels of the image to generate.
int
, optional) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference.
float
, optional) —
Higher guidance scale encourages to generate images that are closely linked to the text prompt
,
usually at the expense of lower image quality.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
Image
The generated image.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Generate an image based on a given text using a specified model.
You must have PIL
installed if you want to work with images (pip install Pillow
).
Example:
>>> 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")
(
text: str
model: typing.Optional[str] = None
)
→
bytes
Parameters
str
) —
The text to synthesize.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
bytes
The generated audio.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Synthesize an audio of a voice pronouncing a given text.
(
image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
labels: typing.List[str]
model: typing.Optional[str] = None
)
→
List[Dict]
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The input image to caption. It can be raw bytes, an image file, or a URL to an online image.
List[str]
) —
List of string possible labels. The len(labels)
must be greater than 1.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
List[Dict]
List of classification outputs containing the predicted labels and their confidence.
Raises
InferenceTimeoutError or HTTPError
HTTPError
—
If the request fails with an HTTP error status code other than HTTP 503.Provide input image and text labels to predict text labels for the image.
Example:
>>> 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"],
... )
[{"label": "dog", "score": 0.956}, ...]
An async version of the client is also provided, based on asyncio
and aiohttp
.
To use it, you can either install aiohttp
directly or use the [inference]
extra:
pip install --upgrade huggingface_hub[inference]
# or
# pip install aiohttp
( model: typing.Optional[str] = None token: typing.Union[str, bool, NoneType] = None timeout: typing.Optional[float] = None headers: typing.Union[typing.Dict[str, str], NoneType] = None cookies: typing.Union[typing.Dict[str, str], NoneType] = None )
Parameters
str
, optional
) —
The model to run inference with. Can be a model id hosted on the Hugging Face Hub, e.g. bigcode/starcoder
or a URL to a deployed Inference Endpoint. Defaults to None, in which case a recommended model is
automatically selected for the task.
str
, optional) —
Hugging Face token. Will default to the locally saved token. Pass token=False
if you don’t want to send
your token to the server.
float
, optional
) —
The maximum number of seconds to wait for a response from the server. Loading a new model in Inference
API can take up to several minutes. Defaults to None, meaning it will loop until the server is available.
Dict[str, str]
, optional
) —
Additional headers to send to the server. By default only the authorization and user-agent headers are sent.
Values in this dictionary will override the default values.
Dict[str, str]
, optional
) —
Additional cookies to send to the server.
Initialize a new Inference Client.
InferenceClient aims to provide a unified experience to perform inference. The client can be used seamlessly with either the (free) Inference API or self-hosted Inference Endpoints.
(
audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
model: typing.Optional[str] = None
)
→
List[Dict]
Parameters
str
, optional) —
The model to use for audio classification. Can be a model ID hosted on the Hugging Face Hub
or a URL to a deployed Inference Endpoint. If not provided, the default recommended model for
audio classification will be used.
Returns
List[Dict]
The classification output containing the predicted label and its confidence.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform audio classification on the provided audio content.
( audio: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path] model: typing.Optional[str] = None ) → str
Parameters
str
, optional) —
The model to use for ASR. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. If not provided, the default recommended model for ASR will be used.
Returns
str
The transcribed text.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform automatic speech recognition (ASR or audio-to-text) on the given audio content.
(
text: str
generated_responses: typing.Optional[typing.List[str]] = None
past_user_inputs: typing.Optional[typing.List[str]] = None
parameters: typing.Union[typing.Dict[str, typing.Any], NoneType] = None
model: typing.Optional[str] = None
)
→
Dict
Parameters
str
) —
The last input from the user in the conversation.
List[str]
, optional) —
A list of strings corresponding to the earlier replies from the model. Defaults to None.
List[str]
, optional) —
A list of strings corresponding to the earlier replies from the user. Should be the same length as
generated_responses
. Defaults to None.
Dict[str, Any]
, optional) —
Additional parameters for the conversational task. Defaults to None. For more details about the available
parameters, please refer to this page
str
, optional) —
The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to
a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used.
Defaults to None.
Returns
Dict
The generated conversational output.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Generate conversational responses based on the given input text (i.e. chat with the API).
Example:
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> output = await client.conversational("Hi, who are you?")
>>> output
{'generated_text': 'I am the one who knocks.', 'conversation': {'generated_responses': ['I am the one who knocks.'], 'past_user_inputs': ['Hi, who are you?']}, 'warnings': ['Setting `pad_token_id` to `eos_token_id`:50256 async for open-end generation.']}
>>> await client.conversational(
... "Wow, that's scary!",
... generated_responses=output["conversation"]["generated_responses"],
... past_user_inputs=output["conversation"]["past_user_inputs"],
... )
(
text: str
model: typing.Optional[str] = None
)
→
np.ndarray
Parameters
str
) —
The text to embed.
str
, optional) —
The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to
a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used.
Defaults to None.
Returns
np.ndarray
The embedding representing the input text as a float32 numpy array.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Generate embeddings for a given text.
Example:
# 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)
(
model: typing.Optional[str] = None
)
→
ModelStatus
Parameters
str
, optional) —
Identifier of the model for witch the status gonna be checked. If model is not provided,
the model associated with this instance of InferenceClient will be used. Only InferenceAPI service can be checked so the
identifier cannot be a URL.
Returns
ModelStatus
An instance of ModelStatus dataclass, containing information, about the state of the model: load, state, compute type and framework.
A function which returns the status of a specific model, from the Inference API.
(
image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
model: typing.Optional[str] = None
)
→
List[Dict]
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The image to classify. It can be raw bytes, an image file, or a URL to an online image.
str
, optional) —
The model to use for image classification. Can be a model ID hosted on the Hugging Face Hub or a URL to a
deployed Inference Endpoint. If not provided, the default recommended model for image classification will be used.
Returns
List[Dict]
a list of dictionaries containing the predicted label and associated probability.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform image classification on the given image using the specified model.
Example:
# 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")
[{'score': 0.9779096841812134, 'label': 'Blenheim spaniel'}, ...]
(
image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
model: typing.Optional[str] = None
)
→
List[Dict]
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The image to segment. It can be raw bytes, an image file, or a URL to an online image.
str
, optional) —
The model to use for image segmentation. Can be a model ID hosted on the Hugging Face Hub or a URL to a
deployed Inference Endpoint. If not provided, the default recommended model for image segmentation will be used.
Returns
List[Dict]
A list of dictionaries containing the segmented masks and associated attributes.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform image segmentation on the given image using the specified model.
You must have PIL
installed if you want to work with images (pip install Pillow
).
Example:
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.image_segmentation("cat.jpg"):
[{'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]
prompt: typing.Optional[str] = None
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
**kwargs
)
→
Image
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The input image for translation. It can be raw bytes, an image file, or a URL to an online image.
str
, optional) —
The text prompt to guide the image generation.
str
, optional) —
A negative prompt to guide the translation process.
int
, optional) —
The height in pixels of the generated image.
int
, optional) —
The width in pixels of the generated image.
int
, optional) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference.
float
, optional) —
Higher guidance scale encourages to generate images that are closely linked to the text prompt
,
usually at the expense of lower image quality.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
Image
The translated image.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Perform image-to-image translation using a specified model.
You must have PIL
installed if you want to work with images (pip install Pillow
).
(
image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
model: typing.Optional[str] = None
)
→
str
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The input image to caption. It can be raw bytes, an image file, or a URL to an online image..
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
str
The generated text.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Takes an input image and return text.
Models can have very different outputs depending on your use case (image captioning, optical character recognition (OCR), Pix2Struct, etc). Please have a look to the model card to learn more about a model’s specificities.
Example:
# 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]
model: typing.Optional[str] = None
)
→
List[ObjectDetectionOutput]
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The image to detect objects on. It can be raw bytes, an image file, or a URL to an online image.
str
, optional) —
The model to use for object detection. Can be a model ID hosted on the Hugging Face Hub or a URL to a
deployed Inference Endpoint. If not provided, the default recommended model for object detection (DETR) will be used.
Returns
List[ObjectDetectionOutput]
A list of dictionaries containing the bounding boxes and associated attributes.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
or ValueError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.ValueError
—
If the request output is not a List.Perform object detection on the given image using the specified model.
You must have PIL
installed if you want to work with images (pip install Pillow
).
( json: typing.Union[str, typing.Dict, typing.List, NoneType] = None data: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path, NoneType] = None model: typing.Optional[str] = None task: typing.Optional[str] = None stream: bool = False ) → bytes
Parameters
Union[str, Dict, List]
, optional) —
The JSON data to send in the request body. Defaults to None.
Union[str, Path, bytes, BinaryIO]
, optional) —
The content to send in the request body. It can be raw bytes, a pointer to an opened file, a local file
path, or a URL to an online resource (image, audio file,…). If both json
and data
are passed,
data
will take precedence. At least json
or data
must be provided. Defaults to None.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. Will override the model defined at the instance level. Defaults to None.
str
, optional) —
The task to perform on the inference. Used only to default to a recommended model if model
is not
provided. At least model
or task
must be provided. Defaults to None.
bool
, optional) —
Whether to iterate over streaming APIs.
Returns
bytes
The raw bytes returned by the server.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Make a POST request to the inference server.
(
sentence: str
other_sentences: typing.List[str]
model: typing.Optional[str] = None
)
→
List[float]
Parameters
str
) —
The main sentence to compare to others.
List[str]
) —
The list of sentences to compare to.
str
, optional) —
The model to use for the conversational task. Can be a model ID hosted on the Hugging Face Hub or a URL to
a deployed Inference Endpoint. If not provided, the default recommended conversational model will be used.
Defaults to None.
Returns
List[float]
The embedding representing the input text.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Compute the semantic similarity between a sentence and a list of other sentences by comparing their embeddings.
Example:
# 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
parameters: typing.Union[typing.Dict[str, typing.Any], NoneType] = None
model: typing.Optional[str] = None
)
→
str
Parameters
str
) —
The input text to summarize.
Dict[str, Any]
, optional) —
Additional parameters for summarization. Check out this page
for more details.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
str
The generated summary text.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Generate a summary of a given text using a specified model.
(
prompt: str
details: bool = False
stream: bool = False
model: typing.Optional[str] = None
do_sample: bool = False
max_new_tokens: int = 20
best_of: typing.Optional[int] = None
repetition_penalty: typing.Optional[float] = None
return_full_text: bool = False
seed: typing.Optional[int] = None
stop_sequences: typing.Optional[typing.List[str]] = None
temperature: typing.Optional[float] = None
top_k: typing.Optional[int] = None
top_p: typing.Optional[float] = None
truncate: typing.Optional[int] = None
typical_p: typing.Optional[float] = None
watermark: bool = False
decoder_input_details: bool = False
)
→
Union[str, TextGenerationResponse, Iterable[str], Iterable[TextGenerationStreamResponse]]
Parameters
str
) —
Input text.
bool
, optional) —
By default, text_generation returns a string. Pass details=True
if you want a detailed output (tokens,
probabilities, seed, finish reason, etc.). Only available for models running on with the
text-generation-inference
backend.
bool
, optional) —
By default, text_generation returns the full generated text. Pass stream=True
if you want a stream of
tokens to be returned. Only available for models running on with the text-generation-inference
backend.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
bool
) —
Activate logits sampling
int
) —
Maximum number of generated tokens
int
) —
Generate best_of sequences and return the one if the highest token logprobs
float
) —
The parameter for repetition penalty. 1.0 means no penalty. See this
paper for more details.
bool
) —
Whether to prepend the prompt to the generated text
int
) —
Random sampling seed
List[str]
) —
Stop generating tokens if a member of stop_sequences
is generated
float
) —
The value used to module the logits distribution.
int
) —
The number of highest probability vocabulary tokens to keep for top-k-filtering.
float
) —
If set to < 1, only the smallest set of most probable tokens with probabilities that add up to top_p
or
higher are kept for generation.
int
) —
Truncate inputs tokens to the given size
float
) —
Typical Decoding mass
See Typical Decoding for Natural Language Generation for more information
bool
) —
Watermarking with A Watermark for Large Language Models
bool
) —
Return the decoder input token logprobs and ids. You must set details=True
as well for it to be taken
into account. Defaults to False
.
Returns
Union[str, TextGenerationResponse, Iterable[str], Iterable[TextGenerationStreamResponse]]
Generated text returned from the server:
stream=False
and details=False
, the generated text is returned as a str
(default)stream=True
and details=False
, the generated text is returned token by token as a Iterable[str]
stream=False
and details=True
, the generated text is returned with more details as a TextGenerationResponsedetails=True
and stream=True
, the generated text is returned token by token as a iterable of TextGenerationStreamResponseRaises
ValidationError
or InferenceTimeoutError or aiohttp.ClientResponseError
ValidationError
—
If input values are not valid. No HTTP call is made to the server.aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Given a prompt, generate the following text.
It is recommended to have Pydantic installed in order to get inputs validated. This is preferable as it allow early failures.
API endpoint is supposed to run with the text-generation-inference
backend (TGI). This backend is the
go-to solution to run large language models at scale. However, for some smaller models (e.g. “gpt2”) the
default transformers
+ api-inference
solution is still in use. Both approaches have very similar APIs, but
not exactly the same. This method is compatible with both approaches but some parameters are only available for
text-generation-inference
. If some parameters are ignored, a warning message is triggered but the process
continues correctly.
To learn more about the TGI project, please refer to https://github.com/huggingface/text-generation-inference.
Example:
# 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 async 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)
TextGenerationResponse(
generated_text='100% open source and built to be easy to use.',
details=Details(
finish_reason=<FinishReason.Length: 'length'>,
generated_tokens=12,
seed=None,
prefill=[
InputToken(id=487, text='The', logprob=None),
InputToken(id=53789, text=' hugging', logprob=-13.171875),
(...)
InputToken(id=204, text=' ', logprob=-7.0390625)
],
tokens=[
Token(id=1425, text='100', logprob=-1.0175781, special=False),
Token(id=16, text='%', logprob=-0.0463562, special=False),
(...)
Token(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)
...
TextGenerationStreamResponse(token=Token(id=1425, text='100', logprob=-1.0175781, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=16, text='%', logprob=-0.0463562, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=1314, text=' open', logprob=-1.3359375, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=3178, text=' source', logprob=-0.28100586, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=273, text=' and', logprob=-0.5961914, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=3426, text=' built', logprob=-1.9423828, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-1.4121094, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=314, text=' be', logprob=-1.5224609, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=1833, text=' easy', logprob=-2.1132812, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=271, text=' to', logprob=-0.08520508, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(id=745, text=' use', logprob=-0.39453125, special=False), generated_text=None, details=None)
TextGenerationStreamResponse(token=Token(
id=25,
text='.',
logprob=-0.5703125,
special=False),
generated_text='100% open source and built to be easy to use.',
details=StreamDetails(finish_reason=<FinishReason.Length: 'length'>, generated_tokens=12, seed=None)
)
(
prompt: str
negative_prompt: typing.Optional[str] = None
height: typing.Optional[float] = None
width: typing.Optional[float] = None
num_inference_steps: typing.Optional[float] = None
guidance_scale: typing.Optional[float] = None
model: typing.Optional[str] = None
**kwargs
)
→
Image
Parameters
str
) —
The prompt to generate an image from.
str
, optional) —
An optional negative prompt for the image generation.
float
, optional) —
The height in pixels of the image to generate.
float
, optional) —
The width in pixels of the image to generate.
int
, optional) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference.
float
, optional) —
Higher guidance scale encourages to generate images that are closely linked to the text prompt
,
usually at the expense of lower image quality.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
Image
The generated image.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Generate an image based on a given text using a specified model.
You must have PIL
installed if you want to work with images (pip install Pillow
).
Example:
# 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")
(
text: str
model: typing.Optional[str] = None
)
→
bytes
Parameters
str
) —
The text to synthesize.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
bytes
The generated audio.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Synthesize an audio of a voice pronouncing a given text.
(
image: typing.Union[bytes, typing.BinaryIO, str, pathlib.Path]
labels: typing.List[str]
model: typing.Optional[str] = None
)
→
List[Dict]
Parameters
Union[str, Path, bytes, BinaryIO]
) —
The input image to caption. It can be raw bytes, an image file, or a URL to an online image.
List[str]
) —
List of string possible labels. The len(labels)
must be greater than 1.
str
, optional) —
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. This parameter overrides the model defined at the instance level. Defaults to None.
Returns
List[Dict]
List of classification outputs containing the predicted labels and their confidence.
Raises
InferenceTimeoutError or aiohttp.ClientResponseError
aiohttp.ClientResponseError
—
If the request fails with an HTTP error status code other than HTTP 503.Provide input image and text labels to predict text labels for the image.
Example:
# 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"],
... )
[{"label": "dog", "score": 0.956}, ...]
Error raised when a model is unavailable or the request times out.
For most tasks, the return value has a built-in type (string, list, image…). Here is a list for the more complex types.
( *args **kwargs )
Dictionary containing the output of a audio_classification() and image_classification() task.
( *args **kwargs )
Dictionary containing the “conversation” part of a conversational() task.
( *args **kwargs )
Dictionary containing the output of a conversational() task.
( *args **kwargs )
Dictionary containing information about a image_segmentation() task. In practice, image segmentation returns a
list of ImageSegmentationOutput
with 1 item per mask.
text_generation() task has a greater support than other tasks in InferenceClient
. In
particular, user inputs and server outputs are validated using Pydantic
if this package is installed. Therefore, we recommend installing it (pip install pydantic
)
for a better user experience.
You can find below the dataclasses used to validate data and in particular TextGenerationParameters (input), TextGenerationResponse (output) and TextGenerationStreamResponse (streaming output).
( do_sample: bool = False max_new_tokens: int = 20 repetition_penalty: typing.Optional[float] = None return_full_text: bool = False stop: typing.List[str] = <factory> seed: typing.Optional[int] = None temperature: typing.Optional[float] = None top_k: typing.Optional[int] = None top_p: typing.Optional[float] = None truncate: typing.Optional[int] = None typical_p: typing.Optional[float] = None best_of: typing.Optional[int] = None watermark: bool = False details: bool = False decoder_input_details: bool = False )
Parameters
bool
, optional) —
Activate logits sampling. Defaults to False.
int
, optional) —
Maximum number of generated tokens. Defaults to 20.
Optional[float]
, optional) —
The parameter for repetition penalty. A value of 1.0 means no penalty. See this paper
for more details. Defaults to None.
bool
, optional) —
Whether to prepend the prompt to the generated text. Defaults to False.
List[str]
, optional) —
Stop generating tokens if a member of stop_sequences
is generated. Defaults to an empty list.
Optional[int]
, optional) —
Random sampling seed. Defaults to None.
Optional[float]
, optional) —
The value used to modulate the logits distribution. Defaults to None.
Optional[int]
, optional) —
The number of highest probability vocabulary tokens to keep for top-k-filtering. Defaults to None.
Optional[float]
, optional) —
If set to a value less than 1, only the smallest set of most probable tokens with probabilities that add up
to top_p
or higher are kept for generation. Defaults to None.
Optional[int]
, optional) —
Truncate input tokens to the given size. Defaults to None.
Optional[float]
, optional) —
Typical Decoding mass. See Typical Decoding for Natural Language Generation
for more information. Defaults to None.
Optional[int]
, optional) —
Generate best_of
sequences and return the one with the highest token logprobs. Defaults to None.
bool
, optional) —
Watermarking with A Watermark for Large Language Models. Defaults to False.
bool
, optional) —
Get generation details. Defaults to False.
bool
, optional) —
Get decoder input token logprobs and ids. Defaults to False.
Parameters for text generation.
( generated_text: str details: typing.Optional[huggingface_hub.inference._text_generation.Details] = None )
Represents a response for text generation.
Only returned when details=True
, otherwise a string is returned.
( token: Token generated_text: typing.Optional[str] = None details: typing.Optional[huggingface_hub.inference._text_generation.StreamDetails] = None )
Represents a response for streaming text generation.
Only returned when details=True
and stream=True
.
( id: int text: str logprob: typing.Optional[float] = None )
Represents an input token.
( id: int text: str logprob: float special: bool )
Represents a token.
( value names = None module = None qualname = None type = None start = 1 )
An enumeration.
( generated_text: str finish_reason: FinishReason generated_tokens: int seed: typing.Optional[int] = None prefill: typing.List[huggingface_hub.inference._text_generation.InputToken] = <factory> tokens: typing.List[huggingface_hub.inference._text_generation.Token] = <factory> )
Parameters
str
) —
The generated text.
FinishReason
) —
The reason for the generation to finish, represented by a FinishReason
value.
int
) —
The number of generated tokens in the sequence.
Optional[int]
) —
The sampling seed if sampling was activated.
List[InputToken]
) —
The decoder input tokens. Empty if decoder_input_details
is False. Defaults to an empty list.
List[Token]
) —
The generated tokens. Defaults to an empty list.
Represents a best-of sequence generated during text generation.
( finish_reason: FinishReason generated_tokens: int seed: typing.Optional[int] = None prefill: typing.List[huggingface_hub.inference._text_generation.InputToken] = <factory> tokens: typing.List[huggingface_hub.inference._text_generation.Token] = <factory> best_of_sequences: typing.Optional[typing.List[huggingface_hub.inference._text_generation.BestOfSequence]] = None )
Parameters
FinishReason
) —
The reason for the generation to finish, represented by a FinishReason
value.
int
) —
The number of generated tokens.
Optional[int]
) —
The sampling seed if sampling was activated.
List[InputToken]
, optional) —
The decoder input tokens. Empty if decoder_input_details
is False. Defaults to an empty list.
List[Token]
) —
The generated tokens. Defaults to an empty list.
Optional[List[BestOfSequence]]
) —
Additional sequences when using the best_of
parameter.
Represents details of a text generation.
( finish_reason: FinishReason generated_tokens: int seed: typing.Optional[int] = None )
Represents details of a text generation stream.
InferenceAPI
is the legacy way to call the Inference API. The interface is more simplistic and requires knowing
the input parameters and output format for each task. It also lacks the ability to connect to other services like
Inference Endpoints or AWS SageMaker. InferenceAPI
will soon be deprecated so we recommend using InferenceClient
whenever possible. Check out this guide to learn how to switch from
InferenceAPI
to InferenceClient in your scripts.
( repo_id: str task: typing.Optional[str] = None token: typing.Optional[str] = None gpu: bool = False )
Client to configure requests and make calls to the HuggingFace Inference API.
Example:
>>> 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'(...)'
( repo_id: str task: typing.Optional[str] = None token: typing.Optional[str] = None gpu: bool = False )
Parameters
str
) —
Id of repository (e.g. user/bert-base-uncased).
str
, optional, defaults None
) —
Whether to force a task instead of using task specified in the
repository.
Inits headers and API call information.
( 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 )
Parameters
str
or Dict
or List[str]
or List[List[str]]
, optional) —
Inputs for the prediction.
Dict
, optional) —
Additional parameters for the models. Will be sent as parameters
in the
payload.
bytes
, optional) —
Bytes content of the request. In this case, leave inputs
and params
empty.
bool
, defaults to False
) —
If True
, the raw Response
object is returned. You can parse its content
as preferred. By default, the content is parsed into a more practical format
(json dictionary or PIL Image for example).
Make a call to the Inference API.