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