client.py 31.4 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,
drbh's avatar
drbh committed
16
17
18
19
20
    ChatRequest,
    ChatCompletionChunk,
    ChatComplete,
    Message,
    Tool,
21
22
23
)
from text_generation.errors import parse_error

24
25
26
# emit deprecation warnings
warnings.simplefilter("always", DeprecationWarning)

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

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__(
50
51
52
53
54
        self,
        base_url: str,
        headers: Optional[Dict[str, str]] = None,
        cookies: Optional[Dict[str, str]] = None,
        timeout: int = 10,
55
56
57
58
59
60
61
    ):
        """
        Args:
            base_url (`str`):
                text-generation-inference instance base url
            headers (`Optional[Dict[str, str]]`):
                Additional headers
62
63
            cookies (`Optional[Dict[str, str]]`):
                Cookies to include in the requests
64
65
66
            timeout (`int`):
                Timeout in seconds
        """
67
        warnings.warn(DEPRECATION_WARNING, DeprecationWarning)
68
69
        self.base_url = base_url
        self.headers = headers
70
        self.cookies = cookies
71
72
        self.timeout = timeout

drbh's avatar
drbh committed
73
74
75
    def chat(
        self,
        messages: List[Message],
76
        repetition_penalty: Optional[float] = None,
drbh's avatar
drbh committed
77
78
79
80
81
82
83
84
85
86
87
88
        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,
89
        tool_prompt: Optional[str] = None,
drbh's avatar
drbh committed
90
91
92
93
94
95
96
97
        tool_choice: Optional[str] = None,
    ):
        """
        Given a list of messages, generate a response asynchronously

        Args:
            messages (`List[Message]`):
                List of messages
98
99
            repetition_penalty (`float`):
                The parameter for repetition penalty. 0.0 means no penalty. See [this
drbh's avatar
drbh committed
100
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
101
102
103
104
            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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
            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
129
130
            tool_prompt (`str`):
                A prompt to be appended before the tools
drbh's avatar
drbh committed
131
132
133
134
135
136
137
            tool_choice (`str`):
                The tool to use

        """
        request = ChatRequest(
            model="tgi",
            messages=messages,
138
            repetition_penalty=repetition_penalty,
drbh's avatar
drbh committed
139
140
141
142
143
144
145
146
147
148
149
150
            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,
151
            tool_prompt=tool_prompt,
drbh's avatar
drbh committed
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
            tool_choice=tool_choice,
        )
        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)

191
192
193
194
    def generate(
        self,
        prompt: str,
        do_sample: bool = False,
195
        max_new_tokens: int = 20,
196
        best_of: Optional[int] = None,
197
        repetition_penalty: Optional[float] = None,
198
        frequency_penalty: Optional[float] = None,
199
200
201
202
203
204
        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,
205
206
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
207
        watermark: bool = False,
208
        decoder_input_details: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
209
        top_n_tokens: Optional[int] = None,
drbh's avatar
drbh committed
210
        grammar: Optional[Grammar] = None,
211
212
213
214
215
216
217
218
219
220
221
    ) -> 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
222
223
            best_of (`int`):
                Generate best_of sequences and return the one if the highest token logprobs
224
225
226
            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.
227
228
229
230
            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.
231
232
233
234
235
236
237
238
239
240
241
242
243
            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.
244
245
246
247
248
            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
249
            watermark (`bool`):
250
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
251
252
            decoder_input_details (`bool`):
                Return the decoder input token logprobs and ids
Nicolas Patry's avatar
Nicolas Patry committed
253
254
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
255
256
257
            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.
258
259
260
261
262
263

        Returns:
            Response: generated response
        """
        # Validate parameters
        parameters = Parameters(
264
            best_of=best_of,
265
266
267
268
            details=True,
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
269
            frequency_penalty=frequency_penalty,
270
271
272
273
274
275
            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,
276
277
            truncate=truncate,
            typical_p=typical_p,
278
            watermark=watermark,
279
            decoder_input_details=decoder_input_details,
OlivierDehaene's avatar
OlivierDehaene committed
280
            top_n_tokens=top_n_tokens,
drbh's avatar
drbh committed
281
            grammar=grammar,
282
283
284
285
286
287
288
        )
        request = Request(inputs=prompt, stream=False, parameters=parameters)

        resp = requests.post(
            self.base_url,
            json=request.dict(),
            headers=self.headers,
289
            cookies=self.cookies,
290
291
292
293
294
295
296
297
298
299
300
            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,
301
        max_new_tokens: int = 20,
302
        repetition_penalty: Optional[float] = None,
303
        frequency_penalty: Optional[float] = None,
304
305
306
307
308
309
        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,
310
311
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
312
        watermark: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
313
        top_n_tokens: Optional[int] = None,
drbh's avatar
drbh committed
314
        grammar: Optional[Grammar] = None,
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    ) -> 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.
329
330
331
332
            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.
333
334
335
336
337
338
339
340
341
342
343
344
345
            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.
346
347
348
349
350
            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
351
            watermark (`bool`):
352
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
Nicolas Patry's avatar
Nicolas Patry committed
353
354
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
355
356
357
            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.
358
359
360
361
362
363

        Returns:
            Iterator[StreamResponse]: stream of generated tokens
        """
        # Validate parameters
        parameters = Parameters(
364
            best_of=None,
365
            details=True,
366
            decoder_input_details=False,
367
368
369
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
370
            frequency_penalty=frequency_penalty,
371
372
373
374
375
376
            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,
377
378
            truncate=truncate,
            typical_p=typical_p,
379
            watermark=watermark,
Nicolas Patry's avatar
Nicolas Patry committed
380
            top_n_tokens=top_n_tokens,
drbh's avatar
drbh committed
381
            grammar=grammar,
382
383
384
385
386
387
388
        )
        request = Request(inputs=prompt, stream=True, parameters=parameters)

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

        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__(
441
442
443
444
445
        self,
        base_url: str,
        headers: Optional[Dict[str, str]] = None,
        cookies: Optional[Dict[str, str]] = None,
        timeout: int = 10,
446
447
448
449
450
451
452
    ):
        """
        Args:
            base_url (`str`):
                text-generation-inference instance base url
            headers (`Optional[Dict[str, str]]`):
                Additional headers
453
454
            cookies (`Optional[Dict[str, str]]`):
                Cookies to include in the requests
455
456
457
            timeout (`int`):
                Timeout in seconds
        """
