together 1.5.34__py3-none-any.whl → 2.0.0a6__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 (208) hide show
  1. together/__init__.py +101 -114
  2. together/_base_client.py +1995 -0
  3. together/_client.py +1033 -0
  4. together/_compat.py +219 -0
  5. together/_constants.py +14 -0
  6. together/_exceptions.py +108 -0
  7. together/_files.py +123 -0
  8. together/_models.py +857 -0
  9. together/_qs.py +150 -0
  10. together/_resource.py +43 -0
  11. together/_response.py +830 -0
  12. together/_streaming.py +370 -0
  13. together/_types.py +260 -0
  14. together/_utils/__init__.py +64 -0
  15. together/_utils/_compat.py +45 -0
  16. together/_utils/_datetime_parse.py +136 -0
  17. together/_utils/_logs.py +25 -0
  18. together/_utils/_proxy.py +65 -0
  19. together/_utils/_reflection.py +42 -0
  20. together/_utils/_resources_proxy.py +24 -0
  21. together/_utils/_streams.py +12 -0
  22. together/_utils/_sync.py +58 -0
  23. together/_utils/_transform.py +457 -0
  24. together/_utils/_typing.py +156 -0
  25. together/_utils/_utils.py +421 -0
  26. together/_version.py +4 -0
  27. together/lib/.keep +4 -0
  28. together/lib/__init__.py +23 -0
  29. together/{cli → lib/cli}/api/endpoints.py +65 -81
  30. together/{cli/api/evaluation.py → lib/cli/api/evals.py} +152 -43
  31. together/{cli → lib/cli}/api/files.py +20 -17
  32. together/{cli/api/finetune.py → lib/cli/api/fine_tuning.py} +116 -172
  33. together/{cli → lib/cli}/api/models.py +34 -27
  34. together/lib/cli/api/utils.py +50 -0
  35. together/{cli → lib/cli}/cli.py +16 -26
  36. together/{constants.py → lib/constants.py} +11 -24
  37. together/lib/resources/__init__.py +11 -0
  38. together/lib/resources/files.py +999 -0
  39. together/lib/resources/fine_tuning.py +280 -0
  40. together/lib/resources/models.py +35 -0
  41. together/lib/types/__init__.py +13 -0
  42. together/lib/types/error.py +9 -0
  43. together/lib/types/fine_tuning.py +397 -0
  44. together/{utils → lib/utils}/__init__.py +6 -14
  45. together/{utils → lib/utils}/_log.py +11 -16
  46. together/{utils → lib/utils}/files.py +90 -288
  47. together/lib/utils/serializer.py +10 -0
  48. together/{utils → lib/utils}/tools.py +19 -55
  49. together/resources/__init__.py +225 -39
  50. together/resources/audio/__init__.py +72 -48
  51. together/resources/audio/audio.py +198 -0
  52. together/resources/audio/speech.py +574 -128
  53. together/resources/audio/transcriptions.py +247 -261
  54. together/resources/audio/translations.py +221 -241
  55. together/resources/audio/voices.py +111 -41
  56. together/resources/batches.py +417 -0
  57. together/resources/chat/__init__.py +30 -21
  58. together/resources/chat/chat.py +102 -0
  59. together/resources/chat/completions.py +1063 -263
  60. together/resources/code_interpreter/__init__.py +33 -0
  61. together/resources/code_interpreter/code_interpreter.py +258 -0
  62. together/resources/code_interpreter/sessions.py +135 -0
  63. together/resources/completions.py +884 -225
  64. together/resources/embeddings.py +172 -68
  65. together/resources/endpoints.py +589 -477
  66. together/resources/evals.py +452 -0
  67. together/resources/files.py +397 -129
  68. together/resources/fine_tuning.py +1033 -0
  69. together/resources/hardware.py +181 -0
  70. together/resources/images.py +258 -104
  71. together/resources/jobs.py +214 -0
  72. together/resources/models.py +223 -193
  73. together/resources/rerank.py +190 -92
  74. together/resources/videos.py +286 -214
  75. together/types/__init__.py +66 -167
  76. together/types/audio/__init__.py +10 -0
  77. together/types/audio/speech_create_params.py +75 -0
  78. together/types/audio/transcription_create_params.py +54 -0
  79. together/types/audio/transcription_create_response.py +111 -0
  80. together/types/audio/translation_create_params.py +40 -0
  81. together/types/audio/translation_create_response.py +70 -0
  82. together/types/audio/voice_list_response.py +23 -0
  83. together/types/audio_speech_stream_chunk.py +16 -0
  84. together/types/autoscaling.py +13 -0
  85. together/types/autoscaling_param.py +15 -0
  86. together/types/batch_create_params.py +24 -0
  87. together/types/batch_create_response.py +14 -0
  88. together/types/batch_job.py +45 -0
  89. together/types/batch_list_response.py +10 -0
  90. together/types/chat/__init__.py +18 -0
  91. together/types/chat/chat_completion.py +60 -0
  92. together/types/chat/chat_completion_chunk.py +61 -0
  93. together/types/chat/chat_completion_structured_message_image_url_param.py +18 -0
  94. together/types/chat/chat_completion_structured_message_text_param.py +13 -0
  95. together/types/chat/chat_completion_structured_message_video_url_param.py +18 -0
  96. together/types/chat/chat_completion_usage.py +13 -0
  97. together/types/chat/chat_completion_warning.py +9 -0
  98. together/types/chat/completion_create_params.py +329 -0
  99. together/types/code_interpreter/__init__.py +5 -0
  100. together/types/code_interpreter/session_list_response.py +31 -0
  101. together/types/code_interpreter_execute_params.py +45 -0
  102. together/types/completion.py +42 -0
  103. together/types/completion_chunk.py +66 -0
  104. together/types/completion_create_params.py +138 -0
  105. together/types/dedicated_endpoint.py +44 -0
  106. together/types/embedding.py +24 -0
  107. together/types/embedding_create_params.py +31 -0
  108. together/types/endpoint_create_params.py +43 -0
  109. together/types/endpoint_list_avzones_response.py +11 -0
  110. together/types/endpoint_list_params.py +18 -0
  111. together/types/endpoint_list_response.py +41 -0
  112. together/types/endpoint_update_params.py +27 -0
  113. together/types/eval_create_params.py +263 -0
  114. together/types/eval_create_response.py +16 -0
  115. together/types/eval_list_params.py +21 -0
  116. together/types/eval_list_response.py +10 -0
  117. together/types/eval_status_response.py +100 -0
  118. together/types/evaluation_job.py +139 -0
  119. together/types/execute_response.py +108 -0
  120. together/types/file_delete_response.py +13 -0
  121. together/types/file_list.py +12 -0
  122. together/types/file_purpose.py +9 -0
  123. together/types/file_response.py +31 -0
  124. together/types/file_type.py +7 -0
  125. together/types/fine_tuning_cancel_response.py +194 -0
  126. together/types/fine_tuning_content_params.py +24 -0
  127. together/types/fine_tuning_delete_params.py +11 -0
  128. together/types/fine_tuning_delete_response.py +12 -0
  129. together/types/fine_tuning_list_checkpoints_response.py +21 -0
  130. together/types/fine_tuning_list_events_response.py +12 -0
  131. together/types/fine_tuning_list_response.py +199 -0
  132. together/types/finetune_event.py +41 -0
  133. together/types/finetune_event_type.py +33 -0
  134. together/types/finetune_response.py +177 -0
  135. together/types/hardware_list_params.py +16 -0
  136. together/types/hardware_list_response.py +58 -0
  137. together/types/image_data_b64.py +15 -0
  138. together/types/image_data_url.py +15 -0
  139. together/types/image_file.py +23 -0
  140. together/types/image_generate_params.py +85 -0
  141. together/types/job_list_response.py +47 -0
  142. together/types/job_retrieve_response.py +43 -0
  143. together/types/log_probs.py +18 -0
  144. together/types/model_list_response.py +10 -0
  145. together/types/model_object.py +42 -0
  146. together/types/model_upload_params.py +36 -0
  147. together/types/model_upload_response.py +23 -0
  148. together/types/rerank_create_params.py +36 -0
  149. together/types/rerank_create_response.py +36 -0
  150. together/types/tool_choice.py +23 -0
  151. together/types/tool_choice_param.py +23 -0
  152. together/types/tools_param.py +23 -0
  153. together/types/training_method_dpo.py +22 -0
  154. together/types/training_method_sft.py +18 -0
  155. together/types/video_create_params.py +86 -0
  156. together/types/video_create_response.py +10 -0
  157. together/types/video_job.py +57 -0
  158. together-2.0.0a6.dist-info/METADATA +729 -0
  159. together-2.0.0a6.dist-info/RECORD +165 -0
  160. {together-1.5.34.dist-info → together-2.0.0a6.dist-info}/WHEEL +1 -1
  161. together-2.0.0a6.dist-info/entry_points.txt +2 -0
  162. {together-1.5.34.dist-info → together-2.0.0a6.dist-info}/licenses/LICENSE +1 -1
  163. together/abstract/api_requestor.py +0 -770
  164. together/cli/api/chat.py +0 -298
  165. together/cli/api/completions.py +0 -119
  166. together/cli/api/images.py +0 -93
  167. together/cli/api/utils.py +0 -139
  168. together/client.py +0 -186
  169. together/error.py +0 -194
  170. together/filemanager.py +0 -635
  171. together/legacy/__init__.py +0 -0
  172. together/legacy/base.py +0 -27
  173. together/legacy/complete.py +0 -93
  174. together/legacy/embeddings.py +0 -27
  175. together/legacy/files.py +0 -146
  176. together/legacy/finetune.py +0 -177
  177. together/legacy/images.py +0 -27
  178. together/legacy/models.py +0 -44
  179. together/resources/batch.py +0 -165
  180. together/resources/code_interpreter.py +0 -82
  181. together/resources/evaluation.py +0 -808
  182. together/resources/finetune.py +0 -1388
  183. together/together_response.py +0 -50
  184. together/types/abstract.py +0 -26
  185. together/types/audio_speech.py +0 -311
  186. together/types/batch.py +0 -54
  187. together/types/chat_completions.py +0 -210
  188. together/types/code_interpreter.py +0 -57
  189. together/types/common.py +0 -67
  190. together/types/completions.py +0 -107
  191. together/types/embeddings.py +0 -35
  192. together/types/endpoints.py +0 -123
  193. together/types/error.py +0 -16
  194. together/types/evaluation.py +0 -93
  195. together/types/files.py +0 -93
  196. together/types/finetune.py +0 -464
  197. together/types/images.py +0 -42
  198. together/types/models.py +0 -96
  199. together/types/rerank.py +0 -43
  200. together/types/videos.py +0 -69
  201. together/utils/api_helpers.py +0 -124
  202. together/version.py +0 -6
  203. together-1.5.34.dist-info/METADATA +0 -583
  204. together-1.5.34.dist-info/RECORD +0 -77
  205. together-1.5.34.dist-info/entry_points.txt +0 -3
  206. /together/{abstract → lib/cli}/__init__.py +0 -0
  207. /together/{cli → lib/cli/api}/__init__.py +0 -0
  208. /together/{cli/api/__init__.py → py.typed} +0 -0
