client.py 38.8 KB
Newer Older
1
2
import json
import requests
3
import warnings
4
5
6

from aiohttp import ClientSession, ClientTimeout
from pydantic import ValidationError
drbh's avatar
drbh committed
7
from typing import Dict, Optional, List, AsyncIterator, Iterator, Union
8

9
from text_generation import DEPRECATION_WARNING
10
11
12
13
14
from text_generation.types import (
    StreamResponse,
    Response,
    Request,
    Parameters,
drbh's avatar
drbh committed
15
    Grammar,
16
17
18
    CompletionRequest,
    Completion,
    CompletionComplete,
drbh's avatar
drbh committed
19
20
21
22
23
    ChatRequest,
    ChatCompletionChunk,
    ChatComplete,
    Message,
    Tool,
24
25
26
)
from text_generation.errors import parse_error

27
28
29
# emit deprecation warnings
warnings.simplefilter("always", DeprecationWarning)

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

class Client:
    """Client to make calls to a text-generation-inference instance

     Example:

     ```python
     >>> from text_generation import Client

     >>> client = Client("https://api-inference.huggingface.co/models/bigscience/bloomz")
     >>> client.generate("Why is the sky blue?").generated_text
     ' Rayleigh scattering'

     >>> result = ""
     >>> for response in client.generate_stream("Why is the sky blue?"):
     >>>     if not response.token.special:
     >>>         result += response.token.text
     >>> result
    ' Rayleigh scattering'
     ```
    """

    def __init__(
53
54
55
56
57
        self,
        base_url: str,
        headers: Optional[Dict[str, str]] = None,
        cookies: Optional[Dict[str, str]] = None,
        timeout: int = 10,
58
59
60
61
62
63
64
    ):
        """
        Args:
            base_url (`str`):
                text-generation-inference instance base url
            headers (`Optional[Dict[str, str]]`):
                Additional headers
65
66
            cookies (`Optional[Dict[str, str]]`):
                Cookies to include in the requests
67
68
69
            timeout (`int`):
                Timeout in seconds
        """
70
        warnings.warn(DEPRECATION_WARNING, DeprecationWarning)
71
72
        self.base_url = base_url
        self.headers = headers
73
        self.cookies = cookies
74
75
        self.timeout = timeout

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
    def completion(
        self,
        prompt: str,
        frequency_penalty: Optional[float] = None,
        max_tokens: Optional[int] = None,
        repetition_penalty: Optional[float] = None,
        seed: Optional[int] = None,
        stream: bool = False,
        temperature: Optional[float] = None,
        top_p: Optional[float] = None,
        stop: Optional[List[str]] = None,
    ):
        """
        Given a prompt, generate a response synchronously

        Args:
            prompt (`str`):
                Prompt
            frequency_penalty (`float`):
                The parameter for frequency penalty. 0.0 means no penalty
                Penalize new tokens based on their existing frequency in the text so far,
                decreasing the model's likelihood to repeat the same line verbatim.
            max_tokens (`int`):
                Maximum number of generated tokens
            repetition_penalty (`float`):
                The parameter for frequency penalty. 0.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
            seed (`int`):
                Random sampling seed
            stream (`bool`):
                Stream the response
            temperature (`float`):
                The value used to module the logits distribution.
            top_p (`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
            stop (`List[str]`):
                Stop generating tokens if a member of `stop` is generated
        """
        request = CompletionRequest(
            model="tgi",
            prompt=prompt,
            frequency_penalty=frequency_penalty,
            max_tokens=max_tokens,
            repetition_penalty=repetition_penalty,
            seed=seed,
            stream=stream,
            temperature=temperature,
            top_p=top_p,
            stop=stop,
        )
        if not stream:
            resp = requests.post(
                f"{self.base_url}/v1/completions",
                json=request.dict(),
                headers=self.headers,
                cookies=self.cookies,
                timeout=self.timeout,
            )
            payload = resp.json()
            if resp.status_code != 200:
                raise parse_error(resp.status_code, payload)
            return Completion(**payload)
        else:
            return self._completion_stream_response(request)

    def _completion_stream_response(self, request):
        resp = requests.post(
            f"{self.base_url}/v1/completions",
            json=request.dict(),
            headers=self.headers,
            cookies=self.cookies,
            timeout=self.timeout,
            stream=True,
        )
        # iterate and print stream
        for byte_payload in resp.iter_lines():
            if byte_payload == b"\n":
                continue
            payload = byte_payload.decode("utf-8")
            if payload.startswith("data:"):
                json_payload = json.loads(payload.lstrip("data:").rstrip("\n"))
                try:
                    response = CompletionComplete(**json_payload)
                    yield response
                except ValidationError:
                    raise parse_error(resp.status, json_payload)