458
        warnings.warn(DEPRECATION_WARNING, DeprecationWarning)
459
460
        self.base_url = base_url
        self.headers = headers
461
        self.cookies = cookies
462
        self.timeout = ClientTimeout(timeout)
463

drbh's avatar
drbh committed
464
465
466
    async def chat(
        self,
        messages: List[Message],
467
        repetition_penalty: Optional[float] = None,
drbh's avatar
drbh committed
468
469
470
471
472
473
474
475
476
477
478
479
        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,
480
        tool_prompt: Optional[str] = None,
drbh's avatar
drbh committed
481
482
483
484
485
486
487
488
        tool_choice: Optional[str] = None,
    ) -> Union[ChatComplete, AsyncIterator[ChatCompletionChunk]]:
        """
        Given a list of messages, generate a response asynchronously

        Args:
            messages (`List[Message]`):
                List of messages
489
            repetition_penalty (`float`):
drbh's avatar
drbh committed
490
491
                The parameter for frequency penalty. 0.0 means no penalty. See [this
                paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
492
493
494
495
            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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
            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
520
521
            tool_prompt (`str`):
                A prompt to be appended before the tools
drbh's avatar
drbh committed
522
523
524
525
526
527
528
            tool_choice (`str`):
                The tool to use

        """
        request = ChatRequest(
            model="tgi",
            messages=messages,
529
            repetition_penalty=repetition_penalty,
drbh's avatar
drbh committed
530
531
532
533
534
535
536
537
538
539
540
541
            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,
542
            tool_prompt=tool_prompt,
drbh's avatar
drbh committed
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
            tool_choice=tool_choice,
        )
        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)

581
582
583
584
    async def generate(
        self,
        prompt: str,
        do_sample: bool = False,
585
        max_new_tokens: int = 20,
586
        best_of: Optional[int] = None,
587
        repetition_penalty: Optional[float] = None,
588
        frequency_penalty: Optional[float] = None,
589
590
591
592
593
594
        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,
595
596
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
597
        watermark: bool = False,
598
        decoder_input_details: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
599
        top_n_tokens: Optional[int] = None,
drbh's avatar
drbh committed
600
        grammar: Optional[Grammar] = None,
601
602
603
604
605
606
607
608
609
610
611
    ) -> 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
612
613
            best_of (`int`):
                Generate best_of sequences and return the one if the highest token logprobs
614
615
616
            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.
617
618
619
620
            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.
621
622
623
624
625
626
627
628
629
630
631
632
633
            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.
634
635
636
637
638
            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
639
            watermark (`bool`):
640
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
641
642
            decoder_input_details (`bool`):
                Return the decoder input token logprobs and ids
Nicolas Patry's avatar
Nicolas Patry committed
643
644
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
645
646
647
            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.
648
649
650
651

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

653
654
        # Validate parameters
        parameters = Parameters(
655
            best_of=best_of,
656
            details=True,
657
            decoder_input_details=decoder_input_details,
658
659
660
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
661
            frequency_penalty=frequency_penalty,
662
663
664
665
666
667
            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,
668
669
            truncate=truncate,
            typical_p=typical_p,
670
            watermark=watermark,
Nicolas Patry's avatar
Nicolas Patry committed
671
            top_n_tokens=top_n_tokens,
drbh's avatar
drbh committed
672
            grammar=grammar,
673
674
675
        )
        request = Request(inputs=prompt, stream=False, parameters=parameters)

676
677
678
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
679
680
681
682
683
684
685
686
687
688
689
            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,
690
        max_new_tokens: int = 20,
691
        repetition_penalty: Optional[float] = None,
692
        frequency_penalty: Optional[float] = None,
693
694
695
696
697
698
        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,
699
700
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
701
        watermark: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
702
        top_n_tokens: Optional[int] = None,
drbh's avatar
drbh committed
703
        grammar: Optional[Grammar] = None,
704
705
706
707
708
709
710
711
712
713
714
715
716
717
    ) -> 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.
718
719
720
721
            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.
722
723
724
725
726
727
728
729
730
731
732
733
734
            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.
735
736
737
738
739
            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
740
            watermark (`bool`):
741
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
Nicolas Patry's avatar
Nicolas Patry committed
742
743
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
744
745
746
            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.
747
748
749
750
751
752

        Returns:
            AsyncIterator[StreamResponse]: stream of generated tokens
        """
        # Validate parameters
        parameters = Parameters(
753
            best_of=None,
754
            details=True,
755
            decoder_input_details=False,
756
757
758
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
759
            frequency_penalty=frequency_penalty,
760
761
762
763
764
765
            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,
766
767
            truncate=truncate,
            typical_p=typical_p,
768
            watermark=watermark,
Nicolas Patry's avatar
Nicolas Patry committed
769
            top_n_tokens=top_n_tokens,
drbh's avatar
drbh committed
770
            grammar=grammar,
771
772
773
        )
        request = Request(inputs=prompt, stream=True, parameters=parameters)

774
775
776
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
            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