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