drbh's avatar
drbh committed
164
165
166
    def chat(
        self,
        messages: List[Message],
167
        repetition_penalty: Optional[float] = None,
drbh's avatar
drbh committed
168
169
170
171
172
173
174
175
176
177
178
179
        frequency_penalty: Optional[float] = None,
        logit_bias: Optional[List[float]] = None,
        logprobs: Optional[bool] = None,
        top_logprobs: Optional[int] = None,
        max_tokens: Optional[int] = None,
        n: Optional[int] = None,
        presence_penalty: Optional[float] = None,
        stream: bool = False,
        seed: Optional[int] = None,
        temperature: Optional[float] = None,
        top_p: Optional[float] = None,
        tools: Optional[List[Tool]] = None,
180
        tool_prompt: Optional[str] = None,
drbh's avatar
drbh committed
181
        tool_choice: Optional[str] = None,
182
        stop: Optional[List[str]] = None,
drbh's avatar
drbh committed
183
184
185
186
187
188
189
    ):
        """
        Given a list of messages, generate a response asynchronously

        Args:
            messages (`List[Message]`):
                List of messages
190
191
            repetition_penalty (`float`):
                The parameter for repetition penalty. 0.0 means no penalty. See [this
drbh's avatar
drbh committed
192
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
193
194
195
196
            frequency_penalty (`float`):
                The parameter for frequency penalty. 0.0 means no penalty
                Penalize new tokens based on their existing frequency in the text so far,
                decreasing the model's likelihood to repeat the same line verbatim.
drbh's avatar
drbh committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
            logit_bias (`List[float]`):
                Adjust the likelihood of specified tokens
            logprobs (`bool`):
                Include log probabilities in the response
            top_logprobs (`int`):
                Include the `n` most likely tokens at each step
            max_tokens (`int`):
                Maximum number of generated tokens
            n (`int`):
                Generate `n` completions
            presence_penalty (`float`):
                The parameter for presence penalty. 0.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
            stream (`bool`):
                Stream the response
            seed (`int`):
                Random sampling seed
            temperature (`float`):
                The value used to module the logits distribution.
            top_p (`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
            tools (`List[Tool]`):
                List of tools to use
221
222
            tool_prompt (`str`):
                A prompt to be appended before the tools
drbh's avatar
drbh committed
223
224
            tool_choice (`str`):
                The tool to use
225
226
            stop (`List[str]`):
                Stop generating tokens if a member of `stop` is generated
drbh's avatar
drbh committed
227
228
229
230
231

        """
        request = ChatRequest(
            model="tgi",
            messages=messages,
232
            repetition_penalty=repetition_penalty,
drbh's avatar
drbh committed
233
234
235
236
237
238
239
240
241
242
243
244
            frequency_penalty=frequency_penalty,
            logit_bias=logit_bias,
            logprobs=logprobs,
            top_logprobs=top_logprobs,
            max_tokens=max_tokens,
            n=n,
            presence_penalty=presence_penalty,
            stream=stream,
            seed=seed,
            temperature=temperature,
            top_p=top_p,
            tools=tools,
245
            tool_prompt=tool_prompt,
drbh's avatar
drbh committed
246
            tool_choice=tool_choice,
247
            stop=stop,
drbh's avatar
drbh committed
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
        )
        if not stream:
            resp = requests.post(
                f"{self.base_url}/v1/chat/completions",
                json=request.dict(),
                headers=self.headers,
                cookies=self.cookies,
                timeout=self.timeout,
            )
            payload = resp.json()
            if resp.status_code != 200:
                raise parse_error(resp.status_code, payload)
            return ChatComplete(**payload)
        else:
            return self._chat_stream_response(request)

    def _chat_stream_response(self, request):
        resp = requests.post(
            f"{self.base_url}/v1/chat/completions",
            json=request.dict(),
            headers=self.headers,
            cookies=self.cookies,
            timeout=self.timeout,
            stream=True,
        )
        # iterate and print stream
        for byte_payload in resp.iter_lines():
            if byte_payload == b"\n":
                continue
            payload = byte_payload.decode("utf-8")
            if payload.startswith("data:"):
                json_payload = json.loads(payload.lstrip("data:").rstrip("\n"))
                try:
                    response = ChatCompletionChunk(**json_payload)
                    yield response
                except ValidationError:
                    raise parse_error(resp.status, json_payload)

