-
Notifications
You must be signed in to change notification settings - Fork 470
/
_async_client.py
2608 lines (2340 loc) · 118 KB
/
_async_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright 2023-present, the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WARNING
# This entire file has been adapted from the sync-client code in `src/huggingface_hub/inference/_client.py`.
# Any change in InferenceClient will be automatically reflected in AsyncInferenceClient.
# To re-generate the code, run `make style` or `python ./utils/generate_async_inference_client.py --update`.
# WARNING
import asyncio
import base64
import logging
import re
import time
import warnings
from typing import (
TYPE_CHECKING,
Any,
AsyncIterable,
Dict,
List,
Literal,
Optional,
Union,
overload,
)
from requests.structures import CaseInsensitiveDict
from huggingface_hub.constants import ALL_INFERENCE_API_FRAMEWORKS, INFERENCE_ENDPOINT, MAIN_INFERENCE_API_FRAMEWORKS
from huggingface_hub.errors import InferenceTimeoutError
from huggingface_hub.inference._common import (
TASKS_EXPECTING_IMAGES,
ContentT,
ModelStatus,
_async_stream_chat_completion_response_from_bytes,
_async_stream_text_generation_response,
_b64_encode,
_b64_to_image,
_bytes_to_dict,
_bytes_to_image,
_bytes_to_list,
_fetch_recommended_models,
_get_unsupported_text_generation_kwargs,
_import_numpy,
_is_chat_completion_server,
_open_as_binary,
_set_as_non_chat_completion_server,
_set_unsupported_text_generation_kwargs,
raise_text_generation_error,
)
from huggingface_hub.inference._generated.types import (
AudioClassificationOutputElement,
AudioToAudioOutputElement,
AutomaticSpeechRecognitionOutput,
ChatCompletionInputTool,
ChatCompletionInputToolTypeClass,
ChatCompletionOutput,
ChatCompletionOutputComplete,
ChatCompletionOutputMessage,
ChatCompletionStreamOutput,
DocumentQuestionAnsweringOutputElement,
FillMaskOutputElement,
ImageClassificationOutputElement,
ImageSegmentationOutputElement,
ImageToTextOutput,
ObjectDetectionOutputElement,
QuestionAnsweringOutputElement,
SummarizationOutput,
TableQuestionAnsweringOutputElement,
TextClassificationOutputElement,
TextGenerationInputGrammarType,
TextGenerationOutput,
TextGenerationStreamOutput,
TokenClassificationOutputElement,
TranslationOutput,
VisualQuestionAnsweringOutputElement,
ZeroShotClassificationOutputElement,
ZeroShotImageClassificationOutputElement,
)
from huggingface_hub.inference._generated.types.chat_completion import ChatCompletionInputToolTypeEnum
from huggingface_hub.inference._types import (
ConversationalOutput, # soon to be removed
)
from huggingface_hub.utils import (
build_hf_headers,
)
from .._common import _async_yield_from, _import_aiohttp
if TYPE_CHECKING:
import numpy as np
from PIL.Image import Image
logger = logging.getLogger(__name__)
MODEL_KWARGS_NOT_USED_REGEX = re.compile(r"The following `model_kwargs` are not used by the model: \[(.*?)\]")
class AsyncInferenceClient:
"""
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.
Args:
model (`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.
token (`str` or `bool`, *optional*):
Hugging Face token. Will default to the locally saved token if not provided.
Pass `token=False` if you don't want to send your token to the server.
timeout (`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.
headers (`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.
cookies (`Dict[str, str]`, `optional`):
Additional cookies to send to the server.
"""
def __init__(
self,
model: Optional[str] = None,
token: Union[str, bool, None] = None,
timeout: Optional[float] = None,
headers: Optional[Dict[str, str]] = None,
cookies: Optional[Dict[str, str]] = None,
) -> None:
self.model: Optional[str] = model
self.token: Union[str, bool, None] = token
self.headers = CaseInsensitiveDict(build_hf_headers(token=token)) # contains 'authorization' + 'user-agent'
if headers is not None:
self.headers.update(headers)
self.cookies = cookies
self.timeout = timeout
def __repr__(self):
return f"<InferenceClient(model='{self.model if self.model else ''}', timeout={self.timeout})>"
@overload
async def post( # type: ignore[misc]
self,
*,
json: Optional[Union[str, Dict, List]] = None,
data: Optional[ContentT] = None,
model: Optional[str] = None,
task: Optional[str] = None,
stream: Literal[False] = ...,
) -> bytes: ...
@overload
async def post( # type: ignore[misc]
self,
*,
json: Optional[Union[str, Dict, List]] = None,
data: Optional[ContentT] = None,
model: Optional[str] = None,
task: Optional[str] = None,
stream: Literal[True] = ...,
) -> AsyncIterable[bytes]: ...
@overload
async def post(
self,
*,
json: Optional[Union[str, Dict, List]] = None,
data: Optional[ContentT] = None,
model: Optional[str] = None,
task: Optional[str] = None,
stream: bool = False,
) -> Union[bytes, AsyncIterable[bytes]]: ...
async def post(
self,
*,
json: Optional[Union[str, Dict, List]] = None,
data: Optional[ContentT] = None,
model: Optional[str] = None,
task: Optional[str] = None,
stream: bool = False,
) -> Union[bytes, AsyncIterable[bytes]]:
"""
Make a POST request to the inference server.
Args:
json (`Union[str, Dict, List]`, *optional*):
The JSON data to send in the request body, specific to each task. Defaults to None.
data (`Union[str, Path, bytes, BinaryIO]`, *optional*):
The content to send in the request body, specific to each task.
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.
model (`str`, *optional*):
The model to use for inference. Can be a model ID hosted on the Hugging Face Hub or a URL to a deployed
Inference Endpoint. Will override the model defined at the instance level. Defaults to None.
task (`str`, *optional*):
The task to perform on the inference. All available tasks can be found
[here](https://huggingface.co/tasks). Used only to default to a recommended model if `model` is not
provided. At least `model` or `task` must be provided. Defaults to None.
stream (`bool`, *optional*):
Whether to iterate over streaming APIs.
Returns:
bytes: The raw bytes returned by the server.
Raises:
[`InferenceTimeoutError`]:
If the model is unavailable or the request times out.
`aiohttp.ClientResponseError`:
If the request fails with an HTTP error status code other than HTTP 503.
"""
aiohttp = _import_aiohttp()
url = self._resolve_url(model, task)
if data is not None and json is not None:
warnings.warn("Ignoring `json` as `data` is passed as binary.")
# Set Accept header if relevant
headers = self.headers.copy()
if task in TASKS_EXPECTING_IMAGES and "Accept" not in headers:
headers["Accept"] = "image/png"
t0 = time.time()
timeout = self.timeout
while True:
with _open_as_binary(data) as data_as_binary:
# Do not use context manager as we don't want to close the connection immediately when returning
# a stream
client = aiohttp.ClientSession(
headers=headers, cookies=self.cookies, timeout=aiohttp.ClientTimeout(self.timeout)
)
try:
response = await client.post(url, json=json, data=data_as_binary)
response_error_payload = None
if response.status != 200:
try:
response_error_payload = await response.json() # get payload before connection closed
except Exception:
pass
response.raise_for_status()
if stream:
return _async_yield_from(client, response)
else:
content = await response.read()
await client.close()
return content
except asyncio.TimeoutError as error:
await client.close()
# Convert any `TimeoutError` to a `InferenceTimeoutError`
raise InferenceTimeoutError(f"Inference call timed out: {url}") from error # type: ignore
except aiohttp.ClientResponseError as error:
error.response_error_payload = response_error_payload
await client.close()
if response.status == 422 and task is not None:
error.message += f". Make sure '{task}' task is supported by the model."
if response.status == 503:
# If Model is unavailable, either raise a TimeoutError...
if timeout is not None and time.time() - t0 > timeout:
raise InferenceTimeoutError(
f"Model not loaded on the server: {url}. Please retry with a higher timeout"
f" (current: {self.timeout}).",
request=error.request,
response=error.response,
) from error
# ...or wait 1s and retry
logger.info(f"Waiting for model to be loaded on the server: {error}")
time.sleep(1)
if timeout is not None:
timeout = max(self.timeout - (time.time() - t0), 1) # type: ignore
continue
raise error
async def audio_classification(
self,
audio: ContentT,
*,
model: Optional[str] = None,
) -> List[AudioClassificationOutputElement]:
"""
Perform audio classification on the provided audio content.
Args:
audio (Union[str, Path, bytes, BinaryIO]):
The audio content to classify. It can be raw audio bytes, a local audio file, or a URL pointing to an
audio file.
model (`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[AudioClassificationOutputElement]`: List of [`AudioClassificationOutputElement`] items containing the predicted labels and their confidence.
Raises:
[`InferenceTimeoutError`]:
If the model is unavailable or the request times out.
`aiohttp.ClientResponseError`:
If the request fails with an HTTP error status code other than HTTP 503.
Example:
```py
# 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'),
...
]
```
"""
response = await self.post(data=audio, model=model, task="audio-classification")
return AudioClassificationOutputElement.parse_obj_as_list(response)
async def audio_to_audio(
self,
audio: ContentT,
*,
model: Optional[str] = None,
) -> List[AudioToAudioOutputElement]:
"""
Performs multiple tasks related to audio-to-audio depending on the model (eg: speech enhancement, source separation).
Args:
audio (Union[str, Path, bytes, BinaryIO]):
The audio content for the model. It can be raw audio bytes, a local audio file, or a URL pointing to an
audio file.
model (`str`, *optional*):
The model can be any model which takes an audio file and returns another audio file. 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_to_audio will be used.
Returns:
`List[AudioToAudioOutputElement]`: A list of [`AudioToAudioOutputElement`] items containing audios label, content-type, and audio content in blob.
Raises:
`InferenceTimeoutError`:
If the model is unavailable or the request times out.
`aiohttp.ClientResponseError`:
If the request fails with an HTTP error status code other than HTTP 503.
Example:
```py
# 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)
```
"""
response = await self.post(data=audio, model=model, task="audio-to-audio")
audio_output = AudioToAudioOutputElement.parse_obj_as_list(response)
for item in audio_output:
item.blob = base64.b64decode(item.blob)
return audio_output
async def automatic_speech_recognition(
self,
audio: ContentT,
*,
model: Optional[str] = None,
) -> AutomaticSpeechRecognitionOutput:
"""
Perform automatic speech recognition (ASR or audio-to-text) on the given audio content.
Args:
audio (Union[str, Path, bytes, BinaryIO]):
The content to transcribe. It can be raw audio bytes, local audio file, or a URL to an audio file.
model (`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:
[`AutomaticSpeechRecognitionOutput`]: An item containing the transcribed text and optionally the timestamp chunks.
Raises:
[`InferenceTimeoutError`]:
If the model is unavailable or the request times out.
`aiohttp.ClientResponseError`:
If the request fails with an HTTP error status code other than HTTP 503.
Example:
```py
# Must be run in an async context
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()
>>> await client.automatic_speech_recognition("hello_world.flac").text
"hello world"
```
"""
response = await self.post(data=audio, model=model, task="automatic-speech-recognition")
return AutomaticSpeechRecognitionOutput.parse_obj_as_instance(response)
@overload
async def chat_completion( # type: ignore
self,
messages: List[Dict[str, str]],
*,
model: Optional[str] = None,
stream: Literal[False] = False,
frequency_penalty: Optional[float] = None,
logit_bias: Optional[List[float]] = None,
logprobs: Optional[bool] = None,
max_tokens: Optional[int] = None,
n: Optional[int] = None,
presence_penalty: Optional[float] = None,
seed: Optional[int] = None,
stop: Optional[List[str]] = None,
temperature: Optional[float] = None,
tool_choice: Optional[Union[ChatCompletionInputToolTypeClass, ChatCompletionInputToolTypeEnum]] = None,
tool_prompt: Optional[str] = None,
tools: Optional[List[ChatCompletionInputTool]] = None,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
) -> ChatCompletionOutput: ...
@overload
async def chat_completion( # type: ignore
self,
messages: List[Dict[str, str]],
*,
model: Optional[str] = None,
stream: Literal[True] = True,
frequency_penalty: Optional[float] = None,
logit_bias: Optional[List[float]] = None,
logprobs: Optional[bool] = None,
max_tokens: Optional[int] = None,
n: Optional[int] = None,
presence_penalty: Optional[float] = None,
seed: Optional[int] = None,
stop: Optional[List[str]] = None,
temperature: Optional[float] = None,
tool_choice: Optional[Union[ChatCompletionInputToolTypeClass, ChatCompletionInputToolTypeEnum]] = None,
tool_prompt: Optional[str] = None,
tools: Optional[List[ChatCompletionInputTool]] = None,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
) -> AsyncIterable[ChatCompletionStreamOutput]: ...
@overload
async def chat_completion(
self,
messages: List[Dict[str, str]],
*,
model: Optional[str] = None,
stream: bool = False,
frequency_penalty: Optional[float] = None,
logit_bias: Optional[List[float]] = None,
logprobs: Optional[bool] = None,
max_tokens: Optional[int] = None,
n: Optional[int] = None,
presence_penalty: Optional[float] = None,
seed: Optional[int] = None,
stop: Optional[List[str]] = None,
temperature: Optional[float] = None,
tool_choice: Optional[Union[ChatCompletionInputToolTypeClass, ChatCompletionInputToolTypeEnum]] = None,
tool_prompt: Optional[str] = None,
tools: Optional[List[ChatCompletionInputTool]] = None,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
) -> Union[ChatCompletionOutput, AsyncIterable[ChatCompletionStreamOutput]]: ...
async def chat_completion(
self,
messages: List[Dict[str, str]],
*,
model: Optional[str] = None,
stream: bool = False,
# Parameters from ChatCompletionInput (handled manually)
frequency_penalty: Optional[float] = None,
logit_bias: Optional[List[float]] = None,
logprobs: Optional[bool] = None,
max_tokens: Optional[int] = None,
n: Optional[int] = None,
presence_penalty: Optional[float] = None,
seed: Optional[int] = None,
stop: Optional[List[str]] = None,
temperature: Optional[float] = None,
tool_choice: Optional[Union[ChatCompletionInputToolTypeClass, ChatCompletionInputToolTypeEnum]] = None,
tool_prompt: Optional[str] = None,
tools: Optional[List[ChatCompletionInputTool]] = None,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
) -> Union[ChatCompletionOutput, AsyncIterable[ChatCompletionStreamOutput]]:
"""
A method for completing conversations using a specified language model.
<Tip>
If the model is served by a server supporting chat-completion, the method will directly call the server's
`/v1/chat/completions` endpoint. If the server does not support chat-completion, the method will render the
chat template client-side based on the information fetched from the Hub API. In this case, you will need to
have `minijinja` template engine installed. Run `pip install "huggingface_hub[inference]"` or `pip install minijinja`
to install it.
</Tip>
Args:
messages (List[Union[`SystemMessage`, `UserMessage`, `AssistantMessage`]]):
Conversation history consisting of roles and content pairs.
model (`str`, *optional*):
The model to use for chat-completion. 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 chat-based text-generation will be used.
See https://huggingface.co/tasks/text-generation for more details.
frequency_penalty (`float`, *optional*):
Penalizes new tokens based on their existing frequency
in the text so far. Range: [-2.0, 2.0]. Defaults to 0.0.
logit_bias (`List[float]`, *optional*):
Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens
(specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically,
the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model,
but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should
result in a ban or exclusive selection of the relevant token. Defaults to None.
logprobs (`bool`, *optional*):
Whether to return log probabilities of the output tokens or not. If true, returns the log
probabilities of each output token returned in the content of message.
max_tokens (`int`, *optional*):
Maximum number of tokens allowed in the response. Defaults to 20.
n (`int`, *optional*):
UNUSED.
presence_penalty (`float`, *optional*):
Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the
text so far, increasing the model's likelihood to talk about new topics.
seed (Optional[`int`], *optional*):
Seed for reproducible control flow. Defaults to None.
stop (Optional[`str`], *optional*):
Up to four strings which trigger the end of the response.
Defaults to None.
stream (`bool`, *optional*):
Enable realtime streaming of responses. Defaults to False.
temperature (`float`, *optional*):
Controls randomness of the generations. Lower values ensure
less random completions. Range: [0, 2]. Defaults to 1.0.
top_logprobs (`int`, *optional*):
An integer between 0 and 5 specifying the number of most likely tokens to return at each token
position, each with an associated log probability. logprobs must be set to true if this parameter is
used.
top_p (`float`, *optional*):
Fraction of the most likely next words to sample from.
Must be between 0 and 1. Defaults to 1.0.
tool_choice ([`ChatCompletionInputToolTypeClass`] or [`ChatCompletionInputToolTypeEnum`], *optional*):
The tool to use for the completion. Defaults to "auto".
tool_prompt (`str`, *optional*):
A prompt to be appended before the tools.
tools (List of [`ChatCompletionInputTool`], *optional*):
A list of tools the model may call. Currently, only functions are supported as a tool. Use this to
provide a list of functions the model may generate JSON inputs for.
Returns:
[`ChatCompletionOutput] or Iterable of [`ChatCompletionStreamOutput`]:
Generated text returned from the server:
- if `stream=False`, the generated text is returned as a [`ChatCompletionOutput`] (default).
- if `stream=True`, the generated text is returned token by token as a sequence of [`ChatCompletionStreamOutput`].
Raises:
[`InferenceTimeoutError`]:
If the model is unavailable or the request times out.
`aiohttp.ClientResponseError`:
If the request fails with an HTTP error status code other than HTTP 503.
Example:
```py
# Must be run in an async context
# Chat example
>>> from huggingface_hub import AsyncInferenceClient
>>> messages = [{"role": "user", "content": "What is the capital of France?"}]
>>> client = AsyncInferenceClient("HuggingFaceH4/zephyr-7b-beta")
>>> await client.chat_completion(messages, max_tokens=100)
ChatCompletionOutput(
choices=[
ChatCompletionOutputComplete(
finish_reason='eos_token',
index=0,
message=ChatCompletionOutputMessage(
content='The capital of France is Paris. The official name of the city is Ville de Paris (City of Paris) and the name of the country governing body, which is located in Paris, is La République française (The French Republic). \nI hope that helps! Let me know if you need any further information.'
)
)
],
created=1710498360
)
>>> 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)
# Chat example with tools
>>> 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 async 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
)
```
"""
# determine model
model = model or self.model or self.get_recommended_model("text-generation")
if _is_chat_completion_server(model):
# First, let's consider the server has a `/v1/chat/completions` endpoint.
# If that's the case, we don't have to render the chat template client-side.
model_url = self._resolve_url(model)
if not model_url.endswith("/chat/completions"):
model_url += "/v1/chat/completions"
try:
data = await self.post(
model=model_url,
json=dict(
model="tgi", # random string
messages=messages,
frequency_penalty=frequency_penalty,
logit_bias=logit_bias,
logprobs=logprobs,
max_tokens=max_tokens,
n=n,
presence_penalty=presence_penalty,
seed=seed,
stop=stop,
temperature=temperature,
tool_choice=tool_choice,
tool_prompt=tool_prompt,
tools=tools,
top_logprobs=top_logprobs,
top_p=top_p,
stream=stream,
),
stream=stream,
)
except _import_aiohttp().ClientResponseError as e:
if e.status in (400, 404, 500):
# Let's consider the server is not a chat completion server.
# Then we call again `chat_completion` which will render the chat template client side.
# (can be HTTP 500, HTTP 400, HTTP 404 depending on the server)
_set_as_non_chat_completion_server(model)
logger.warning(
f"Server {model_url} does not seem to support chat completion. Falling back to text generation. Error: {e}"
)
return await self.chat_completion(
messages=messages,
model=model,
stream=stream,
max_tokens=max_tokens,
seed=seed,
stop=stop,
temperature=temperature,
top_p=top_p,
)
raise
if stream:
return _async_stream_chat_completion_response_from_bytes(data) # type: ignore[arg-type]
return ChatCompletionOutput.parse_obj_as_instance(data) # type: ignore[arg-type]
# At this point, we know the server is not a chat completion server.
# It means it's a transformers-backed server for which we can send a list of messages directly to the
# `text-generation` pipeline. We won't receive a detailed response but only the generated text.
if stream:
raise ValueError(
"Streaming token is not supported by the model. This is due to the model not been served by a "
"Text-Generation-Inference server. Please pass `stream=False` as input."
)
if tool_choice is not None or tool_prompt is not None or tools is not None:
warnings.warn(
"Tools are not supported by the model. This is due to the model not been served by a "
"Text-Generation-Inference server. The provided tool parameters will be ignored."
)
# generate response
text_generation_output = await self.text_generation(
prompt=messages, # type: ignore # Not correct type but works implicitly
model=model,
stream=False,
details=False,
max_new_tokens=max_tokens,
seed=seed,
stop_sequences=stop,
temperature=temperature,
top_p=top_p,
)
# Format as a ChatCompletionOutput with dummy values for fields we can't provide
return ChatCompletionOutput(
id="dummy",
model="dummy",
object="dummy",
system_fingerprint="dummy",
usage=None, # type: ignore # set to `None` as we don't want to provide false information
created=int(time.time()),
choices=[
ChatCompletionOutputComplete(
finish_reason="unk", # type: ignore # set to `unk` as we don't want to provide false information
index=0,
message=ChatCompletionOutputMessage(
content=text_generation_output,
role="assistant",
),
)
],
)
async def conversational(
self,
text: str,
generated_responses: Optional[List[str]] = None,
past_user_inputs: Optional[List[str]] = None,
*,
parameters: Optional[Dict[str, Any]] = None,
model: Optional[str] = None,
) -> ConversationalOutput:
"""
Generate conversational responses based on the given input text (i.e. chat with the API).
<Tip warning={true}>
[`InferenceClient.conversational`] API is deprecated and will be removed in a future release. Please use
[`InferenceClient.chat_completion`] instead.
</Tip>
Args:
text (`str`):
The last input from the user in the conversation.
generated_responses (`List[str]`, *optional*):
A list of strings corresponding to the earlier replies from the model. Defaults to None.
past_user_inputs (`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.
parameters (`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](https://huggingface.co/docs/api-inference/detailed_parameters#conversational-task)
model (`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`]:
If the model is unavailable or the request times out.
`aiohttp.ClientResponseError`:
If the request fails with an HTTP error status code other than HTTP 503.
Example:
```py
# 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"],
... )
```
"""
warnings.warn(
"'InferenceClient.conversational' is deprecated and will be removed starting from huggingface_hub>=0.25. "
"Please use the more appropriate 'InferenceClient.chat_completion' API instead.",
FutureWarning,
)
payload: Dict[str, Any] = {"inputs": {"text": text}}
if generated_responses is not None:
payload["inputs"]["generated_responses"] = generated_responses
if past_user_inputs is not None:
payload["inputs"]["past_user_inputs"] = past_user_inputs
if parameters is not None:
payload["parameters"] = parameters
response = await self.post(json=payload, model=model, task="conversational")
return _bytes_to_dict(response) # type: ignore
async def document_question_answering(
self,
image: ContentT,
question: str,
*,
model: Optional[str] = None,
) -> List[DocumentQuestionAnsweringOutputElement]:
"""
Answer questions on document images.
Args:
image (`Union[str, Path, bytes, BinaryIO]`):
The input image for the context. It can be raw bytes, an image file, or a URL to an online image.
question (`str`):
Question to be answered.
model (`str`, *optional*):
The model to use for the document question answering 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 document question answering model will be used.
Defaults to None.
Returns:
`List[DocumentQuestionAnsweringOutputElement]`: a list of [`DocumentQuestionAnsweringOutputElement`] items containing the predicted label, associated probability, word ids, and page number.
Raises:
[`InferenceTimeoutError`]:
If the model is unavailable or the request times out.
`aiohttp.ClientResponseError`:
If the request fails with an HTTP error status code other than HTTP 503.
Example:
```py
# 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(score=0.42515629529953003, answer='us-001', start=16, end=16)]
```
"""
payload: Dict[str, Any] = {"question": question, "image": _b64_encode(image)}
response = await self.post(json=payload, model=model, task="document-question-answering")
return DocumentQuestionAnsweringOutputElement.parse_obj_as_list(response)
async def feature_extraction(self, text: str, *, model: Optional[str] = None) -> "np.ndarray":
"""
Generate embeddings for a given text.
Args:
text (`str`):
The text to embed.
model (`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`]:
If the model is unavailable or the request times out.
`aiohttp.ClientResponseError`:
If the request fails with an HTTP error status code other than HTTP 503.
Example:
```py
# 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)
```
"""
response = await self.post(json={"inputs": text}, model=model, task="feature-extraction")
np = _import_numpy()
return np.array(_bytes_to_dict(response), dtype="float32")
async def fill_mask(self, text: str, *, model: Optional[str] = None) -> List[FillMaskOutputElement]:
"""
Fill in a hole with a missing word (token to be precise).
Args:
text (`str`):
a string to be filled from, must contain the [MASK] token (check model card for exact name of the mask).
model (`str`, *optional*):
The model to use for the fill mask 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 fill mask model will be used.
Defaults to None.
Returns:
`List[FillMaskOutputElement]`: a list of [`FillMaskOutputElement`] items containing the predicted label, associated
probability, token reference, and completed text.
Raises:
[`InferenceTimeoutError`]:
If the model is unavailable or the request times out.
`aiohttp.ClientResponseError`:
If the request fails with an HTTP error status code other than HTTP 503.
Example:
```py
# 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.')
]
```
"""
response = await self.post(json={"inputs": text}, model=model, task="fill-mask")
return FillMaskOutputElement.parse_obj_as_list(response)
async def image_classification(
self,
image: ContentT,
*,
model: Optional[str] = None,
) -> List[ImageClassificationOutputElement]:
"""
Perform image classification on the given image using the specified model.