together/_streaming.py ADDED
@@ -0,0 +1,370 @@
1
+ # Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import inspect
6
+ from types import TracebackType
7
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, AsyncIterator, cast
8
+ from typing_extensions import Self, Protocol, TypeGuard, override, get_origin, runtime_checkable
9
+
10
+ import httpx
11
+
12
+ from ._utils import is_mapping, extract_type_var_from_base
13
+ from ._exceptions import APIError
14
+
15
+ if TYPE_CHECKING:
16
+ from ._client import Together, AsyncTogether
17
+
18
+
19
+ _T = TypeVar("_T")
20
+
21
+
22
+ class Stream(Generic[_T]):
23
+ """Provides the core interface to iterate over a synchronous stream response."""
24
+
25
+ response: httpx.Response
26
+
27
+ _decoder: SSEBytesDecoder
28
+
29
+ def __init__(
30
+ self,
31
+ *,
32
+ cast_to: type[_T],
33
+ response: httpx.Response,
34
+ client: Together,
35
+ ) -> None:
36
+ self.response = response
37
+ self._cast_to = cast_to
38
+ self._client = client
39
+ self._decoder = client._make_sse_decoder()
40
+ self._iterator = self.__stream__()
41
+
42
+ def __next__(self) -> _T:
43
+ return self._iterator.__next__()
44
+
45
+ def __iter__(self) -> Iterator[_T]:
46
+ for item in self._iterator:
47
+ yield item
48
+
49
+ def _iter_events(self) -> Iterator[ServerSentEvent]:
50
+ yield from self._decoder.iter_bytes(self.response.iter_bytes())
51
+
52
+ def __stream__(self) -> Iterator[_T]:
53
+ cast_to = cast(Any, self._cast_to)
54
+ response = self.response
55
+ process_data = self._client._process_response_data
56
+ iterator = self._iter_events()
57
+
58
+ for sse in iterator:
59
+ if sse.data.startswith("[DONE]"):
60
+ break
61
+
62
+ if sse.event is None:
63
+ data = sse.json()
64
+ if is_mapping(data) and data.get("error"):
65
+ message = None
66
+ error = data.get("error")
67
+ if is_mapping(error):
68
+ message = error.get("message")
69
+ if not message or not isinstance(message, str):
70
+ message = "An error occurred during streaming"
71
+
72
+ raise APIError(
73
+ message=message,
74
+ request=self.response.request,
75
+ body=data["error"],
76
+ )
77
+
78
+ yield process_data(data=data, cast_to=cast_to, response=response)
79
+
80
+ # As we might not fully consume the response stream, we need to close it explicitly
81
+ response.close()
82
+
83
+ def __enter__(self) -> Self:
84
+ return self
85
+
86
+ def __exit__(
87
+ self,
88
+ exc_type: type[BaseException] | None,
89
+ exc: BaseException | None,
90
+ exc_tb: TracebackType | None,
91
+ ) -> None:
92
+ self.close()
93
+
94
+ def close(self) -> None:
95
+ """
96
+ Close the response and release the connection.
97
+
98
+ Automatically called if the response body is read to completion.
99
+ """
100
+ self.response.close()
101
+
102
+
103
+ class AsyncStream(Generic[_T]):
104
+ """Provides the core interface to iterate over an asynchronous stream response."""
105
+
106
+ response: httpx.Response
107
+
108
+ _decoder: SSEDecoder | SSEBytesDecoder
109
+
110
+ def __init__(
111
+ self,
112
+ *,
113
+ cast_to: type[_T],
114
+ response: httpx.Response,
115
+ client: AsyncTogether,
116
+ ) -> None:
117
+ self.response = response
118
+ self._cast_to = cast_to
119
+ self._client = client
120
+ self._decoder = client._make_sse_decoder()
121
+ self._iterator = self.__stream__()
122
+
123
+ async def __anext__(self) -> _T:
124
+ return await self._iterator.__anext__()
125
+
126
+ async def __aiter__(self) -> AsyncIterator[_T]:
127
+ async for item in self._iterator:
128
+ yield item
129
+
130
+ async def _iter_events(self) -> AsyncIterator[ServerSentEvent]:
131
+ async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()):
132
+ yield sse
133
+
134
+ async def __stream__(self) -> AsyncIterator[_T]:
135
+ cast_to = cast(Any, self._cast_to)
136
+ response = self.response
137
+ process_data = self._client._process_response_data
138
+ iterator = self._iter_events()
139
+
140
+ async for sse in iterator:
141
+ if sse.data.startswith("[DONE]"):
142
+ break
143
+
144
+ if sse.event is None:
145
+ data = sse.json()
146
+ if is_mapping(data) and data.get("error"):
147
+ message = None
148
+ error = data.get("error")
149
+ if is_mapping(error):
150
+ message = error.get("message")
151
+ if not message or not isinstance(message, str):
152
+ message = "An error occurred during streaming"
153
+
154
+ raise APIError(
155
+ message=message,
156
+ request=self.response.request,
157
+ body=data["error"],
158
+ )
159
+
160
+ yield process_data(data=data, cast_to=cast_to, response=response)
161
+
162
+ # As we might not fully consume the response stream, we need to close it explicitly
163
+ await response.aclose()
164
+
165
+ async def __aenter__(self) -> Self:
166
+ return self
167
+
168
+ async def __aexit__(
169
+ self,
170
+ exc_type: type[BaseException] | None,
171
+ exc: BaseException | None,
172
+ exc_tb: TracebackType | None,
173
+ ) -> None:
174
+ await self.close()
175
+
176
+ async def close(self) -> None:
177
+ """
178
+ Close the response and release the connection.
179
+
180
+ Automatically called if the response body is read to completion.
181
+ """
182
+ await self.response.aclose()
183
+
184
+
185
+ class ServerSentEvent:
186
+ def __init__(
187
+ self,
188
+ *,
189
+ event: str | None = None,
190
+ data: str | None = None,
191
+ id: str | None = None,
192
+ retry: int | None = None,
193
+ ) -> None:
194
+ if data is None:
195
+ data = ""
196
+
197
+ self._id = id
198
+ self._data = data
199
+ self._event = event or None
200
+ self._retry = retry
201
+
202
+ @property
203
+ def event(self) -> str | None:
204
+ return self._event
205
+
206
+ @property
207
+ def id(self) -> str | None:
208
+ return self._id
209
+
210
+ @property
211
+ def retry(self) -> int | None:
212
+ return self._retry
213
+
214
+ @property
215
+ def data(self) -> str:
216
+ return self._data
217
+
218
+ def json(self) -> Any:
219
+ return json.loads(self.data)
220
+
221
+ @override
222
+ def __repr__(self) -> str:
223
+ return f"ServerSentEvent(event={self.event}, data={self.data}, id={self.id}, retry={self.retry})"
224
+
225
+
226
+ class SSEDecoder:
227
+ _data: list[str]
228
+ _event: str | None
229
+ _retry: int | None
230
+ _last_event_id: str | None
231
+
232
+ def __init__(self) -> None:
233
+ self._event = None
234
+ self._data = []
235
+ self._last_event_id = None
236
+ self._retry = None
237
+
238
+ def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
239
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
240
+ for chunk in self._iter_chunks(iterator):
241
+ # Split before decoding so splitlines() only uses \r and \n
242
+ for raw_line in chunk.splitlines():
243
+ line = raw_line.decode("utf-8")
244
+ sse = self.decode(line)
245
+ if sse:
246
+ yield sse
247
+
248
+ def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]:
249
+ """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
250
+ data = b""
251
+ for chunk in iterator:
252
+ for line in chunk.splitlines(keepends=True):
253
+ data += line
254
+ if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
255
+ yield data
256
+ data = b""
257
+ if data:
258
+ yield data
259
+
260
+ async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]:
261
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
262
+ async for chunk in self._aiter_chunks(iterator):
263
+ # Split before decoding so splitlines() only uses \r and \n
264
+ for raw_line in chunk.splitlines():
265
+ line = raw_line.decode("utf-8")
266
+ sse = self.decode(line)
267
+ if sse:
268
+ yield sse
269
+
270
+ async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]:
271
+ """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
272
+ data = b""
273
+ async for chunk in iterator:
274
+ for line in chunk.splitlines(keepends=True):
275
+ data += line
276
+ if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
277
+ yield data
278
+ data = b""
279
+ if data:
280
+ yield data
281
+
282
+ def decode(self, line: str) -> ServerSentEvent | None:
283
+ # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501
284
+
285
+ if not line:
286
+ if not self._event and not self._data and not self._last_event_id and self._retry is None:
287
+ return None
288
+
289
+ sse = ServerSentEvent(
290
+ event=self._event,
291
+ data="\n".join(self._data),
292
+ id=self._last_event_id,
293
+ retry=self._retry,
294
+ )
295
+
296
+ # NOTE: as per the SSE spec, do not reset last_event_id.
297
+ self._event = None
298
+ self._data = []
299
+ self._retry = None
300
+
301
+ return sse
302
+
303
+ if line.startswith(":"):
304
+ return None
305
+
306
+ fieldname, _, value = line.partition(":")
307
+
308
+ if value.startswith(" "):
309
+ value = value[1:]
310
+
311
+ if fieldname == "event":
312
+ self._event = value
313
+ elif fieldname == "data":
314
+ self._data.append(value)
315
+ elif fieldname == "id":
316
+ if "\0" in value:
317
+ pass
318
+ else:
319
+ self._last_event_id = value
320
+ elif fieldname == "retry":
321
+ try:
322
+ self._retry = int(value)
323
+ except (TypeError, ValueError):
324
+ pass
325
+ else:
326
+ pass # Field is ignored.
327
+
328
+ return None
329
+
330
+
331
+ @runtime_checkable
332
+ class SSEBytesDecoder(Protocol):
333
+ def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
334
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
335
+ ...
336
+
337
+ def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]:
338
+ """Given an async iterator that yields raw binary data, iterate over it & yield every event encountered"""
339
+ ...
340
+
341
+
342
+ def is_stream_class_type(typ: type) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]:
343
+ """TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`"""
344
+ origin = get_origin(typ) or typ
345
+ return inspect.isclass(origin) and issubclass(origin, (Stream, AsyncStream))
346
+
347
+
348
+ def extract_stream_chunk_type(
349
+ stream_cls: type,
350
+ *,
351
+ failure_message: str | None = None,
352
+ ) -> type:
353
+ """Given a type like `Stream[T]`, returns the generic type variable `T`.
354
+
355
+ This also handles the case where a concrete subclass is given, e.g.
356
+ ```py
357
+ class MyStream(Stream[bytes]):
358
+ ...
359
+
360
+ extract_stream_chunk_type(MyStream) -> bytes
361
+ ```
362
+ """
363
+ from ._base_client import Stream, AsyncStream
364
+
365
+ return extract_type_var_from_base(
366
+ stream_cls,
367
+ index=0,
368
+ generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)),
369
+ failure_message=failure_message,
370
+ )
together/_types.py ADDED
@@ -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 together 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