286
287
288
289
    def generate(
        self,
        prompt: str,
        do_sample: bool = False,
290
        max_new_tokens: int = 20,
291
        best_of: Optional[int] = None,
292
        repetition_penalty: Optional[float] = None,
293
        frequency_penalty: Optional[float] = None,
294
295
296
297
298
299
        return_full_text: bool = False,
        seed: Optional[int] = None,
        stop_sequences: Optional[List[str]] = None,
        temperature: Optional[float] = None,
        top_k: Optional[int] = None,
        top_p: Optional[float] = None,
300
301
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
302
        watermark: bool = False,
303
        decoder_input_details: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
304
        top_n_tokens: Optional[int] = None,
drbh's avatar
drbh committed
305
        grammar: Optional[Grammar] = None,
306
307
308
309
310
311
312
313
314
315
316
    ) -> Response:
        """
        Given a prompt, generate the following text

        Args:
            prompt (`str`):
                Input text
            do_sample (`bool`):
                Activate logits sampling
            max_new_tokens (`int`):
                Maximum number of generated tokens
317
318
            best_of (`int`):
                Generate best_of sequences and return the one if the highest token logprobs
319
320
321
            repetition_penalty (`float`):
                The parameter for repetition penalty. 1.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
322
323
324
325
            frequency_penalty (`float`):
                The parameter for frequency penalty. 1.0 means no penalty
                Penalize new tokens based on their existing frequency in the text so far,
                decreasing the model's likelihood to repeat the same line verbatim.
326
327
328
329
330
331
332
333
334
335
336
337
338
            return_full_text (`bool`):
                Whether to prepend the prompt to the generated text
            seed (`int`):
                Random sampling seed
            stop_sequences (`List[str]`):
                Stop generating tokens if a member of `stop_sequences` is generated
            temperature (`float`):
                The value used to module the logits distribution.
            top_k (`int`):
                The number of highest probability vocabulary tokens to keep for top-k-filtering.
            top_p (`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.
339
340
341
342
343
            truncate (`int`):
                Truncate inputs tokens to the given size
            typical_p (`float`):
                Typical Decoding mass
                See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information
344
            watermark (`bool`):
345
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
346
347
            decoder_input_details (`bool`):
                Return the decoder input token logprobs and ids
Nicolas Patry's avatar
Nicolas Patry committed
348
349
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
350
351
352
            grammar (`Grammar`):
                Whether to use a grammar for the generation and the grammar to use. Grammars will constrain the generation
                of the text to match a regular expression or JSON schema.
353
354
355
356
357
358

        Returns:
            Response: generated response
        """
        # Validate parameters
        parameters = Parameters(
359
            best_of=best_of,
360
361
362
363
            details=True,
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
364
            frequency_penalty=frequency_penalty,
365
366
367
368
369
370
            return_full_text=return_full_text,
            seed=seed,
            stop=stop_sequences if stop_sequences is not None else [],
            temperature=temperature,
            top_k=top_k,
            top_p=top_p,
371
372
            truncate=truncate,
            typical_p=typical_p,
373
            watermark=watermark,
374
            decoder_input_details=decoder_input_details,
OlivierDehaene's avatar
OlivierDehaene committed
375
            top_n_tokens=top_n_tokens,
drbh's avatar
drbh committed
376
            grammar=grammar,
377
378
379
380
381
382
383
        )
        request = Request(inputs=prompt, stream=False, parameters=parameters)

        resp = requests.post(
            self.base_url,
            json=request.dict(),
            headers=self.headers,
384
            cookies=self.cookies,
385
386
387
388
389
390
391
392
393
394
395
            timeout=self.timeout,
        )
        payload = resp.json()
        if resp.status_code != 200:
            raise parse_error(resp.status_code, payload)
        return Response(**payload[0])

    def generate_stream(
        self,
        prompt: str,
        do_sample: bool = False,
396
        max_new_tokens: int = 20,
397
        repetition_penalty: Optional[float] = None,
398
        frequency_penalty: Optional[float] = None,
399
400
401
402
403
404
        return_full_text: bool = False,
        seed: Optional[int] = None,
        stop_sequences: Optional[List[str]] = None,
        temperature: Optional[float] = None,
        top_k: Optional[int] = None,
        top_p: Optional[float] = None,
405
406
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
407
        watermark: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
408
        top_n_tokens: Optional[int] = None,
drbh's avatar
drbh committed
409
        grammar: Optional[Grammar] = None,
410
411
412
413
414
415
416
417
418
419
420
421
422
423
    ) -> Iterator[StreamResponse]:
        """
        Given a prompt, generate the following stream of tokens

        Args:
            prompt (`str`):
                Input text
            do_sample (`bool`):
                Activate logits sampling
            max_new_tokens (`int`):
                Maximum number of generated tokens
            repetition_penalty (`float`):
                The parameter for repetition penalty. 1.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
424
425
426
427
            frequency_penalty (`float`):
                The parameter for frequency penalty. 1.0 means no penalty
                Penalize new tokens based on their existing frequency in the text so far,
                decreasing the model's likelihood to repeat the same line verbatim.
428
429
430
431
432
433
434
435
436
437
438
439
440
            return_full_text (`bool`):
                Whether to prepend the prompt to the generated text
            seed (`int`):
                Random sampling seed
            stop_sequences (`List[str]`):
                Stop generating tokens if a member of `stop_sequences` is generated
            temperature (`float`):
                The value used to module the logits distribution.
            top_k (`int`):
                The number of highest probability vocabulary tokens to keep for top-k-filtering.
            top_p (`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.
441
442
443
444
445
            truncate (`int`):
                Truncate inputs tokens to the given size
            typical_p (`float`):
                Typical Decoding mass
                See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information
446
            watermark (`bool`):
447
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
Nicolas Patry's avatar
Nicolas Patry committed
448
449
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
450
451
452
            grammar (`Grammar`):
                Whether to use a grammar for the generation and the grammar to use. Grammars will constrain the generation
                of the text to match a regular expression or JSON schema.
453
454
455
456
457
458

        Returns:
            Iterator[StreamResponse]: stream of generated tokens
        """
        # Validate parameters
        parameters = Parameters(
459
            best_of=None,
460
            details=True,
461
            decoder_input_details=False,
462
463
464
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
465
            frequency_penalty=frequency_penalty,
466
467
468
469
470
471
            return_full_text=return_full_text,
            seed=seed,
            stop=stop_sequences if stop_sequences is not None else [],
            temperature=temperature,
            top_k=top_k,
            top_p=top_p,
472
473
            truncate=truncate,
            typical_p=typical_p,
474
            watermark=watermark,
Nicolas Patry's avatar
Nicolas Patry committed
475
            top_n_tokens=top_n_tokens,
drbh's avatar
drbh committed
476
            grammar=grammar,
477
478
479
480
481
482
483
        )
        request = Request(inputs=prompt, stream=True, parameters=parameters)

        resp = requests.post(
            self.base_url,
            json=request.dict(),
            headers=self.headers,
484
            cookies=self.cookies,
485
            timeout=self.timeout,
486
            stream=True,
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
        )

        if resp.status_code != 200:
            raise parse_error(resp.status_code, resp.json())

        # Parse ServerSentEvents
        for byte_payload in resp.iter_lines():
            # Skip line
            if byte_payload == b"\n":
                continue

            payload = byte_payload.decode("utf-8")

            # Event data
            if payload.startswith("data:"):
                # Decode payload
                json_payload = json.loads(payload.lstrip("data:").rstrip("/n"))
                # Parse payload
                try:
                    response = StreamResponse(**json_payload)
                except ValidationError:
                    # If we failed to parse the payload, then it is an error payload
                    raise parse_error(resp.status_code, json_payload)
                yield response


