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