isaacus 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
isaacus/_response.py ADDED
@@ -0,0 +1,830 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ import logging
6
+ import datetime
7
+ import functools
8
+ from types import TracebackType
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Any,
12
+ Union,
13
+ Generic,
14
+ TypeVar,
15
+ Callable,
16
+ Iterator,
17
+ AsyncIterator,
18
+ cast,
19
+ overload,
20
+ )
21
+ from typing_extensions import Awaitable, ParamSpec, override, get_origin
22
+
23
+ import anyio
24
+ import httpx
25
+ import pydantic
26
+
27
+ from ._types import NoneType
28
+ from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type, extract_type_var_from_base
29
+ from ._models import BaseModel, is_basemodel
30
+ from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER
31
+ from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type
32
+ from ._exceptions import IsaacusError, APIResponseValidationError
33
+
34
+ if TYPE_CHECKING:
35
+ from ._models import FinalRequestOptions
36
+ from ._base_client import BaseClient
37
+
38
+
39
+ P = ParamSpec("P")
40
+ R = TypeVar("R")
41
+ _T = TypeVar("_T")
42
+ _APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]")
43
+ _AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="AsyncAPIResponse[Any]")
44
+
45
+ log: logging.Logger = logging.getLogger(__name__)
46
+
47
+
48
+ class BaseAPIResponse(Generic[R]):
49
+ _cast_to: type[R]
50
+ _client: BaseClient[Any, Any]
51
+ _parsed_by_type: dict[type[Any], Any]
52
+ _is_sse_stream: bool
53
+ _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None
54
+ _options: FinalRequestOptions
55
+
56
+ http_response: httpx.Response
57
+
58
+ retries_taken: int
59
+ """The number of retries made. If no retries happened this will be `0`"""
60
+
61
+ def __init__(
62
+ self,
63
+ *,
64
+ raw: httpx.Response,
65
+ cast_to: type[R],
66
+ client: BaseClient[Any, Any],
67
+ stream: bool,
68
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
69
+ options: FinalRequestOptions,
70
+ retries_taken: int = 0,
71
+ ) -> None:
72
+ self._cast_to = cast_to
73
+ self._client = client
74
+ self._parsed_by_type = {}
75
+ self._is_sse_stream = stream
76
+ self._stream_cls = stream_cls
77
+ self._options = options
78
+ self.http_response = raw
79
+ self.retries_taken = retries_taken
80
+
81
+ @property
82
+ def headers(self) -> httpx.Headers:
83
+ return self.http_response.headers
84
+
85
+ @property
86
+ def http_request(self) -> httpx.Request:
87
+ """Returns the httpx Request instance associated with the current response."""
88
+ return self.http_response.request
89
+
90
+ @property
91
+ def status_code(self) -> int:
92
+ return self.http_response.status_code
93
+
94
+ @property
95
+ def url(self) -> httpx.URL:
96
+ """Returns the URL for which the request was made."""
97
+ return self.http_response.url
98
+
99
+ @property
100
+ def method(self) -> str:
101
+ return self.http_request.method
102
+
103
+ @property
104
+ def http_version(self) -> str:
105
+ return self.http_response.http_version
106
+
107
+ @property
108
+ def elapsed(self) -> datetime.timedelta:
109
+ """The time taken for the complete request/response cycle to complete."""
110
+ return self.http_response.elapsed
111
+
112
+ @property
113
+ def is_closed(self) -> bool:
114
+ """Whether or not the response body has been closed.
115
+
116
+ If this is False then there is response data that has not been read yet.
117
+ You must either fully consume the response body or call `.close()`
118
+ before discarding the response to prevent resource leaks.
119
+ """
120
+ return self.http_response.is_closed
121
+
122
+ @override
123
+ def __repr__(self) -> str:
124
+ return (
125
+ f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>"
126
+ )
127
+
128
+ def _parse(self, *, to: type[_T] | None = None) -> R | _T:
129
+ cast_to = to if to is not None else self._cast_to
130
+
131
+ # unwrap `TypeAlias('Name', T)` -> `T`
132
+ if is_type_alias_type(cast_to):
133
+ cast_to = cast_to.__value__ # type: ignore[unreachable]
134
+
135
+ # unwrap `Annotated[T, ...]` -> `T`
136
+ if cast_to and is_annotated_type(cast_to):
137
+ cast_to = extract_type_arg(cast_to, 0)
138
+
139
+ origin = get_origin(cast_to) or cast_to
140
+
141
+ if self._is_sse_stream:
142
+ if to:
143
+ if not is_stream_class_type(to):
144
+ raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}")
145
+
146
+ return cast(
147
+ _T,
148
+ to(
149
+ cast_to=extract_stream_chunk_type(
150
+ to,
151
+ failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]",
152
+ ),
153
+ response=self.http_response,
154
+ client=cast(Any, self._client),
155
+ ),
156
+ )
157
+
158
+ if self._stream_cls:
159
+ return cast(
160
+ R,
161
+ self._stream_cls(
162
+ cast_to=extract_stream_chunk_type(self._stream_cls),
163
+ response=self.http_response,
164
+ client=cast(Any, self._client),
165
+ ),
166
+ )
167
+
168
+ stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls)
169
+ if stream_cls is None:
170
+ raise MissingStreamClassError()
171
+
172
+ return cast(
173
+ R,
174
+ stream_cls(
175
+ cast_to=cast_to,
176
+ response=self.http_response,
177
+ client=cast(Any, self._client),
178
+ ),
179
+ )
180
+
181
+ if cast_to is NoneType:
182
+ return cast(R, None)
183
+
184
+ response = self.http_response
185
+ if cast_to == str:
186
+ return cast(R, response.text)
187
+
188
+ if cast_to == bytes:
189
+ return cast(R, response.content)
190
+
191
+ if cast_to == int:
192
+ return cast(R, int(response.text))
193
+
194
+ if cast_to == float:
195
+ return cast(R, float(response.text))
196
+
197
+ if cast_to == bool:
198
+ return cast(R, response.text.lower() == "true")
199
+
200
+ if origin == APIResponse:
201
+ raise RuntimeError("Unexpected state - cast_to is `APIResponse`")
202
+
203
+ if inspect.isclass(origin) and issubclass(origin, httpx.Response):
204
+ # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response
205
+ # and pass that class to our request functions. We cannot change the variance to be either
206
+ # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct
207
+ # the response class ourselves but that is something that should be supported directly in httpx
208
+ # as it would be easy to incorrectly construct the Response object due to the multitude of arguments.
209
+ if cast_to != httpx.Response:
210
+ raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`")
211
+ return cast(R, response)
212
+
213
+ if (
214
+ inspect.isclass(
215
+ origin # pyright: ignore[reportUnknownArgumentType]
216
+ )
217
+ and not issubclass(origin, BaseModel)
218
+ and issubclass(origin, pydantic.BaseModel)
219
+ ):
220
+ raise TypeError("Pydantic models must subclass our base model type, e.g. `from isaacus import BaseModel`")
221
+
222
+ if (
223
+ cast_to is not object
224
+ and not origin is list
225
+ and not origin is dict
226
+ and not origin is Union
227
+ and not issubclass(origin, BaseModel)
228
+ ):
229
+ raise RuntimeError(
230
+ f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}."
231
+ )
232
+
233
+ # split is required to handle cases where additional information is included
234
+ # in the response, e.g. application/json; charset=utf-8
235
+ content_type, *_ = response.headers.get("content-type", "*").split(";")
236
+ if content_type != "application/json":
237
+ if is_basemodel(cast_to):
238
+ try:
239
+ data = response.json()
240
+ except Exception as exc:
241
+ log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc)
242
+ else:
243
+ return self._client._process_response_data(
244
+ data=data,
245
+ cast_to=cast_to, # type: ignore
246
+ response=response,
247
+ )
248
+
249
+ if self._client._strict_response_validation:
250
+ raise APIResponseValidationError(
251
+ response=response,
252
+ message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.",
253
+ body=response.text,
254
+ )
255
+
256
+ # If the API responds with content that isn't JSON then we just return
257
+ # the (decoded) text without performing any parsing so that you can still
258
+ # handle the response however you need to.
259
+ return response.text # type: ignore
260
+
261
+ data = response.json()
262
+
263
+ return self._client._process_response_data(
264
+ data=data,
265
+ cast_to=cast_to, # type: ignore
266
+ response=response,
267
+ )
268
+
269
+
270
+ class APIResponse(BaseAPIResponse[R]):
271
+ @overload
272
+ def parse(self, *, to: type[_T]) -> _T: ...
273
+
274
+ @overload
275
+ def parse(self) -> R: ...
276
+
277
+ def parse(self, *, to: type[_T] | None = None) -> R | _T:
278
+ """Returns the rich python representation of this response's data.
279
+
280
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
281
+
282
+ You can customise the type that the response is parsed into through
283
+ the `to` argument, e.g.
284
+
285
+ ```py
286
+ from isaacus import BaseModel
287
+
288
+
289
+ class MyModel(BaseModel):
290
+ foo: str
291
+
292
+
293
+ obj = response.parse(to=MyModel)
294
+ print(obj.foo)
295
+ ```
296
+
297
+ We support parsing:
298
+ - `BaseModel`
299
+ - `dict`
300
+ - `list`
301
+ - `Union`
302
+ - `str`
303
+ - `int`
304
+ - `float`
305
+ - `httpx.Response`
306
+ """
307
+ cache_key = to if to is not None else self._cast_to
308
+ cached = self._parsed_by_type.get(cache_key)
309
+ if cached is not None:
310
+ return cached # type: ignore[no-any-return]
311
+
312
+ if not self._is_sse_stream:
313
+ self.read()
314
+
315
+ parsed = self._parse(to=to)
316
+ if is_given(self._options.post_parser):
317
+ parsed = self._options.post_parser(parsed)
318
+
319
+ self._parsed_by_type[cache_key] = parsed
320
+ return parsed
321
+
322
+ def read(self) -> bytes:
323
+ """Read and return the binary response content."""
324
+ try:
325
+ return self.http_response.read()
326
+ except httpx.StreamConsumed as exc:
327
+ # The default error raised by httpx isn't very
328
+ # helpful in our case so we re-raise it with
329
+ # a different error message.
330
+ raise StreamAlreadyConsumed() from exc
331
+
332
+ def text(self) -> str:
333
+ """Read and decode the response content into a string."""
334
+ self.read()
335
+ return self.http_response.text
336
+
337
+ def json(self) -> object:
338
+ """Read and decode the JSON response content."""
339
+ self.read()
340
+ return self.http_response.json()
341
+
342
+ def close(self) -> None:
343
+ """Close the response and release the connection.
344
+
345
+ Automatically called if the response body is read to completion.
346
+ """
347
+ self.http_response.close()
348
+
349
+ def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
350
+ """
351
+ A byte-iterator over the decoded response content.
352
+
353
+ This automatically handles gzip, deflate and brotli encoded responses.
354
+ """
355
+ for chunk in self.http_response.iter_bytes(chunk_size):
356
+ yield chunk
357
+
358
+ def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
359
+ """A str-iterator over the decoded response content
360
+ that handles both gzip, deflate, etc but also detects the content's
361
+ string encoding.
362
+ """
363
+ for chunk in self.http_response.iter_text(chunk_size):
364
+ yield chunk
365
+
366
+ def iter_lines(self) -> Iterator[str]:
367
+ """Like `iter_text()` but will only yield chunks for each line"""
368
+ for chunk in self.http_response.iter_lines():
369
+ yield chunk
370
+
371
+
372
+ class AsyncAPIResponse(BaseAPIResponse[R]):
373
+ @overload
374
+ async def parse(self, *, to: type[_T]) -> _T: ...
375
+
376
+ @overload
377
+ async def parse(self) -> R: ...
378
+
379
+ async def parse(self, *, to: type[_T] | None = None) -> R | _T:
380
+ """Returns the rich python representation of this response's data.
381
+
382
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
383
+
384
+ You can customise the type that the response is parsed into through
385
+ the `to` argument, e.g.
386
+
387
+ ```py
388
+ from isaacus import BaseModel
389
+
390
+
391
+ class MyModel(BaseModel):
392
+ foo: str
393
+
394
+
395
+ obj = response.parse(to=MyModel)
396
+ print(obj.foo)
397
+ ```
398
+
399
+ We support parsing:
400
+ - `BaseModel`
401
+ - `dict`
402
+ - `list`
403
+ - `Union`
404
+ - `str`
405
+ - `httpx.Response`
406
+ """
407
+ cache_key = to if to is not None else self._cast_to
408
+ cached = self._parsed_by_type.get(cache_key)
409
+ if cached is not None:
410
+ return cached # type: ignore[no-any-return]
411
+
412
+ if not self._is_sse_stream:
413
+ await self.read()
414
+
415
+ parsed = self._parse(to=to)
416
+ if is_given(self._options.post_parser):
417
+ parsed = self._options.post_parser(parsed)
418
+
419
+ self._parsed_by_type[cache_key] = parsed
420
+ return parsed
421
+
422
+ async def read(self) -> bytes:
423
+ """Read and return the binary response content."""
424
+ try:
425
+ return await self.http_response.aread()
426
+ except httpx.StreamConsumed as exc:
427
+ # the default error raised by httpx isn't very
428
+ # helpful in our case so we re-raise it with
429
+ # a different error message
430
+ raise StreamAlreadyConsumed() from exc
431
+
432
+ async def text(self) -> str:
433
+ """Read and decode the response content into a string."""
434
+ await self.read()
435
+ return self.http_response.text
436
+
437
+ async def json(self) -> object:
438
+ """Read and decode the JSON response content."""
439
+ await self.read()
440
+ return self.http_response.json()
441
+
442
+ async def close(self) -> None:
443
+ """Close the response and release the connection.
444
+
445
+ Automatically called if the response body is read to completion.
446
+ """
447
+ await self.http_response.aclose()
448
+
449
+ async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
450
+ """
451
+ A byte-iterator over the decoded response content.
452
+
453
+ This automatically handles gzip, deflate and brotli encoded responses.
454
+ """
455
+ async for chunk in self.http_response.aiter_bytes(chunk_size):
456
+ yield chunk
457
+
458
+ async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
459
+ """A str-iterator over the decoded response content
460
+ that handles both gzip, deflate, etc but also detects the content's
461
+ string encoding.
462
+ """
463
+ async for chunk in self.http_response.aiter_text(chunk_size):
464
+ yield chunk
465
+
466
+ async def iter_lines(self) -> AsyncIterator[str]:
467
+ """Like `iter_text()` but will only yield chunks for each line"""
468
+ async for chunk in self.http_response.aiter_lines():
469
+ yield chunk
470
+
471
+
472
+ class BinaryAPIResponse(APIResponse[bytes]):
473
+ """Subclass of APIResponse providing helpers for dealing with binary data.
474
+
475
+ Note: If you want to stream the response data instead of eagerly reading it
476
+ all at once then you should use `.with_streaming_response` when making
477
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
478
+ """
479
+
480
+ def write_to_file(
481
+ self,
482
+ file: str | os.PathLike[str],
483
+ ) -> None:
484
+ """Write the output to the given file.
485
+
486
+ Accepts a filename or any path-like object, e.g. pathlib.Path
487
+
488
+ Note: if you want to stream the data to the file instead of writing
489
+ all at once then you should use `.with_streaming_response` when making
490
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
491
+ """
492
+ with open(file, mode="wb") as f:
493
+ for data in self.iter_bytes():
494
+ f.write(data)
495
+
496
+
497
+ class AsyncBinaryAPIResponse(AsyncAPIResponse[bytes]):
498
+ """Subclass of APIResponse providing helpers for dealing with binary data.
499
+
500
+ Note: If you want to stream the response data instead of eagerly reading it
501
+ all at once then you should use `.with_streaming_response` when making
502
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
503
+ """
504
+
505
+ async def write_to_file(
506
+ self,
507
+ file: str | os.PathLike[str],
508
+ ) -> None:
509
+ """Write the output to the given file.
510
+
511
+ Accepts a filename or any path-like object, e.g. pathlib.Path
512
+
513
+ Note: if you want to stream the data to the file instead of writing
514
+ all at once then you should use `.with_streaming_response` when making
515
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
516
+ """
517
+ path = anyio.Path(file)
518
+ async with await path.open(mode="wb") as f:
519
+ async for data in self.iter_bytes():
520
+ await f.write(data)
521
+
522
+
523
+ class StreamedBinaryAPIResponse(APIResponse[bytes]):
524
+ def stream_to_file(
525
+ self,
526
+ file: str | os.PathLike[str],
527
+ *,
528
+ chunk_size: int | None = None,
529
+ ) -> None:
530
+ """Streams the output to the given file.
531
+
532
+ Accepts a filename or any path-like object, e.g. pathlib.Path
533
+ """
534
+ with open(file, mode="wb") as f:
535
+ for data in self.iter_bytes(chunk_size):
536
+ f.write(data)
537
+
538
+
539
+ class AsyncStreamedBinaryAPIResponse(AsyncAPIResponse[bytes]):
540
+ async def stream_to_file(
541
+ self,
542
+ file: str | os.PathLike[str],
543
+ *,
544
+ chunk_size: int | None = None,
545
+ ) -> None:
546
+ """Streams the output to the given file.
547
+
548
+ Accepts a filename or any path-like object, e.g. pathlib.Path
549
+ """
550
+ path = anyio.Path(file)
551
+ async with await path.open(mode="wb") as f:
552
+ async for data in self.iter_bytes(chunk_size):
553
+ await f.write(data)
554
+
555
+
556
+ class MissingStreamClassError(TypeError):
557
+ def __init__(self) -> None:
558
+ super().__init__(
559
+ "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `isaacus._streaming` for reference",
560
+ )
561
+
562
+
563
+ class StreamAlreadyConsumed(IsaacusError):
564
+ """
565
+ Attempted to read or stream content, but the content has already
566
+ been streamed.
567
+
568
+ This can happen if you use a method like `.iter_lines()` and then attempt
569
+ to read th entire response body afterwards, e.g.
570
+
571
+ ```py
572
+ response = await client.post(...)
573
+ async for line in response.iter_lines():
574
+ ... # do something with `line`
575
+
576
+ content = await response.read()
577
+ # ^ error
578
+ ```
579
+
580
+ If you want this behaviour you'll need to either manually accumulate the response
581
+ content or call `await response.read()` before iterating over the stream.
582
+ """
583
+
584
+ def __init__(self) -> None:
585
+ message = (
586
+ "Attempted to read or stream some content, but the content has "
587
+ "already been streamed. "
588
+ "This could be due to attempting to stream the response "
589
+ "content more than once."
590
+ "\n\n"
591
+ "You can fix this by manually accumulating the response content while streaming "
592
+ "or by calling `.read()` before starting to stream."
593
+ )
594
+ super().__init__(message)
595
+
596
+
597
+ class ResponseContextManager(Generic[_APIResponseT]):
598
+ """Context manager for ensuring that a request is not made
599
+ until it is entered and that the response will always be closed
600
+ when the context manager exits
601
+ """
602
+
603
+ def __init__(self, request_func: Callable[[], _APIResponseT]) -> None:
604
+ self._request_func = request_func
605
+ self.__response: _APIResponseT | None = None
606
+
607
+ def __enter__(self) -> _APIResponseT:
608
+ self.__response = self._request_func()
609
+ return self.__response
610
+
611
+ def __exit__(
612
+ self,
613
+ exc_type: type[BaseException] | None,
614
+ exc: BaseException | None,
615
+ exc_tb: TracebackType | None,
616
+ ) -> None:
617
+ if self.__response is not None:
618
+ self.__response.close()
619
+
620
+
621
+ class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]):
622
+ """Context manager for ensuring that a request is not made
623
+ until it is entered and that the response will always be closed
624
+ when the context manager exits
625
+ """
626
+
627
+ def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None:
628
+ self._api_request = api_request
629
+ self.__response: _AsyncAPIResponseT | None = None
630
+
631
+ async def __aenter__(self) -> _AsyncAPIResponseT:
632
+ self.__response = await self._api_request
633
+ return self.__response
634
+
635
+ async def __aexit__(
636
+ self,
637
+ exc_type: type[BaseException] | None,
638
+ exc: BaseException | None,
639
+ exc_tb: TracebackType | None,
640
+ ) -> None:
641
+ if self.__response is not None:
642
+ await self.__response.close()
643
+
644
+
645
+ def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseContextManager[APIResponse[R]]]:
646
+ """Higher order function that takes one of our bound API methods and wraps it
647
+ to support streaming and returning the raw `APIResponse` object directly.
648
+ """
649
+
650
+ @functools.wraps(func)
651
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]:
652
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
653
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
654
+
655
+ kwargs["extra_headers"] = extra_headers
656
+
657
+ make_request = functools.partial(func, *args, **kwargs)
658
+
659
+ return ResponseContextManager(cast(Callable[[], APIResponse[R]], make_request))
660
+
661
+ return wrapped
662
+
663
+
664
+ def async_to_streamed_response_wrapper(
665
+ func: Callable[P, Awaitable[R]],
666
+ ) -> Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]]:
667
+ """Higher order function that takes one of our bound API methods and wraps it
668
+ to support streaming and returning the raw `APIResponse` object directly.
669
+ """
670
+
671
+ @functools.wraps(func)
672
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]:
673
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
674
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
675
+
676
+ kwargs["extra_headers"] = extra_headers
677
+
678
+ make_request = func(*args, **kwargs)
679
+
680
+ return AsyncResponseContextManager(cast(Awaitable[AsyncAPIResponse[R]], make_request))
681
+
682
+ return wrapped
683
+
684
+
685
+ def to_custom_streamed_response_wrapper(
686
+ func: Callable[P, object],
687
+ response_cls: type[_APIResponseT],
688
+ ) -> Callable[P, ResponseContextManager[_APIResponseT]]:
689
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
690
+ and wraps the method to support streaming and returning the given response class directly.
691
+
692
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
693
+ """
694
+
695
+ @functools.wraps(func)
696
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]:
697
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
698
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
699
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
700
+
701
+ kwargs["extra_headers"] = extra_headers
702
+
703
+ make_request = functools.partial(func, *args, **kwargs)
704
+
705
+ return ResponseContextManager(cast(Callable[[], _APIResponseT], make_request))
706
+
707
+ return wrapped
708
+
709
+
710
+ def async_to_custom_streamed_response_wrapper(
711
+ func: Callable[P, Awaitable[object]],
712
+ response_cls: type[_AsyncAPIResponseT],
713
+ ) -> Callable[P, AsyncResponseContextManager[_AsyncAPIResponseT]]:
714
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
715
+ and wraps the method to support streaming and returning the given response class directly.
716
+
717
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
718
+ """
719
+
720
+ @functools.wraps(func)
721
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]:
722
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
723
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
724
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
725
+
726
+ kwargs["extra_headers"] = extra_headers
727
+
728
+ make_request = func(*args, **kwargs)
729
+
730
+ return AsyncResponseContextManager(cast(Awaitable[_AsyncAPIResponseT], make_request))
731
+
732
+ return wrapped
733
+
734
+
735
+ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]:
736
+ """Higher order function that takes one of our bound API methods and wraps it
737
+ to support returning the raw `APIResponse` object directly.
738
+ """
739
+
740
+ @functools.wraps(func)
741
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]:
742
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
743
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
744
+
745
+ kwargs["extra_headers"] = extra_headers
746
+
747
+ return cast(APIResponse[R], func(*args, **kwargs))
748
+
749
+ return wrapped
750
+
751
+
752
+ def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[AsyncAPIResponse[R]]]:
753
+ """Higher order function that takes one of our bound API methods and wraps it
754
+ to support returning the raw `APIResponse` object directly.
755
+ """
756
+
757
+ @functools.wraps(func)
758
+ async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]:
759
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
760
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
761
+
762
+ kwargs["extra_headers"] = extra_headers
763
+
764
+ return cast(AsyncAPIResponse[R], await func(*args, **kwargs))
765
+
766
+ return wrapped
767
+
768
+
769
+ def to_custom_raw_response_wrapper(
770
+ func: Callable[P, object],
771
+ response_cls: type[_APIResponseT],
772
+ ) -> Callable[P, _APIResponseT]:
773
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
774
+ and wraps the method to support returning the given response class directly.
775
+
776
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
777
+ """
778
+
779
+ @functools.wraps(func)
780
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT:
781
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
782
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
783
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
784
+
785
+ kwargs["extra_headers"] = extra_headers
786
+
787
+ return cast(_APIResponseT, func(*args, **kwargs))
788
+
789
+ return wrapped
790
+
791
+
792
+ def async_to_custom_raw_response_wrapper(
793
+ func: Callable[P, Awaitable[object]],
794
+ response_cls: type[_AsyncAPIResponseT],
795
+ ) -> Callable[P, Awaitable[_AsyncAPIResponseT]]:
796
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
797
+ and wraps the method to support returning the given response class directly.
798
+
799
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
800
+ """
801
+
802
+ @functools.wraps(func)
803
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]:
804
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
805
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
806
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
807
+
808
+ kwargs["extra_headers"] = extra_headers
809
+
810
+ return cast(Awaitable[_AsyncAPIResponseT], func(*args, **kwargs))
811
+
812
+ return wrapped
813
+
814
+
815
+ def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type:
816
+ """Given a type like `APIResponse[T]`, returns the generic type variable `T`.
817
+
818
+ This also handles the case where a concrete subclass is given, e.g.
819
+ ```py
820
+ class MyResponse(APIResponse[bytes]):
821
+ ...
822
+
823
+ extract_response_type(MyResponse) -> bytes
824
+ ```
825
+ """
826
+ return extract_type_var_from_base(
827
+ typ,
828
+ generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse, AsyncAPIResponse)),
829
+ index=0,
830
+ )