class AsyncClient:
    """Asynchronous Client to make calls to a text-generation-inference instance

     Example:

     ```python
     >>> from text_generation import AsyncClient

     >>> client = AsyncClient("https://api-inference.huggingface.co/models/bigscience/bloomz")
     >>> response = await client.generate("Why is the sky blue?")
     >>> response.generated_text
     ' Rayleigh scattering'

     >>> result = ""
     >>> async for response in client.generate_stream("Why is the sky blue?"):
     >>>     if not response.token.special:
     >>>         result += response.token.text
     >>> result
    ' Rayleigh scattering'
     ```
    """

    def __init__(
536
537
538
539
540
        self,
        base_url: str,
        headers: Optional[Dict[str, str]] = None,
        cookies: Optional[Dict[str, str]] = None,
        timeout: int = 10,
541
542
543
544
545
546
547
    ):
        """
        Args:
            base_url (`str`):
                text-generation-inference instance base url
            headers (`Optional[Dict[str, str]]`):
                Additional headers
548
549
            cookies (`Optional[Dict[str, str]]`):
                Cookies to include in the requests
550
551
552
            timeout (`int`):
                Timeout in seconds
        """
553
        warnings.warn(DEPRECATION_WARNING, DeprecationWarning)
554
555
        self.base_url = base_url
        self.headers = headers
