runloop_api_client 0.61.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 (187) hide show
  1. runloop_api_client/__init__.py +92 -0
  2. runloop_api_client/_base_client.py +1995 -0
  3. runloop_api_client/_client.py +668 -0
  4. runloop_api_client/_compat.py +219 -0
  5. runloop_api_client/_constants.py +14 -0
  6. runloop_api_client/_exceptions.py +108 -0
  7. runloop_api_client/_files.py +123 -0
  8. runloop_api_client/_models.py +835 -0
  9. runloop_api_client/_qs.py +150 -0
  10. runloop_api_client/_resource.py +43 -0
  11. runloop_api_client/_response.py +832 -0
  12. runloop_api_client/_streaming.py +520 -0
  13. runloop_api_client/_types.py +260 -0
  14. runloop_api_client/_utils/__init__.py +64 -0
  15. runloop_api_client/_utils/_compat.py +45 -0
  16. runloop_api_client/_utils/_datetime_parse.py +136 -0
  17. runloop_api_client/_utils/_logs.py +25 -0
  18. runloop_api_client/_utils/_proxy.py +65 -0
  19. runloop_api_client/_utils/_reflection.py +42 -0
  20. runloop_api_client/_utils/_resources_proxy.py +24 -0
  21. runloop_api_client/_utils/_streams.py +12 -0
  22. runloop_api_client/_utils/_sync.py +86 -0
  23. runloop_api_client/_utils/_transform.py +457 -0
  24. runloop_api_client/_utils/_typing.py +156 -0
  25. runloop_api_client/_utils/_utils.py +421 -0
  26. runloop_api_client/_version.py +4 -0
  27. runloop_api_client/lib/.keep +4 -0
  28. runloop_api_client/lib/polling.py +75 -0
  29. runloop_api_client/lib/polling_async.py +60 -0
  30. runloop_api_client/pagination.py +761 -0
  31. runloop_api_client/py.typed +0 -0
  32. runloop_api_client/resources/__init__.py +103 -0
  33. runloop_api_client/resources/benchmarks/__init__.py +33 -0
  34. runloop_api_client/resources/benchmarks/benchmarks.py +982 -0
  35. runloop_api_client/resources/benchmarks/runs.py +587 -0
  36. runloop_api_client/resources/blueprints.py +1206 -0
  37. runloop_api_client/resources/devboxes/__init__.py +89 -0
  38. runloop_api_client/resources/devboxes/browsers.py +267 -0
  39. runloop_api_client/resources/devboxes/computers.py +648 -0
  40. runloop_api_client/resources/devboxes/devboxes.py +3414 -0
  41. runloop_api_client/resources/devboxes/disk_snapshots.py +519 -0
  42. runloop_api_client/resources/devboxes/executions.py +1059 -0
  43. runloop_api_client/resources/devboxes/logs.py +197 -0
  44. runloop_api_client/resources/objects.py +860 -0
  45. runloop_api_client/resources/repositories.py +717 -0
  46. runloop_api_client/resources/scenarios/__init__.py +47 -0
  47. runloop_api_client/resources/scenarios/runs.py +949 -0
  48. runloop_api_client/resources/scenarios/scenarios.py +1079 -0
  49. runloop_api_client/resources/scenarios/scorers.py +629 -0
  50. runloop_api_client/resources/secrets.py +500 -0
  51. runloop_api_client/types/__init__.py +95 -0
  52. runloop_api_client/types/benchmark_create_params.py +40 -0
  53. runloop_api_client/types/benchmark_definitions_params.py +15 -0
  54. runloop_api_client/types/benchmark_list_params.py +15 -0
  55. runloop_api_client/types/benchmark_list_public_params.py +15 -0
  56. runloop_api_client/types/benchmark_run_list_view.py +19 -0
  57. runloop_api_client/types/benchmark_run_view.py +51 -0
  58. runloop_api_client/types/benchmark_start_run_params.py +25 -0
  59. runloop_api_client/types/benchmark_update_params.py +40 -0
  60. runloop_api_client/types/benchmark_view.py +45 -0
  61. runloop_api_client/types/benchmarks/__init__.py +6 -0
  62. runloop_api_client/types/benchmarks/run_list_params.py +18 -0
  63. runloop_api_client/types/benchmarks/run_list_scenario_runs_params.py +18 -0
  64. runloop_api_client/types/blueprint_build_log.py +16 -0
  65. runloop_api_client/types/blueprint_build_logs_list_view.py +16 -0
  66. runloop_api_client/types/blueprint_build_parameters.py +87 -0
  67. runloop_api_client/types/blueprint_create_params.py +90 -0
  68. runloop_api_client/types/blueprint_list_params.py +18 -0
  69. runloop_api_client/types/blueprint_list_public_params.py +18 -0
  70. runloop_api_client/types/blueprint_list_view.py +19 -0
  71. runloop_api_client/types/blueprint_preview_params.py +90 -0
  72. runloop_api_client/types/blueprint_preview_view.py +10 -0
  73. runloop_api_client/types/blueprint_view.py +86 -0
  74. runloop_api_client/types/devbox_async_execution_detail_view.py +40 -0
  75. runloop_api_client/types/devbox_create_params.py +70 -0
  76. runloop_api_client/types/devbox_create_ssh_key_response.py +16 -0
  77. runloop_api_client/types/devbox_create_tunnel_params.py +12 -0
  78. runloop_api_client/types/devbox_download_file_params.py +15 -0
  79. runloop_api_client/types/devbox_execute_async_params.py +25 -0
  80. runloop_api_client/types/devbox_execute_params.py +34 -0
  81. runloop_api_client/types/devbox_execute_sync_params.py +25 -0
  82. runloop_api_client/types/devbox_execution_detail_view.py +24 -0
  83. runloop_api_client/types/devbox_list_disk_snapshots_params.py +29 -0
  84. runloop_api_client/types/devbox_list_params.py +20 -0
  85. runloop_api_client/types/devbox_list_view.py +19 -0
  86. runloop_api_client/types/devbox_read_file_contents_params.py +15 -0
  87. runloop_api_client/types/devbox_read_file_contents_response.py +7 -0
  88. runloop_api_client/types/devbox_remove_tunnel_params.py +12 -0
  89. runloop_api_client/types/devbox_snapshot_disk_async_params.py +16 -0
  90. runloop_api_client/types/devbox_snapshot_disk_params.py +16 -0
  91. runloop_api_client/types/devbox_snapshot_list_view.py +19 -0
  92. runloop_api_client/types/devbox_snapshot_view.py +24 -0
  93. runloop_api_client/types/devbox_tunnel_view.py +16 -0
  94. runloop_api_client/types/devbox_update_params.py +16 -0
  95. runloop_api_client/types/devbox_upload_file_params.py +19 -0
  96. runloop_api_client/types/devbox_view.py +94 -0
  97. runloop_api_client/types/devbox_wait_for_command_params.py +25 -0
  98. runloop_api_client/types/devbox_write_file_contents_params.py +18 -0
  99. runloop_api_client/types/devboxes/__init__.py +32 -0
  100. runloop_api_client/types/devboxes/browser_create_params.py +13 -0
  101. runloop_api_client/types/devboxes/browser_view.py +25 -0
  102. runloop_api_client/types/devboxes/computer_create_params.py +24 -0
  103. runloop_api_client/types/devboxes/computer_keyboard_interaction_params.py +16 -0
  104. runloop_api_client/types/devboxes/computer_keyboard_interaction_response.py +15 -0
  105. runloop_api_client/types/devboxes/computer_mouse_interaction_params.py +30 -0
  106. runloop_api_client/types/devboxes/computer_mouse_interaction_response.py +15 -0
  107. runloop_api_client/types/devboxes/computer_screen_interaction_params.py +12 -0
  108. runloop_api_client/types/devboxes/computer_screen_interaction_response.py +15 -0
  109. runloop_api_client/types/devboxes/computer_view.py +19 -0
  110. runloop_api_client/types/devboxes/devbox_logs_list_view.py +39 -0
  111. runloop_api_client/types/devboxes/devbox_snapshot_async_status_view.py +20 -0
  112. runloop_api_client/types/devboxes/disk_snapshot_list_params.py +29 -0
  113. runloop_api_client/types/devboxes/disk_snapshot_update_params.py +16 -0
  114. runloop_api_client/types/devboxes/execution_execute_async_params.py +25 -0
  115. runloop_api_client/types/devboxes/execution_execute_sync_params.py +25 -0
  116. runloop_api_client/types/devboxes/execution_kill_params.py +18 -0
  117. runloop_api_client/types/devboxes/execution_retrieve_params.py +14 -0
  118. runloop_api_client/types/devboxes/execution_stream_stderr_updates_params.py +14 -0
  119. runloop_api_client/types/devboxes/execution_stream_stdout_updates_params.py +14 -0
  120. runloop_api_client/types/devboxes/execution_update_chunk.py +15 -0
  121. runloop_api_client/types/devboxes/log_list_params.py +15 -0
  122. runloop_api_client/types/input_context.py +15 -0
  123. runloop_api_client/types/input_context_param.py +16 -0
  124. runloop_api_client/types/input_context_update_param.py +16 -0
  125. runloop_api_client/types/object_create_params.py +19 -0
  126. runloop_api_client/types/object_download_params.py +12 -0
  127. runloop_api_client/types/object_download_url_view.py +10 -0
  128. runloop_api_client/types/object_list_params.py +27 -0
  129. runloop_api_client/types/object_list_public_params.py +27 -0
  130. runloop_api_client/types/object_list_view.py +22 -0
  131. runloop_api_client/types/object_view.py +28 -0
  132. runloop_api_client/types/repository_connection_list_view.py +19 -0
  133. runloop_api_client/types/repository_connection_view.py +16 -0
  134. runloop_api_client/types/repository_create_params.py +22 -0
  135. runloop_api_client/types/repository_inspection_details.py +77 -0
  136. runloop_api_client/types/repository_inspection_list_view.py +13 -0
  137. runloop_api_client/types/repository_list_params.py +21 -0
  138. runloop_api_client/types/repository_manifest_view.py +158 -0
  139. runloop_api_client/types/repository_refresh_params.py +16 -0
  140. runloop_api_client/types/scenario_create_params.py +53 -0
  141. runloop_api_client/types/scenario_definition_list_view.py +19 -0
  142. runloop_api_client/types/scenario_environment.py +25 -0
  143. runloop_api_client/types/scenario_environment_param.py +27 -0
  144. runloop_api_client/types/scenario_list_params.py +21 -0
  145. runloop_api_client/types/scenario_list_public_params.py +18 -0
  146. runloop_api_client/types/scenario_run_list_view.py +19 -0
  147. runloop_api_client/types/scenario_run_view.py +50 -0
  148. runloop_api_client/types/scenario_start_run_params.py +28 -0
  149. runloop_api_client/types/scenario_update_params.py +46 -0
  150. runloop_api_client/types/scenario_view.py +57 -0
  151. runloop_api_client/types/scenarios/__init__.py +14 -0
  152. runloop_api_client/types/scenarios/run_list_params.py +18 -0
  153. runloop_api_client/types/scenarios/scorer_create_params.py +18 -0
  154. runloop_api_client/types/scenarios/scorer_create_response.py +16 -0
  155. runloop_api_client/types/scenarios/scorer_list_params.py +15 -0
  156. runloop_api_client/types/scenarios/scorer_list_response.py +16 -0
  157. runloop_api_client/types/scenarios/scorer_retrieve_response.py +16 -0
  158. runloop_api_client/types/scenarios/scorer_update_params.py +18 -0
  159. runloop_api_client/types/scenarios/scorer_update_response.py +16 -0
  160. runloop_api_client/types/scenarios/scorer_validate_params.py +17 -0
  161. runloop_api_client/types/scenarios/scorer_validate_response.py +23 -0
  162. runloop_api_client/types/scoring_contract.py +13 -0
  163. runloop_api_client/types/scoring_contract_param.py +15 -0
  164. runloop_api_client/types/scoring_contract_result_view.py +16 -0
  165. runloop_api_client/types/scoring_contract_update_param.py +15 -0
  166. runloop_api_client/types/scoring_function.py +135 -0
  167. runloop_api_client/types/scoring_function_param.py +131 -0
  168. runloop_api_client/types/scoring_function_result_view.py +21 -0
  169. runloop_api_client/types/secret_create_params.py +23 -0
  170. runloop_api_client/types/secret_list_params.py +12 -0
  171. runloop_api_client/types/secret_list_view.py +22 -0
  172. runloop_api_client/types/secret_update_params.py +16 -0
  173. runloop_api_client/types/secret_view.py +22 -0
  174. runloop_api_client/types/shared/__init__.py +6 -0
  175. runloop_api_client/types/shared/after_idle.py +15 -0
  176. runloop_api_client/types/shared/code_mount_parameters.py +24 -0
  177. runloop_api_client/types/shared/launch_parameters.py +79 -0
  178. runloop_api_client/types/shared/run_profile.py +33 -0
  179. runloop_api_client/types/shared_params/__init__.py +6 -0
  180. runloop_api_client/types/shared_params/after_idle.py +15 -0
  181. runloop_api_client/types/shared_params/code_mount_parameters.py +25 -0
  182. runloop_api_client/types/shared_params/launch_parameters.py +81 -0
  183. runloop_api_client/types/shared_params/run_profile.py +34 -0
  184. runloop_api_client-0.61.0.dist-info/METADATA +496 -0
  185. runloop_api_client-0.61.0.dist-info/RECORD +187 -0
  186. runloop_api_client-0.61.0.dist-info/WHEEL +4 -0
  187. runloop_api_client-0.61.0.dist-info/licenses/LICENSE +7 -0
