"tests/vscode:/vscode.git/clone" did not exist on "d1fab39e59a98ddce2490b0ef85633bb33cb0301"
client.py 19 KB
Newer Older
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
import json
import requests

from aiohttp import ClientSession, ClientTimeout
from pydantic import ValidationError
from typing import Dict, Optional, List, AsyncIterator, Iterator

from text_generation.types import (
    StreamResponse,
    Response,
    Request,
    Parameters,
)
from text_generation.errors import parse_error


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__(
39
40
41
42
43
        self,
        base_url: str,
        headers: Optional[Dict[str, str]] = None,
        cookies: Optional[Dict[str, str]] = None,
        timeout: int = 10,
44
45
46
47
48
49
50
    ):
        """
        Args:
            base_url (`str`):
                text-generation-inference instance base url
            headers (`Optional[Dict[str, str]]`):
                Additional headers
51
52
            cookies (`Optional[Dict[str, str]]`):
                Cookies to include in the requests
53
54
55
56
57
            timeout (`int`):
                Timeout in seconds
        """
        self.base_url = base_url
        self.headers = headers
58
        self.cookies = cookies
59
60
61
62
63
64
65
        self.timeout = timeout

    def generate(
        self,
        prompt: str,
        do_sample: bool = False,
        max_new_tokens: int = 20,
66
        best_of: Optional[int] = None,
67
68
69
70
71
72
73
        repetition_penalty: Optional[float] = None,
        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,
74
75
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
76
        watermark: bool = False,
77
        decoder_input_details: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
78
        top_n_tokens: Optional[int] = None,
79
80
81
82
83
84
85
86
87
88
89
    ) -> 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
90
91
            best_of (`int`):
                Generate best_of sequences and return the one if the highest token logprobs
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
            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.
            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.
108
109
110
111
112
            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
113
            watermark (`bool`):
114
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
115
116
            decoder_input_details (`bool`):
                Return the decoder input token logprobs and ids
Nicolas Patry's avatar
Nicolas Patry committed
117
118
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
119
120
121
122
123
124

        Returns:
            Response: generated response
        """
        # Validate parameters
        parameters = Parameters(
125
            best_of=best_of,
126
127
128
129
130
131
132
133
134
135
            details=True,
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
            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,
136
137
            truncate=truncate,
            typical_p=typical_p,
138
            watermark=watermark,
139
            decoder_input_details=decoder_input_details,
OlivierDehaene's avatar
OlivierDehaene committed
140
            top_n_tokens=top_n_tokens,
141
142
143
144
145
146
147
        )
        request = Request(inputs=prompt, stream=False, parameters=parameters)

        resp = requests.post(
            self.base_url,
            json=request.dict(),
            headers=self.headers,
148
            cookies=self.cookies,
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
            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,
        max_new_tokens: int = 20,
        repetition_penalty: Optional[float] = None,
        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,
168
169
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
170
        watermark: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
171
        top_n_tokens: Optional[int] = None,
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
    ) -> 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.
            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.
199
200
201
202
203
            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
204
            watermark (`bool`):
205
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
Nicolas Patry's avatar
Nicolas Patry committed
206
207
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
208
209
210
211
212
213

        Returns:
            Iterator[StreamResponse]: stream of generated tokens
        """
        # Validate parameters
        parameters = Parameters(
214
            best_of=None,
215
            details=True,
216
            decoder_input_details=False,
217
218
219
220
221
222
223
224
225
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
            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,
226
227
            truncate=truncate,
            typical_p=typical_p,
228
            watermark=watermark,
Nicolas Patry's avatar
Nicolas Patry committed
229
            top_n_tokens=top_n_tokens,
230
231
232
233
234
235
236
        )
        request = Request(inputs=prompt, stream=True, parameters=parameters)

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

        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__(
289
290
291
292
293
        self,
        base_url: str,
        headers: Optional[Dict[str, str]] = None,
        cookies: Optional[Dict[str, str]] = None,
        timeout: int = 10,
294
295
296
297
298
299
300
    ):
        """
        Args:
            base_url (`str`):
                text-generation-inference instance base url
            headers (`Optional[Dict[str, str]]`):
                Additional headers
301
302
            cookies (`Optional[Dict[str, str]]`):
                Cookies to include in the requests
303
304
305
306
307
            timeout (`int`):
                Timeout in seconds
        """
        self.base_url = base_url
        self.headers = headers
308
        self.cookies = cookies
309
310
311
312
313
314
315
        self.timeout = ClientTimeout(timeout * 60)

    async def generate(
        self,
        prompt: str,
        do_sample: bool = False,
        max_new_tokens: int = 20,
316
        best_of: Optional[int] = None,
317
318
319
320
321
322
323
        repetition_penalty: Optional[float] = None,
        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,
324
325
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
326
        watermark: bool = False,
327
        decoder_input_details: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
328
        top_n_tokens: Optional[int] = None,
329
330
331
332
333
334
335
336
337
338
339
    ) -> 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
340
341
            best_of (`int`):
                Generate best_of sequences and return the one if the highest token logprobs
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
            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.
            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.
358
359
360
361
362
            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
363
            watermark (`bool`):
364
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
365
366
            decoder_input_details (`bool`):
                Return the decoder input token logprobs and ids
Nicolas Patry's avatar
Nicolas Patry committed
367
368
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
369
370
371
372
373
374

        Returns:
            Response: generated response
        """
        # Validate parameters
        parameters = Parameters(
375
            best_of=best_of,
376
            details=True,
377
            decoder_input_details=decoder_input_details,
378
379
380
381
382
383
384
385
386
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
            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,
387
388
            truncate=truncate,
            typical_p=typical_p,
389
            watermark=watermark,
Nicolas Patry's avatar
Nicolas Patry committed
390
            top_n_tokens=top_n_tokens,
391
392
393
        )
        request = Request(inputs=prompt, stream=False, parameters=parameters)

394
395
396
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
            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,
        max_new_tokens: int = 20,
        repetition_penalty: Optional[float] = None,
        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,
416
417
        truncate: Optional[int] = None,
        typical_p: Optional[float] = None,
418
        watermark: bool = False,
Nicolas Patry's avatar
Nicolas Patry committed
419
        top_n_tokens: Optional[int] = None,
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
    ) -> 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.
            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.
447
448
449
450
451
            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
452
            watermark (`bool`):
453
                Watermarking with [A Watermark for Large Language Models](https://arxiv.org/abs/2301.10226)
Nicolas Patry's avatar
Nicolas Patry committed
454
455
            top_n_tokens (`int`):
                Return the `n` most likely tokens at each step
456
457
458
459
460
461

        Returns:
            AsyncIterator[StreamResponse]: stream of generated tokens
        """
        # Validate parameters
        parameters = Parameters(
462
            best_of=None,
463
            details=True,
464
            decoder_input_details=False,
465
466
467
468
469
470
471
472
473
            do_sample=do_sample,
            max_new_tokens=max_new_tokens,
            repetition_penalty=repetition_penalty,
            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,
474
475
            truncate=truncate,
            typical_p=typical_p,
476
            watermark=watermark,
Nicolas Patry's avatar
Nicolas Patry committed
477
            top_n_tokens=top_n_tokens,
478
479
480
        )
        request = Request(inputs=prompt, stream=True, parameters=parameters)

481
482
483
        async with ClientSession(
            headers=self.headers, cookies=self.cookies, timeout=self.timeout
        ) as session:
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
            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