556
        self.cookies = cookies
557
        self.timeout = ClientTimeout(timeout)
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
    async def completion(
        self,
        prompt: str,
        frequency_penalty: Optional[float] = None,
        max_tokens: Optional[int] = None,
        repetition_penalty: Optional[float] = None,
        seed: Optional[int] = None,
        stream: bool = False,
        temperature: Optional[float] = None,
        top_p: Optional[float] = None,
        stop: Optional[List[str]] = None,
    ) -> Union[Completion, AsyncIterator[CompletionComplete]]:
        """
        Given a prompt, generate a response asynchronously

        Args:
            prompt (`str`):
                Prompt
            frequency_penalty (`float`):
                The parameter for frequency penalty. 0.0 means no penalty
                Penalize new tokens based on their existing frequency in the text so far,
                decreasing the model's likelihood to repeat the same line verbatim.
            max_tokens (`int`):
                Maximum number of generated tokens
            repetition_penalty (`float`):
                The parameter for frequency penalty. 0.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
            seed (`int`):
                Random sampling seed
            stream (`bool`):
                Stream the response
            temperature (`float`):
                The value used to module the logits distribution.
            top_p (`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
            stop (`List[str]`):
                Stop generating tokens if a member of `stop` is generated
        """
        request = CompletionRequest(
            model="tgi",
            prompt=prompt,
            frequency_penalty=frequency_penalty,
            max_tokens=max_tokens,
            repetition_penalty=repetition_penalty,
            seed=seed,
            stream=stream,
            temperature=temperature,
            top_p=top_p,
            stop=stop,
        )
        if not stream:
            return await self._completion_single_response(request)
        else:
            return self._completion_stream_response(request)

    async def _completion_single_response(self, request):
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
            async with session.post(
                f"{self.base_url}/v1/completions", json=request.dict()
            ) as resp:
                payload = await resp.json()
                if resp.status != 200:
                    raise parse_error(resp.status, payload)
                return Completion(**payload)

    async def _completion_stream_response(self, request):
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
            async with session.post(
                f"{self.base_url}/v1/completions", json=request.dict()
            ) as resp:
                async for byte_payload in resp.content:
                    if byte_payload == b"\n":
                        continue
                    payload = byte_payload.decode("utf-8")
                    if payload.startswith("data:"):
                        json_payload = json.loads(payload.lstrip("data:").rstrip("\n"))
                        try:
                            response = CompletionComplete(**json_payload)
                            yield response
                        except ValidationError:
                            raise parse_error(resp.status, json_payload)