@@ -0,0 +1,260 @@
1
+ from __future__ import annotations
2
+
3
+ from os import PathLike
4
+ from typing import (
5
+ IO,
6
+ TYPE_CHECKING,
7
+ Any,
8
+ Dict,
9
+ List,
10
+ Type,
11
+ Tuple,
12
+ Union,
13
+ Mapping,
14
+ TypeVar,
15
+ Callable,
16
+ Iterator,
17
+ Optional,
18
+ Sequence,
19
+ )
20
+ from typing_extensions import (
21
+ Set,
22
+ Literal,
23
+ Protocol,
24
+ TypeAlias,
25
+ TypedDict,
26
+ SupportsIndex,
27
+ overload,
28
+ override,
29
+ runtime_checkable,
30
+ )
31
+
32
+ import httpx
33
+ import pydantic
34
+ from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport
35
+
36
+ if TYPE_CHECKING:
37
+ from ._models import BaseModel
38
+ from ._response import APIResponse, AsyncAPIResponse
39
+
40
+ Transport = BaseTransport
41
+ AsyncTransport = AsyncBaseTransport
42
+ Query = Mapping[str, object]
43
+ Body = object
44
+ AnyMapping = Mapping[str, object]
45
+ ModelT = TypeVar("ModelT", bound=pydantic.BaseModel)
46
+ _T = TypeVar("_T")
47
+
48
+
49
+ # Approximates httpx internal ProxiesTypes and RequestFiles types
50
+ # while adding support for `PathLike` instances
51
+ ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]]
52
+ ProxiesTypes = Union[str, Proxy, ProxiesDict]
53
+ if TYPE_CHECKING:
54
+ Base64FileInput = Union[IO[bytes], PathLike[str]]
55
+ FileContent = Union[IO[bytes], bytes, PathLike[str]]
56
+ else:
57
+ Base64FileInput = Union[IO[bytes], PathLike]
58
+ FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8.
59
+ FileTypes = Union[
60
+ # file (or bytes)
61
+ FileContent,
62
+ # (filename, file (or bytes))
63
+ Tuple[Optional[str], FileContent],
64
+ # (filename, file (or bytes), content_type)
65
+ Tuple[Optional[str], FileContent, Optional[str]],
66
+ # (filename, file (or bytes), content_type, headers)
67
+ Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],
68
+ ]
69
+ RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
70
+
71
+ # duplicate of the above but without our custom file support
72
+ HttpxFileContent = Union[IO[bytes], bytes]
73
+ HttpxFileTypes = Union[
74
+ # file (or bytes)
75
+ HttpxFileContent,
76
+ # (filename, file (or bytes))
77
+ Tuple[Optional[str], HttpxFileContent],
78
+ # (filename, file (or bytes), content_type)
79
+ Tuple[Optional[str], HttpxFileContent, Optional[str]],
80
+ # (filename, file (or bytes), content_type, headers)
81
+ Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]],
82
+ ]
83
+ HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]]
84
+
85
+ # Workaround to support (cast_to: Type[ResponseT]) -> ResponseT
86
+ # where ResponseT includes `None`. In order to support directly
87
+ # passing `None`, overloads would have to be defined for every
88
+ # method that uses `ResponseT` which would lead to an unacceptable
89
+ # amount of code duplication and make it unreadable. See _base_client.py
90
+ # for example usage.
91
+ #
92
+ # This unfortunately means that you will either have
93
+ # to import this type and pass it explicitly:
94
+ #
95
+ # from runloop_api_client import NoneType
96
+ # client.get('/foo', cast_to=NoneType)
97
+ #
98
+ # or build it yourself:
99
+ #
100
+ # client.get('/foo', cast_to=type(None))
101
+ if TYPE_CHECKING:
102
+ NoneType: Type[None]
103
+ else:
104
+ NoneType = type(None)
105
+
106
+
107
+ class RequestOptions(TypedDict, total=False):
108
+ headers: Headers
109
+ max_retries: int
110
+ timeout: float | Timeout | None
111
+ params: Query
112
+ extra_json: AnyMapping
113
+ idempotency_key: str
114
+ follow_redirects: bool
115
+
116
+
117
+ # Sentinel class used until PEP 0661 is accepted
118
+ class NotGiven:
119
+ """
120
+ For parameters with a meaningful None value, we need to distinguish between
121
+ the user explicitly passing None, and the user not passing the parameter at
122
+ all.
123
+
124
+ User code shouldn't need to use not_given directly.
125
+
126
+ For example:
127
+
128
+ ```py
129
+ def create(timeout: Timeout | None | NotGiven = not_given): ...
130
+
131
+
132
+ create(timeout=1) # 1s timeout
133
+ create(timeout=None) # No timeout
134
+ create() # Default timeout behavior
135
+ ```
136
+ """
137
+
138
+ def __bool__(self) -> Literal[False]:
139
+ return False
140
+
141
+ @override
142
+ def __repr__(self) -> str:
143
+ return "NOT_GIVEN"
144
+
145
+
146
+ not_given = NotGiven()
147
+ # for backwards compatibility:
148
+ NOT_GIVEN = NotGiven()
149
+
150
+
151
+ class Omit:
152
+ """
153
+ To explicitly omit something from being sent in a request, use `omit`.
154
+
155
+ ```py
156
+ # as the default `Content-Type` header is `application/json` that will be sent
157
+ client.post("/upload/files", files={"file": b"my raw file content"})
158
+
159
+ # you can't explicitly override the header as it has to be dynamically generated
160
+ # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
161
+ client.post(..., headers={"Content-Type": "multipart/form-data"})
162
+
163
+ # instead you can remove the default `application/json` header by passing omit
164
+ client.post(..., headers={"Content-Type": omit})
165
+ ```
166
+ """
167
+
168
+ def __bool__(self) -> Literal[False]:
169
+ return False
170
+
171
+
172
+ omit = Omit()
173
+
174
+
175
+ @runtime_checkable
176
+ class ModelBuilderProtocol(Protocol):
177
+ @classmethod
178
+ def build(
179
+ cls: type[_T],
180
+ *,
181
+ response: Response,
182
+ data: object,
183
+ ) -> _T: ...
184
+
185
+
186
+ Headers = Mapping[str, Union[str, Omit]]
187
+
188
+
189
+ class HeadersLikeProtocol(Protocol):
190
+ def get(self, __key: str) -> str | None: ...
191
+
192
+
193
+ HeadersLike = Union[Headers, HeadersLikeProtocol]
194
+
195
+ ResponseT = TypeVar(
196
+ "ResponseT",
197
+ bound=Union[
198
+ object,
199
+ str,
200
+ None,
201
+ "BaseModel",
202
+ List[Any],
203
+ Dict[str, Any],
204
+ Response,
205
+ ModelBuilderProtocol,
206
+ "APIResponse[Any]",
207
+ "AsyncAPIResponse[Any]",
208
+ ],
209
+ )
210
+
211
+ StrBytesIntFloat = Union[str, bytes, int, float]
212
+
213
+ # Note: copied from Pydantic
214
+ # https://github.com/pydantic/pydantic/blob/6f31f8f68ef011f84357330186f603ff295312fd/pydantic/main.py#L79
215
+ IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union["IncEx", bool]], Mapping[str, Union["IncEx", bool]]]
216
+
217
+ PostParser = Callable[[Any], Any]
218
+
219
+
220
+ @runtime_checkable
221
+ class InheritsGeneric(Protocol):
222
+ """Represents a type that has inherited from `Generic`
223
+
224
+ The `__orig_bases__` property can be used to determine the resolved
225
+ type variable for a given base class.
226
+ """
227
+
228
+ __orig_bases__: tuple[_GenericAlias]
229
+
230
+
231
+ class _GenericAlias(Protocol):
232
+ __origin__: type[object]
233
+
234
+
235
+ class HttpxSendArgs(TypedDict, total=False):
236
+ auth: httpx.Auth
237
+ follow_redirects: bool
238
+
239
+
240
+ _T_co = TypeVar("_T_co", covariant=True)
241
+
242
+
243
+ if TYPE_CHECKING:
244
+ # This works because str.__contains__ does not accept object (either in typeshed or at runtime)
245
+ # https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d068e7679fd7fec9cfab0eff3b/useful_types/__init__.py#L285
246
+ class SequenceNotStr(Protocol[_T_co]):
247
+ @overload
248
+ def __getitem__(self, index: SupportsIndex, /) -> _T_co: ...
249
+ @overload
250
+ def __getitem__(self, index: slice, /) -> Sequence[_T_co]: ...
251
+ def __contains__(self, value: object, /) -> bool: ...
252
+ def __len__(self) -> int: ...
253
+ def __iter__(self) -> Iterator[_T_co]: ...
254
+ def index(self, value: Any, start: int = 0, stop: int = ..., /) -> int: ...
255
+ def count(self, value: Any, /) -> int: ...
256
+ def __reversed__(self) -> Iterator[_T_co]: ...
257
+ else:
258
+ # just point this to a normal `Sequence` at runtime to avoid having to special case
259
+ # deserializing our custom sequence type
260
+ SequenceNotStr = Sequence
@@ -0,0 +1,64 @@
1
+ from ._sync import asyncify as asyncify
2
+ from ._proxy import LazyProxy as LazyProxy
3
+ from ._utils import (
4
+ flatten as flatten,
5
+ is_dict as is_dict,
6
+ is_list as is_list,
7
+ is_given as is_given,
8
+ is_tuple as is_tuple,
9
+ json_safe as json_safe,
10
+ lru_cache as lru_cache,
11
+ is_mapping as is_mapping,
12
+ is_tuple_t as is_tuple_t,
13
+ is_iterable as is_iterable,
14
+ is_sequence as is_sequence,
15
+ coerce_float as coerce_float,
16
+ is_mapping_t as is_mapping_t,
17
+ removeprefix as removeprefix,
18
+ removesuffix as removesuffix,
19
+ extract_files as extract_files,
20
+ is_sequence_t as is_sequence_t,
21
+ required_args as required_args,
22
+ coerce_boolean as coerce_boolean,
23
+ coerce_integer as coerce_integer,
24
+ file_from_path as file_from_path,
25
+ strip_not_given as strip_not_given,
26
+ deepcopy_minimal as deepcopy_minimal,
27
+ get_async_library as get_async_library,
28
+ maybe_coerce_float as maybe_coerce_float,
29
+ get_required_header as get_required_header,
30
+ maybe_coerce_boolean as maybe_coerce_boolean,
31
+ maybe_coerce_integer as maybe_coerce_integer,
32
+ )
33
+ from ._compat import (
34
+ get_args as get_args,
35
+ is_union as is_union,
36
+ get_origin as get_origin,
37
+ is_typeddict as is_typeddict,
38
+ is_literal_type as is_literal_type,
39
+ )
40
+ from ._typing import (
41
+ is_list_type as is_list_type,
42
+ is_union_type as is_union_type,
43
+ extract_type_arg as extract_type_arg,
44
+ is_iterable_type as is_iterable_type,
45
+ is_required_type as is_required_type,
46
+ is_sequence_type as is_sequence_type,
47
+ is_annotated_type as is_annotated_type,
48
+ is_type_alias_type as is_type_alias_type,
49
+ strip_annotated_type as strip_annotated_type,
50
+ extract_type_var_from_base as extract_type_var_from_base,
51
+ )
52
+ from ._streams import consume_sync_iterator as consume_sync_iterator, consume_async_iterator as consume_async_iterator
53
+ from ._transform import (
54
+ PropertyInfo as PropertyInfo,
55
+ transform as transform,
56
+ async_transform as async_transform,
57
+ maybe_transform as maybe_transform,
58
+ async_maybe_transform as async_maybe_transform,
59
+ )
60
+ from ._reflection import (
61
+ function_has_argument as function_has_argument,
62
+ assert_signatures_in_sync as assert_signatures_in_sync,
63
+ )
64
+ from ._datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import typing_extensions
5
+ from typing import Any, Type, Union, Literal, Optional
6
+ from datetime import date, datetime
7
+ from typing_extensions import get_args as _get_args, get_origin as _get_origin
8
+
9
+ from .._types import StrBytesIntFloat
10
+ from ._datetime_parse import parse_date as _parse_date, parse_datetime as _parse_datetime
11
+
12
+ _LITERAL_TYPES = {Literal, typing_extensions.Literal}
13
+
14
+
15
+ def get_args(tp: type[Any]) -> tuple[Any, ...]:
16
+ return _get_args(tp)
17
+
18
+
19
+ def get_origin(tp: type[Any]) -> type[Any] | None:
20
+ return _get_origin(tp)
21
+
22
+
23
+ def is_union(tp: Optional[Type[Any]]) -> bool:
24
+ if sys.version_info < (3, 10):
25
+ return tp is Union # type: ignore[comparison-overlap]
26
+ else:
27
+ import types
28
+
29
+ return tp is Union or tp is types.UnionType
30
+
31
+
32
+ def is_typeddict(tp: Type[Any]) -> bool:
33
+ return typing_extensions.is_typeddict(tp)
34
+
35
+
36
+ def is_literal_type(tp: Type[Any]) -> bool:
37
+ return get_origin(tp) in _LITERAL_TYPES
38
+
39
+
40
+ def parse_date(value: Union[date, StrBytesIntFloat]) -> date:
41
+ return _parse_date(value)
42
+
43
+
44
+ def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime:
45
+ return _parse_datetime(value)
@@ -0,0 +1,136 @@
1
+ """
2
+ This file contains code from https://github.com/pydantic/pydantic/blob/main/pydantic/v1/datetime_parse.py
3
+ without the Pydantic v1 specific errors.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from typing import Dict, Union, Optional
10
+ from datetime import date, datetime, timezone, timedelta
11
+
12
+ from .._types import StrBytesIntFloat
13
+
14
+ date_expr = r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
15
+ time_expr = (
16
+ r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
17
+ r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?"
18
+ r"(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
19
+ )
20
+
21
+ date_re = re.compile(f"{date_expr}$")
22
+ datetime_re = re.compile(f"{date_expr}[T ]{time_expr}")
23
+
24
+
25
+ EPOCH = datetime(1970, 1, 1)
26
+ # if greater than this, the number is in ms, if less than or equal it's in seconds
27
+ # (in seconds this is 11th October 2603, in ms it's 20th August 1970)
28
+ MS_WATERSHED = int(2e10)
29
+ # slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9
30
+ MAX_NUMBER = int(3e20)
31
+
32
+
33
+ def _get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[None, int, float]:
34
+ if isinstance(value, (int, float)):
35
+ return value
36
+ try:
37
+ return float(value)
38
+ except ValueError:
39
+ return None
40
+ except TypeError:
41
+ raise TypeError(f"invalid type; expected {native_expected_type}, string, bytes, int or float") from None
42
+
43
+
44
+ def _from_unix_seconds(seconds: Union[int, float]) -> datetime:
45
+ if seconds > MAX_NUMBER:
46
+ return datetime.max
47
+ elif seconds < -MAX_NUMBER:
48
+ return datetime.min
49
+
50
+ while abs(seconds) > MS_WATERSHED:
51
+ seconds /= 1000
52
+ dt = EPOCH + timedelta(seconds=seconds)
53
+ return dt.replace(tzinfo=timezone.utc)
54
+
55
+
56
+ def _parse_timezone(value: Optional[str]) -> Union[None, int, timezone]:
57
+ if value == "Z":
58
+ return timezone.utc
59
+ elif value is not None:
60
+ offset_mins = int(value[-2:]) if len(value) > 3 else 0
61
+ offset = 60 * int(value[1:3]) + offset_mins
62
+ if value[0] == "-":
63
+ offset = -offset
64
+ return timezone(timedelta(minutes=offset))
65
+ else:
66
+ return None
67
+
68
+
69
+ def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime:
70
+ """
71
+ Parse a datetime/int/float/string and return a datetime.datetime.
72
+
73
+ This function supports time zone offsets. When the input contains one,
74
+ the output uses a timezone with a fixed offset from UTC.
75
+
76
+ Raise ValueError if the input is well formatted but not a valid datetime.
77
+ Raise ValueError if the input isn't well formatted.
78
+ """
79
+ if isinstance(value, datetime):
80
+ return value
81
+
82
+ number = _get_numeric(value, "datetime")
83
+ if number is not None:
84
+ return _from_unix_seconds(number)
85
+
86
+ if isinstance(value, bytes):
87
+ value = value.decode()
88
+
89
+ assert not isinstance(value, (float, int))
90
+
91
+ match = datetime_re.match(value)
92
+ if match is None:
93
+ raise ValueError("invalid datetime format")
94
+
95
+ kw = match.groupdict()
96
+ if kw["microsecond"]:
97
+ kw["microsecond"] = kw["microsecond"].ljust(6, "0")
98
+
99
+ tzinfo = _parse_timezone(kw.pop("tzinfo"))
100
+ kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None}
101
+ kw_["tzinfo"] = tzinfo
102
+
103
+ return datetime(**kw_) # type: ignore
104
+
105
+
106
+ def parse_date(value: Union[date, StrBytesIntFloat]) -> date:
107
+ """
108
+ Parse a date/int/float/string and return a datetime.date.
109
+
110
+ Raise ValueError if the input is well formatted but not a valid date.
111
+ Raise ValueError if the input isn't well formatted.
112
+ """
113
+ if isinstance(value, date):
114
+ if isinstance(value, datetime):
115
+ return value.date()
116
+ else:
117
+ return value
118
+
119
+ number = _get_numeric(value, "date")
120
+ if number is not None:
121
+ return _from_unix_seconds(number).date()
122
+
123
+ if isinstance(value, bytes):
124
+ value = value.decode()
125
+
126
+ assert not isinstance(value, (float, int))
127
+ match = date_re.match(value)
128
+ if match is None:
129
+ raise ValueError("invalid date format")
130
+
131
+ kw = {k: int(v) for k, v in match.groupdict().items()}
132
+
133
+ try:
134
+ return date(**kw)
135
+ except ValueError:
136
+ raise ValueError("invalid date format") from None
@@ -0,0 +1,25 @@
1
+ import os
2
+ import logging
3
+
4
+ logger: logging.Logger = logging.getLogger("runloop_api_client")
5
+ httpx_logger: logging.Logger = logging.getLogger("httpx")
6
+
7
+
8
+ def _basic_config() -> None:
9
+ # e.g. [2023-10-05 14:12:26 - runloop_api_client._base_client:818 - DEBUG] HTTP Request: POST http://127.0.0.1:4010/foo/bar "200 OK"
10
+ logging.basicConfig(
11
+ format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s",
12
+ datefmt="%Y-%m-%d %H:%M:%S",
13
+ )
14
+
15
+
16
+ def setup_logging() -> None:
17
+ env = os.environ.get("RUNLOOP_LOG")
18
+ if env == "debug":
19
+ _basic_config()
20
+ logger.setLevel(logging.DEBUG)
21
+ httpx_logger.setLevel(logging.DEBUG)
22
+ elif env == "info":
23
+ _basic_config()
24
+ logger.setLevel(logging.INFO)
25
+ httpx_logger.setLevel(logging.INFO)
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Generic, TypeVar, Iterable, cast
5
+ from typing_extensions import override
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ class LazyProxy(Generic[T], ABC):
11
+ """Implements data methods to pretend that an instance is another instance.
12
+
13
+ This includes forwarding attribute access and other methods.
14
+ """
15
+
16
+ # Note: we have to special case proxies that themselves return proxies
17
+ # to support using a proxy as a catch-all for any random access, e.g. `proxy.foo.bar.baz`
18
+
19
+ def __getattr__(self, attr: str) -> object:
20
+ proxied = self.__get_proxied__()
21
+ if isinstance(proxied, LazyProxy):
22
+ return proxied # pyright: ignore
23
+ return getattr(proxied, attr)
24
+
25
+ @override
26
+ def __repr__(self) -> str:
27
+ proxied = self.__get_proxied__()
28
+ if isinstance(proxied, LazyProxy):
29
+ return proxied.__class__.__name__
30
+ return repr(self.__get_proxied__())
31
+
32
+ @override
33
+ def __str__(self) -> str:
34
+ proxied = self.__get_proxied__()
35
+ if isinstance(proxied, LazyProxy):
36
+ return proxied.__class__.__name__
37
+ return str(proxied)
38
+
39
+ @override
40
+ def __dir__(self) -> Iterable[str]:
41
+ proxied = self.__get_proxied__()
42
+ if isinstance(proxied, LazyProxy):
43
+ return []
44
+ return proxied.__dir__()
45
+
46
+ @property # type: ignore
47
+ @override
48
+ def __class__(self) -> type: # pyright: ignore
49
+ try:
50
+ proxied = self.__get_proxied__()
51
+ except Exception:
52
+ return type(self)
53
+ if issubclass(type(proxied), LazyProxy):
54
+ return type(proxied)
55
+ return proxied.__class__
56
+
57
+ def __get_proxied__(self) -> T:
58
+ return self.__load__()
59
+
60
+ def __as_proxied__(self) -> T:
61
+ """Helper method that returns the current proxy, typed as the loaded object"""
62
+ return cast(T, self)
63
+
64
+ @abstractmethod
65
+ def __load__(self) -> T: ...
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from typing import Any, Callable
5
+
6
+
7
+ def function_has_argument(func: Callable[..., Any], arg_name: str) -> bool:
8
+ """Returns whether or not the given function has a specific parameter"""
9
+ sig = inspect.signature(func)
10
+ return arg_name in sig.parameters
11
+
12
+
13
+ def assert_signatures_in_sync(
14
+ source_func: Callable[..., Any],
15
+ check_func: Callable[..., Any],
16
+ *,
17
+ exclude_params: set[str] = set(),
18
+ ) -> None:
19
+ """Ensure that the signature of the second function matches the first."""
20
+
21
+ check_sig = inspect.signature(check_func)
22
+ source_sig = inspect.signature(source_func)
23
+
24
+ errors: list[str] = []
25
+
26
+ for name, source_param in source_sig.parameters.items():
27
+ if name in exclude_params:
28
+ continue
29
+
30
+ custom_param = check_sig.parameters.get(name)
31
+ if not custom_param:
32
+ errors.append(f"the `{name}` param is missing")
33
+ continue
34
+
35
+ if custom_param.annotation != source_param.annotation:
36
+ errors.append(
37
+ f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(custom_param.annotation)}"
38
+ )
39
+ continue
40
+
41
+ if errors:
42
+ raise AssertionError(f"{len(errors)} errors encountered when comparing signatures:\n\n" + "\n\n".join(errors))
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+ from typing_extensions import override
5
+
6
+ from ._proxy import LazyProxy
7
+
8
+
9
+ class ResourcesProxy(LazyProxy[Any]):
10
+ """A proxy for the `runloop_api_client.resources` module.
11
+
12
+ This is used so that we can lazily import `runloop_api_client.resources` only when
13
+ needed *and* so that users can just import `runloop_api_client` and reference `runloop_api_client.resources`
14
+ """
15
+
16
+ @override
17
+ def __load__(self) -> Any:
18
+ import importlib
19
+
20
+ mod = importlib.import_module("runloop_api_client.resources")
21
+ return mod
22
+
23
+
24
+ resources = ResourcesProxy().__as_proxied__()
@@ -0,0 +1,12 @@
1
+ from typing import Any
2
+ from typing_extensions import Iterator, AsyncIterator
3
+
4
+
5
+ def consume_sync_iterator(iterator: Iterator[Any]) -> None:
6
+ for _ in iterator:
7
+ ...
8
+
9
+
10
+ async def consume_async_iterator(iterator: AsyncIterator[Any]) -> None:
11
+ async for _ in iterator:
12
+ ...