drbh's avatar
drbh committed
646
647
648
    async def chat(
        self,
        messages: List[Message],
649
        repetition_penalty: Optional[float] = None,
drbh's avatar
drbh committed
650
651
652
653
654
655
656
657
658
659
660
661
        frequency_penalty: Optional[float] = None,
        logit_bias: Optional[List[float]] = None,
        logprobs: Optional[bool] = None,
        top_logprobs: Optional[int] = None,
        max_tokens: Optional[int] = None,
        n: Optional[int] = None,
        presence_penalty: Optional[float] = None,
        stream: bool = False,
        seed: Optional[int] = None,
        temperature: Optional[float] = None,
        top_p: Optional[float] = None,
        tools: Optional[List[Tool]] = None,
662
        tool_prompt: Optional[str] = None,
drbh's avatar
drbh committed
663
        tool_choice: Optional[str] = None,
664
        stop: Optional[List[str]] = None,
drbh's avatar
drbh committed
665
666
667
668
669
670
671
    ) -> Union[ChatComplete, AsyncIterator[ChatCompletionChunk]]:
        """
        Given a list of messages, generate a response asynchronously

        Args:
            messages (`List[Message]`):
                List of messages
672
            repetition_penalty (`float`):
drbh's avatar
drbh committed
673
674
                The parameter for frequency penalty. 0.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
675
676
677
678
            frequency_penalty (`float`):
                The parameter for frequency penalty. 0.0 means no penalty
                Penalize new tokens based on their existing frequency in the text so far,
                decreasing the model's likelihood to repeat the same line verbatim.
drbh's avatar
drbh committed
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
            logit_bias (`List[float]`):
                Adjust the likelihood of specified tokens
            logprobs (`bool`):
                Include log probabilities in the response
            top_logprobs (`int`):
                Include the `n` most likely tokens at each step
            max_tokens (`int`):
                Maximum number of generated tokens
            n (`int`):
                Generate `n` completions
            presence_penalty (`float`):
                The parameter for presence penalty. 0.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
            stream (`bool`):
                Stream the response
            seed (`int`):
                Random sampling seed
            temperature (`float`):
                The value used to module the logits distribution.
            top_p (`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
            tools (`List[Tool]`):
                List of tools to use
703
704
            tool_prompt (`str`):
                A prompt to be appended before the tools
drbh's avatar
drbh committed
705
706
            tool_choice (`str`):
                The tool to use
707
708
            stop (`List[str]`):
                Stop generating tokens if a member of `stop` is generated
drbh's avatar
drbh committed
709
710
711
712
713

        """
        request = ChatRequest(
            model="tgi",
            messages=messages,
714
            repetition_penalty=repetition_penalty,
drbh's avatar
drbh committed
715
716
717
718
719
720
721
722
723
724
725
726
            frequency_penalty=frequency_penalty,
            logit_bias=logit_bias,
            logprobs=logprobs,
            top_logprobs=top_logprobs,
            max_tokens=max_tokens,
            n=n,
            presence_penalty=presence_penalty,
            stream=stream,
            seed=seed,
            temperature=temperature,
            top_p=top_p,
            tools=tools,
727
            tool_prompt=tool_prompt,
drbh's avatar
drbh committed
728
            tool_choice=tool_choice,
729
            stop=stop,
drbh's avatar
drbh committed
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
        )
        if not stream:
            return await self._chat_single_response(request)
        else:
            return self._chat_stream_response(request)

    async def _chat_single_response(self, request):
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
            async with session.post(
                f"{self.base_url}/v1/chat/completions", json=request.dict()
            ) as resp:
                payload = await resp.json()
                if resp.status != 200:
                    raise parse_error(resp.status, payload)
                return ChatComplete(**payload)

    async def _chat_stream_response(self, request):
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
            async with session.post(
                f"{self.base_url}/v1/chat/completions", json=request.dict()
            ) as resp:
                async for byte_payload in resp.content:
                    if byte_payload == b"\n":
                        continue
                    payload = byte_payload.decode("utf-8")
                    if payload.startswith("data:"):
                        json_payload = json.loads(payload.lstrip("data:").rstrip("\n"))
                        try:
                            response = ChatCompletionChunk(**json_payload)
                            yield response
                        except ValidationError:
                            raise parse_error(resp.status, json_payload)

767
768
769
770
    async def generate(
        self,
        prompt: str,
        do_sample: bool = False,
771
        max_new_tokens: int = 20,
772
        best_of: Optional[int] = None,
773
        repetition_penalty: Optional[float] = None,
774
        frequency_penalty: Optional[float] = None,
775
776
777
778
779
780
        return_full_text: bool = False,
        seed: Optional[int] = None,
        stop_sequences: Optional[List[str]] = None,
        temperature: Optional[float] = None,
        top_k: Optional[int] = None,
        top_p: Optional[float] = None,
781
782
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
783
        watermark: bool = False,
784
        decoder_input_details: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
785
        top_n_tokens: Optional[int] = None,
drbh's avatar
drbh committed
786
        grammar: Optional[Grammar] = None,
787
788
789
790
791
792
793
794
795
796
797
    ) -> Response:
        """
        Given a prompt, generate the following text asynchronously

        Args:
            prompt (`str`):
                Input text
            do_sample (`bool`):
                Activate logits sampling
            max_new_tokens (`int`):
                Maximum number of generated tokens
798
799
            best_of (`int`):
                Generate best_of sequences and return the one if the highest token logprobs
800
801
802
            repetition_penalty (`float`):
                The parameter for repetition penalty. 1.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
803
804
805
806
            frequency_penalty (`float`):
                The parameter for frequency penalty. 1.0 means no penalty
                Penalize new tokens based on their existing frequency in the text so far,
                decreasing the model's likelihood to repeat the same line verbatim.
807
808
809
810
811
812
813
814
815
816
817
818
819
            return_full_text (`bool`):
                Whether to prepend the prompt to the generated text
            seed (`int`):
                Random sampling seed
            stop_sequences (`List[str]`):
                Stop generating tokens if a member of `stop_sequences` is generated
            temperature (`float`):
                The value used to module the logits distribution.
            top_k (`int`):
                The number of highest probability vocabulary tokens to keep for top-k-filtering.
            top_p (`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.
820
821
822
823
824
            truncate (`int`):
                Truncate inputs tokens to the given size
            typical_p (`float`):
                Typical Decoding mass
                See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information
825
            watermark (`bool`):
826
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
827
828
            decoder_input_details (`bool`):
                Return the decoder input token logprobs and ids
Nicolas Patry's avatar
Nicolas Patry committed
829
830
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
831
832
833
            grammar (`Grammar`):
                Whether to use a grammar for the generation and the grammar to use. Grammars will constrain the generation
                of the text to match a regular expression or JSON schema.
834
835
836
837

        Returns:
            Response: generated response
        """
drbh's avatar
drbh committed
838

839
840
        # Validate parameters
        parameters = Parameters(
841
            best_of=best_of,
842
            details=True,
843
            decoder_input_details=decoder_input_details,
844
845
846
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
847
            frequency_penalty=frequency_penalty,
848
849
850
851
852
853
            return_full_text=return_full_text,
            seed=seed,
            stop=stop_sequences if stop_sequences is not None else [],
            temperature=temperature,
            top_k=top_k,
            top_p=top_p,
854
855
            truncate=truncate,
            typical_p=typical_p,
856
            watermark=watermark,
Nicolas Patry's avatar
Nicolas Patry committed
857
            top_n_tokens=top_n_tokens,
drbh's avatar
drbh committed
858
            grammar=grammar,
859
860
861
        )
        request = Request(inputs=prompt, stream=False, parameters=parameters)

862
863
864
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
865
866
867
868
869
870
871
872
873
874
875
            async with session.post(self.base_url, json=request.dict()) as resp:
                payload = await resp.json()

                if resp.status != 200:
                    raise parse_error(resp.status, payload)
                return Response(**payload[0])

    async def generate_stream(
        self,
        prompt: str,
        do_sample: bool = False,
876
        max_new_tokens: int = 20,
877
        repetition_penalty: Optional[float] = None,
878
        frequency_penalty: Optional[float] = None,
879
880
881
882
883
884
        return_full_text: bool = False,
        seed: Optional[int] = None,
        stop_sequences: Optional[List[str]] = None,
        temperature: Optional[float] = None,
        top_k: Optional[int] = None,
        top_p: Optional[float] = None,
885
886
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
887
        watermark: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
888
        top_n_tokens: Optional[int] = None,
drbh's avatar
drbh committed
889
        grammar: Optional[Grammar] = None,
890
891
892
893
894
895
896
897
898
899
900
901
902
903
    ) -> AsyncIterator[StreamResponse]:
        """
        Given a prompt, generate the following stream of tokens asynchronously

        Args:
            prompt (`str`):
                Input text
            do_sample (`bool`):
                Activate logits sampling
            max_new_tokens (`int`):
                Maximum number of generated tokens
            repetition_penalty (`float`):
                The parameter for repetition penalty. 1.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
904
905
906
907
            frequency_penalty (`float`):
                The parameter for frequency penalty. 1.0 means no penalty
                Penalize new tokens based on their existing frequency in the text so far,
                decreasing the model's likelihood to repeat the same line verbatim.
908
909
910
911
912
913
914
915
916
917
918
919
920
            return_full_text (`bool`):
                Whether to prepend the prompt to the generated text
            seed (`int`):
                Random sampling seed
            stop_sequences (`List[str]`):
                Stop generating tokens if a member of `stop_sequences` is generated
            temperature (`float`):
                The value used to module the logits distribution.
            top_k (`int`):
                The number of highest probability vocabulary tokens to keep for top-k-filtering.
            top_p (`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.
921
922
923
924
925
            truncate (`int`):
                Truncate inputs tokens to the given size
            typical_p (`float`):
                Typical Decoding mass
                See [Typical Decoding for Natural Language Generation](https://arxiv.org/abs/2202.00666) for more information
926
            watermark (`bool`):
927
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
Nicolas Patry's avatar
Nicolas Patry committed
928
929
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
930
931
932
            grammar (`Grammar`):
                Whether to use a grammar for the generation and the grammar to use. Grammars will constrain the generation
                of the text to match a regular expression or JSON schema.
933
934
935
936
937
938

        Returns:
            AsyncIterator[StreamResponse]: stream of generated tokens
        """
        # Validate parameters
        parameters = Parameters(
939
            best_of=None,
940
            details=True,
941
            decoder_input_details=False,
942
943
944
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
945
            frequency_penalty=frequency_penalty,
946
947
948
949
950
951
            return_full_text=return_full_text,
            seed=seed,
            stop=stop_sequences if stop_sequences is not None else [],
            temperature=temperature,
            top_k=top_k,
            top_p=top_p,
952
953
            truncate=truncate,
            typical_p=typical_p,
954
            watermark=watermark,
Nicolas Patry's avatar
Nicolas Patry committed
955
            top_n_tokens=top_n_tokens,
drbh's avatar
drbh committed
956
            grammar=grammar,
957
958
959
        )
        request = Request(inputs=prompt, stream=True, parameters=parameters)

960
961
962
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
            async with session.post(self.base_url, json=request.dict()) as resp:
                if resp.status != 200:
                    raise parse_error(resp.status, await resp.json())

                # Parse ServerSentEvents
                async for byte_payload in resp.content:
                    # Skip line
                    if byte_payload == b"\n":
                        continue

                    payload = byte_payload.decode("utf-8")

                    # Event data
                    if payload.startswith("data:"):
                        # Decode payload
                        json_payload = json.loads(payload.lstrip("data:").rstrip("/n"))
                        # Parse payload
                        try:
                            response = StreamResponse(**json_payload)
                        except ValidationError:
                            # If we failed to parse the payload, then it is an error payload
                            raise parse_error(resp.status, json_payload)
                        yield response