ZTWHHH commited on
Commit
ed61e66
·
verified ·
1 Parent(s): cf15a39

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/lstm_mps_backward.h +39 -0
  2. vllm/lib/python3.10/site-packages/openai/_client.py +539 -0
  3. vllm/lib/python3.10/site-packages/openai/_models.py +831 -0
  4. vllm/lib/python3.10/site-packages/openai/_module_client.py +85 -0
  5. vllm/lib/python3.10/site-packages/openai/_resource.py +43 -0
  6. vllm/lib/python3.10/site-packages/openai/_streaming.py +410 -0
  7. vllm/lib/python3.10/site-packages/openai/_types.py +219 -0
  8. vllm/lib/python3.10/site-packages/openai/_utils/__init__.py +58 -0
  9. vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/__init__.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_logs.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_proxy.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_reflection.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_streams.cpython-310.pyc +0 -0
  14. vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_sync.cpython-310.pyc +0 -0
  15. vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_transform.cpython-310.pyc +0 -0
  16. vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_typing.cpython-310.pyc +0 -0
  17. vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_utils.cpython-310.pyc +0 -0
  18. vllm/lib/python3.10/site-packages/openai/_utils/_logs.py +42 -0
  19. vllm/lib/python3.10/site-packages/openai/_utils/_proxy.py +62 -0
  20. vllm/lib/python3.10/site-packages/openai/_utils/_reflection.py +45 -0
  21. vllm/lib/python3.10/site-packages/openai/_utils/_streams.py +12 -0
  22. vllm/lib/python3.10/site-packages/openai/_utils/_sync.py +70 -0
  23. vllm/lib/python3.10/site-packages/openai/_utils/_transform.py +392 -0
  24. vllm/lib/python3.10/site-packages/openai/_utils/_typing.py +149 -0
  25. vllm/lib/python3.10/site-packages/openai/_utils/_utils.py +414 -0
  26. vllm/lib/python3.10/site-packages/openai/_version.py +4 -0
  27. vllm/lib/python3.10/site-packages/openai/resources/__init__.py +173 -0
  28. vllm/lib/python3.10/site-packages/openai/resources/__pycache__/__init__.cpython-310.pyc +0 -0
  29. vllm/lib/python3.10/site-packages/openai/resources/__pycache__/batches.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/openai/resources/__pycache__/completions.cpython-310.pyc +0 -0
  31. vllm/lib/python3.10/site-packages/openai/resources/__pycache__/embeddings.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/openai/resources/__pycache__/files.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/openai/resources/__pycache__/images.cpython-310.pyc +0 -0
  34. vllm/lib/python3.10/site-packages/openai/resources/__pycache__/models.cpython-310.pyc +0 -0
  35. vllm/lib/python3.10/site-packages/openai/resources/__pycache__/moderations.cpython-310.pyc +0 -0
  36. vllm/lib/python3.10/site-packages/openai/resources/batches.py +509 -0
  37. vllm/lib/python3.10/site-packages/openai/resources/beta/__init__.py +61 -0
  38. vllm/lib/python3.10/site-packages/openai/resources/beta/assistants.py +888 -0
  39. vllm/lib/python3.10/site-packages/openai/resources/beta/beta.py +175 -0
  40. vllm/lib/python3.10/site-packages/openai/resources/beta/chat/__init__.py +11 -0
  41. vllm/lib/python3.10/site-packages/openai/resources/beta/chat/__pycache__/__init__.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/openai/resources/beta/chat/__pycache__/chat.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/openai/resources/beta/chat/__pycache__/completions.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/openai/resources/beta/chat/chat.py +21 -0
  45. vllm/lib/python3.10/site-packages/openai/resources/beta/chat/completions.py +618 -0
  46. vllm/lib/python3.10/site-packages/openai/resources/beta/threads/runs/__init__.py +33 -0
  47. vllm/lib/python3.10/site-packages/openai/resources/beta/threads/runs/__pycache__/runs.cpython-310.pyc +0 -0
  48. vllm/lib/python3.10/site-packages/openai/resources/beta/threads/runs/runs.py +0 -0
  49. vllm/lib/python3.10/site-packages/openai/resources/beta/threads/runs/steps.py +381 -0
  50. vllm/lib/python3.10/site-packages/openai/resources/beta/vector_stores/__init__.py +47 -0
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/lstm_mps_backward.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/lstm_mps_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::lstm_mps_backward(Tensor? grad_y, Tensor? grad_hy, Tensor? grad_cy, Tensor z_state, Tensor cell_state_fwd, Tensor input, Tensor layersOutputs, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor[], Tensor[])
26
+ inline ::std::tuple<at::Tensor,::std::vector<at::Tensor>,::std::vector<at::Tensor>> lstm_mps_backward(const c10::optional<at::Tensor> & grad_y, const c10::optional<at::Tensor> & grad_hy, const c10::optional<at::Tensor> & grad_cy, const at::Tensor & z_state, const at::Tensor & cell_state_fwd, const at::Tensor & input, const at::Tensor & layersOutputs, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first) {
27
+ return at::_ops::lstm_mps_backward::call(grad_y, grad_hy, grad_cy, z_state, cell_state_fwd, input, layersOutputs, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first);
28
+ }
29
+
30
+ // aten::lstm_mps_backward.out(Tensor? grad_y, Tensor? grad_hy, Tensor? grad_cy, Tensor z_state, Tensor cell_state_fwd, Tensor input, Tensor layersOutputs, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, *, Tensor(a!) out0, Tensor(b!)[] out1, Tensor(c!)[] out2) -> ()
31
+ inline void lstm_mps_backward_out(at::Tensor & out0, at::TensorList out1, at::TensorList out2, const c10::optional<at::Tensor> & grad_y, const c10::optional<at::Tensor> & grad_hy, const c10::optional<at::Tensor> & grad_cy, const at::Tensor & z_state, const at::Tensor & cell_state_fwd, const at::Tensor & input, const at::Tensor & layersOutputs, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first) {
32
+ return at::_ops::lstm_mps_backward_out::call(grad_y, grad_hy, grad_cy, z_state, cell_state_fwd, input, layersOutputs, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first, out0, out1, out2);
33
+ }
34
+ // aten::lstm_mps_backward.out(Tensor? grad_y, Tensor? grad_hy, Tensor? grad_cy, Tensor z_state, Tensor cell_state_fwd, Tensor input, Tensor layersOutputs, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, *, Tensor(a!) out0, Tensor(b!)[] out1, Tensor(c!)[] out2) -> ()
35
+ inline void lstm_mps_backward_outf(const c10::optional<at::Tensor> & grad_y, const c10::optional<at::Tensor> & grad_hy, const c10::optional<at::Tensor> & grad_cy, const at::Tensor & z_state, const at::Tensor & cell_state_fwd, const at::Tensor & input, const at::Tensor & layersOutputs, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first, at::Tensor & out0, at::TensorList out1, at::TensorList out2) {
36
+ return at::_ops::lstm_mps_backward_out::call(grad_y, grad_hy, grad_cy, z_state, cell_state_fwd, input, layersOutputs, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first, out0, out1, out2);
37
+ }
38
+
39
+ }
vllm/lib/python3.10/site-packages/openai/_client.py ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any, Union, Mapping
7
+ from typing_extensions import Self, override
8
+
9
+ import httpx
10
+
11
+ from . import _exceptions
12
+ from ._qs import Querystring
13
+ from ._types import (
14
+ NOT_GIVEN,
15
+ Omit,
16
+ Timeout,
17
+ NotGiven,
18
+ Transport,
19
+ ProxiesTypes,
20
+ RequestOptions,
21
+ )
22
+ from ._utils import (
23
+ is_given,
24
+ is_mapping,
25
+ get_async_library,
26
+ )
27
+ from ._version import __version__
28
+ from .resources import files, images, models, batches, embeddings, completions, moderations
29
+ from ._streaming import Stream as Stream, AsyncStream as AsyncStream
30
+ from ._exceptions import OpenAIError, APIStatusError
31
+ from ._base_client import (
32
+ DEFAULT_MAX_RETRIES,
33
+ SyncAPIClient,
34
+ AsyncAPIClient,
35
+ )
36
+ from .resources.beta import beta
37
+ from .resources.chat import chat
38
+ from .resources.audio import audio
39
+ from .resources.uploads import uploads
40
+ from .resources.fine_tuning import fine_tuning
41
+
42
+ __all__ = ["Timeout", "Transport", "ProxiesTypes", "RequestOptions", "OpenAI", "AsyncOpenAI", "Client", "AsyncClient"]
43
+
44
+
45
+ class OpenAI(SyncAPIClient):
46
+ completions: completions.Completions
47
+ chat: chat.Chat
48
+ embeddings: embeddings.Embeddings
49
+ files: files.Files
50
+ images: images.Images
51
+ audio: audio.Audio
52
+ moderations: moderations.Moderations
53
+ models: models.Models
54
+ fine_tuning: fine_tuning.FineTuning
55
+ beta: beta.Beta
56
+ batches: batches.Batches
57
+ uploads: uploads.Uploads
58
+ with_raw_response: OpenAIWithRawResponse
59
+ with_streaming_response: OpenAIWithStreamedResponse
60
+
61
+ # client options
62
+ api_key: str
63
+ organization: str | None
64
+ project: str | None
65
+
66
+ def __init__(
67
+ self,
68
+ *,
69
+ api_key: str | None = None,
70
+ organization: str | None = None,
71
+ project: str | None = None,
72
+ base_url: str | httpx.URL | None = None,
73
+ timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
74
+ max_retries: int = DEFAULT_MAX_RETRIES,
75
+ default_headers: Mapping[str, str] | None = None,
76
+ default_query: Mapping[str, object] | None = None,
77
+ # Configure a custom httpx client.
78
+ # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
79
+ # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details.
80
+ http_client: httpx.Client | None = None,
81
+ # Enable or disable schema validation for data returned by the API.
82
+ # When enabled an error APIResponseValidationError is raised
83
+ # if the API responds with invalid data for the expected schema.
84
+ #
85
+ # This parameter may be removed or changed in the future.
86
+ # If you rely on this feature, please open a GitHub issue
87
+ # outlining your use-case to help us decide if it should be
88
+ # part of our public interface in the future.
89
+ _strict_response_validation: bool = False,
90
+ ) -> None:
91
+ """Construct a new synchronous openai client instance.
92
+
93
+ This automatically infers the following arguments from their corresponding environment variables if they are not provided:
94
+ - `api_key` from `OPENAI_API_KEY`
95
+ - `organization` from `OPENAI_ORG_ID`
96
+ - `project` from `OPENAI_PROJECT_ID`
97
+ """
98
+ if api_key is None:
99
+ api_key = os.environ.get("OPENAI_API_KEY")
100
+ if api_key is None:
101
+ raise OpenAIError(
102
+ "The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable"
103
+ )
104
+ self.api_key = api_key
105
+
106
+ if organization is None:
107
+ organization = os.environ.get("OPENAI_ORG_ID")
108
+ self.organization = organization
109
+
110
+ if project is None:
111
+ project = os.environ.get("OPENAI_PROJECT_ID")
112
+ self.project = project
113
+
114
+ if base_url is None:
115
+ base_url = os.environ.get("OPENAI_BASE_URL")
116
+ if base_url is None:
117
+ base_url = f"https://api.openai.com/v1"
118
+
119
+ super().__init__(
120
+ version=__version__,
121
+ base_url=base_url,
122
+ max_retries=max_retries,
123
+ timeout=timeout,
124
+ http_client=http_client,
125
+ custom_headers=default_headers,
126
+ custom_query=default_query,
127
+ _strict_response_validation=_strict_response_validation,
128
+ )
129
+
130
+ self._default_stream_cls = Stream
131
+
132
+ self.completions = completions.Completions(self)
133
+ self.chat = chat.Chat(self)
134
+ self.embeddings = embeddings.Embeddings(self)
135
+ self.files = files.Files(self)
136
+ self.images = images.Images(self)
137
+ self.audio = audio.Audio(self)
138
+ self.moderations = moderations.Moderations(self)
139
+ self.models = models.Models(self)
140
+ self.fine_tuning = fine_tuning.FineTuning(self)
141
+ self.beta = beta.Beta(self)
142
+ self.batches = batches.Batches(self)
143
+ self.uploads = uploads.Uploads(self)
144
+ self.with_raw_response = OpenAIWithRawResponse(self)
145
+ self.with_streaming_response = OpenAIWithStreamedResponse(self)
146
+
147
+ @property
148
+ @override
149
+ def qs(self) -> Querystring:
150
+ return Querystring(array_format="brackets")
151
+
152
+ @property
153
+ @override
154
+ def auth_headers(self) -> dict[str, str]:
155
+ api_key = self.api_key
156
+ return {"Authorization": f"Bearer {api_key}"}
157
+
158
+ @property
159
+ @override
160
+ def default_headers(self) -> dict[str, str | Omit]:
161
+ return {
162
+ **super().default_headers,
163
+ "X-Stainless-Async": "false",
164
+ "OpenAI-Organization": self.organization if self.organization is not None else Omit(),
165
+ "OpenAI-Project": self.project if self.project is not None else Omit(),
166
+ **self._custom_headers,
167
+ }
168
+
169
+ def copy(
170
+ self,
171
+ *,
172
+ api_key: str | None = None,
173
+ organization: str | None = None,
174
+ project: str | None = None,
175
+ base_url: str | httpx.URL | None = None,
176
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
177
+ http_client: httpx.Client | None = None,
178
+ max_retries: int | NotGiven = NOT_GIVEN,
179
+ default_headers: Mapping[str, str] | None = None,
180
+ set_default_headers: Mapping[str, str] | None = None,
181
+ default_query: Mapping[str, object] | None = None,
182
+ set_default_query: Mapping[str, object] | None = None,
183
+ _extra_kwargs: Mapping[str, Any] = {},
184
+ ) -> Self:
185
+ """
186
+ Create a new client instance re-using the same options given to the current client with optional overriding.
187
+ """
188
+ if default_headers is not None and set_default_headers is not None:
189
+ raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
190
+
191
+ if default_query is not None and set_default_query is not None:
192
+ raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
193
+
194
+ headers = self._custom_headers
195
+ if default_headers is not None:
196
+ headers = {**headers, **default_headers}
197
+ elif set_default_headers is not None:
198
+ headers = set_default_headers
199
+
200
+ params = self._custom_query
201
+ if default_query is not None:
202
+ params = {**params, **default_query}
203
+ elif set_default_query is not None:
204
+ params = set_default_query
205
+
206
+ http_client = http_client or self._client
207
+ return self.__class__(
208
+ api_key=api_key or self.api_key,
209
+ organization=organization or self.organization,
210
+ project=project or self.project,
211
+ base_url=base_url or self.base_url,
212
+ timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
213
+ http_client=http_client,
214
+ max_retries=max_retries if is_given(max_retries) else self.max_retries,
215
+ default_headers=headers,
216
+ default_query=params,
217
+ **_extra_kwargs,
218
+ )
219
+
220
+ # Alias for `copy` for nicer inline usage, e.g.
221
+ # client.with_options(timeout=10).foo.create(...)
222
+ with_options = copy
223
+
224
+ @override
225
+ def _make_status_error(
226
+ self,
227
+ err_msg: str,
228
+ *,
229
+ body: object,
230
+ response: httpx.Response,
231
+ ) -> APIStatusError:
232
+ data = body.get("error", body) if is_mapping(body) else body
233
+ if response.status_code == 400:
234
+ return _exceptions.BadRequestError(err_msg, response=response, body=data)
235
+
236
+ if response.status_code == 401:
237
+ return _exceptions.AuthenticationError(err_msg, response=response, body=data)
238
+
239
+ if response.status_code == 403:
240
+ return _exceptions.PermissionDeniedError(err_msg, response=response, body=data)
241
+
242
+ if response.status_code == 404:
243
+ return _exceptions.NotFoundError(err_msg, response=response, body=data)
244
+
245
+ if response.status_code == 409:
246
+ return _exceptions.ConflictError(err_msg, response=response, body=data)
247
+
248
+ if response.status_code == 422:
249
+ return _exceptions.UnprocessableEntityError(err_msg, response=response, body=data)
250
+
251
+ if response.status_code == 429:
252
+ return _exceptions.RateLimitError(err_msg, response=response, body=data)
253
+
254
+ if response.status_code >= 500:
255
+ return _exceptions.InternalServerError(err_msg, response=response, body=data)
256
+ return APIStatusError(err_msg, response=response, body=data)
257
+
258
+
259
+ class AsyncOpenAI(AsyncAPIClient):
260
+ completions: completions.AsyncCompletions
261
+ chat: chat.AsyncChat
262
+ embeddings: embeddings.AsyncEmbeddings
263
+ files: files.AsyncFiles
264
+ images: images.AsyncImages
265
+ audio: audio.AsyncAudio
266
+ moderations: moderations.AsyncModerations
267
+ models: models.AsyncModels
268
+ fine_tuning: fine_tuning.AsyncFineTuning
269
+ beta: beta.AsyncBeta
270
+ batches: batches.AsyncBatches
271
+ uploads: uploads.AsyncUploads
272
+ with_raw_response: AsyncOpenAIWithRawResponse
273
+ with_streaming_response: AsyncOpenAIWithStreamedResponse
274
+
275
+ # client options
276
+ api_key: str
277
+ organization: str | None
278
+ project: str | None
279
+
280
+ def __init__(
281
+ self,
282
+ *,
283
+ api_key: str | None = None,
284
+ organization: str | None = None,
285
+ project: str | None = None,
286
+ base_url: str | httpx.URL | None = None,
287
+ timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
288
+ max_retries: int = DEFAULT_MAX_RETRIES,
289
+ default_headers: Mapping[str, str] | None = None,
290
+ default_query: Mapping[str, object] | None = None,
291
+ # Configure a custom httpx client.
292
+ # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
293
+ # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details.
294
+ http_client: httpx.AsyncClient | None = None,
295
+ # Enable or disable schema validation for data returned by the API.
296
+ # When enabled an error APIResponseValidationError is raised
297
+ # if the API responds with invalid data for the expected schema.
298
+ #
299
+ # This parameter may be removed or changed in the future.
300
+ # If you rely on this feature, please open a GitHub issue
301
+ # outlining your use-case to help us decide if it should be
302
+ # part of our public interface in the future.
303
+ _strict_response_validation: bool = False,
304
+ ) -> None:
305
+ """Construct a new async openai client instance.
306
+
307
+ This automatically infers the following arguments from their corresponding environment variables if they are not provided:
308
+ - `api_key` from `OPENAI_API_KEY`
309
+ - `organization` from `OPENAI_ORG_ID`
310
+ - `project` from `OPENAI_PROJECT_ID`
311
+ """
312
+ if api_key is None:
313
+ api_key = os.environ.get("OPENAI_API_KEY")
314
+ if api_key is None:
315
+ raise OpenAIError(
316
+ "The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable"
317
+ )
318
+ self.api_key = api_key
319
+
320
+ if organization is None:
321
+ organization = os.environ.get("OPENAI_ORG_ID")
322
+ self.organization = organization
323
+
324
+ if project is None:
325
+ project = os.environ.get("OPENAI_PROJECT_ID")
326
+ self.project = project
327
+
328
+ if base_url is None:
329
+ base_url = os.environ.get("OPENAI_BASE_URL")
330
+ if base_url is None:
331
+ base_url = f"https://api.openai.com/v1"
332
+
333
+ super().__init__(
334
+ version=__version__,
335
+ base_url=base_url,
336
+ max_retries=max_retries,
337
+ timeout=timeout,
338
+ http_client=http_client,
339
+ custom_headers=default_headers,
340
+ custom_query=default_query,
341
+ _strict_response_validation=_strict_response_validation,
342
+ )
343
+
344
+ self._default_stream_cls = AsyncStream
345
+
346
+ self.completions = completions.AsyncCompletions(self)
347
+ self.chat = chat.AsyncChat(self)
348
+ self.embeddings = embeddings.AsyncEmbeddings(self)
349
+ self.files = files.AsyncFiles(self)
350
+ self.images = images.AsyncImages(self)
351
+ self.audio = audio.AsyncAudio(self)
352
+ self.moderations = moderations.AsyncModerations(self)
353
+ self.models = models.AsyncModels(self)
354
+ self.fine_tuning = fine_tuning.AsyncFineTuning(self)
355
+ self.beta = beta.AsyncBeta(self)
356
+ self.batches = batches.AsyncBatches(self)
357
+ self.uploads = uploads.AsyncUploads(self)
358
+ self.with_raw_response = AsyncOpenAIWithRawResponse(self)
359
+ self.with_streaming_response = AsyncOpenAIWithStreamedResponse(self)
360
+
361
+ @property
362
+ @override
363
+ def qs(self) -> Querystring:
364
+ return Querystring(array_format="brackets")
365
+
366
+ @property
367
+ @override
368
+ def auth_headers(self) -> dict[str, str]:
369
+ api_key = self.api_key
370
+ return {"Authorization": f"Bearer {api_key}"}
371
+
372
+ @property
373
+ @override
374
+ def default_headers(self) -> dict[str, str | Omit]:
375
+ return {
376
+ **super().default_headers,
377
+ "X-Stainless-Async": f"async:{get_async_library()}",
378
+ "OpenAI-Organization": self.organization if self.organization is not None else Omit(),
379
+ "OpenAI-Project": self.project if self.project is not None else Omit(),
380
+ **self._custom_headers,
381
+ }
382
+
383
+ def copy(
384
+ self,
385
+ *,
386
+ api_key: str | None = None,
387
+ organization: str | None = None,
388
+ project: str | None = None,
389
+ base_url: str | httpx.URL | None = None,
390
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
391
+ http_client: httpx.AsyncClient | None = None,
392
+ max_retries: int | NotGiven = NOT_GIVEN,
393
+ default_headers: Mapping[str, str] | None = None,
394
+ set_default_headers: Mapping[str, str] | None = None,
395
+ default_query: Mapping[str, object] | None = None,
396
+ set_default_query: Mapping[str, object] | None = None,
397
+ _extra_kwargs: Mapping[str, Any] = {},
398
+ ) -> Self:
399
+ """
400
+ Create a new client instance re-using the same options given to the current client with optional overriding.
401
+ """
402
+ if default_headers is not None and set_default_headers is not None:
403
+ raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
404
+
405
+ if default_query is not None and set_default_query is not None:
406
+ raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
407
+
408
+ headers = self._custom_headers
409
+ if default_headers is not None:
410
+ headers = {**headers, **default_headers}
411
+ elif set_default_headers is not None:
412
+ headers = set_default_headers
413
+
414
+ params = self._custom_query
415
+ if default_query is not None:
416
+ params = {**params, **default_query}
417
+ elif set_default_query is not None:
418
+ params = set_default_query
419
+
420
+ http_client = http_client or self._client
421
+ return self.__class__(
422
+ api_key=api_key or self.api_key,
423
+ organization=organization or self.organization,
424
+ project=project or self.project,
425
+ base_url=base_url or self.base_url,
426
+ timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
427
+ http_client=http_client,
428
+ max_retries=max_retries if is_given(max_retries) else self.max_retries,
429
+ default_headers=headers,
430
+ default_query=params,
431
+ **_extra_kwargs,
432
+ )
433
+
434
+ # Alias for `copy` for nicer inline usage, e.g.
435
+ # client.with_options(timeout=10).foo.create(...)
436
+ with_options = copy
437
+
438
+ @override
439
+ def _make_status_error(
440
+ self,
441
+ err_msg: str,
442
+ *,
443
+ body: object,
444
+ response: httpx.Response,
445
+ ) -> APIStatusError:
446
+ data = body.get("error", body) if is_mapping(body) else body
447
+ if response.status_code == 400:
448
+ return _exceptions.BadRequestError(err_msg, response=response, body=data)
449
+
450
+ if response.status_code == 401:
451
+ return _exceptions.AuthenticationError(err_msg, response=response, body=data)
452
+
453
+ if response.status_code == 403:
454
+ return _exceptions.PermissionDeniedError(err_msg, response=response, body=data)
455
+
456
+ if response.status_code == 404:
457
+ return _exceptions.NotFoundError(err_msg, response=response, body=data)
458
+
459
+ if response.status_code == 409:
460
+ return _exceptions.ConflictError(err_msg, response=response, body=data)
461
+
462
+ if response.status_code == 422:
463
+ return _exceptions.UnprocessableEntityError(err_msg, response=response, body=data)
464
+
465
+ if response.status_code == 429:
466
+ return _exceptions.RateLimitError(err_msg, response=response, body=data)
467
+
468
+ if response.status_code >= 500:
469
+ return _exceptions.InternalServerError(err_msg, response=response, body=data)
470
+ return APIStatusError(err_msg, response=response, body=data)
471
+
472
+
473
+ class OpenAIWithRawResponse:
474
+ def __init__(self, client: OpenAI) -> None:
475
+ self.completions = completions.CompletionsWithRawResponse(client.completions)
476
+ self.chat = chat.ChatWithRawResponse(client.chat)
477
+ self.embeddings = embeddings.EmbeddingsWithRawResponse(client.embeddings)
478
+ self.files = files.FilesWithRawResponse(client.files)
479
+ self.images = images.ImagesWithRawResponse(client.images)
480
+ self.audio = audio.AudioWithRawResponse(client.audio)
481
+ self.moderations = moderations.ModerationsWithRawResponse(client.moderations)
482
+ self.models = models.ModelsWithRawResponse(client.models)
483
+ self.fine_tuning = fine_tuning.FineTuningWithRawResponse(client.fine_tuning)
484
+ self.beta = beta.BetaWithRawResponse(client.beta)
485
+ self.batches = batches.BatchesWithRawResponse(client.batches)
486
+ self.uploads = uploads.UploadsWithRawResponse(client.uploads)
487
+
488
+
489
+ class AsyncOpenAIWithRawResponse:
490
+ def __init__(self, client: AsyncOpenAI) -> None:
491
+ self.completions = completions.AsyncCompletionsWithRawResponse(client.completions)
492
+ self.chat = chat.AsyncChatWithRawResponse(client.chat)
493
+ self.embeddings = embeddings.AsyncEmbeddingsWithRawResponse(client.embeddings)
494
+ self.files = files.AsyncFilesWithRawResponse(client.files)
495
+ self.images = images.AsyncImagesWithRawResponse(client.images)
496
+ self.audio = audio.AsyncAudioWithRawResponse(client.audio)
497
+ self.moderations = moderations.AsyncModerationsWithRawResponse(client.moderations)
498
+ self.models = models.AsyncModelsWithRawResponse(client.models)
499
+ self.fine_tuning = fine_tuning.AsyncFineTuningWithRawResponse(client.fine_tuning)
500
+ self.beta = beta.AsyncBetaWithRawResponse(client.beta)
501
+ self.batches = batches.AsyncBatchesWithRawResponse(client.batches)
502
+ self.uploads = uploads.AsyncUploadsWithRawResponse(client.uploads)
503
+
504
+
505
+ class OpenAIWithStreamedResponse:
506
+ def __init__(self, client: OpenAI) -> None:
507
+ self.completions = completions.CompletionsWithStreamingResponse(client.completions)
508
+ self.chat = chat.ChatWithStreamingResponse(client.chat)
509
+ self.embeddings = embeddings.EmbeddingsWithStreamingResponse(client.embeddings)
510
+ self.files = files.FilesWithStreamingResponse(client.files)
511
+ self.images = images.ImagesWithStreamingResponse(client.images)
512
+ self.audio = audio.AudioWithStreamingResponse(client.audio)
513
+ self.moderations = moderations.ModerationsWithStreamingResponse(client.moderations)
514
+ self.models = models.ModelsWithStreamingResponse(client.models)
515
+ self.fine_tuning = fine_tuning.FineTuningWithStreamingResponse(client.fine_tuning)
516
+ self.beta = beta.BetaWithStreamingResponse(client.beta)
517
+ self.batches = batches.BatchesWithStreamingResponse(client.batches)
518
+ self.uploads = uploads.UploadsWithStreamingResponse(client.uploads)
519
+
520
+
521
+ class AsyncOpenAIWithStreamedResponse:
522
+ def __init__(self, client: AsyncOpenAI) -> None:
523
+ self.completions = completions.AsyncCompletionsWithStreamingResponse(client.completions)
524
+ self.chat = chat.AsyncChatWithStreamingResponse(client.chat)
525
+ self.embeddings = embeddings.AsyncEmbeddingsWithStreamingResponse(client.embeddings)
526
+ self.files = files.AsyncFilesWithStreamingResponse(client.files)
527
+ self.images = images.AsyncImagesWithStreamingResponse(client.images)
528
+ self.audio = audio.AsyncAudioWithStreamingResponse(client.audio)
529
+ self.moderations = moderations.AsyncModerationsWithStreamingResponse(client.moderations)
530
+ self.models = models.AsyncModelsWithStreamingResponse(client.models)
531
+ self.fine_tuning = fine_tuning.AsyncFineTuningWithStreamingResponse(client.fine_tuning)
532
+ self.beta = beta.AsyncBetaWithStreamingResponse(client.beta)
533
+ self.batches = batches.AsyncBatchesWithStreamingResponse(client.batches)
534
+ self.uploads = uploads.AsyncUploadsWithStreamingResponse(client.uploads)
535
+
536
+
537
+ Client = OpenAI
538
+
539
+ AsyncClient = AsyncOpenAI
vllm/lib/python3.10/site-packages/openai/_models.py ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ from typing import TYPE_CHECKING, Any, Type, Tuple, Union, Generic, TypeVar, Callable, Optional, cast
6
+ from datetime import date, datetime
7
+ from typing_extensions import (
8
+ Unpack,
9
+ Literal,
10
+ ClassVar,
11
+ Protocol,
12
+ Required,
13
+ Sequence,
14
+ ParamSpec,
15
+ TypedDict,
16
+ TypeGuard,
17
+ final,
18
+ override,
19
+ runtime_checkable,
20
+ )
21
+
22
+ import pydantic
23
+ import pydantic.generics
24
+ from pydantic.fields import FieldInfo
25
+
26
+ from ._types import (
27
+ Body,
28
+ IncEx,
29
+ Query,
30
+ ModelT,
31
+ Headers,
32
+ Timeout,
33
+ NotGiven,
34
+ AnyMapping,
35
+ HttpxRequestFiles,
36
+ )
37
+ from ._utils import (
38
+ PropertyInfo,
39
+ is_list,
40
+ is_given,
41
+ json_safe,
42
+ lru_cache,
43
+ is_mapping,
44
+ parse_date,
45
+ coerce_boolean,
46
+ parse_datetime,
47
+ strip_not_given,
48
+ extract_type_arg,
49
+ is_annotated_type,
50
+ is_type_alias_type,
51
+ strip_annotated_type,
52
+ )
53
+ from ._compat import (
54
+ PYDANTIC_V2,
55
+ ConfigDict,
56
+ GenericModel as BaseGenericModel,
57
+ get_args,
58
+ is_union,
59
+ parse_obj,
60
+ get_origin,
61
+ is_literal_type,
62
+ get_model_config,
63
+ get_model_fields,
64
+ field_get_default,
65
+ )
66
+ from ._constants import RAW_RESPONSE_HEADER
67
+
68
+ if TYPE_CHECKING:
69
+ from pydantic_core.core_schema import ModelField, LiteralSchema, ModelFieldsSchema
70
+
71
+ __all__ = ["BaseModel", "GenericModel"]
72
+
73
+ _T = TypeVar("_T")
74
+ _BaseModelT = TypeVar("_BaseModelT", bound="BaseModel")
75
+
76
+ P = ParamSpec("P")
77
+
78
+ ReprArgs = Sequence[Tuple[Optional[str], Any]]
79
+
80
+
81
+ @runtime_checkable
82
+ class _ConfigProtocol(Protocol):
83
+ allow_population_by_field_name: bool
84
+
85
+
86
+ class BaseModel(pydantic.BaseModel):
87
+ if PYDANTIC_V2:
88
+ model_config: ClassVar[ConfigDict] = ConfigDict(
89
+ extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true"))
90
+ )
91
+ else:
92
+
93
+ @property
94
+ @override
95
+ def model_fields_set(self) -> set[str]:
96
+ # a forwards-compat shim for pydantic v2
97
+ return self.__fields_set__ # type: ignore
98
+
99
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
100
+ extra: Any = pydantic.Extra.allow # type: ignore
101
+
102
+ @override
103
+ def __repr_args__(self) -> ReprArgs:
104
+ # we don't want these attributes to be included when something like `rich.print` is used
105
+ return [arg for arg in super().__repr_args__() if arg[0] not in {"_request_id", "__exclude_fields__"}]
106
+
107
+ if TYPE_CHECKING:
108
+ _request_id: Optional[str] = None
109
+ """The ID of the request, returned via the X-Request-ID header. Useful for debugging requests and reporting issues to OpenAI.
110
+
111
+ This will **only** be set for the top-level response object, it will not be defined for nested objects. For example:
112
+
113
+ ```py
114
+ completion = await client.chat.completions.create(...)
115
+ completion._request_id # req_id_xxx
116
+ completion.usage._request_id # raises `AttributeError`
117
+ ```
118
+
119
+ Note: unlike other properties that use an `_` prefix, this property
120
+ *is* public. Unless documented otherwise, all other `_` prefix properties,
121
+ methods and modules are *private*.
122
+ """
123
+
124
+ def to_dict(
125
+ self,
126
+ *,
127
+ mode: Literal["json", "python"] = "python",
128
+ use_api_names: bool = True,
129
+ exclude_unset: bool = True,
130
+ exclude_defaults: bool = False,
131
+ exclude_none: bool = False,
132
+ warnings: bool = True,
133
+ ) -> dict[str, object]:
134
+ """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
135
+
136
+ By default, fields that were not set by the API will not be included,
137
+ and keys will match the API response, *not* the property names from the model.
138
+
139
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
140
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
141
+
142
+ Args:
143
+ mode:
144
+ If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`.
145
+ If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)`
146
+
147
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
148
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
149
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
150
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
151
+ warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2.
152
+ """
153
+ return self.model_dump(
154
+ mode=mode,
155
+ by_alias=use_api_names,
156
+ exclude_unset=exclude_unset,
157
+ exclude_defaults=exclude_defaults,
158
+ exclude_none=exclude_none,
159
+ warnings=warnings,
160
+ )
161
+
162
+ def to_json(
163
+ self,
164
+ *,
165
+ indent: int | None = 2,
166
+ use_api_names: bool = True,
167
+ exclude_unset: bool = True,
168
+ exclude_defaults: bool = False,
169
+ exclude_none: bool = False,
170
+ warnings: bool = True,
171
+ ) -> str:
172
+ """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation).
173
+
174
+ By default, fields that were not set by the API will not be included,
175
+ and keys will match the API response, *not* the property names from the model.
176
+
177
+ For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property,
178
+ the output will use the `"fooBar"` key (unless `use_api_names=False` is passed).
179
+
180
+ Args:
181
+ indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2`
182
+ use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`.
183
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
184
+ exclude_defaults: Whether to exclude fields that have the default value.
185
+ exclude_none: Whether to exclude fields that have a value of `None`.
186
+ warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2.
187
+ """
188
+ return self.model_dump_json(
189
+ indent=indent,
190
+ by_alias=use_api_names,
191
+ exclude_unset=exclude_unset,
192
+ exclude_defaults=exclude_defaults,
193
+ exclude_none=exclude_none,
194
+ warnings=warnings,
195
+ )
196
+
197
+ @override
198
+ def __str__(self) -> str:
199
+ # mypy complains about an invalid self arg
200
+ return f'{self.__repr_name__()}({self.__repr_str__(", ")})' # type: ignore[misc]
201
+
202
+ # Override the 'construct' method in a way that supports recursive parsing without validation.
203
+ # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836.
204
+ @classmethod
205
+ @override
206
+ def construct( # pyright: ignore[reportIncompatibleMethodOverride]
207
+ cls: Type[ModelT],
208
+ _fields_set: set[str] | None = None,
209
+ **values: object,
210
+ ) -> ModelT:
211
+ m = cls.__new__(cls)
212
+ fields_values: dict[str, object] = {}
213
+
214
+ config = get_model_config(cls)
215
+ populate_by_name = (
216
+ config.allow_population_by_field_name
217
+ if isinstance(config, _ConfigProtocol)
218
+ else config.get("populate_by_name")
219
+ )
220
+
221
+ if _fields_set is None:
222
+ _fields_set = set()
223
+
224
+ model_fields = get_model_fields(cls)
225
+ for name, field in model_fields.items():
226
+ key = field.alias
227
+ if key is None or (key not in values and populate_by_name):
228
+ key = name
229
+
230
+ if key in values:
231
+ fields_values[name] = _construct_field(value=values[key], field=field, key=key)
232
+ _fields_set.add(name)
233
+ else:
234
+ fields_values[name] = field_get_default(field)
235
+
236
+ _extra = {}
237
+ for key, value in values.items():
238
+ if key not in model_fields:
239
+ if PYDANTIC_V2:
240
+ _extra[key] = value
241
+ else:
242
+ _fields_set.add(key)
243
+ fields_values[key] = value
244
+
245
+ object.__setattr__(m, "__dict__", fields_values)
246
+
247
+ if PYDANTIC_V2:
248
+ # these properties are copied from Pydantic's `model_construct()` method
249
+ object.__setattr__(m, "__pydantic_private__", None)
250
+ object.__setattr__(m, "__pydantic_extra__", _extra)
251
+ object.__setattr__(m, "__pydantic_fields_set__", _fields_set)
252
+ else:
253
+ # init_private_attributes() does not exist in v2
254
+ m._init_private_attributes() # type: ignore
255
+
256
+ # copied from Pydantic v1's `construct()` method
257
+ object.__setattr__(m, "__fields_set__", _fields_set)
258
+
259
+ return m
260
+
261
+ if not TYPE_CHECKING:
262
+ # type checkers incorrectly complain about this assignment
263
+ # because the type signatures are technically different
264
+ # although not in practice
265
+ model_construct = construct
266
+
267
+ if not PYDANTIC_V2:
268
+ # we define aliases for some of the new pydantic v2 methods so
269
+ # that we can just document these methods without having to specify
270
+ # a specific pydantic version as some users may not know which
271
+ # pydantic version they are currently using
272
+
273
+ @override
274
+ def model_dump(
275
+ self,
276
+ *,
277
+ mode: Literal["json", "python"] | str = "python",
278
+ include: IncEx | None = None,
279
+ exclude: IncEx | None = None,
280
+ by_alias: bool = False,
281
+ exclude_unset: bool = False,
282
+ exclude_defaults: bool = False,
283
+ exclude_none: bool = False,
284
+ round_trip: bool = False,
285
+ warnings: bool | Literal["none", "warn", "error"] = True,
286
+ context: dict[str, Any] | None = None,
287
+ serialize_as_any: bool = False,
288
+ ) -> dict[str, Any]:
289
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
290
+
291
+ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
292
+
293
+ Args:
294
+ mode: The mode in which `to_python` should run.
295
+ If mode is 'json', the dictionary will only contain JSON serializable types.
296
+ If mode is 'python', the dictionary may contain any Python objects.
297
+ include: A list of fields to include in the output.
298
+ exclude: A list of fields to exclude from the output.
299
+ by_alias: Whether to use the field's alias in the dictionary key if defined.
300
+ exclude_unset: Whether to exclude fields that are unset or None from the output.
301
+ exclude_defaults: Whether to exclude fields that are set to their default value from the output.
302
+ exclude_none: Whether to exclude fields that have a value of `None` from the output.
303
+ round_trip: Whether to enable serialization and deserialization round-trip support.
304
+ warnings: Whether to log warnings when invalid fields are encountered.
305
+
306
+ Returns:
307
+ A dictionary representation of the model.
308
+ """
309
+ if mode not in {"json", "python"}:
310
+ raise ValueError("mode must be either 'json' or 'python'")
311
+ if round_trip != False:
312
+ raise ValueError("round_trip is only supported in Pydantic v2")
313
+ if warnings != True:
314
+ raise ValueError("warnings is only supported in Pydantic v2")
315
+ if context is not None:
316
+ raise ValueError("context is only supported in Pydantic v2")
317
+ if serialize_as_any != False:
318
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
319
+ dumped = super().dict( # pyright: ignore[reportDeprecated]
320
+ include=include,
321
+ exclude=exclude,
322
+ by_alias=by_alias,
323
+ exclude_unset=exclude_unset,
324
+ exclude_defaults=exclude_defaults,
325
+ exclude_none=exclude_none,
326
+ )
327
+
328
+ return cast(dict[str, Any], json_safe(dumped)) if mode == "json" else dumped
329
+
330
+ @override
331
+ def model_dump_json(
332
+ self,
333
+ *,
334
+ indent: int | None = None,
335
+ include: IncEx | None = None,
336
+ exclude: IncEx | None = None,
337
+ by_alias: bool = False,
338
+ exclude_unset: bool = False,
339
+ exclude_defaults: bool = False,
340
+ exclude_none: bool = False,
341
+ round_trip: bool = False,
342
+ warnings: bool | Literal["none", "warn", "error"] = True,
343
+ context: dict[str, Any] | None = None,
344
+ serialize_as_any: bool = False,
345
+ ) -> str:
346
+ """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json
347
+
348
+ Generates a JSON representation of the model using Pydantic's `to_json` method.
349
+
350
+ Args:
351
+ indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
352
+ include: Field(s) to include in the JSON output. Can take either a string or set of strings.
353
+ exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings.
354
+ by_alias: Whether to serialize using field aliases.
355
+ exclude_unset: Whether to exclude fields that have not been explicitly set.
356
+ exclude_defaults: Whether to exclude fields that have the default value.
357
+ exclude_none: Whether to exclude fields that have a value of `None`.
358
+ round_trip: Whether to use serialization/deserialization between JSON and class instance.
359
+ warnings: Whether to show any warnings that occurred during serialization.
360
+
361
+ Returns:
362
+ A JSON string representation of the model.
363
+ """
364
+ if round_trip != False:
365
+ raise ValueError("round_trip is only supported in Pydantic v2")
366
+ if warnings != True:
367
+ raise ValueError("warnings is only supported in Pydantic v2")
368
+ if context is not None:
369
+ raise ValueError("context is only supported in Pydantic v2")
370
+ if serialize_as_any != False:
371
+ raise ValueError("serialize_as_any is only supported in Pydantic v2")
372
+ return super().json( # type: ignore[reportDeprecated]
373
+ indent=indent,
374
+ include=include,
375
+ exclude=exclude,
376
+ by_alias=by_alias,
377
+ exclude_unset=exclude_unset,
378
+ exclude_defaults=exclude_defaults,
379
+ exclude_none=exclude_none,
380
+ )
381
+
382
+
383
+ def _construct_field(value: object, field: FieldInfo, key: str) -> object:
384
+ if value is None:
385
+ return field_get_default(field)
386
+
387
+ if PYDANTIC_V2:
388
+ type_ = field.annotation
389
+ else:
390
+ type_ = cast(type, field.outer_type_) # type: ignore
391
+
392
+ if type_ is None:
393
+ raise RuntimeError(f"Unexpected field type is None for {key}")
394
+
395
+ return construct_type(value=value, type_=type_)
396
+
397
+
398
+ def is_basemodel(type_: type) -> bool:
399
+ """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`"""
400
+ if is_union(type_):
401
+ for variant in get_args(type_):
402
+ if is_basemodel(variant):
403
+ return True
404
+
405
+ return False
406
+
407
+ return is_basemodel_type(type_)
408
+
409
+
410
+ def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]:
411
+ origin = get_origin(type_) or type_
412
+ if not inspect.isclass(origin):
413
+ return False
414
+ return issubclass(origin, BaseModel) or issubclass(origin, GenericModel)
415
+
416
+
417
+ def build(
418
+ base_model_cls: Callable[P, _BaseModelT],
419
+ *args: P.args,
420
+ **kwargs: P.kwargs,
421
+ ) -> _BaseModelT:
422
+ """Construct a BaseModel class without validation.
423
+
424
+ This is useful for cases where you need to instantiate a `BaseModel`
425
+ from an API response as this provides type-safe params which isn't supported
426
+ by helpers like `construct_type()`.
427
+
428
+ ```py
429
+ build(MyModel, my_field_a="foo", my_field_b=123)
430
+ ```
431
+ """
432
+ if args:
433
+ raise TypeError(
434
+ "Received positional arguments which are not supported; Keyword arguments must be used instead",
435
+ )
436
+
437
+ return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs))
438
+
439
+
440
+ def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T:
441
+ """Loose coercion to the expected type with construction of nested values.
442
+
443
+ Note: the returned value from this function is not guaranteed to match the
444
+ given type.
445
+ """
446
+ return cast(_T, construct_type(value=value, type_=type_))
447
+
448
+
449
+ def construct_type(*, value: object, type_: object) -> object:
450
+ """Loose coercion to the expected type with construction of nested values.
451
+
452
+ If the given value does not match the expected type then it is returned as-is.
453
+ """
454
+ # we allow `object` as the input type because otherwise, passing things like
455
+ # `Literal['value']` will be reported as a type error by type checkers
456
+ type_ = cast("type[object]", type_)
457
+ if is_type_alias_type(type_):
458
+ type_ = type_.__value__ # type: ignore[unreachable]
459
+
460
+ # unwrap `Annotated[T, ...]` -> `T`
461
+ if is_annotated_type(type_):
462
+ meta: tuple[Any, ...] = get_args(type_)[1:]
463
+ type_ = extract_type_arg(type_, 0)
464
+ else:
465
+ meta = tuple()
466
+
467
+ # we need to use the origin class for any types that are subscripted generics
468
+ # e.g. Dict[str, object]
469
+ origin = get_origin(type_) or type_
470
+ args = get_args(type_)
471
+
472
+ if is_union(origin):
473
+ try:
474
+ return validate_type(type_=cast("type[object]", type_), value=value)
475
+ except Exception:
476
+ pass
477
+
478
+ # if the type is a discriminated union then we want to construct the right variant
479
+ # in the union, even if the data doesn't match exactly, otherwise we'd break code
480
+ # that relies on the constructed class types, e.g.
481
+ #
482
+ # class FooType:
483
+ # kind: Literal['foo']
484
+ # value: str
485
+ #
486
+ # class BarType:
487
+ # kind: Literal['bar']
488
+ # value: int
489
+ #
490
+ # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then
491
+ # we'd end up constructing `FooType` when it should be `BarType`.
492
+ discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta)
493
+ if discriminator and is_mapping(value):
494
+ variant_value = value.get(discriminator.field_alias_from or discriminator.field_name)
495
+ if variant_value and isinstance(variant_value, str):
496
+ variant_type = discriminator.mapping.get(variant_value)
497
+ if variant_type:
498
+ return construct_type(type_=variant_type, value=value)
499
+
500
+ # if the data is not valid, use the first variant that doesn't fail while deserializing
501
+ for variant in args:
502
+ try:
503
+ return construct_type(value=value, type_=variant)
504
+ except Exception:
505
+ continue
506
+
507
+ raise RuntimeError(f"Could not convert data into a valid instance of {type_}")
508
+
509
+ if origin == dict:
510
+ if not is_mapping(value):
511
+ return value
512
+
513
+ _, items_type = get_args(type_) # Dict[_, items_type]
514
+ return {key: construct_type(value=item, type_=items_type) for key, item in value.items()}
515
+
516
+ if not is_literal_type(type_) and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)):
517
+ if is_list(value):
518
+ return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value]
519
+
520
+ if is_mapping(value):
521
+ if issubclass(type_, BaseModel):
522
+ return type_.construct(**value) # type: ignore[arg-type]
523
+
524
+ return cast(Any, type_).construct(**value)
525
+
526
+ if origin == list:
527
+ if not is_list(value):
528
+ return value
529
+
530
+ inner_type = args[0] # List[inner_type]
531
+ return [construct_type(value=entry, type_=inner_type) for entry in value]
532
+
533
+ if origin == float:
534
+ if isinstance(value, int):
535
+ coerced = float(value)
536
+ if coerced != value:
537
+ return value
538
+ return coerced
539
+
540
+ return value
541
+
542
+ if type_ == datetime:
543
+ try:
544
+ return parse_datetime(value) # type: ignore
545
+ except Exception:
546
+ return value
547
+
548
+ if type_ == date:
549
+ try:
550
+ return parse_date(value) # type: ignore
551
+ except Exception:
552
+ return value
553
+
554
+ return value
555
+
556
+
557
+ @runtime_checkable
558
+ class CachedDiscriminatorType(Protocol):
559
+ __discriminator__: DiscriminatorDetails
560
+
561
+
562
+ class DiscriminatorDetails:
563
+ field_name: str
564
+ """The name of the discriminator field in the variant class, e.g.
565
+
566
+ ```py
567
+ class Foo(BaseModel):
568
+ type: Literal['foo']
569
+ ```
570
+
571
+ Will result in field_name='type'
572
+ """
573
+
574
+ field_alias_from: str | None
575
+ """The name of the discriminator field in the API response, e.g.
576
+
577
+ ```py
578
+ class Foo(BaseModel):
579
+ type: Literal['foo'] = Field(alias='type_from_api')
580
+ ```
581
+
582
+ Will result in field_alias_from='type_from_api'
583
+ """
584
+
585
+ mapping: dict[str, type]
586
+ """Mapping of discriminator value to variant type, e.g.
587
+
588
+ {'foo': FooVariant, 'bar': BarVariant}
589
+ """
590
+
591
+ def __init__(
592
+ self,
593
+ *,
594
+ mapping: dict[str, type],
595
+ discriminator_field: str,
596
+ discriminator_alias: str | None,
597
+ ) -> None:
598
+ self.mapping = mapping
599
+ self.field_name = discriminator_field
600
+ self.field_alias_from = discriminator_alias
601
+
602
+
603
+ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None:
604
+ if isinstance(union, CachedDiscriminatorType):
605
+ return union.__discriminator__
606
+
607
+ discriminator_field_name: str | None = None
608
+
609
+ for annotation in meta_annotations:
610
+ if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None:
611
+ discriminator_field_name = annotation.discriminator
612
+ break
613
+
614
+ if not discriminator_field_name:
615
+ return None
616
+
617
+ mapping: dict[str, type] = {}
618
+ discriminator_alias: str | None = None
619
+
620
+ for variant in get_args(union):
621
+ variant = strip_annotated_type(variant)
622
+ if is_basemodel_type(variant):
623
+ if PYDANTIC_V2:
624
+ field = _extract_field_schema_pv2(variant, discriminator_field_name)
625
+ if not field:
626
+ continue
627
+
628
+ # Note: if one variant defines an alias then they all should
629
+ discriminator_alias = field.get("serialization_alias")
630
+
631
+ field_schema = field["schema"]
632
+
633
+ if field_schema["type"] == "literal":
634
+ for entry in cast("LiteralSchema", field_schema)["expected"]:
635
+ if isinstance(entry, str):
636
+ mapping[entry] = variant
637
+ else:
638
+ field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
639
+ if not field_info:
640
+ continue
641
+
642
+ # Note: if one variant defines an alias then they all should
643
+ discriminator_alias = field_info.alias
644
+
645
+ if field_info.annotation and is_literal_type(field_info.annotation):
646
+ for entry in get_args(field_info.annotation):
647
+ if isinstance(entry, str):
648
+ mapping[entry] = variant
649
+
650
+ if not mapping:
651
+ return None
652
+
653
+ details = DiscriminatorDetails(
654
+ mapping=mapping,
655
+ discriminator_field=discriminator_field_name,
656
+ discriminator_alias=discriminator_alias,
657
+ )
658
+ cast(CachedDiscriminatorType, union).__discriminator__ = details
659
+ return details
660
+
661
+
662
+ def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None:
663
+ schema = model.__pydantic_core_schema__
664
+ if schema["type"] != "model":
665
+ return None
666
+
667
+ fields_schema = schema["schema"]
668
+ if fields_schema["type"] != "model-fields":
669
+ return None
670
+
671
+ fields_schema = cast("ModelFieldsSchema", fields_schema)
672
+
673
+ field = fields_schema["fields"].get(field_name)
674
+ if not field:
675
+ return None
676
+
677
+ return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast]
678
+
679
+
680
+ def validate_type(*, type_: type[_T], value: object) -> _T:
681
+ """Strict validation that the given value matches the expected type"""
682
+ if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel):
683
+ return cast(_T, parse_obj(type_, value))
684
+
685
+ return cast(_T, _validate_non_model_type(type_=type_, value=value))
686
+
687
+
688
+ def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None:
689
+ """Add a pydantic config for the given type.
690
+
691
+ Note: this is a no-op on Pydantic v1.
692
+ """
693
+ setattr(typ, "__pydantic_config__", config) # noqa: B010
694
+
695
+
696
+ def add_request_id(obj: BaseModel, request_id: str | None) -> None:
697
+ obj._request_id = request_id
698
+
699
+ # in Pydantic v1, using setattr like we do above causes the attribute
700
+ # to be included when serializing the model which we don't want in this
701
+ # case so we need to explicitly exclude it
702
+ if not PYDANTIC_V2:
703
+ try:
704
+ exclude_fields = obj.__exclude_fields__ # type: ignore
705
+ except AttributeError:
706
+ cast(Any, obj).__exclude_fields__ = {"_request_id", "__exclude_fields__"}
707
+ else:
708
+ cast(Any, obj).__exclude_fields__ = {*(exclude_fields or {}), "_request_id", "__exclude_fields__"}
709
+
710
+
711
+ # our use of subclasssing here causes weirdness for type checkers,
712
+ # so we just pretend that we don't subclass
713
+ if TYPE_CHECKING:
714
+ GenericModel = BaseModel
715
+ else:
716
+
717
+ class GenericModel(BaseGenericModel, BaseModel):
718
+ pass
719
+
720
+
721
+ if PYDANTIC_V2:
722
+ from pydantic import TypeAdapter as _TypeAdapter
723
+
724
+ _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter))
725
+
726
+ if TYPE_CHECKING:
727
+ from pydantic import TypeAdapter
728
+ else:
729
+ TypeAdapter = _CachedTypeAdapter
730
+
731
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
732
+ return TypeAdapter(type_).validate_python(value)
733
+
734
+ elif not TYPE_CHECKING: # TODO: condition is weird
735
+
736
+ class RootModel(GenericModel, Generic[_T]):
737
+ """Used as a placeholder to easily convert runtime types to a Pydantic format
738
+ to provide validation.
739
+
740
+ For example:
741
+ ```py
742
+ validated = RootModel[int](__root__="5").__root__
743
+ # validated: 5
744
+ ```
745
+ """
746
+
747
+ __root__: _T
748
+
749
+ def _validate_non_model_type(*, type_: type[_T], value: object) -> _T:
750
+ model = _create_pydantic_model(type_).validate(value)
751
+ return cast(_T, model.__root__)
752
+
753
+ def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]:
754
+ return RootModel[type_] # type: ignore
755
+
756
+
757
+ class FinalRequestOptionsInput(TypedDict, total=False):
758
+ method: Required[str]
759
+ url: Required[str]
760
+ params: Query
761
+ headers: Headers
762
+ max_retries: int
763
+ timeout: float | Timeout | None
764
+ files: HttpxRequestFiles | None
765
+ idempotency_key: str
766
+ json_data: Body
767
+ extra_json: AnyMapping
768
+
769
+
770
+ @final
771
+ class FinalRequestOptions(pydantic.BaseModel):
772
+ method: str
773
+ url: str
774
+ params: Query = {}
775
+ headers: Union[Headers, NotGiven] = NotGiven()
776
+ max_retries: Union[int, NotGiven] = NotGiven()
777
+ timeout: Union[float, Timeout, None, NotGiven] = NotGiven()
778
+ files: Union[HttpxRequestFiles, None] = None
779
+ idempotency_key: Union[str, None] = None
780
+ post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven()
781
+
782
+ # It should be noted that we cannot use `json` here as that would override
783
+ # a BaseModel method in an incompatible fashion.
784
+ json_data: Union[Body, None] = None
785
+ extra_json: Union[AnyMapping, None] = None
786
+
787
+ if PYDANTIC_V2:
788
+ model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True)
789
+ else:
790
+
791
+ class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated]
792
+ arbitrary_types_allowed: bool = True
793
+
794
+ def get_max_retries(self, max_retries: int) -> int:
795
+ if isinstance(self.max_retries, NotGiven):
796
+ return max_retries
797
+ return self.max_retries
798
+
799
+ def _strip_raw_response_header(self) -> None:
800
+ if not is_given(self.headers):
801
+ return
802
+
803
+ if self.headers.get(RAW_RESPONSE_HEADER):
804
+ self.headers = {**self.headers}
805
+ self.headers.pop(RAW_RESPONSE_HEADER)
806
+
807
+ # override the `construct` method so that we can run custom transformations.
808
+ # this is necessary as we don't want to do any actual runtime type checking
809
+ # (which means we can't use validators) but we do want to ensure that `NotGiven`
810
+ # values are not present
811
+ #
812
+ # type ignore required because we're adding explicit types to `**values`
813
+ @classmethod
814
+ def construct( # type: ignore
815
+ cls,
816
+ _fields_set: set[str] | None = None,
817
+ **values: Unpack[FinalRequestOptionsInput],
818
+ ) -> FinalRequestOptions:
819
+ kwargs: dict[str, Any] = {
820
+ # we unconditionally call `strip_not_given` on any value
821
+ # as it will just ignore any non-mapping types
822
+ key: strip_not_given(value)
823
+ for key, value in values.items()
824
+ }
825
+ if PYDANTIC_V2:
826
+ return super().model_construct(_fields_set, **kwargs)
827
+ return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated]
828
+
829
+ if not TYPE_CHECKING:
830
+ # type checkers incorrectly complain about this assignment
831
+ model_construct = construct
vllm/lib/python3.10/site-packages/openai/_module_client.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from typing_extensions import override
4
+
5
+ from . import resources, _load_client
6
+ from ._utils import LazyProxy
7
+
8
+
9
+ class ChatProxy(LazyProxy[resources.Chat]):
10
+ @override
11
+ def __load__(self) -> resources.Chat:
12
+ return _load_client().chat
13
+
14
+
15
+ class BetaProxy(LazyProxy[resources.Beta]):
16
+ @override
17
+ def __load__(self) -> resources.Beta:
18
+ return _load_client().beta
19
+
20
+
21
+ class FilesProxy(LazyProxy[resources.Files]):
22
+ @override
23
+ def __load__(self) -> resources.Files:
24
+ return _load_client().files
25
+
26
+
27
+ class AudioProxy(LazyProxy[resources.Audio]):
28
+ @override
29
+ def __load__(self) -> resources.Audio:
30
+ return _load_client().audio
31
+
32
+
33
+ class ImagesProxy(LazyProxy[resources.Images]):
34
+ @override
35
+ def __load__(self) -> resources.Images:
36
+ return _load_client().images
37
+
38
+
39
+ class ModelsProxy(LazyProxy[resources.Models]):
40
+ @override
41
+ def __load__(self) -> resources.Models:
42
+ return _load_client().models
43
+
44
+
45
+ class BatchesProxy(LazyProxy[resources.Batches]):
46
+ @override
47
+ def __load__(self) -> resources.Batches:
48
+ return _load_client().batches
49
+
50
+
51
+ class EmbeddingsProxy(LazyProxy[resources.Embeddings]):
52
+ @override
53
+ def __load__(self) -> resources.Embeddings:
54
+ return _load_client().embeddings
55
+
56
+
57
+ class CompletionsProxy(LazyProxy[resources.Completions]):
58
+ @override
59
+ def __load__(self) -> resources.Completions:
60
+ return _load_client().completions
61
+
62
+
63
+ class ModerationsProxy(LazyProxy[resources.Moderations]):
64
+ @override
65
+ def __load__(self) -> resources.Moderations:
66
+ return _load_client().moderations
67
+
68
+
69
+ class FineTuningProxy(LazyProxy[resources.FineTuning]):
70
+ @override
71
+ def __load__(self) -> resources.FineTuning:
72
+ return _load_client().fine_tuning
73
+
74
+
75
+ chat: resources.Chat = ChatProxy().__as_proxied__()
76
+ beta: resources.Beta = BetaProxy().__as_proxied__()
77
+ files: resources.Files = FilesProxy().__as_proxied__()
78
+ audio: resources.Audio = AudioProxy().__as_proxied__()
79
+ images: resources.Images = ImagesProxy().__as_proxied__()
80
+ models: resources.Models = ModelsProxy().__as_proxied__()
81
+ batches: resources.Batches = BatchesProxy().__as_proxied__()
82
+ embeddings: resources.Embeddings = EmbeddingsProxy().__as_proxied__()
83
+ completions: resources.Completions = CompletionsProxy().__as_proxied__()
84
+ moderations: resources.Moderations = ModerationsProxy().__as_proxied__()
85
+ fine_tuning: resources.FineTuning = FineTuningProxy().__as_proxied__()
vllm/lib/python3.10/site-packages/openai/_resource.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import TYPE_CHECKING
7
+
8
+ import anyio
9
+
10
+ if TYPE_CHECKING:
11
+ from ._client import OpenAI, AsyncOpenAI
12
+
13
+
14
+ class SyncAPIResource:
15
+ _client: OpenAI
16
+
17
+ def __init__(self, client: OpenAI) -> None:
18
+ self._client = client
19
+ self._get = client.get
20
+ self._post = client.post
21
+ self._patch = client.patch
22
+ self._put = client.put
23
+ self._delete = client.delete
24
+ self._get_api_list = client.get_api_list
25
+
26
+ def _sleep(self, seconds: float) -> None:
27
+ time.sleep(seconds)
28
+
29
+
30
+ class AsyncAPIResource:
31
+ _client: AsyncOpenAI
32
+
33
+ def __init__(self, client: AsyncOpenAI) -> None:
34
+ self._client = client
35
+ self._get = client.get
36
+ self._post = client.post
37
+ self._patch = client.patch
38
+ self._put = client.put
39
+ self._delete = client.delete
40
+ self._get_api_list = client.get_api_list
41
+
42
+ async def _sleep(self, seconds: float) -> None:
43
+ await anyio.sleep(seconds)
vllm/lib/python3.10/site-packages/openai/_streaming.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OpenAI, AsyncOpenAI
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: OpenAI,
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
+ else:
81
+ data = sse.json()
82
+
83
+ if sse.event == "error" and is_mapping(data) and data.get("error"):
84
+ message = None
85
+ error = data.get("error")
86
+ if is_mapping(error):
87
+ message = error.get("message")
88
+ if not message or not isinstance(message, str):
89
+ message = "An error occurred during streaming"
90
+
91
+ raise APIError(
92
+ message=message,
93
+ request=self.response.request,
94
+ body=data["error"],
95
+ )
96
+
97
+ yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response)
98
+
99
+ # Ensure the entire stream is consumed
100
+ for _sse in iterator:
101
+ ...
102
+
103
+ def __enter__(self) -> Self:
104
+ return self
105
+
106
+ def __exit__(
107
+ self,
108
+ exc_type: type[BaseException] | None,
109
+ exc: BaseException | None,
110
+ exc_tb: TracebackType | None,
111
+ ) -> None:
112
+ self.close()
113
+
114
+ def close(self) -> None:
115
+ """
116
+ Close the response and release the connection.
117
+
118
+ Automatically called if the response body is read to completion.
119
+ """
120
+ self.response.close()
121
+
122
+
123
+ class AsyncStream(Generic[_T]):
124
+ """Provides the core interface to iterate over an asynchronous stream response."""
125
+
126
+ response: httpx.Response
127
+
128
+ _decoder: SSEDecoder | SSEBytesDecoder
129
+
130
+ def __init__(
131
+ self,
132
+ *,
133
+ cast_to: type[_T],
134
+ response: httpx.Response,
135
+ client: AsyncOpenAI,
136
+ ) -> None:
137
+ self.response = response
138
+ self._cast_to = cast_to
139
+ self._client = client
140
+ self._decoder = client._make_sse_decoder()
141
+ self._iterator = self.__stream__()
142
+
143
+ async def __anext__(self) -> _T:
144
+ return await self._iterator.__anext__()
145
+
146
+ async def __aiter__(self) -> AsyncIterator[_T]:
147
+ async for item in self._iterator:
148
+ yield item
149
+
150
+ async def _iter_events(self) -> AsyncIterator[ServerSentEvent]:
151
+ async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()):
152
+ yield sse
153
+
154
+ async def __stream__(self) -> AsyncIterator[_T]:
155
+ cast_to = cast(Any, self._cast_to)
156
+ response = self.response
157
+ process_data = self._client._process_response_data
158
+ iterator = self._iter_events()
159
+
160
+ async for sse in iterator:
161
+ if sse.data.startswith("[DONE]"):
162
+ break
163
+
164
+ if sse.event is None:
165
+ data = sse.json()
166
+ if is_mapping(data) and data.get("error"):
167
+ message = None
168
+ error = data.get("error")
169
+ if is_mapping(error):
170
+ message = error.get("message")
171
+ if not message or not isinstance(message, str):
172
+ message = "An error occurred during streaming"
173
+
174
+ raise APIError(
175
+ message=message,
176
+ request=self.response.request,
177
+ body=data["error"],
178
+ )
179
+
180
+ yield process_data(data=data, cast_to=cast_to, response=response)
181
+
182
+ else:
183
+ data = sse.json()
184
+
185
+ if sse.event == "error" and is_mapping(data) and data.get("error"):
186
+ message = None
187
+ error = data.get("error")
188
+ if is_mapping(error):
189
+ message = error.get("message")
190
+ if not message or not isinstance(message, str):
191
+ message = "An error occurred during streaming"
192
+
193
+ raise APIError(
194
+ message=message,
195
+ request=self.response.request,
196
+ body=data["error"],
197
+ )
198
+
199
+ yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response)
200
+
201
+ # Ensure the entire stream is consumed
202
+ async for _sse in iterator:
203
+ ...
204
+
205
+ async def __aenter__(self) -> Self:
206
+ return self
207
+
208
+ async def __aexit__(
209
+ self,
210
+ exc_type: type[BaseException] | None,
211
+ exc: BaseException | None,
212
+ exc_tb: TracebackType | None,
213
+ ) -> None:
214
+ await self.close()
215
+
216
+ async def close(self) -> None:
217
+ """
218
+ Close the response and release the connection.
219
+
220
+ Automatically called if the response body is read to completion.
221
+ """
222
+ await self.response.aclose()
223
+
224
+
225
+ class ServerSentEvent:
226
+ def __init__(
227
+ self,
228
+ *,
229
+ event: str | None = None,
230
+ data: str | None = None,
231
+ id: str | None = None,
232
+ retry: int | None = None,
233
+ ) -> None:
234
+ if data is None:
235
+ data = ""
236
+
237
+ self._id = id
238
+ self._data = data
239
+ self._event = event or None
240
+ self._retry = retry
241
+
242
+ @property
243
+ def event(self) -> str | None:
244
+ return self._event
245
+
246
+ @property
247
+ def id(self) -> str | None:
248
+ return self._id
249
+
250
+ @property
251
+ def retry(self) -> int | None:
252
+ return self._retry
253
+
254
+ @property
255
+ def data(self) -> str:
256
+ return self._data
257
+
258
+ def json(self) -> Any:
259
+ return json.loads(self.data)
260
+
261
+ @override
262
+ def __repr__(self) -> str:
263
+ return f"ServerSentEvent(event={self.event}, data={self.data}, id={self.id}, retry={self.retry})"
264
+
265
+
266
+ class SSEDecoder:
267
+ _data: list[str]
268
+ _event: str | None
269
+ _retry: int | None
270
+ _last_event_id: str | None
271
+
272
+ def __init__(self) -> None:
273
+ self._event = None
274
+ self._data = []
275
+ self._last_event_id = None
276
+ self._retry = None
277
+
278
+ def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
279
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
280
+ for chunk in self._iter_chunks(iterator):
281
+ # Split before decoding so splitlines() only uses \r and \n
282
+ for raw_line in chunk.splitlines():
283
+ line = raw_line.decode("utf-8")
284
+ sse = self.decode(line)
285
+ if sse:
286
+ yield sse
287
+
288
+ def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]:
289
+ """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
290
+ data = b""
291
+ for chunk in iterator:
292
+ for line in chunk.splitlines(keepends=True):
293
+ data += line
294
+ if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
295
+ yield data
296
+ data = b""
297
+ if data:
298
+ yield data
299
+
300
+ async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]:
301
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
302
+ async for chunk in self._aiter_chunks(iterator):
303
+ # Split before decoding so splitlines() only uses \r and \n
304
+ for raw_line in chunk.splitlines():
305
+ line = raw_line.decode("utf-8")
306
+ sse = self.decode(line)
307
+ if sse:
308
+ yield sse
309
+
310
+ async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]:
311
+ """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks"""
312
+ data = b""
313
+ async for chunk in iterator:
314
+ for line in chunk.splitlines(keepends=True):
315
+ data += line
316
+ if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")):
317
+ yield data
318
+ data = b""
319
+ if data:
320
+ yield data
321
+
322
+ def decode(self, line: str) -> ServerSentEvent | None:
323
+ # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501
324
+
325
+ if not line:
326
+ if not self._event and not self._data and not self._last_event_id and self._retry is None:
327
+ return None
328
+
329
+ sse = ServerSentEvent(
330
+ event=self._event,
331
+ data="\n".join(self._data),
332
+ id=self._last_event_id,
333
+ retry=self._retry,
334
+ )
335
+
336
+ # NOTE: as per the SSE spec, do not reset last_event_id.
337
+ self._event = None
338
+ self._data = []
339
+ self._retry = None
340
+
341
+ return sse
342
+
343
+ if line.startswith(":"):
344
+ return None
345
+
346
+ fieldname, _, value = line.partition(":")
347
+
348
+ if value.startswith(" "):
349
+ value = value[1:]
350
+
351
+ if fieldname == "event":
352
+ self._event = value
353
+ elif fieldname == "data":
354
+ self._data.append(value)
355
+ elif fieldname == "id":
356
+ if "\0" in value:
357
+ pass
358
+ else:
359
+ self._last_event_id = value
360
+ elif fieldname == "retry":
361
+ try:
362
+ self._retry = int(value)
363
+ except (TypeError, ValueError):
364
+ pass
365
+ else:
366
+ pass # Field is ignored.
367
+
368
+ return None
369
+
370
+
371
+ @runtime_checkable
372
+ class SSEBytesDecoder(Protocol):
373
+ def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]:
374
+ """Given an iterator that yields raw binary data, iterate over it & yield every event encountered"""
375
+ ...
376
+
377
+ def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]:
378
+ """Given an async iterator that yields raw binary data, iterate over it & yield every event encountered"""
379
+ ...
380
+
381
+
382
+ def is_stream_class_type(typ: type) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]:
383
+ """TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`"""
384
+ origin = get_origin(typ) or typ
385
+ return inspect.isclass(origin) and issubclass(origin, (Stream, AsyncStream))
386
+
387
+
388
+ def extract_stream_chunk_type(
389
+ stream_cls: type,
390
+ *,
391
+ failure_message: str | None = None,
392
+ ) -> type:
393
+ """Given a type like `Stream[T]`, returns the generic type variable `T`.
394
+
395
+ This also handles the case where a concrete subclass is given, e.g.
396
+ ```py
397
+ class MyStream(Stream[bytes]):
398
+ ...
399
+
400
+ extract_stream_chunk_type(MyStream) -> bytes
401
+ ```
402
+ """
403
+ from ._base_client import Stream, AsyncStream
404
+
405
+ return extract_type_var_from_base(
406
+ stream_cls,
407
+ index=0,
408
+ generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)),
409
+ failure_message=failure_message,
410
+ )
vllm/lib/python3.10/site-packages/openai/_types.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Optional,
17
+ Sequence,
18
+ )
19
+ from typing_extensions import Set, Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable
20
+
21
+ import httpx
22
+ import pydantic
23
+ from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport
24
+
25
+ if TYPE_CHECKING:
26
+ from ._models import BaseModel
27
+ from ._response import APIResponse, AsyncAPIResponse
28
+ from ._legacy_response import HttpxBinaryResponseContent
29
+
30
+ Transport = BaseTransport
31
+ AsyncTransport = AsyncBaseTransport
32
+ Query = Mapping[str, object]
33
+ Body = object
34
+ AnyMapping = Mapping[str, object]
35
+ ModelT = TypeVar("ModelT", bound=pydantic.BaseModel)
36
+ _T = TypeVar("_T")
37
+
38
+
39
+ # Approximates httpx internal ProxiesTypes and RequestFiles types
40
+ # while adding support for `PathLike` instances
41
+ ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]]
42
+ ProxiesTypes = Union[str, Proxy, ProxiesDict]
43
+ if TYPE_CHECKING:
44
+ Base64FileInput = Union[IO[bytes], PathLike[str]]
45
+ FileContent = Union[IO[bytes], bytes, PathLike[str]]
46
+ else:
47
+ Base64FileInput = Union[IO[bytes], PathLike]
48
+ FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8.
49
+ FileTypes = Union[
50
+ # file (or bytes)
51
+ FileContent,
52
+ # (filename, file (or bytes))
53
+ Tuple[Optional[str], FileContent],
54
+ # (filename, file (or bytes), content_type)
55
+ Tuple[Optional[str], FileContent, Optional[str]],
56
+ # (filename, file (or bytes), content_type, headers)
57
+ Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]],
58
+ ]
59
+ RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
60
+
61
+ # duplicate of the above but without our custom file support
62
+ HttpxFileContent = Union[IO[bytes], bytes]
63
+ HttpxFileTypes = Union[
64
+ # file (or bytes)
65
+ HttpxFileContent,
66
+ # (filename, file (or bytes))
67
+ Tuple[Optional[str], HttpxFileContent],
68
+ # (filename, file (or bytes), content_type)
69
+ Tuple[Optional[str], HttpxFileContent, Optional[str]],
70
+ # (filename, file (or bytes), content_type, headers)
71
+ Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]],
72
+ ]
73
+ HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]]
74
+
75
+ # Workaround to support (cast_to: Type[ResponseT]) -> ResponseT
76
+ # where ResponseT includes `None`. In order to support directly
77
+ # passing `None`, overloads would have to be defined for every
78
+ # method that uses `ResponseT` which would lead to an unacceptable
79
+ # amount of code duplication and make it unreadable. See _base_client.py
80
+ # for example usage.
81
+ #
82
+ # This unfortunately means that you will either have
83
+ # to import this type and pass it explicitly:
84
+ #
85
+ # from openai import NoneType
86
+ # client.get('/foo', cast_to=NoneType)
87
+ #
88
+ # or build it yourself:
89
+ #
90
+ # client.get('/foo', cast_to=type(None))
91
+ if TYPE_CHECKING:
92
+ NoneType: Type[None]
93
+ else:
94
+ NoneType = type(None)
95
+
96
+
97
+ class RequestOptions(TypedDict, total=False):
98
+ headers: Headers
99
+ max_retries: int
100
+ timeout: float | Timeout | None
101
+ params: Query
102
+ extra_json: AnyMapping
103
+ idempotency_key: str
104
+
105
+
106
+ # Sentinel class used until PEP 0661 is accepted
107
+ class NotGiven:
108
+ """
109
+ A sentinel singleton class used to distinguish omitted keyword arguments
110
+ from those passed in with the value None (which may have different behavior).
111
+
112
+ For example:
113
+
114
+ ```py
115
+ def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: ...
116
+
117
+
118
+ get(timeout=1) # 1s timeout
119
+ get(timeout=None) # No timeout
120
+ get() # Default timeout behavior, which may not be statically known at the method definition.
121
+ ```
122
+ """
123
+
124
+ def __bool__(self) -> Literal[False]:
125
+ return False
126
+
127
+ @override
128
+ def __repr__(self) -> str:
129
+ return "NOT_GIVEN"
130
+
131
+
132
+ NotGivenOr = Union[_T, NotGiven]
133
+ NOT_GIVEN = NotGiven()
134
+
135
+
136
+ class Omit:
137
+ """In certain situations you need to be able to represent a case where a default value has
138
+ to be explicitly removed and `None` is not an appropriate substitute, for example:
139
+
140
+ ```py
141
+ # as the default `Content-Type` header is `application/json` that will be sent
142
+ client.post("/upload/files", files={"file": b"my raw file content"})
143
+
144
+ # you can't explicitly override the header as it has to be dynamically generated
145
+ # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
146
+ client.post(..., headers={"Content-Type": "multipart/form-data"})
147
+
148
+ # instead you can remove the default `application/json` header by passing Omit
149
+ client.post(..., headers={"Content-Type": Omit()})
150
+ ```
151
+ """
152
+
153
+ def __bool__(self) -> Literal[False]:
154
+ return False
155
+
156
+
157
+ @runtime_checkable
158
+ class ModelBuilderProtocol(Protocol):
159
+ @classmethod
160
+ def build(
161
+ cls: type[_T],
162
+ *,
163
+ response: Response,
164
+ data: object,
165
+ ) -> _T: ...
166
+
167
+
168
+ Headers = Mapping[str, Union[str, Omit]]
169
+
170
+
171
+ class HeadersLikeProtocol(Protocol):
172
+ def get(self, __key: str) -> str | None: ...
173
+
174
+
175
+ HeadersLike = Union[Headers, HeadersLikeProtocol]
176
+
177
+ ResponseT = TypeVar(
178
+ "ResponseT",
179
+ bound=Union[
180
+ object,
181
+ str,
182
+ None,
183
+ "BaseModel",
184
+ List[Any],
185
+ Dict[str, Any],
186
+ Response,
187
+ ModelBuilderProtocol,
188
+ "APIResponse[Any]",
189
+ "AsyncAPIResponse[Any]",
190
+ "HttpxBinaryResponseContent",
191
+ ],
192
+ )
193
+
194
+ StrBytesIntFloat = Union[str, bytes, int, float]
195
+
196
+ # Note: copied from Pydantic
197
+ # https://github.com/pydantic/pydantic/blob/6f31f8f68ef011f84357330186f603ff295312fd/pydantic/main.py#L79
198
+ IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union["IncEx", bool]], Mapping[str, Union["IncEx", bool]]]
199
+
200
+ PostParser = Callable[[Any], Any]
201
+
202
+
203
+ @runtime_checkable
204
+ class InheritsGeneric(Protocol):
205
+ """Represents a type that has inherited from `Generic`
206
+
207
+ The `__orig_bases__` property can be used to determine the resolved
208
+ type variable for a given base class.
209
+ """
210
+
211
+ __orig_bases__: tuple[_GenericAlias]
212
+
213
+
214
+ class _GenericAlias(Protocol):
215
+ __origin__: type[object]
216
+
217
+
218
+ class HttpxSendArgs(TypedDict, total=False):
219
+ auth: httpx.Auth
vllm/lib/python3.10/site-packages/openai/_utils/__init__.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._logs import SensitiveHeadersFilter as SensitiveHeadersFilter
2
+ from ._sync import asyncify as asyncify
3
+ from ._proxy import LazyProxy as LazyProxy
4
+ from ._utils import (
5
+ flatten as flatten,
6
+ is_dict as is_dict,
7
+ is_list as is_list,
8
+ is_given as is_given,
9
+ is_tuple as is_tuple,
10
+ json_safe as json_safe,
11
+ lru_cache as lru_cache,
12
+ is_mapping as is_mapping,
13
+ is_tuple_t as is_tuple_t,
14
+ parse_date as parse_date,
15
+ is_iterable as is_iterable,
16
+ is_sequence as is_sequence,
17
+ coerce_float as coerce_float,
18
+ is_mapping_t as is_mapping_t,
19
+ removeprefix as removeprefix,
20
+ removesuffix as removesuffix,
21
+ extract_files as extract_files,
22
+ is_sequence_t as is_sequence_t,
23
+ required_args as required_args,
24
+ coerce_boolean as coerce_boolean,
25
+ coerce_integer as coerce_integer,
26
+ file_from_path as file_from_path,
27
+ parse_datetime as parse_datetime,
28
+ strip_not_given as strip_not_given,
29
+ deepcopy_minimal as deepcopy_minimal,
30
+ get_async_library as get_async_library,
31
+ maybe_coerce_float as maybe_coerce_float,
32
+ get_required_header as get_required_header,
33
+ maybe_coerce_boolean as maybe_coerce_boolean,
34
+ maybe_coerce_integer as maybe_coerce_integer,
35
+ )
36
+ from ._typing import (
37
+ is_list_type as is_list_type,
38
+ is_union_type as is_union_type,
39
+ extract_type_arg as extract_type_arg,
40
+ is_iterable_type as is_iterable_type,
41
+ is_required_type as is_required_type,
42
+ is_annotated_type as is_annotated_type,
43
+ is_type_alias_type as is_type_alias_type,
44
+ strip_annotated_type as strip_annotated_type,
45
+ extract_type_var_from_base as extract_type_var_from_base,
46
+ )
47
+ from ._streams import consume_sync_iterator as consume_sync_iterator, consume_async_iterator as consume_async_iterator
48
+ from ._transform import (
49
+ PropertyInfo as PropertyInfo,
50
+ transform as transform,
51
+ async_transform as async_transform,
52
+ maybe_transform as maybe_transform,
53
+ async_maybe_transform as async_maybe_transform,
54
+ )
55
+ from ._reflection import (
56
+ function_has_argument as function_has_argument,
57
+ assert_signatures_in_sync as assert_signatures_in_sync,
58
+ )
vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_logs.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_proxy.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_reflection.cpython-310.pyc ADDED
Binary file (1.49 kB). View file
 
vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_streams.cpython-310.pyc ADDED
Binary file (599 Bytes). View file
 
vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_sync.cpython-310.pyc ADDED
Binary file (2.65 kB). View file
 
vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_transform.cpython-310.pyc ADDED
Binary file (8.81 kB). View file
 
vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_typing.cpython-310.pyc ADDED
Binary file (3.9 kB). View file
 
vllm/lib/python3.10/site-packages/openai/_utils/__pycache__/_utils.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
vllm/lib/python3.10/site-packages/openai/_utils/_logs.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from typing_extensions import override
4
+
5
+ from ._utils import is_dict
6
+
7
+ logger: logging.Logger = logging.getLogger("openai")
8
+ httpx_logger: logging.Logger = logging.getLogger("httpx")
9
+
10
+
11
+ SENSITIVE_HEADERS = {"api-key", "authorization"}
12
+
13
+
14
+ def _basic_config() -> None:
15
+ # e.g. [2023-10-05 14:12:26 - openai._base_client:818 - DEBUG] HTTP Request: POST http://127.0.0.1:4010/foo/bar "200 OK"
16
+ logging.basicConfig(
17
+ format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s",
18
+ datefmt="%Y-%m-%d %H:%M:%S",
19
+ )
20
+
21
+
22
+ def setup_logging() -> None:
23
+ env = os.environ.get("OPENAI_LOG")
24
+ if env == "debug":
25
+ _basic_config()
26
+ logger.setLevel(logging.DEBUG)
27
+ httpx_logger.setLevel(logging.DEBUG)
28
+ elif env == "info":
29
+ _basic_config()
30
+ logger.setLevel(logging.INFO)
31
+ httpx_logger.setLevel(logging.INFO)
32
+
33
+
34
+ class SensitiveHeadersFilter(logging.Filter):
35
+ @override
36
+ def filter(self, record: logging.LogRecord) -> bool:
37
+ if is_dict(record.args) and "headers" in record.args and is_dict(record.args["headers"]):
38
+ headers = record.args["headers"] = {**record.args["headers"]}
39
+ for header in headers:
40
+ if str(header).lower() in SENSITIVE_HEADERS:
41
+ headers[header] = "<redacted>"
42
+ return True
vllm/lib/python3.10/site-packages/openai/_utils/_proxy.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ proxied = self.__get_proxied__()
50
+ if issubclass(type(proxied), LazyProxy):
51
+ return type(proxied)
52
+ return proxied.__class__
53
+
54
+ def __get_proxied__(self) -> T:
55
+ return self.__load__()
56
+
57
+ def __as_proxied__(self) -> T:
58
+ """Helper method that returns the current proxy, typed as the loaded object"""
59
+ return cast(T, self)
60
+
61
+ @abstractmethod
62
+ def __load__(self) -> T: ...
vllm/lib/python3.10/site-packages/openai/_utils/_reflection.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ description: str = "",
19
+ ) -> None:
20
+ """Ensure that the signature of the second function matches the first."""
21
+
22
+ check_sig = inspect.signature(check_func)
23
+ source_sig = inspect.signature(source_func)
24
+
25
+ errors: list[str] = []
26
+
27
+ for name, source_param in source_sig.parameters.items():
28
+ if name in exclude_params:
29
+ continue
30
+
31
+ custom_param = check_sig.parameters.get(name)
32
+ if not custom_param:
33
+ errors.append(f"the `{name}` param is missing")
34
+ continue
35
+
36
+ if custom_param.annotation != source_param.annotation:
37
+ errors.append(
38
+ f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(custom_param.annotation)}"
39
+ )
40
+ continue
41
+
42
+ if errors:
43
+ raise AssertionError(
44
+ f"{len(errors)} errors encountered when comparing signatures{description}:\n\n" + "\n\n".join(errors)
45
+ )
vllm/lib/python3.10/site-packages/openai/_utils/_streams.py ADDED
@@ -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
+ ...
vllm/lib/python3.10/site-packages/openai/_utils/_sync.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import asyncio
5
+ import functools
6
+ import contextvars
7
+ from typing import Any, TypeVar, Callable, Awaitable
8
+ from typing_extensions import ParamSpec
9
+
10
+ T_Retval = TypeVar("T_Retval")
11
+ T_ParamSpec = ParamSpec("T_ParamSpec")
12
+
13
+
14
+ if sys.version_info >= (3, 9):
15
+ to_thread = asyncio.to_thread
16
+ else:
17
+ # backport of https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread
18
+ # for Python 3.8 support
19
+ async def to_thread(
20
+ func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
21
+ ) -> Any:
22
+ """Asynchronously run function *func* in a separate thread.
23
+
24
+ Any *args and **kwargs supplied for this function are directly passed
25
+ to *func*. Also, the current :class:`contextvars.Context` is propagated,
26
+ allowing context variables from the main thread to be accessed in the
27
+ separate thread.
28
+
29
+ Returns a coroutine that can be awaited to get the eventual result of *func*.
30
+ """
31
+ loop = asyncio.events.get_running_loop()
32
+ ctx = contextvars.copy_context()
33
+ func_call = functools.partial(ctx.run, func, *args, **kwargs)
34
+ return await loop.run_in_executor(None, func_call)
35
+
36
+
37
+ # inspired by `asyncer`, https://github.com/tiangolo/asyncer
38
+ def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]:
39
+ """
40
+ Take a blocking function and create an async one that receives the same
41
+ positional and keyword arguments. For python version 3.9 and above, it uses
42
+ asyncio.to_thread to run the function in a separate thread. For python version
43
+ 3.8, it uses locally defined copy of the asyncio.to_thread function which was
44
+ introduced in python 3.9.
45
+
46
+ Usage:
47
+
48
+ ```python
49
+ def blocking_func(arg1, arg2, kwarg1=None):
50
+ # blocking code
51
+ return result
52
+
53
+ result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1)
54
+ ```
55
+
56
+ ## Arguments
57
+
58
+ `function`: a blocking regular callable (e.g. a function)
59
+
60
+ ## Return
61
+
62
+ An async function that takes the same positional and keyword arguments as the
63
+ original one, that when called runs the same original function in a thread worker
64
+ and returns the result.
65
+ """
66
+
67
+ async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval:
68
+ return await to_thread(function, *args, **kwargs)
69
+
70
+ return wrapper
vllm/lib/python3.10/site-packages/openai/_utils/_transform.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import base64
5
+ import pathlib
6
+ from typing import Any, Mapping, TypeVar, cast
7
+ from datetime import date, datetime
8
+ from typing_extensions import Literal, get_args, override, get_type_hints
9
+
10
+ import anyio
11
+ import pydantic
12
+
13
+ from ._utils import (
14
+ is_list,
15
+ is_mapping,
16
+ is_iterable,
17
+ )
18
+ from .._files import is_base64_file_input
19
+ from ._typing import (
20
+ is_list_type,
21
+ is_union_type,
22
+ extract_type_arg,
23
+ is_iterable_type,
24
+ is_required_type,
25
+ is_annotated_type,
26
+ strip_annotated_type,
27
+ )
28
+ from .._compat import model_dump, is_typeddict
29
+
30
+ _T = TypeVar("_T")
31
+
32
+
33
+ # TODO: support for drilling globals() and locals()
34
+ # TODO: ensure works correctly with forward references in all cases
35
+
36
+
37
+ PropertyFormat = Literal["iso8601", "base64", "custom"]
38
+
39
+
40
+ class PropertyInfo:
41
+ """Metadata class to be used in Annotated types to provide information about a given type.
42
+
43
+ For example:
44
+
45
+ class MyParams(TypedDict):
46
+ account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')]
47
+
48
+ This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API.
49
+ """
50
+
51
+ alias: str | None
52
+ format: PropertyFormat | None
53
+ format_template: str | None
54
+ discriminator: str | None
55
+
56
+ def __init__(
57
+ self,
58
+ *,
59
+ alias: str | None = None,
60
+ format: PropertyFormat | None = None,
61
+ format_template: str | None = None,
62
+ discriminator: str | None = None,
63
+ ) -> None:
64
+ self.alias = alias
65
+ self.format = format
66
+ self.format_template = format_template
67
+ self.discriminator = discriminator
68
+
69
+ @override
70
+ def __repr__(self) -> str:
71
+ return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}', discriminator='{self.discriminator}')"
72
+
73
+
74
+ def maybe_transform(
75
+ data: object,
76
+ expected_type: object,
77
+ ) -> Any | None:
78
+ """Wrapper over `transform()` that allows `None` to be passed.
79
+
80
+ See `transform()` for more details.
81
+ """
82
+ if data is None:
83
+ return None
84
+ return transform(data, expected_type)
85
+
86
+
87
+ # Wrapper over _transform_recursive providing fake types
88
+ def transform(
89
+ data: _T,
90
+ expected_type: object,
91
+ ) -> _T:
92
+ """Transform dictionaries based off of type information from the given type, for example:
93
+
94
+ ```py
95
+ class Params(TypedDict, total=False):
96
+ card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
97
+
98
+
99
+ transformed = transform({"card_id": "<my card ID>"}, Params)
100
+ # {'cardID': '<my card ID>'}
101
+ ```
102
+
103
+ Any keys / data that does not have type information given will be included as is.
104
+
105
+ It should be noted that the transformations that this function does are not represented in the type system.
106
+ """
107
+ transformed = _transform_recursive(data, annotation=cast(type, expected_type))
108
+ return cast(_T, transformed)
109
+
110
+
111
+ def _get_annotated_type(type_: type) -> type | None:
112
+ """If the given type is an `Annotated` type then it is returned, if not `None` is returned.
113
+
114
+ This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]`
115
+ """
116
+ if is_required_type(type_):
117
+ # Unwrap `Required[Annotated[T, ...]]` to `Annotated[T, ...]`
118
+ type_ = get_args(type_)[0]
119
+
120
+ if is_annotated_type(type_):
121
+ return type_
122
+
123
+ return None
124
+
125
+
126
+ def _maybe_transform_key(key: str, type_: type) -> str:
127
+ """Transform the given `data` based on the annotations provided in `type_`.
128
+
129
+ Note: this function only looks at `Annotated` types that contain `PropertInfo` metadata.
130
+ """
131
+ annotated_type = _get_annotated_type(type_)
132
+ if annotated_type is None:
133
+ # no `Annotated` definition for this type, no transformation needed
134
+ return key
135
+
136
+ # ignore the first argument as it is the actual type
137
+ annotations = get_args(annotated_type)[1:]
138
+ for annotation in annotations:
139
+ if isinstance(annotation, PropertyInfo) and annotation.alias is not None:
140
+ return annotation.alias
141
+
142
+ return key
143
+
144
+
145
+ def _transform_recursive(
146
+ data: object,
147
+ *,
148
+ annotation: type,
149
+ inner_type: type | None = None,
150
+ ) -> object:
151
+ """Transform the given data against the expected type.
152
+
153
+ Args:
154
+ annotation: The direct type annotation given to the particular piece of data.
155
+ This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
156
+
157
+ inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
158
+ is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
159
+ the list can be transformed using the metadata from the container type.
160
+
161
+ Defaults to the same value as the `annotation` argument.
162
+ """
163
+ if inner_type is None:
164
+ inner_type = annotation
165
+
166
+ stripped_type = strip_annotated_type(inner_type)
167
+ if is_typeddict(stripped_type) and is_mapping(data):
168
+ return _transform_typeddict(data, stripped_type)
169
+
170
+ if (
171
+ # List[T]
172
+ (is_list_type(stripped_type) and is_list(data))
173
+ # Iterable[T]
174
+ or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
175
+ ):
176
+ # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
177
+ # intended as an iterable, so we don't transform it.
178
+ if isinstance(data, dict):
179
+ return cast(object, data)
180
+
181
+ inner_type = extract_type_arg(stripped_type, 0)
182
+ return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
183
+
184
+ if is_union_type(stripped_type):
185
+ # For union types we run the transformation against all subtypes to ensure that everything is transformed.
186
+ #
187
+ # TODO: there may be edge cases where the same normalized field name will transform to two different names
188
+ # in different subtypes.
189
+ for subtype in get_args(stripped_type):
190
+ data = _transform_recursive(data, annotation=annotation, inner_type=subtype)
191
+ return data
192
+
193
+ if isinstance(data, pydantic.BaseModel):
194
+ return model_dump(data, exclude_unset=True, mode="json")
195
+
196
+ annotated_type = _get_annotated_type(annotation)
197
+ if annotated_type is None:
198
+ return data
199
+
200
+ # ignore the first argument as it is the actual type
201
+ annotations = get_args(annotated_type)[1:]
202
+ for annotation in annotations:
203
+ if isinstance(annotation, PropertyInfo) and annotation.format is not None:
204
+ return _format_data(data, annotation.format, annotation.format_template)
205
+
206
+ return data
207
+
208
+
209
+ def _format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
210
+ if isinstance(data, (date, datetime)):
211
+ if format_ == "iso8601":
212
+ return data.isoformat()
213
+
214
+ if format_ == "custom" and format_template is not None:
215
+ return data.strftime(format_template)
216
+
217
+ if format_ == "base64" and is_base64_file_input(data):
218
+ binary: str | bytes | None = None
219
+
220
+ if isinstance(data, pathlib.Path):
221
+ binary = data.read_bytes()
222
+ elif isinstance(data, io.IOBase):
223
+ binary = data.read()
224
+
225
+ if isinstance(binary, str): # type: ignore[unreachable]
226
+ binary = binary.encode()
227
+
228
+ if not isinstance(binary, bytes):
229
+ raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
230
+
231
+ return base64.b64encode(binary).decode("ascii")
232
+
233
+ return data
234
+
235
+
236
+ def _transform_typeddict(
237
+ data: Mapping[str, object],
238
+ expected_type: type,
239
+ ) -> Mapping[str, object]:
240
+ result: dict[str, object] = {}
241
+ annotations = get_type_hints(expected_type, include_extras=True)
242
+ for key, value in data.items():
243
+ type_ = annotations.get(key)
244
+ if type_ is None:
245
+ # we do not have a type annotation for this field, leave it as is
246
+ result[key] = value
247
+ else:
248
+ result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_)
249
+ return result
250
+
251
+
252
+ async def async_maybe_transform(
253
+ data: object,
254
+ expected_type: object,
255
+ ) -> Any | None:
256
+ """Wrapper over `async_transform()` that allows `None` to be passed.
257
+
258
+ See `async_transform()` for more details.
259
+ """
260
+ if data is None:
261
+ return None
262
+ return await async_transform(data, expected_type)
263
+
264
+
265
+ async def async_transform(
266
+ data: _T,
267
+ expected_type: object,
268
+ ) -> _T:
269
+ """Transform dictionaries based off of type information from the given type, for example:
270
+
271
+ ```py
272
+ class Params(TypedDict, total=False):
273
+ card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
274
+
275
+
276
+ transformed = transform({"card_id": "<my card ID>"}, Params)
277
+ # {'cardID': '<my card ID>'}
278
+ ```
279
+
280
+ Any keys / data that does not have type information given will be included as is.
281
+
282
+ It should be noted that the transformations that this function does are not represented in the type system.
283
+ """
284
+ transformed = await _async_transform_recursive(data, annotation=cast(type, expected_type))
285
+ return cast(_T, transformed)
286
+
287
+
288
+ async def _async_transform_recursive(
289
+ data: object,
290
+ *,
291
+ annotation: type,
292
+ inner_type: type | None = None,
293
+ ) -> object:
294
+ """Transform the given data against the expected type.
295
+
296
+ Args:
297
+ annotation: The direct type annotation given to the particular piece of data.
298
+ This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
299
+
300
+ inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
301
+ is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
302
+ the list can be transformed using the metadata from the container type.
303
+
304
+ Defaults to the same value as the `annotation` argument.
305
+ """
306
+ if inner_type is None:
307
+ inner_type = annotation
308
+
309
+ stripped_type = strip_annotated_type(inner_type)
310
+ if is_typeddict(stripped_type) and is_mapping(data):
311
+ return await _async_transform_typeddict(data, stripped_type)
312
+
313
+ if (
314
+ # List[T]
315
+ (is_list_type(stripped_type) and is_list(data))
316
+ # Iterable[T]
317
+ or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
318
+ ):
319
+ # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
320
+ # intended as an iterable, so we don't transform it.
321
+ if isinstance(data, dict):
322
+ return cast(object, data)
323
+
324
+ inner_type = extract_type_arg(stripped_type, 0)
325
+ return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
326
+
327
+ if is_union_type(stripped_type):
328
+ # For union types we run the transformation against all subtypes to ensure that everything is transformed.
329
+ #
330
+ # TODO: there may be edge cases where the same normalized field name will transform to two different names
331
+ # in different subtypes.
332
+ for subtype in get_args(stripped_type):
333
+ data = await _async_transform_recursive(data, annotation=annotation, inner_type=subtype)
334
+ return data
335
+
336
+ if isinstance(data, pydantic.BaseModel):
337
+ return model_dump(data, exclude_unset=True, mode="json")
338
+
339
+ annotated_type = _get_annotated_type(annotation)
340
+ if annotated_type is None:
341
+ return data
342
+
343
+ # ignore the first argument as it is the actual type
344
+ annotations = get_args(annotated_type)[1:]
345
+ for annotation in annotations:
346
+ if isinstance(annotation, PropertyInfo) and annotation.format is not None:
347
+ return await _async_format_data(data, annotation.format, annotation.format_template)
348
+
349
+ return data
350
+
351
+
352
+ async def _async_format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
353
+ if isinstance(data, (date, datetime)):
354
+ if format_ == "iso8601":
355
+ return data.isoformat()
356
+
357
+ if format_ == "custom" and format_template is not None:
358
+ return data.strftime(format_template)
359
+
360
+ if format_ == "base64" and is_base64_file_input(data):
361
+ binary: str | bytes | None = None
362
+
363
+ if isinstance(data, pathlib.Path):
364
+ binary = await anyio.Path(data).read_bytes()
365
+ elif isinstance(data, io.IOBase):
366
+ binary = data.read()
367
+
368
+ if isinstance(binary, str): # type: ignore[unreachable]
369
+ binary = binary.encode()
370
+
371
+ if not isinstance(binary, bytes):
372
+ raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
373
+
374
+ return base64.b64encode(binary).decode("ascii")
375
+
376
+ return data
377
+
378
+
379
+ async def _async_transform_typeddict(
380
+ data: Mapping[str, object],
381
+ expected_type: type,
382
+ ) -> Mapping[str, object]:
383
+ result: dict[str, object] = {}
384
+ annotations = get_type_hints(expected_type, include_extras=True)
385
+ for key, value in data.items():
386
+ type_ = annotations.get(key)
387
+ if type_ is None:
388
+ # we do not have a type annotation for this field, leave it as is
389
+ result[key] = value
390
+ else:
391
+ result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(value, annotation=type_)
392
+ return result
vllm/lib/python3.10/site-packages/openai/_utils/_typing.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import typing
5
+ import typing_extensions
6
+ from typing import Any, TypeVar, Iterable, cast
7
+ from collections import abc as _c_abc
8
+ from typing_extensions import (
9
+ TypeIs,
10
+ Required,
11
+ Annotated,
12
+ get_args,
13
+ get_origin,
14
+ )
15
+
16
+ from .._types import InheritsGeneric
17
+ from .._compat import is_union as _is_union
18
+
19
+
20
+ def is_annotated_type(typ: type) -> bool:
21
+ return get_origin(typ) == Annotated
22
+
23
+
24
+ def is_list_type(typ: type) -> bool:
25
+ return (get_origin(typ) or typ) == list
26
+
27
+
28
+ def is_iterable_type(typ: type) -> bool:
29
+ """If the given type is `typing.Iterable[T]`"""
30
+ origin = get_origin(typ) or typ
31
+ return origin == Iterable or origin == _c_abc.Iterable
32
+
33
+
34
+ def is_union_type(typ: type) -> bool:
35
+ return _is_union(get_origin(typ))
36
+
37
+
38
+ def is_required_type(typ: type) -> bool:
39
+ return get_origin(typ) == Required
40
+
41
+
42
+ def is_typevar(typ: type) -> bool:
43
+ # type ignore is required because type checkers
44
+ # think this expression will always return False
45
+ return type(typ) == TypeVar # type: ignore
46
+
47
+
48
+ _TYPE_ALIAS_TYPES: tuple[type[typing_extensions.TypeAliasType], ...] = (typing_extensions.TypeAliasType,)
49
+ if sys.version_info >= (3, 12):
50
+ _TYPE_ALIAS_TYPES = (*_TYPE_ALIAS_TYPES, typing.TypeAliasType)
51
+
52
+
53
+ def is_type_alias_type(tp: Any, /) -> TypeIs[typing_extensions.TypeAliasType]:
54
+ """Return whether the provided argument is an instance of `TypeAliasType`.
55
+
56
+ ```python
57
+ type Int = int
58
+ is_type_alias_type(Int)
59
+ # > True
60
+ Str = TypeAliasType("Str", str)
61
+ is_type_alias_type(Str)
62
+ # > True
63
+ ```
64
+ """
65
+ return isinstance(tp, _TYPE_ALIAS_TYPES)
66
+
67
+
68
+ # Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]]
69
+ def strip_annotated_type(typ: type) -> type:
70
+ if is_required_type(typ) or is_annotated_type(typ):
71
+ return strip_annotated_type(cast(type, get_args(typ)[0]))
72
+
73
+ return typ
74
+
75
+
76
+ def extract_type_arg(typ: type, index: int) -> type:
77
+ args = get_args(typ)
78
+ try:
79
+ return cast(type, args[index])
80
+ except IndexError as err:
81
+ raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err
82
+
83
+
84
+ def extract_type_var_from_base(
85
+ typ: type,
86
+ *,
87
+ generic_bases: tuple[type, ...],
88
+ index: int,
89
+ failure_message: str | None = None,
90
+ ) -> type:
91
+ """Given a type like `Foo[T]`, returns the generic type variable `T`.
92
+
93
+ This also handles the case where a concrete subclass is given, e.g.
94
+ ```py
95
+ class MyResponse(Foo[bytes]):
96
+ ...
97
+
98
+ extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes
99
+ ```
100
+
101
+ And where a generic subclass is given:
102
+ ```py
103
+ _T = TypeVar('_T')
104
+ class MyResponse(Foo[_T]):
105
+ ...
106
+
107
+ extract_type_var(MyResponse[bytes], bases=(Foo,), index=0) -> bytes
108
+ ```
109
+ """
110
+ cls = cast(object, get_origin(typ) or typ)
111
+ if cls in generic_bases:
112
+ # we're given the class directly
113
+ return extract_type_arg(typ, index)
114
+
115
+ # if a subclass is given
116
+ # ---
117
+ # this is needed as __orig_bases__ is not present in the typeshed stubs
118
+ # because it is intended to be for internal use only, however there does
119
+ # not seem to be a way to resolve generic TypeVars for inherited subclasses
120
+ # without using it.
121
+ if isinstance(cls, InheritsGeneric):
122
+ target_base_class: Any | None = None
123
+ for base in cls.__orig_bases__:
124
+ if base.__origin__ in generic_bases:
125
+ target_base_class = base
126
+ break
127
+
128
+ if target_base_class is None:
129
+ raise RuntimeError(
130
+ "Could not find the generic base class;\n"
131
+ "This should never happen;\n"
132
+ f"Does {cls} inherit from one of {generic_bases} ?"
133
+ )
134
+
135
+ extracted = extract_type_arg(target_base_class, index)
136
+ if is_typevar(extracted):
137
+ # If the extracted type argument is itself a type variable
138
+ # then that means the subclass itself is generic, so we have
139
+ # to resolve the type argument from the class itself, not
140
+ # the base class.
141
+ #
142
+ # Note: if there is more than 1 type argument, the subclass could
143
+ # change the ordering of the type arguments, this is not currently
144
+ # supported.
145
+ return extract_type_arg(typ, index)
146
+
147
+ return extracted
148
+
149
+ raise RuntimeError(failure_message or f"Could not resolve inner type variable at index {index} for {typ}")
vllm/lib/python3.10/site-packages/openai/_utils/_utils.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import re
5
+ import inspect
6
+ import functools
7
+ from typing import (
8
+ Any,
9
+ Tuple,
10
+ Mapping,
11
+ TypeVar,
12
+ Callable,
13
+ Iterable,
14
+ Sequence,
15
+ cast,
16
+ overload,
17
+ )
18
+ from pathlib import Path
19
+ from datetime import date, datetime
20
+ from typing_extensions import TypeGuard
21
+
22
+ import sniffio
23
+
24
+ from .._types import NotGiven, FileTypes, NotGivenOr, HeadersLike
25
+ from .._compat import parse_date as parse_date, parse_datetime as parse_datetime
26
+
27
+ _T = TypeVar("_T")
28
+ _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...])
29
+ _MappingT = TypeVar("_MappingT", bound=Mapping[str, object])
30
+ _SequenceT = TypeVar("_SequenceT", bound=Sequence[object])
31
+ CallableT = TypeVar("CallableT", bound=Callable[..., Any])
32
+
33
+
34
+ def flatten(t: Iterable[Iterable[_T]]) -> list[_T]:
35
+ return [item for sublist in t for item in sublist]
36
+
37
+
38
+ def extract_files(
39
+ # TODO: this needs to take Dict but variance issues.....
40
+ # create protocol type ?
41
+ query: Mapping[str, object],
42
+ *,
43
+ paths: Sequence[Sequence[str]],
44
+ ) -> list[tuple[str, FileTypes]]:
45
+ """Recursively extract files from the given dictionary based on specified paths.
46
+
47
+ A path may look like this ['foo', 'files', '<array>', 'data'].
48
+
49
+ Note: this mutates the given dictionary.
50
+ """
51
+ files: list[tuple[str, FileTypes]] = []
52
+ for path in paths:
53
+ files.extend(_extract_items(query, path, index=0, flattened_key=None))
54
+ return files
55
+
56
+
57
+ def _extract_items(
58
+ obj: object,
59
+ path: Sequence[str],
60
+ *,
61
+ index: int,
62
+ flattened_key: str | None,
63
+ ) -> list[tuple[str, FileTypes]]:
64
+ try:
65
+ key = path[index]
66
+ except IndexError:
67
+ if isinstance(obj, NotGiven):
68
+ # no value was provided - we can safely ignore
69
+ return []
70
+
71
+ # cyclical import
72
+ from .._files import assert_is_file_content
73
+
74
+ # We have exhausted the path, return the entry we found.
75
+ assert_is_file_content(obj, key=flattened_key)
76
+ assert flattened_key is not None
77
+ return [(flattened_key, cast(FileTypes, obj))]
78
+
79
+ index += 1
80
+ if is_dict(obj):
81
+ try:
82
+ # We are at the last entry in the path so we must remove the field
83
+ if (len(path)) == index:
84
+ item = obj.pop(key)
85
+ else:
86
+ item = obj[key]
87
+ except KeyError:
88
+ # Key was not present in the dictionary, this is not indicative of an error
89
+ # as the given path may not point to a required field. We also do not want
90
+ # to enforce required fields as the API may differ from the spec in some cases.
91
+ return []
92
+ if flattened_key is None:
93
+ flattened_key = key
94
+ else:
95
+ flattened_key += f"[{key}]"
96
+ return _extract_items(
97
+ item,
98
+ path,
99
+ index=index,
100
+ flattened_key=flattened_key,
101
+ )
102
+ elif is_list(obj):
103
+ if key != "<array>":
104
+ return []
105
+
106
+ return flatten(
107
+ [
108
+ _extract_items(
109
+ item,
110
+ path,
111
+ index=index,
112
+ flattened_key=flattened_key + "[]" if flattened_key is not None else "[]",
113
+ )
114
+ for item in obj
115
+ ]
116
+ )
117
+
118
+ # Something unexpected was passed, just ignore it.
119
+ return []
120
+
121
+
122
+ def is_given(obj: NotGivenOr[_T]) -> TypeGuard[_T]:
123
+ return not isinstance(obj, NotGiven)
124
+
125
+
126
+ # Type safe methods for narrowing types with TypeVars.
127
+ # The default narrowing for isinstance(obj, dict) is dict[unknown, unknown],
128
+ # however this cause Pyright to rightfully report errors. As we know we don't
129
+ # care about the contained types we can safely use `object` in it's place.
130
+ #
131
+ # There are two separate functions defined, `is_*` and `is_*_t` for different use cases.
132
+ # `is_*` is for when you're dealing with an unknown input
133
+ # `is_*_t` is for when you're narrowing a known union type to a specific subset
134
+
135
+
136
+ def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]:
137
+ return isinstance(obj, tuple)
138
+
139
+
140
+ def is_tuple_t(obj: _TupleT | object) -> TypeGuard[_TupleT]:
141
+ return isinstance(obj, tuple)
142
+
143
+
144
+ def is_sequence(obj: object) -> TypeGuard[Sequence[object]]:
145
+ return isinstance(obj, Sequence)
146
+
147
+
148
+ def is_sequence_t(obj: _SequenceT | object) -> TypeGuard[_SequenceT]:
149
+ return isinstance(obj, Sequence)
150
+
151
+
152
+ def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]:
153
+ return isinstance(obj, Mapping)
154
+
155
+
156
+ def is_mapping_t(obj: _MappingT | object) -> TypeGuard[_MappingT]:
157
+ return isinstance(obj, Mapping)
158
+
159
+
160
+ def is_dict(obj: object) -> TypeGuard[dict[object, object]]:
161
+ return isinstance(obj, dict)
162
+
163
+
164
+ def is_list(obj: object) -> TypeGuard[list[object]]:
165
+ return isinstance(obj, list)
166
+
167
+
168
+ def is_iterable(obj: object) -> TypeGuard[Iterable[object]]:
169
+ return isinstance(obj, Iterable)
170
+
171
+
172
+ def deepcopy_minimal(item: _T) -> _T:
173
+ """Minimal reimplementation of copy.deepcopy() that will only copy certain object types:
174
+
175
+ - mappings, e.g. `dict`
176
+ - list
177
+
178
+ This is done for performance reasons.
179
+ """
180
+ if is_mapping(item):
181
+ return cast(_T, {k: deepcopy_minimal(v) for k, v in item.items()})
182
+ if is_list(item):
183
+ return cast(_T, [deepcopy_minimal(entry) for entry in item])
184
+ return item
185
+
186
+
187
+ # copied from https://github.com/Rapptz/RoboDanny
188
+ def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str:
189
+ size = len(seq)
190
+ if size == 0:
191
+ return ""
192
+
193
+ if size == 1:
194
+ return seq[0]
195
+
196
+ if size == 2:
197
+ return f"{seq[0]} {final} {seq[1]}"
198
+
199
+ return delim.join(seq[:-1]) + f" {final} {seq[-1]}"
200
+
201
+
202
+ def quote(string: str) -> str:
203
+ """Add single quotation marks around the given string. Does *not* do any escaping."""
204
+ return f"'{string}'"
205
+
206
+
207
+ def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]:
208
+ """Decorator to enforce a given set of arguments or variants of arguments are passed to the decorated function.
209
+
210
+ Useful for enforcing runtime validation of overloaded functions.
211
+
212
+ Example usage:
213
+ ```py
214
+ @overload
215
+ def foo(*, a: str) -> str: ...
216
+
217
+
218
+ @overload
219
+ def foo(*, b: bool) -> str: ...
220
+
221
+
222
+ # This enforces the same constraints that a static type checker would
223
+ # i.e. that either a or b must be passed to the function
224
+ @required_args(["a"], ["b"])
225
+ def foo(*, a: str | None = None, b: bool | None = None) -> str: ...
226
+ ```
227
+ """
228
+
229
+ def inner(func: CallableT) -> CallableT:
230
+ params = inspect.signature(func).parameters
231
+ positional = [
232
+ name
233
+ for name, param in params.items()
234
+ if param.kind
235
+ in {
236
+ param.POSITIONAL_ONLY,
237
+ param.POSITIONAL_OR_KEYWORD,
238
+ }
239
+ ]
240
+
241
+ @functools.wraps(func)
242
+ def wrapper(*args: object, **kwargs: object) -> object:
243
+ given_params: set[str] = set()
244
+ for i, _ in enumerate(args):
245
+ try:
246
+ given_params.add(positional[i])
247
+ except IndexError:
248
+ raise TypeError(
249
+ f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given"
250
+ ) from None
251
+
252
+ for key in kwargs.keys():
253
+ given_params.add(key)
254
+
255
+ for variant in variants:
256
+ matches = all((param in given_params for param in variant))
257
+ if matches:
258
+ break
259
+ else: # no break
260
+ if len(variants) > 1:
261
+ variations = human_join(
262
+ ["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants]
263
+ )
264
+ msg = f"Missing required arguments; Expected either {variations} arguments to be given"
265
+ else:
266
+ assert len(variants) > 0
267
+
268
+ # TODO: this error message is not deterministic
269
+ missing = list(set(variants[0]) - given_params)
270
+ if len(missing) > 1:
271
+ msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}"
272
+ else:
273
+ msg = f"Missing required argument: {quote(missing[0])}"
274
+ raise TypeError(msg)
275
+ return func(*args, **kwargs)
276
+
277
+ return wrapper # type: ignore
278
+
279
+ return inner
280
+
281
+
282
+ _K = TypeVar("_K")
283
+ _V = TypeVar("_V")
284
+
285
+
286
+ @overload
287
+ def strip_not_given(obj: None) -> None: ...
288
+
289
+
290
+ @overload
291
+ def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]: ...
292
+
293
+
294
+ @overload
295
+ def strip_not_given(obj: object) -> object: ...
296
+
297
+
298
+ def strip_not_given(obj: object | None) -> object:
299
+ """Remove all top-level keys where their values are instances of `NotGiven`"""
300
+ if obj is None:
301
+ return None
302
+
303
+ if not is_mapping(obj):
304
+ return obj
305
+
306
+ return {key: value for key, value in obj.items() if not isinstance(value, NotGiven)}
307
+
308
+
309
+ def coerce_integer(val: str) -> int:
310
+ return int(val, base=10)
311
+
312
+
313
+ def coerce_float(val: str) -> float:
314
+ return float(val)
315
+
316
+
317
+ def coerce_boolean(val: str) -> bool:
318
+ return val == "true" or val == "1" or val == "on"
319
+
320
+
321
+ def maybe_coerce_integer(val: str | None) -> int | None:
322
+ if val is None:
323
+ return None
324
+ return coerce_integer(val)
325
+
326
+
327
+ def maybe_coerce_float(val: str | None) -> float | None:
328
+ if val is None:
329
+ return None
330
+ return coerce_float(val)
331
+
332
+
333
+ def maybe_coerce_boolean(val: str | None) -> bool | None:
334
+ if val is None:
335
+ return None
336
+ return coerce_boolean(val)
337
+
338
+
339
+ def removeprefix(string: str, prefix: str) -> str:
340
+ """Remove a prefix from a string.
341
+
342
+ Backport of `str.removeprefix` for Python < 3.9
343
+ """
344
+ if string.startswith(prefix):
345
+ return string[len(prefix) :]
346
+ return string
347
+
348
+
349
+ def removesuffix(string: str, suffix: str) -> str:
350
+ """Remove a suffix from a string.
351
+
352
+ Backport of `str.removesuffix` for Python < 3.9
353
+ """
354
+ if string.endswith(suffix):
355
+ return string[: -len(suffix)]
356
+ return string
357
+
358
+
359
+ def file_from_path(path: str) -> FileTypes:
360
+ contents = Path(path).read_bytes()
361
+ file_name = os.path.basename(path)
362
+ return (file_name, contents)
363
+
364
+
365
+ def get_required_header(headers: HeadersLike, header: str) -> str:
366
+ lower_header = header.lower()
367
+ if is_mapping_t(headers):
368
+ # mypy doesn't understand the type narrowing here
369
+ for k, v in headers.items(): # type: ignore
370
+ if k.lower() == lower_header and isinstance(v, str):
371
+ return v
372
+
373
+ # to deal with the case where the header looks like Stainless-Event-Id
374
+ intercaps_header = re.sub(r"([^\w])(\w)", lambda pat: pat.group(1) + pat.group(2).upper(), header.capitalize())
375
+
376
+ for normalized_header in [header, lower_header, header.upper(), intercaps_header]:
377
+ value = headers.get(normalized_header)
378
+ if value:
379
+ return value
380
+
381
+ raise ValueError(f"Could not find {header} header")
382
+
383
+
384
+ def get_async_library() -> str:
385
+ try:
386
+ return sniffio.current_async_library()
387
+ except Exception:
388
+ return "false"
389
+
390
+
391
+ def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]:
392
+ """A version of functools.lru_cache that retains the type signature
393
+ for the wrapped function arguments.
394
+ """
395
+ wrapper = functools.lru_cache( # noqa: TID251
396
+ maxsize=maxsize,
397
+ )
398
+ return cast(Any, wrapper) # type: ignore[no-any-return]
399
+
400
+
401
+ def json_safe(data: object) -> object:
402
+ """Translates a mapping / sequence recursively in the same fashion
403
+ as `pydantic` v2's `model_dump(mode="json")`.
404
+ """
405
+ if is_mapping(data):
406
+ return {json_safe(key): json_safe(value) for key, value in data.items()}
407
+
408
+ if is_iterable(data) and not isinstance(data, (str, bytes, bytearray)):
409
+ return [json_safe(item) for item in data]
410
+
411
+ if isinstance(data, (datetime, date)):
412
+ return data.isoformat()
413
+
414
+ return data
vllm/lib/python3.10/site-packages/openai/_version.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ __title__ = "openai"
4
+ __version__ = "1.57.4" # x-release-please-version
vllm/lib/python3.10/site-packages/openai/resources/__init__.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from .beta import (
4
+ Beta,
5
+ AsyncBeta,
6
+ BetaWithRawResponse,
7
+ AsyncBetaWithRawResponse,
8
+ BetaWithStreamingResponse,
9
+ AsyncBetaWithStreamingResponse,
10
+ )
11
+ from .chat import (
12
+ Chat,
13
+ AsyncChat,
14
+ ChatWithRawResponse,
15
+ AsyncChatWithRawResponse,
16
+ ChatWithStreamingResponse,
17
+ AsyncChatWithStreamingResponse,
18
+ )
19
+ from .audio import (
20
+ Audio,
21
+ AsyncAudio,
22
+ AudioWithRawResponse,
23
+ AsyncAudioWithRawResponse,
24
+ AudioWithStreamingResponse,
25
+ AsyncAudioWithStreamingResponse,
26
+ )
27
+ from .files import (
28
+ Files,
29
+ AsyncFiles,
30
+ FilesWithRawResponse,
31
+ AsyncFilesWithRawResponse,
32
+ FilesWithStreamingResponse,
33
+ AsyncFilesWithStreamingResponse,
34
+ )
35
+ from .images import (
36
+ Images,
37
+ AsyncImages,
38
+ ImagesWithRawResponse,
39
+ AsyncImagesWithRawResponse,
40
+ ImagesWithStreamingResponse,
41
+ AsyncImagesWithStreamingResponse,
42
+ )
43
+ from .models import (
44
+ Models,
45
+ AsyncModels,
46
+ ModelsWithRawResponse,
47
+ AsyncModelsWithRawResponse,
48
+ ModelsWithStreamingResponse,
49
+ AsyncModelsWithStreamingResponse,
50
+ )
51
+ from .batches import (
52
+ Batches,
53
+ AsyncBatches,
54
+ BatchesWithRawResponse,
55
+ AsyncBatchesWithRawResponse,
56
+ BatchesWithStreamingResponse,
57
+ AsyncBatchesWithStreamingResponse,
58
+ )
59
+ from .uploads import (
60
+ Uploads,
61
+ AsyncUploads,
62
+ UploadsWithRawResponse,
63
+ AsyncUploadsWithRawResponse,
64
+ UploadsWithStreamingResponse,
65
+ AsyncUploadsWithStreamingResponse,
66
+ )
67
+ from .embeddings import (
68
+ Embeddings,
69
+ AsyncEmbeddings,
70
+ EmbeddingsWithRawResponse,
71
+ AsyncEmbeddingsWithRawResponse,
72
+ EmbeddingsWithStreamingResponse,
73
+ AsyncEmbeddingsWithStreamingResponse,
74
+ )
75
+ from .completions import (
76
+ Completions,
77
+ AsyncCompletions,
78
+ CompletionsWithRawResponse,
79
+ AsyncCompletionsWithRawResponse,
80
+ CompletionsWithStreamingResponse,
81
+ AsyncCompletionsWithStreamingResponse,
82
+ )
83
+ from .fine_tuning import (
84
+ FineTuning,
85
+ AsyncFineTuning,
86
+ FineTuningWithRawResponse,
87
+ AsyncFineTuningWithRawResponse,
88
+ FineTuningWithStreamingResponse,
89
+ AsyncFineTuningWithStreamingResponse,
90
+ )
91
+ from .moderations import (
92
+ Moderations,
93
+ AsyncModerations,
94
+ ModerationsWithRawResponse,
95
+ AsyncModerationsWithRawResponse,
96
+ ModerationsWithStreamingResponse,
97
+ AsyncModerationsWithStreamingResponse,
98
+ )
99
+
100
+ __all__ = [
101
+ "Completions",
102
+ "AsyncCompletions",
103
+ "CompletionsWithRawResponse",
104
+ "AsyncCompletionsWithRawResponse",
105
+ "CompletionsWithStreamingResponse",
106
+ "AsyncCompletionsWithStreamingResponse",
107
+ "Chat",
108
+ "AsyncChat",
109
+ "ChatWithRawResponse",
110
+ "AsyncChatWithRawResponse",
111
+ "ChatWithStreamingResponse",
112
+ "AsyncChatWithStreamingResponse",
113
+ "Embeddings",
114
+ "AsyncEmbeddings",
115
+ "EmbeddingsWithRawResponse",
116
+ "AsyncEmbeddingsWithRawResponse",
117
+ "EmbeddingsWithStreamingResponse",
118
+ "AsyncEmbeddingsWithStreamingResponse",
119
+ "Files",
120
+ "AsyncFiles",
121
+ "FilesWithRawResponse",
122
+ "AsyncFilesWithRawResponse",
123
+ "FilesWithStreamingResponse",
124
+ "AsyncFilesWithStreamingResponse",
125
+ "Images",
126
+ "AsyncImages",
127
+ "ImagesWithRawResponse",
128
+ "AsyncImagesWithRawResponse",
129
+ "ImagesWithStreamingResponse",
130
+ "AsyncImagesWithStreamingResponse",
131
+ "Audio",
132
+ "AsyncAudio",
133
+ "AudioWithRawResponse",
134
+ "AsyncAudioWithRawResponse",
135
+ "AudioWithStreamingResponse",
136
+ "AsyncAudioWithStreamingResponse",
137
+ "Moderations",
138
+ "AsyncModerations",
139
+ "ModerationsWithRawResponse",
140
+ "AsyncModerationsWithRawResponse",
141
+ "ModerationsWithStreamingResponse",
142
+ "AsyncModerationsWithStreamingResponse",
143
+ "Models",
144
+ "AsyncModels",
145
+ "ModelsWithRawResponse",
146
+ "AsyncModelsWithRawResponse",
147
+ "ModelsWithStreamingResponse",
148
+ "AsyncModelsWithStreamingResponse",
149
+ "FineTuning",
150
+ "AsyncFineTuning",
151
+ "FineTuningWithRawResponse",
152
+ "AsyncFineTuningWithRawResponse",
153
+ "FineTuningWithStreamingResponse",
154
+ "AsyncFineTuningWithStreamingResponse",
155
+ "Beta",
156
+ "AsyncBeta",
157
+ "BetaWithRawResponse",
158
+ "AsyncBetaWithRawResponse",
159
+ "BetaWithStreamingResponse",
160
+ "AsyncBetaWithStreamingResponse",
161
+ "Batches",
162
+ "AsyncBatches",
163
+ "BatchesWithRawResponse",
164
+ "AsyncBatchesWithRawResponse",
165
+ "BatchesWithStreamingResponse",
166
+ "AsyncBatchesWithStreamingResponse",
167
+ "Uploads",
168
+ "AsyncUploads",
169
+ "UploadsWithRawResponse",
170
+ "AsyncUploadsWithRawResponse",
171
+ "UploadsWithStreamingResponse",
172
+ "AsyncUploadsWithStreamingResponse",
173
+ ]
vllm/lib/python3.10/site-packages/openai/resources/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.15 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/__pycache__/batches.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/__pycache__/completions.cpython-310.pyc ADDED
Binary file (22.4 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/__pycache__/embeddings.cpython-310.pyc ADDED
Binary file (7.58 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/__pycache__/files.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/__pycache__/images.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/__pycache__/models.cpython-310.pyc ADDED
Binary file (6.42 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/__pycache__/moderations.cpython-310.pyc ADDED
Binary file (5.86 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/batches.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Dict, Optional
6
+ from typing_extensions import Literal
7
+
8
+ import httpx
9
+
10
+ from .. import _legacy_response
11
+ from ..types import batch_list_params, batch_create_params
12
+ from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
13
+ from .._utils import (
14
+ maybe_transform,
15
+ async_maybe_transform,
16
+ )
17
+ from .._compat import cached_property
18
+ from .._resource import SyncAPIResource, AsyncAPIResource
19
+ from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
20
+ from ..pagination import SyncCursorPage, AsyncCursorPage
21
+ from ..types.batch import Batch
22
+ from .._base_client import (
23
+ AsyncPaginator,
24
+ make_request_options,
25
+ )
26
+
27
+ __all__ = ["Batches", "AsyncBatches"]
28
+
29
+
30
+ class Batches(SyncAPIResource):
31
+ @cached_property
32
+ def with_raw_response(self) -> BatchesWithRawResponse:
33
+ """
34
+ This property can be used as a prefix for any HTTP method call to return the
35
+ the raw response object instead of the parsed content.
36
+
37
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
38
+ """
39
+ return BatchesWithRawResponse(self)
40
+
41
+ @cached_property
42
+ def with_streaming_response(self) -> BatchesWithStreamingResponse:
43
+ """
44
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
45
+
46
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
47
+ """
48
+ return BatchesWithStreamingResponse(self)
49
+
50
+ def create(
51
+ self,
52
+ *,
53
+ completion_window: Literal["24h"],
54
+ endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
55
+ input_file_id: str,
56
+ metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN,
57
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
58
+ # The extra values given here take precedence over values defined on the client or passed to this method.
59
+ extra_headers: Headers | None = None,
60
+ extra_query: Query | None = None,
61
+ extra_body: Body | None = None,
62
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
63
+ ) -> Batch:
64
+ """
65
+ Creates and executes a batch from an uploaded file of requests
66
+
67
+ Args:
68
+ completion_window: The time frame within which the batch should be processed. Currently only `24h`
69
+ is supported.
70
+
71
+ endpoint: The endpoint to be used for all requests in the batch. Currently
72
+ `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported.
73
+ Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000
74
+ embedding inputs across all requests in the batch.
75
+
76
+ input_file_id: The ID of an uploaded file that contains requests for the new batch.
77
+
78
+ See [upload file](https://platform.openai.com/docs/api-reference/files/create)
79
+ for how to upload a file.
80
+
81
+ Your input file must be formatted as a
82
+ [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input),
83
+ and must be uploaded with the purpose `batch`. The file can contain up to 50,000
84
+ requests, and can be up to 200 MB in size.
85
+
86
+ metadata: Optional custom metadata for the batch.
87
+
88
+ extra_headers: Send extra headers
89
+
90
+ extra_query: Add additional query parameters to the request
91
+
92
+ extra_body: Add additional JSON properties to the request
93
+
94
+ timeout: Override the client-level default timeout for this request, in seconds
95
+ """
96
+ return self._post(
97
+ "/batches",
98
+ body=maybe_transform(
99
+ {
100
+ "completion_window": completion_window,
101
+ "endpoint": endpoint,
102
+ "input_file_id": input_file_id,
103
+ "metadata": metadata,
104
+ },
105
+ batch_create_params.BatchCreateParams,
106
+ ),
107
+ options=make_request_options(
108
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
109
+ ),
110
+ cast_to=Batch,
111
+ )
112
+
113
+ def retrieve(
114
+ self,
115
+ batch_id: str,
116
+ *,
117
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
118
+ # The extra values given here take precedence over values defined on the client or passed to this method.
119
+ extra_headers: Headers | None = None,
120
+ extra_query: Query | None = None,
121
+ extra_body: Body | None = None,
122
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
123
+ ) -> Batch:
124
+ """
125
+ Retrieves a batch.
126
+
127
+ Args:
128
+ extra_headers: Send extra headers
129
+
130
+ extra_query: Add additional query parameters to the request
131
+
132
+ extra_body: Add additional JSON properties to the request
133
+
134
+ timeout: Override the client-level default timeout for this request, in seconds
135
+ """
136
+ if not batch_id:
137
+ raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
138
+ return self._get(
139
+ f"/batches/{batch_id}",
140
+ options=make_request_options(
141
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
142
+ ),
143
+ cast_to=Batch,
144
+ )
145
+
146
+ def list(
147
+ self,
148
+ *,
149
+ after: str | NotGiven = NOT_GIVEN,
150
+ limit: int | NotGiven = NOT_GIVEN,
151
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
152
+ # The extra values given here take precedence over values defined on the client or passed to this method.
153
+ extra_headers: Headers | None = None,
154
+ extra_query: Query | None = None,
155
+ extra_body: Body | None = None,
156
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
157
+ ) -> SyncCursorPage[Batch]:
158
+ """List your organization's batches.
159
+
160
+ Args:
161
+ after: A cursor for use in pagination.
162
+
163
+ `after` is an object ID that defines your place
164
+ in the list. For instance, if you make a list request and receive 100 objects,
165
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
166
+ fetch the next page of the list.
167
+
168
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
169
+ 100, and the default is 20.
170
+
171
+ extra_headers: Send extra headers
172
+
173
+ extra_query: Add additional query parameters to the request
174
+
175
+ extra_body: Add additional JSON properties to the request
176
+
177
+ timeout: Override the client-level default timeout for this request, in seconds
178
+ """
179
+ return self._get_api_list(
180
+ "/batches",
181
+ page=SyncCursorPage[Batch],
182
+ options=make_request_options(
183
+ extra_headers=extra_headers,
184
+ extra_query=extra_query,
185
+ extra_body=extra_body,
186
+ timeout=timeout,
187
+ query=maybe_transform(
188
+ {
189
+ "after": after,
190
+ "limit": limit,
191
+ },
192
+ batch_list_params.BatchListParams,
193
+ ),
194
+ ),
195
+ model=Batch,
196
+ )
197
+
198
+ def cancel(
199
+ self,
200
+ batch_id: str,
201
+ *,
202
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
203
+ # The extra values given here take precedence over values defined on the client or passed to this method.
204
+ extra_headers: Headers | None = None,
205
+ extra_query: Query | None = None,
206
+ extra_body: Body | None = None,
207
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
208
+ ) -> Batch:
209
+ """Cancels an in-progress batch.
210
+
211
+ The batch will be in status `cancelling` for up to
212
+ 10 minutes, before changing to `cancelled`, where it will have partial results
213
+ (if any) available in the output file.
214
+
215
+ Args:
216
+ extra_headers: Send extra headers
217
+
218
+ extra_query: Add additional query parameters to the request
219
+
220
+ extra_body: Add additional JSON properties to the request
221
+
222
+ timeout: Override the client-level default timeout for this request, in seconds
223
+ """
224
+ if not batch_id:
225
+ raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
226
+ return self._post(
227
+ f"/batches/{batch_id}/cancel",
228
+ options=make_request_options(
229
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
230
+ ),
231
+ cast_to=Batch,
232
+ )
233
+
234
+
235
+ class AsyncBatches(AsyncAPIResource):
236
+ @cached_property
237
+ def with_raw_response(self) -> AsyncBatchesWithRawResponse:
238
+ """
239
+ This property can be used as a prefix for any HTTP method call to return the
240
+ the raw response object instead of the parsed content.
241
+
242
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
243
+ """
244
+ return AsyncBatchesWithRawResponse(self)
245
+
246
+ @cached_property
247
+ def with_streaming_response(self) -> AsyncBatchesWithStreamingResponse:
248
+ """
249
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
250
+
251
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
252
+ """
253
+ return AsyncBatchesWithStreamingResponse(self)
254
+
255
+ async def create(
256
+ self,
257
+ *,
258
+ completion_window: Literal["24h"],
259
+ endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
260
+ input_file_id: str,
261
+ metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN,
262
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
263
+ # The extra values given here take precedence over values defined on the client or passed to this method.
264
+ extra_headers: Headers | None = None,
265
+ extra_query: Query | None = None,
266
+ extra_body: Body | None = None,
267
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
268
+ ) -> Batch:
269
+ """
270
+ Creates and executes a batch from an uploaded file of requests
271
+
272
+ Args:
273
+ completion_window: The time frame within which the batch should be processed. Currently only `24h`
274
+ is supported.
275
+
276
+ endpoint: The endpoint to be used for all requests in the batch. Currently
277
+ `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported.
278
+ Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000
279
+ embedding inputs across all requests in the batch.
280
+
281
+ input_file_id: The ID of an uploaded file that contains requests for the new batch.
282
+
283
+ See [upload file](https://platform.openai.com/docs/api-reference/files/create)
284
+ for how to upload a file.
285
+
286
+ Your input file must be formatted as a
287
+ [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input),
288
+ and must be uploaded with the purpose `batch`. The file can contain up to 50,000
289
+ requests, and can be up to 200 MB in size.
290
+
291
+ metadata: Optional custom metadata for the batch.
292
+
293
+ extra_headers: Send extra headers
294
+
295
+ extra_query: Add additional query parameters to the request
296
+
297
+ extra_body: Add additional JSON properties to the request
298
+
299
+ timeout: Override the client-level default timeout for this request, in seconds
300
+ """
301
+ return await self._post(
302
+ "/batches",
303
+ body=await async_maybe_transform(
304
+ {
305
+ "completion_window": completion_window,
306
+ "endpoint": endpoint,
307
+ "input_file_id": input_file_id,
308
+ "metadata": metadata,
309
+ },
310
+ batch_create_params.BatchCreateParams,
311
+ ),
312
+ options=make_request_options(
313
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
314
+ ),
315
+ cast_to=Batch,
316
+ )
317
+
318
+ async def retrieve(
319
+ self,
320
+ batch_id: str,
321
+ *,
322
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
323
+ # The extra values given here take precedence over values defined on the client or passed to this method.
324
+ extra_headers: Headers | None = None,
325
+ extra_query: Query | None = None,
326
+ extra_body: Body | None = None,
327
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
328
+ ) -> Batch:
329
+ """
330
+ Retrieves a batch.
331
+
332
+ Args:
333
+ extra_headers: Send extra headers
334
+
335
+ extra_query: Add additional query parameters to the request
336
+
337
+ extra_body: Add additional JSON properties to the request
338
+
339
+ timeout: Override the client-level default timeout for this request, in seconds
340
+ """
341
+ if not batch_id:
342
+ raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
343
+ return await self._get(
344
+ f"/batches/{batch_id}",
345
+ options=make_request_options(
346
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
347
+ ),
348
+ cast_to=Batch,
349
+ )
350
+
351
+ def list(
352
+ self,
353
+ *,
354
+ after: str | NotGiven = NOT_GIVEN,
355
+ limit: int | NotGiven = NOT_GIVEN,
356
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
357
+ # The extra values given here take precedence over values defined on the client or passed to this method.
358
+ extra_headers: Headers | None = None,
359
+ extra_query: Query | None = None,
360
+ extra_body: Body | None = None,
361
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
362
+ ) -> AsyncPaginator[Batch, AsyncCursorPage[Batch]]:
363
+ """List your organization's batches.
364
+
365
+ Args:
366
+ after: A cursor for use in pagination.
367
+
368
+ `after` is an object ID that defines your place
369
+ in the list. For instance, if you make a list request and receive 100 objects,
370
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
371
+ fetch the next page of the list.
372
+
373
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
374
+ 100, and the default is 20.
375
+
376
+ extra_headers: Send extra headers
377
+
378
+ extra_query: Add additional query parameters to the request
379
+
380
+ extra_body: Add additional JSON properties to the request
381
+
382
+ timeout: Override the client-level default timeout for this request, in seconds
383
+ """
384
+ return self._get_api_list(
385
+ "/batches",
386
+ page=AsyncCursorPage[Batch],
387
+ options=make_request_options(
388
+ extra_headers=extra_headers,
389
+ extra_query=extra_query,
390
+ extra_body=extra_body,
391
+ timeout=timeout,
392
+ query=maybe_transform(
393
+ {
394
+ "after": after,
395
+ "limit": limit,
396
+ },
397
+ batch_list_params.BatchListParams,
398
+ ),
399
+ ),
400
+ model=Batch,
401
+ )
402
+
403
+ async def cancel(
404
+ self,
405
+ batch_id: str,
406
+ *,
407
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
408
+ # The extra values given here take precedence over values defined on the client or passed to this method.
409
+ extra_headers: Headers | None = None,
410
+ extra_query: Query | None = None,
411
+ extra_body: Body | None = None,
412
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
413
+ ) -> Batch:
414
+ """Cancels an in-progress batch.
415
+
416
+ The batch will be in status `cancelling` for up to
417
+ 10 minutes, before changing to `cancelled`, where it will have partial results
418
+ (if any) available in the output file.
419
+
420
+ Args:
421
+ extra_headers: Send extra headers
422
+
423
+ extra_query: Add additional query parameters to the request
424
+
425
+ extra_body: Add additional JSON properties to the request
426
+
427
+ timeout: Override the client-level default timeout for this request, in seconds
428
+ """
429
+ if not batch_id:
430
+ raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
431
+ return await self._post(
432
+ f"/batches/{batch_id}/cancel",
433
+ options=make_request_options(
434
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
435
+ ),
436
+ cast_to=Batch,
437
+ )
438
+
439
+
440
+ class BatchesWithRawResponse:
441
+ def __init__(self, batches: Batches) -> None:
442
+ self._batches = batches
443
+
444
+ self.create = _legacy_response.to_raw_response_wrapper(
445
+ batches.create,
446
+ )
447
+ self.retrieve = _legacy_response.to_raw_response_wrapper(
448
+ batches.retrieve,
449
+ )
450
+ self.list = _legacy_response.to_raw_response_wrapper(
451
+ batches.list,
452
+ )
453
+ self.cancel = _legacy_response.to_raw_response_wrapper(
454
+ batches.cancel,
455
+ )
456
+
457
+
458
+ class AsyncBatchesWithRawResponse:
459
+ def __init__(self, batches: AsyncBatches) -> None:
460
+ self._batches = batches
461
+
462
+ self.create = _legacy_response.async_to_raw_response_wrapper(
463
+ batches.create,
464
+ )
465
+ self.retrieve = _legacy_response.async_to_raw_response_wrapper(
466
+ batches.retrieve,
467
+ )
468
+ self.list = _legacy_response.async_to_raw_response_wrapper(
469
+ batches.list,
470
+ )
471
+ self.cancel = _legacy_response.async_to_raw_response_wrapper(
472
+ batches.cancel,
473
+ )
474
+
475
+
476
+ class BatchesWithStreamingResponse:
477
+ def __init__(self, batches: Batches) -> None:
478
+ self._batches = batches
479
+
480
+ self.create = to_streamed_response_wrapper(
481
+ batches.create,
482
+ )
483
+ self.retrieve = to_streamed_response_wrapper(
484
+ batches.retrieve,
485
+ )
486
+ self.list = to_streamed_response_wrapper(
487
+ batches.list,
488
+ )
489
+ self.cancel = to_streamed_response_wrapper(
490
+ batches.cancel,
491
+ )
492
+
493
+
494
+ class AsyncBatchesWithStreamingResponse:
495
+ def __init__(self, batches: AsyncBatches) -> None:
496
+ self._batches = batches
497
+
498
+ self.create = async_to_streamed_response_wrapper(
499
+ batches.create,
500
+ )
501
+ self.retrieve = async_to_streamed_response_wrapper(
502
+ batches.retrieve,
503
+ )
504
+ self.list = async_to_streamed_response_wrapper(
505
+ batches.list,
506
+ )
507
+ self.cancel = async_to_streamed_response_wrapper(
508
+ batches.cancel,
509
+ )
vllm/lib/python3.10/site-packages/openai/resources/beta/__init__.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from .beta import (
4
+ Beta,
5
+ AsyncBeta,
6
+ BetaWithRawResponse,
7
+ AsyncBetaWithRawResponse,
8
+ BetaWithStreamingResponse,
9
+ AsyncBetaWithStreamingResponse,
10
+ )
11
+ from .threads import (
12
+ Threads,
13
+ AsyncThreads,
14
+ ThreadsWithRawResponse,
15
+ AsyncThreadsWithRawResponse,
16
+ ThreadsWithStreamingResponse,
17
+ AsyncThreadsWithStreamingResponse,
18
+ )
19
+ from .assistants import (
20
+ Assistants,
21
+ AsyncAssistants,
22
+ AssistantsWithRawResponse,
23
+ AsyncAssistantsWithRawResponse,
24
+ AssistantsWithStreamingResponse,
25
+ AsyncAssistantsWithStreamingResponse,
26
+ )
27
+ from .vector_stores import (
28
+ VectorStores,
29
+ AsyncVectorStores,
30
+ VectorStoresWithRawResponse,
31
+ AsyncVectorStoresWithRawResponse,
32
+ VectorStoresWithStreamingResponse,
33
+ AsyncVectorStoresWithStreamingResponse,
34
+ )
35
+
36
+ __all__ = [
37
+ "VectorStores",
38
+ "AsyncVectorStores",
39
+ "VectorStoresWithRawResponse",
40
+ "AsyncVectorStoresWithRawResponse",
41
+ "VectorStoresWithStreamingResponse",
42
+ "AsyncVectorStoresWithStreamingResponse",
43
+ "Assistants",
44
+ "AsyncAssistants",
45
+ "AssistantsWithRawResponse",
46
+ "AsyncAssistantsWithRawResponse",
47
+ "AssistantsWithStreamingResponse",
48
+ "AsyncAssistantsWithStreamingResponse",
49
+ "Threads",
50
+ "AsyncThreads",
51
+ "ThreadsWithRawResponse",
52
+ "AsyncThreadsWithRawResponse",
53
+ "ThreadsWithStreamingResponse",
54
+ "AsyncThreadsWithStreamingResponse",
55
+ "Beta",
56
+ "AsyncBeta",
57
+ "BetaWithRawResponse",
58
+ "AsyncBetaWithRawResponse",
59
+ "BetaWithStreamingResponse",
60
+ "AsyncBetaWithStreamingResponse",
61
+ ]
vllm/lib/python3.10/site-packages/openai/resources/beta/assistants.py ADDED
@@ -0,0 +1,888 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Union, Iterable, Optional
6
+ from typing_extensions import Literal
7
+
8
+ import httpx
9
+
10
+ from ... import _legacy_response
11
+ from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven
12
+ from ..._utils import (
13
+ maybe_transform,
14
+ async_maybe_transform,
15
+ )
16
+ from ..._compat import cached_property
17
+ from ..._resource import SyncAPIResource, AsyncAPIResource
18
+ from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
19
+ from ...pagination import SyncCursorPage, AsyncCursorPage
20
+ from ...types.beta import (
21
+ assistant_list_params,
22
+ assistant_create_params,
23
+ assistant_update_params,
24
+ )
25
+ from ..._base_client import AsyncPaginator, make_request_options
26
+ from ...types.chat_model import ChatModel
27
+ from ...types.beta.assistant import Assistant
28
+ from ...types.beta.assistant_deleted import AssistantDeleted
29
+ from ...types.beta.assistant_tool_param import AssistantToolParam
30
+ from ...types.beta.assistant_response_format_option_param import AssistantResponseFormatOptionParam
31
+
32
+ __all__ = ["Assistants", "AsyncAssistants"]
33
+
34
+
35
+ class Assistants(SyncAPIResource):
36
+ @cached_property
37
+ def with_raw_response(self) -> AssistantsWithRawResponse:
38
+ """
39
+ This property can be used as a prefix for any HTTP method call to return the
40
+ the raw response object instead of the parsed content.
41
+
42
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
43
+ """
44
+ return AssistantsWithRawResponse(self)
45
+
46
+ @cached_property
47
+ def with_streaming_response(self) -> AssistantsWithStreamingResponse:
48
+ """
49
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
50
+
51
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
52
+ """
53
+ return AssistantsWithStreamingResponse(self)
54
+
55
+ def create(
56
+ self,
57
+ *,
58
+ model: Union[str, ChatModel],
59
+ description: Optional[str] | NotGiven = NOT_GIVEN,
60
+ instructions: Optional[str] | NotGiven = NOT_GIVEN,
61
+ metadata: Optional[object] | NotGiven = NOT_GIVEN,
62
+ name: Optional[str] | NotGiven = NOT_GIVEN,
63
+ response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN,
64
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
65
+ tool_resources: Optional[assistant_create_params.ToolResources] | NotGiven = NOT_GIVEN,
66
+ tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN,
67
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
68
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
69
+ # The extra values given here take precedence over values defined on the client or passed to this method.
70
+ extra_headers: Headers | None = None,
71
+ extra_query: Query | None = None,
72
+ extra_body: Body | None = None,
73
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
74
+ ) -> Assistant:
75
+ """
76
+ Create an assistant with a model and instructions.
77
+
78
+ Args:
79
+ model: ID of the model to use. You can use the
80
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
81
+ see all of your available models, or see our
82
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
83
+ them.
84
+
85
+ description: The description of the assistant. The maximum length is 512 characters.
86
+
87
+ instructions: The system instructions that the assistant uses. The maximum length is 256,000
88
+ characters.
89
+
90
+ metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful
91
+ for storing additional information about the object in a structured format. Keys
92
+ can be a maximum of 64 characters long and values can be a maximum of 512
93
+ characters long.
94
+
95
+ name: The name of the assistant. The maximum length is 256 characters.
96
+
97
+ response_format: Specifies the format that the model must output. Compatible with
98
+ [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),
99
+ [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),
100
+ and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.
101
+
102
+ Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured
103
+ Outputs which ensures the model will match your supplied JSON schema. Learn more
104
+ in the
105
+ [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
106
+
107
+ Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the
108
+ message the model generates is valid JSON.
109
+
110
+ **Important:** when using JSON mode, you **must** also instruct the model to
111
+ produce JSON yourself via a system or user message. Without this, the model may
112
+ generate an unending stream of whitespace until the generation reaches the token
113
+ limit, resulting in a long-running and seemingly "stuck" request. Also note that
114
+ the message content may be partially cut off if `finish_reason="length"`, which
115
+ indicates the generation exceeded `max_tokens` or the conversation exceeded the
116
+ max context length.
117
+
118
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
119
+ make the output more random, while lower values like 0.2 will make it more
120
+ focused and deterministic.
121
+
122
+ tool_resources: A set of resources that are used by the assistant's tools. The resources are
123
+ specific to the type of tool. For example, the `code_interpreter` tool requires
124
+ a list of file IDs, while the `file_search` tool requires a list of vector store
125
+ IDs.
126
+
127
+ tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per
128
+ assistant. Tools can be of types `code_interpreter`, `file_search`, or
129
+ `function`.
130
+
131
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
132
+ model considers the results of the tokens with top_p probability mass. So 0.1
133
+ means only the tokens comprising the top 10% probability mass are considered.
134
+
135
+ We generally recommend altering this or temperature but not both.
136
+
137
+ extra_headers: Send extra headers
138
+
139
+ extra_query: Add additional query parameters to the request
140
+
141
+ extra_body: Add additional JSON properties to the request
142
+
143
+ timeout: Override the client-level default timeout for this request, in seconds
144
+ """
145
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
146
+ return self._post(
147
+ "/assistants",
148
+ body=maybe_transform(
149
+ {
150
+ "model": model,
151
+ "description": description,
152
+ "instructions": instructions,
153
+ "metadata": metadata,
154
+ "name": name,
155
+ "response_format": response_format,
156
+ "temperature": temperature,
157
+ "tool_resources": tool_resources,
158
+ "tools": tools,
159
+ "top_p": top_p,
160
+ },
161
+ assistant_create_params.AssistantCreateParams,
162
+ ),
163
+ options=make_request_options(
164
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
165
+ ),
166
+ cast_to=Assistant,
167
+ )
168
+
169
+ def retrieve(
170
+ self,
171
+ assistant_id: str,
172
+ *,
173
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
174
+ # The extra values given here take precedence over values defined on the client or passed to this method.
175
+ extra_headers: Headers | None = None,
176
+ extra_query: Query | None = None,
177
+ extra_body: Body | None = None,
178
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
179
+ ) -> Assistant:
180
+ """
181
+ Retrieves an assistant.
182
+
183
+ Args:
184
+ extra_headers: Send extra headers
185
+
186
+ extra_query: Add additional query parameters to the request
187
+
188
+ extra_body: Add additional JSON properties to the request
189
+
190
+ timeout: Override the client-level default timeout for this request, in seconds
191
+ """
192
+ if not assistant_id:
193
+ raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}")
194
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
195
+ return self._get(
196
+ f"/assistants/{assistant_id}",
197
+ options=make_request_options(
198
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
199
+ ),
200
+ cast_to=Assistant,
201
+ )
202
+
203
+ def update(
204
+ self,
205
+ assistant_id: str,
206
+ *,
207
+ description: Optional[str] | NotGiven = NOT_GIVEN,
208
+ instructions: Optional[str] | NotGiven = NOT_GIVEN,
209
+ metadata: Optional[object] | NotGiven = NOT_GIVEN,
210
+ model: str | NotGiven = NOT_GIVEN,
211
+ name: Optional[str] | NotGiven = NOT_GIVEN,
212
+ response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN,
213
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
214
+ tool_resources: Optional[assistant_update_params.ToolResources] | NotGiven = NOT_GIVEN,
215
+ tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN,
216
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
217
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
218
+ # The extra values given here take precedence over values defined on the client or passed to this method.
219
+ extra_headers: Headers | None = None,
220
+ extra_query: Query | None = None,
221
+ extra_body: Body | None = None,
222
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
223
+ ) -> Assistant:
224
+ """Modifies an assistant.
225
+
226
+ Args:
227
+ description: The description of the assistant.
228
+
229
+ The maximum length is 512 characters.
230
+
231
+ instructions: The system instructions that the assistant uses. The maximum length is 256,000
232
+ characters.
233
+
234
+ metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful
235
+ for storing additional information about the object in a structured format. Keys
236
+ can be a maximum of 64 characters long and values can be a maximum of 512
237
+ characters long.
238
+
239
+ model: ID of the model to use. You can use the
240
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
241
+ see all of your available models, or see our
242
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
243
+ them.
244
+
245
+ name: The name of the assistant. The maximum length is 256 characters.
246
+
247
+ response_format: Specifies the format that the model must output. Compatible with
248
+ [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),
249
+ [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),
250
+ and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.
251
+
252
+ Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured
253
+ Outputs which ensures the model will match your supplied JSON schema. Learn more
254
+ in the
255
+ [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
256
+
257
+ Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the
258
+ message the model generates is valid JSON.
259
+
260
+ **Important:** when using JSON mode, you **must** also instruct the model to
261
+ produce JSON yourself via a system or user message. Without this, the model may
262
+ generate an unending stream of whitespace until the generation reaches the token
263
+ limit, resulting in a long-running and seemingly "stuck" request. Also note that
264
+ the message content may be partially cut off if `finish_reason="length"`, which
265
+ indicates the generation exceeded `max_tokens` or the conversation exceeded the
266
+ max context length.
267
+
268
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
269
+ make the output more random, while lower values like 0.2 will make it more
270
+ focused and deterministic.
271
+
272
+ tool_resources: A set of resources that are used by the assistant's tools. The resources are
273
+ specific to the type of tool. For example, the `code_interpreter` tool requires
274
+ a list of file IDs, while the `file_search` tool requires a list of vector store
275
+ IDs.
276
+
277
+ tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per
278
+ assistant. Tools can be of types `code_interpreter`, `file_search`, or
279
+ `function`.
280
+
281
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
282
+ model considers the results of the tokens with top_p probability mass. So 0.1
283
+ means only the tokens comprising the top 10% probability mass are considered.
284
+
285
+ We generally recommend altering this or temperature but not both.
286
+
287
+ extra_headers: Send extra headers
288
+
289
+ extra_query: Add additional query parameters to the request
290
+
291
+ extra_body: Add additional JSON properties to the request
292
+
293
+ timeout: Override the client-level default timeout for this request, in seconds
294
+ """
295
+ if not assistant_id:
296
+ raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}")
297
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
298
+ return self._post(
299
+ f"/assistants/{assistant_id}",
300
+ body=maybe_transform(
301
+ {
302
+ "description": description,
303
+ "instructions": instructions,
304
+ "metadata": metadata,
305
+ "model": model,
306
+ "name": name,
307
+ "response_format": response_format,
308
+ "temperature": temperature,
309
+ "tool_resources": tool_resources,
310
+ "tools": tools,
311
+ "top_p": top_p,
312
+ },
313
+ assistant_update_params.AssistantUpdateParams,
314
+ ),
315
+ options=make_request_options(
316
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
317
+ ),
318
+ cast_to=Assistant,
319
+ )
320
+
321
+ def list(
322
+ self,
323
+ *,
324
+ after: str | NotGiven = NOT_GIVEN,
325
+ before: str | NotGiven = NOT_GIVEN,
326
+ limit: int | NotGiven = NOT_GIVEN,
327
+ order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN,
328
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
329
+ # The extra values given here take precedence over values defined on the client or passed to this method.
330
+ extra_headers: Headers | None = None,
331
+ extra_query: Query | None = None,
332
+ extra_body: Body | None = None,
333
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
334
+ ) -> SyncCursorPage[Assistant]:
335
+ """Returns a list of assistants.
336
+
337
+ Args:
338
+ after: A cursor for use in pagination.
339
+
340
+ `after` is an object ID that defines your place
341
+ in the list. For instance, if you make a list request and receive 100 objects,
342
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
343
+ fetch the next page of the list.
344
+
345
+ before: A cursor for use in pagination. `before` is an object ID that defines your place
346
+ in the list. For instance, if you make a list request and receive 100 objects,
347
+ starting with obj_foo, your subsequent call can include before=obj_foo in order
348
+ to fetch the previous page of the list.
349
+
350
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
351
+ 100, and the default is 20.
352
+
353
+ order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending
354
+ order and `desc` for descending order.
355
+
356
+ extra_headers: Send extra headers
357
+
358
+ extra_query: Add additional query parameters to the request
359
+
360
+ extra_body: Add additional JSON properties to the request
361
+
362
+ timeout: Override the client-level default timeout for this request, in seconds
363
+ """
364
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
365
+ return self._get_api_list(
366
+ "/assistants",
367
+ page=SyncCursorPage[Assistant],
368
+ options=make_request_options(
369
+ extra_headers=extra_headers,
370
+ extra_query=extra_query,
371
+ extra_body=extra_body,
372
+ timeout=timeout,
373
+ query=maybe_transform(
374
+ {
375
+ "after": after,
376
+ "before": before,
377
+ "limit": limit,
378
+ "order": order,
379
+ },
380
+ assistant_list_params.AssistantListParams,
381
+ ),
382
+ ),
383
+ model=Assistant,
384
+ )
385
+
386
+ def delete(
387
+ self,
388
+ assistant_id: str,
389
+ *,
390
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
391
+ # The extra values given here take precedence over values defined on the client or passed to this method.
392
+ extra_headers: Headers | None = None,
393
+ extra_query: Query | None = None,
394
+ extra_body: Body | None = None,
395
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
396
+ ) -> AssistantDeleted:
397
+ """
398
+ Delete an assistant.
399
+
400
+ Args:
401
+ extra_headers: Send extra headers
402
+
403
+ extra_query: Add additional query parameters to the request
404
+
405
+ extra_body: Add additional JSON properties to the request
406
+
407
+ timeout: Override the client-level default timeout for this request, in seconds
408
+ """
409
+ if not assistant_id:
410
+ raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}")
411
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
412
+ return self._delete(
413
+ f"/assistants/{assistant_id}",
414
+ options=make_request_options(
415
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
416
+ ),
417
+ cast_to=AssistantDeleted,
418
+ )
419
+
420
+
421
+ class AsyncAssistants(AsyncAPIResource):
422
+ @cached_property
423
+ def with_raw_response(self) -> AsyncAssistantsWithRawResponse:
424
+ """
425
+ This property can be used as a prefix for any HTTP method call to return the
426
+ the raw response object instead of the parsed content.
427
+
428
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
429
+ """
430
+ return AsyncAssistantsWithRawResponse(self)
431
+
432
+ @cached_property
433
+ def with_streaming_response(self) -> AsyncAssistantsWithStreamingResponse:
434
+ """
435
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
436
+
437
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
438
+ """
439
+ return AsyncAssistantsWithStreamingResponse(self)
440
+
441
+ async def create(
442
+ self,
443
+ *,
444
+ model: Union[str, ChatModel],
445
+ description: Optional[str] | NotGiven = NOT_GIVEN,
446
+ instructions: Optional[str] | NotGiven = NOT_GIVEN,
447
+ metadata: Optional[object] | NotGiven = NOT_GIVEN,
448
+ name: Optional[str] | NotGiven = NOT_GIVEN,
449
+ response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN,
450
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
451
+ tool_resources: Optional[assistant_create_params.ToolResources] | NotGiven = NOT_GIVEN,
452
+ tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN,
453
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
454
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
455
+ # The extra values given here take precedence over values defined on the client or passed to this method.
456
+ extra_headers: Headers | None = None,
457
+ extra_query: Query | None = None,
458
+ extra_body: Body | None = None,
459
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
460
+ ) -> Assistant:
461
+ """
462
+ Create an assistant with a model and instructions.
463
+
464
+ Args:
465
+ model: ID of the model to use. You can use the
466
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
467
+ see all of your available models, or see our
468
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
469
+ them.
470
+
471
+ description: The description of the assistant. The maximum length is 512 characters.
472
+
473
+ instructions: The system instructions that the assistant uses. The maximum length is 256,000
474
+ characters.
475
+
476
+ metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful
477
+ for storing additional information about the object in a structured format. Keys
478
+ can be a maximum of 64 characters long and values can be a maximum of 512
479
+ characters long.
480
+
481
+ name: The name of the assistant. The maximum length is 256 characters.
482
+
483
+ response_format: Specifies the format that the model must output. Compatible with
484
+ [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),
485
+ [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),
486
+ and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.
487
+
488
+ Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured
489
+ Outputs which ensures the model will match your supplied JSON schema. Learn more
490
+ in the
491
+ [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
492
+
493
+ Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the
494
+ message the model generates is valid JSON.
495
+
496
+ **Important:** when using JSON mode, you **must** also instruct the model to
497
+ produce JSON yourself via a system or user message. Without this, the model may
498
+ generate an unending stream of whitespace until the generation reaches the token
499
+ limit, resulting in a long-running and seemingly "stuck" request. Also note that
500
+ the message content may be partially cut off if `finish_reason="length"`, which
501
+ indicates the generation exceeded `max_tokens` or the conversation exceeded the
502
+ max context length.
503
+
504
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
505
+ make the output more random, while lower values like 0.2 will make it more
506
+ focused and deterministic.
507
+
508
+ tool_resources: A set of resources that are used by the assistant's tools. The resources are
509
+ specific to the type of tool. For example, the `code_interpreter` tool requires
510
+ a list of file IDs, while the `file_search` tool requires a list of vector store
511
+ IDs.
512
+
513
+ tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per
514
+ assistant. Tools can be of types `code_interpreter`, `file_search`, or
515
+ `function`.
516
+
517
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
518
+ model considers the results of the tokens with top_p probability mass. So 0.1
519
+ means only the tokens comprising the top 10% probability mass are considered.
520
+
521
+ We generally recommend altering this or temperature but not both.
522
+
523
+ extra_headers: Send extra headers
524
+
525
+ extra_query: Add additional query parameters to the request
526
+
527
+ extra_body: Add additional JSON properties to the request
528
+
529
+ timeout: Override the client-level default timeout for this request, in seconds
530
+ """
531
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
532
+ return await self._post(
533
+ "/assistants",
534
+ body=await async_maybe_transform(
535
+ {
536
+ "model": model,
537
+ "description": description,
538
+ "instructions": instructions,
539
+ "metadata": metadata,
540
+ "name": name,
541
+ "response_format": response_format,
542
+ "temperature": temperature,
543
+ "tool_resources": tool_resources,
544
+ "tools": tools,
545
+ "top_p": top_p,
546
+ },
547
+ assistant_create_params.AssistantCreateParams,
548
+ ),
549
+ options=make_request_options(
550
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
551
+ ),
552
+ cast_to=Assistant,
553
+ )
554
+
555
+ async def retrieve(
556
+ self,
557
+ assistant_id: str,
558
+ *,
559
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
560
+ # The extra values given here take precedence over values defined on the client or passed to this method.
561
+ extra_headers: Headers | None = None,
562
+ extra_query: Query | None = None,
563
+ extra_body: Body | None = None,
564
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
565
+ ) -> Assistant:
566
+ """
567
+ Retrieves an assistant.
568
+
569
+ Args:
570
+ extra_headers: Send extra headers
571
+
572
+ extra_query: Add additional query parameters to the request
573
+
574
+ extra_body: Add additional JSON properties to the request
575
+
576
+ timeout: Override the client-level default timeout for this request, in seconds
577
+ """
578
+ if not assistant_id:
579
+ raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}")
580
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
581
+ return await self._get(
582
+ f"/assistants/{assistant_id}",
583
+ options=make_request_options(
584
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
585
+ ),
586
+ cast_to=Assistant,
587
+ )
588
+
589
+ async def update(
590
+ self,
591
+ assistant_id: str,
592
+ *,
593
+ description: Optional[str] | NotGiven = NOT_GIVEN,
594
+ instructions: Optional[str] | NotGiven = NOT_GIVEN,
595
+ metadata: Optional[object] | NotGiven = NOT_GIVEN,
596
+ model: str | NotGiven = NOT_GIVEN,
597
+ name: Optional[str] | NotGiven = NOT_GIVEN,
598
+ response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN,
599
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
600
+ tool_resources: Optional[assistant_update_params.ToolResources] | NotGiven = NOT_GIVEN,
601
+ tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN,
602
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
603
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
604
+ # The extra values given here take precedence over values defined on the client or passed to this method.
605
+ extra_headers: Headers | None = None,
606
+ extra_query: Query | None = None,
607
+ extra_body: Body | None = None,
608
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
609
+ ) -> Assistant:
610
+ """Modifies an assistant.
611
+
612
+ Args:
613
+ description: The description of the assistant.
614
+
615
+ The maximum length is 512 characters.
616
+
617
+ instructions: The system instructions that the assistant uses. The maximum length is 256,000
618
+ characters.
619
+
620
+ metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful
621
+ for storing additional information about the object in a structured format. Keys
622
+ can be a maximum of 64 characters long and values can be a maximum of 512
623
+ characters long.
624
+
625
+ model: ID of the model to use. You can use the
626
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
627
+ see all of your available models, or see our
628
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
629
+ them.
630
+
631
+ name: The name of the assistant. The maximum length is 256 characters.
632
+
633
+ response_format: Specifies the format that the model must output. Compatible with
634
+ [GPT-4o](https://platform.openai.com/docs/models#gpt-4o),
635
+ [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4),
636
+ and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.
637
+
638
+ Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured
639
+ Outputs which ensures the model will match your supplied JSON schema. Learn more
640
+ in the
641
+ [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
642
+
643
+ Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the
644
+ message the model generates is valid JSON.
645
+
646
+ **Important:** when using JSON mode, you **must** also instruct the model to
647
+ produce JSON yourself via a system or user message. Without this, the model may
648
+ generate an unending stream of whitespace until the generation reaches the token
649
+ limit, resulting in a long-running and seemingly "stuck" request. Also note that
650
+ the message content may be partially cut off if `finish_reason="length"`, which
651
+ indicates the generation exceeded `max_tokens` or the conversation exceeded the
652
+ max context length.
653
+
654
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
655
+ make the output more random, while lower values like 0.2 will make it more
656
+ focused and deterministic.
657
+
658
+ tool_resources: A set of resources that are used by the assistant's tools. The resources are
659
+ specific to the type of tool. For example, the `code_interpreter` tool requires
660
+ a list of file IDs, while the `file_search` tool requires a list of vector store
661
+ IDs.
662
+
663
+ tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per
664
+ assistant. Tools can be of types `code_interpreter`, `file_search`, or
665
+ `function`.
666
+
667
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
668
+ model considers the results of the tokens with top_p probability mass. So 0.1
669
+ means only the tokens comprising the top 10% probability mass are considered.
670
+
671
+ We generally recommend altering this or temperature but not both.
672
+
673
+ extra_headers: Send extra headers
674
+
675
+ extra_query: Add additional query parameters to the request
676
+
677
+ extra_body: Add additional JSON properties to the request
678
+
679
+ timeout: Override the client-level default timeout for this request, in seconds
680
+ """
681
+ if not assistant_id:
682
+ raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}")
683
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
684
+ return await self._post(
685
+ f"/assistants/{assistant_id}",
686
+ body=await async_maybe_transform(
687
+ {
688
+ "description": description,
689
+ "instructions": instructions,
690
+ "metadata": metadata,
691
+ "model": model,
692
+ "name": name,
693
+ "response_format": response_format,
694
+ "temperature": temperature,
695
+ "tool_resources": tool_resources,
696
+ "tools": tools,
697
+ "top_p": top_p,
698
+ },
699
+ assistant_update_params.AssistantUpdateParams,
700
+ ),
701
+ options=make_request_options(
702
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
703
+ ),
704
+ cast_to=Assistant,
705
+ )
706
+
707
+ def list(
708
+ self,
709
+ *,
710
+ after: str | NotGiven = NOT_GIVEN,
711
+ before: str | NotGiven = NOT_GIVEN,
712
+ limit: int | NotGiven = NOT_GIVEN,
713
+ order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN,
714
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
715
+ # The extra values given here take precedence over values defined on the client or passed to this method.
716
+ extra_headers: Headers | None = None,
717
+ extra_query: Query | None = None,
718
+ extra_body: Body | None = None,
719
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
720
+ ) -> AsyncPaginator[Assistant, AsyncCursorPage[Assistant]]:
721
+ """Returns a list of assistants.
722
+
723
+ Args:
724
+ after: A cursor for use in pagination.
725
+
726
+ `after` is an object ID that defines your place
727
+ in the list. For instance, if you make a list request and receive 100 objects,
728
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
729
+ fetch the next page of the list.
730
+
731
+ before: A cursor for use in pagination. `before` is an object ID that defines your place
732
+ in the list. For instance, if you make a list request and receive 100 objects,
733
+ starting with obj_foo, your subsequent call can include before=obj_foo in order
734
+ to fetch the previous page of the list.
735
+
736
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
737
+ 100, and the default is 20.
738
+
739
+ order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending
740
+ order and `desc` for descending order.
741
+
742
+ extra_headers: Send extra headers
743
+
744
+ extra_query: Add additional query parameters to the request
745
+
746
+ extra_body: Add additional JSON properties to the request
747
+
748
+ timeout: Override the client-level default timeout for this request, in seconds
749
+ """
750
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
751
+ return self._get_api_list(
752
+ "/assistants",
753
+ page=AsyncCursorPage[Assistant],
754
+ options=make_request_options(
755
+ extra_headers=extra_headers,
756
+ extra_query=extra_query,
757
+ extra_body=extra_body,
758
+ timeout=timeout,
759
+ query=maybe_transform(
760
+ {
761
+ "after": after,
762
+ "before": before,
763
+ "limit": limit,
764
+ "order": order,
765
+ },
766
+ assistant_list_params.AssistantListParams,
767
+ ),
768
+ ),
769
+ model=Assistant,
770
+ )
771
+
772
+ async def delete(
773
+ self,
774
+ assistant_id: str,
775
+ *,
776
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
777
+ # The extra values given here take precedence over values defined on the client or passed to this method.
778
+ extra_headers: Headers | None = None,
779
+ extra_query: Query | None = None,
780
+ extra_body: Body | None = None,
781
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
782
+ ) -> AssistantDeleted:
783
+ """
784
+ Delete an assistant.
785
+
786
+ Args:
787
+ extra_headers: Send extra headers
788
+
789
+ extra_query: Add additional query parameters to the request
790
+
791
+ extra_body: Add additional JSON properties to the request
792
+
793
+ timeout: Override the client-level default timeout for this request, in seconds
794
+ """
795
+ if not assistant_id:
796
+ raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}")
797
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
798
+ return await self._delete(
799
+ f"/assistants/{assistant_id}",
800
+ options=make_request_options(
801
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
802
+ ),
803
+ cast_to=AssistantDeleted,
804
+ )
805
+
806
+
807
+ class AssistantsWithRawResponse:
808
+ def __init__(self, assistants: Assistants) -> None:
809
+ self._assistants = assistants
810
+
811
+ self.create = _legacy_response.to_raw_response_wrapper(
812
+ assistants.create,
813
+ )
814
+ self.retrieve = _legacy_response.to_raw_response_wrapper(
815
+ assistants.retrieve,
816
+ )
817
+ self.update = _legacy_response.to_raw_response_wrapper(
818
+ assistants.update,
819
+ )
820
+ self.list = _legacy_response.to_raw_response_wrapper(
821
+ assistants.list,
822
+ )
823
+ self.delete = _legacy_response.to_raw_response_wrapper(
824
+ assistants.delete,
825
+ )
826
+
827
+
828
+ class AsyncAssistantsWithRawResponse:
829
+ def __init__(self, assistants: AsyncAssistants) -> None:
830
+ self._assistants = assistants
831
+
832
+ self.create = _legacy_response.async_to_raw_response_wrapper(
833
+ assistants.create,
834
+ )
835
+ self.retrieve = _legacy_response.async_to_raw_response_wrapper(
836
+ assistants.retrieve,
837
+ )
838
+ self.update = _legacy_response.async_to_raw_response_wrapper(
839
+ assistants.update,
840
+ )
841
+ self.list = _legacy_response.async_to_raw_response_wrapper(
842
+ assistants.list,
843
+ )
844
+ self.delete = _legacy_response.async_to_raw_response_wrapper(
845
+ assistants.delete,
846
+ )
847
+
848
+
849
+ class AssistantsWithStreamingResponse:
850
+ def __init__(self, assistants: Assistants) -> None:
851
+ self._assistants = assistants
852
+
853
+ self.create = to_streamed_response_wrapper(
854
+ assistants.create,
855
+ )
856
+ self.retrieve = to_streamed_response_wrapper(
857
+ assistants.retrieve,
858
+ )
859
+ self.update = to_streamed_response_wrapper(
860
+ assistants.update,
861
+ )
862
+ self.list = to_streamed_response_wrapper(
863
+ assistants.list,
864
+ )
865
+ self.delete = to_streamed_response_wrapper(
866
+ assistants.delete,
867
+ )
868
+
869
+
870
+ class AsyncAssistantsWithStreamingResponse:
871
+ def __init__(self, assistants: AsyncAssistants) -> None:
872
+ self._assistants = assistants
873
+
874
+ self.create = async_to_streamed_response_wrapper(
875
+ assistants.create,
876
+ )
877
+ self.retrieve = async_to_streamed_response_wrapper(
878
+ assistants.retrieve,
879
+ )
880
+ self.update = async_to_streamed_response_wrapper(
881
+ assistants.update,
882
+ )
883
+ self.list = async_to_streamed_response_wrapper(
884
+ assistants.list,
885
+ )
886
+ self.delete = async_to_streamed_response_wrapper(
887
+ assistants.delete,
888
+ )
vllm/lib/python3.10/site-packages/openai/resources/beta/beta.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from ..._compat import cached_property
6
+ from .chat.chat import Chat, AsyncChat
7
+ from .assistants import (
8
+ Assistants,
9
+ AsyncAssistants,
10
+ AssistantsWithRawResponse,
11
+ AsyncAssistantsWithRawResponse,
12
+ AssistantsWithStreamingResponse,
13
+ AsyncAssistantsWithStreamingResponse,
14
+ )
15
+ from ..._resource import SyncAPIResource, AsyncAPIResource
16
+ from .threads.threads import (
17
+ Threads,
18
+ AsyncThreads,
19
+ ThreadsWithRawResponse,
20
+ AsyncThreadsWithRawResponse,
21
+ ThreadsWithStreamingResponse,
22
+ AsyncThreadsWithStreamingResponse,
23
+ )
24
+ from .vector_stores.vector_stores import (
25
+ VectorStores,
26
+ AsyncVectorStores,
27
+ VectorStoresWithRawResponse,
28
+ AsyncVectorStoresWithRawResponse,
29
+ VectorStoresWithStreamingResponse,
30
+ AsyncVectorStoresWithStreamingResponse,
31
+ )
32
+
33
+ __all__ = ["Beta", "AsyncBeta"]
34
+
35
+
36
+ class Beta(SyncAPIResource):
37
+ @cached_property
38
+ def chat(self) -> Chat:
39
+ return Chat(self._client)
40
+
41
+ @cached_property
42
+ def vector_stores(self) -> VectorStores:
43
+ return VectorStores(self._client)
44
+
45
+ @cached_property
46
+ def assistants(self) -> Assistants:
47
+ return Assistants(self._client)
48
+
49
+ @cached_property
50
+ def threads(self) -> Threads:
51
+ return Threads(self._client)
52
+
53
+ @cached_property
54
+ def with_raw_response(self) -> BetaWithRawResponse:
55
+ """
56
+ This property can be used as a prefix for any HTTP method call to return the
57
+ the raw response object instead of the parsed content.
58
+
59
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
60
+ """
61
+ return BetaWithRawResponse(self)
62
+
63
+ @cached_property
64
+ def with_streaming_response(self) -> BetaWithStreamingResponse:
65
+ """
66
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
67
+
68
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
69
+ """
70
+ return BetaWithStreamingResponse(self)
71
+
72
+
73
+ class AsyncBeta(AsyncAPIResource):
74
+ @cached_property
75
+ def chat(self) -> AsyncChat:
76
+ return AsyncChat(self._client)
77
+
78
+ @cached_property
79
+ def vector_stores(self) -> AsyncVectorStores:
80
+ return AsyncVectorStores(self._client)
81
+
82
+ @cached_property
83
+ def assistants(self) -> AsyncAssistants:
84
+ return AsyncAssistants(self._client)
85
+
86
+ @cached_property
87
+ def threads(self) -> AsyncThreads:
88
+ return AsyncThreads(self._client)
89
+
90
+ @cached_property
91
+ def with_raw_response(self) -> AsyncBetaWithRawResponse:
92
+ """
93
+ This property can be used as a prefix for any HTTP method call to return the
94
+ the raw response object instead of the parsed content.
95
+
96
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
97
+ """
98
+ return AsyncBetaWithRawResponse(self)
99
+
100
+ @cached_property
101
+ def with_streaming_response(self) -> AsyncBetaWithStreamingResponse:
102
+ """
103
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
104
+
105
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
106
+ """
107
+ return AsyncBetaWithStreamingResponse(self)
108
+
109
+
110
+ class BetaWithRawResponse:
111
+ def __init__(self, beta: Beta) -> None:
112
+ self._beta = beta
113
+
114
+ @cached_property
115
+ def vector_stores(self) -> VectorStoresWithRawResponse:
116
+ return VectorStoresWithRawResponse(self._beta.vector_stores)
117
+
118
+ @cached_property
119
+ def assistants(self) -> AssistantsWithRawResponse:
120
+ return AssistantsWithRawResponse(self._beta.assistants)
121
+
122
+ @cached_property
123
+ def threads(self) -> ThreadsWithRawResponse:
124
+ return ThreadsWithRawResponse(self._beta.threads)
125
+
126
+
127
+ class AsyncBetaWithRawResponse:
128
+ def __init__(self, beta: AsyncBeta) -> None:
129
+ self._beta = beta
130
+
131
+ @cached_property
132
+ def vector_stores(self) -> AsyncVectorStoresWithRawResponse:
133
+ return AsyncVectorStoresWithRawResponse(self._beta.vector_stores)
134
+
135
+ @cached_property
136
+ def assistants(self) -> AsyncAssistantsWithRawResponse:
137
+ return AsyncAssistantsWithRawResponse(self._beta.assistants)
138
+
139
+ @cached_property
140
+ def threads(self) -> AsyncThreadsWithRawResponse:
141
+ return AsyncThreadsWithRawResponse(self._beta.threads)
142
+
143
+
144
+ class BetaWithStreamingResponse:
145
+ def __init__(self, beta: Beta) -> None:
146
+ self._beta = beta
147
+
148
+ @cached_property
149
+ def vector_stores(self) -> VectorStoresWithStreamingResponse:
150
+ return VectorStoresWithStreamingResponse(self._beta.vector_stores)
151
+
152
+ @cached_property
153
+ def assistants(self) -> AssistantsWithStreamingResponse:
154
+ return AssistantsWithStreamingResponse(self._beta.assistants)
155
+
156
+ @cached_property
157
+ def threads(self) -> ThreadsWithStreamingResponse:
158
+ return ThreadsWithStreamingResponse(self._beta.threads)
159
+
160
+
161
+ class AsyncBetaWithStreamingResponse:
162
+ def __init__(self, beta: AsyncBeta) -> None:
163
+ self._beta = beta
164
+
165
+ @cached_property
166
+ def vector_stores(self) -> AsyncVectorStoresWithStreamingResponse:
167
+ return AsyncVectorStoresWithStreamingResponse(self._beta.vector_stores)
168
+
169
+ @cached_property
170
+ def assistants(self) -> AsyncAssistantsWithStreamingResponse:
171
+ return AsyncAssistantsWithStreamingResponse(self._beta.assistants)
172
+
173
+ @cached_property
174
+ def threads(self) -> AsyncThreadsWithStreamingResponse:
175
+ return AsyncThreadsWithStreamingResponse(self._beta.threads)
vllm/lib/python3.10/site-packages/openai/resources/beta/chat/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from .chat import Chat, AsyncChat
4
+ from .completions import Completions, AsyncCompletions
5
+
6
+ __all__ = [
7
+ "Completions",
8
+ "AsyncCompletions",
9
+ "Chat",
10
+ "AsyncChat",
11
+ ]
vllm/lib/python3.10/site-packages/openai/resources/beta/chat/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (344 Bytes). View file
 
vllm/lib/python3.10/site-packages/openai/resources/beta/chat/__pycache__/chat.cpython-310.pyc ADDED
Binary file (1 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/beta/chat/__pycache__/completions.cpython-310.pyc ADDED
Binary file (17.5 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/beta/chat/chat.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from ...._compat import cached_property
6
+ from .completions import Completions, AsyncCompletions
7
+ from ...._resource import SyncAPIResource, AsyncAPIResource
8
+
9
+ __all__ = ["Chat", "AsyncChat"]
10
+
11
+
12
+ class Chat(SyncAPIResource):
13
+ @cached_property
14
+ def completions(self) -> Completions:
15
+ return Completions(self._client)
16
+
17
+
18
+ class AsyncChat(AsyncAPIResource):
19
+ @cached_property
20
+ def completions(self) -> AsyncCompletions:
21
+ return AsyncCompletions(self._client)
vllm/lib/python3.10/site-packages/openai/resources/beta/chat/completions.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Dict, List, Type, Union, Iterable, Optional, cast
6
+ from functools import partial
7
+ from typing_extensions import Literal
8
+
9
+ import httpx
10
+
11
+ from .... import _legacy_response
12
+ from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven
13
+ from ...._utils import maybe_transform, async_maybe_transform
14
+ from ...._compat import cached_property
15
+ from ...._resource import SyncAPIResource, AsyncAPIResource
16
+ from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
17
+ from ...._streaming import Stream
18
+ from ....types.chat import completion_create_params
19
+ from ...._base_client import make_request_options
20
+ from ....lib._parsing import (
21
+ ResponseFormatT,
22
+ validate_input_tools as _validate_input_tools,
23
+ parse_chat_completion as _parse_chat_completion,
24
+ type_to_response_format_param as _type_to_response_format,
25
+ )
26
+ from ....types.chat_model import ChatModel
27
+ from ....lib.streaming.chat import ChatCompletionStreamManager, AsyncChatCompletionStreamManager
28
+ from ....types.chat.chat_completion import ChatCompletion
29
+ from ....types.chat.chat_completion_chunk import ChatCompletionChunk
30
+ from ....types.chat.parsed_chat_completion import ParsedChatCompletion
31
+ from ....types.chat.chat_completion_modality import ChatCompletionModality
32
+ from ....types.chat.chat_completion_tool_param import ChatCompletionToolParam
33
+ from ....types.chat.chat_completion_audio_param import ChatCompletionAudioParam
34
+ from ....types.chat.chat_completion_message_param import ChatCompletionMessageParam
35
+ from ....types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam
36
+ from ....types.chat.chat_completion_prediction_content_param import ChatCompletionPredictionContentParam
37
+ from ....types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam
38
+
39
+ __all__ = ["Completions", "AsyncCompletions"]
40
+
41
+
42
+ class Completions(SyncAPIResource):
43
+ @cached_property
44
+ def with_raw_response(self) -> CompletionsWithRawResponse:
45
+ """
46
+ This property can be used as a prefix for any HTTP method call to return the
47
+ the raw response object instead of the parsed content.
48
+
49
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
50
+ """
51
+ return CompletionsWithRawResponse(self)
52
+
53
+ @cached_property
54
+ def with_streaming_response(self) -> CompletionsWithStreamingResponse:
55
+ """
56
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
57
+
58
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
59
+ """
60
+ return CompletionsWithStreamingResponse(self)
61
+
62
+ def parse(
63
+ self,
64
+ *,
65
+ messages: Iterable[ChatCompletionMessageParam],
66
+ model: Union[str, ChatModel],
67
+ audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN,
68
+ response_format: type[ResponseFormatT] | NotGiven = NOT_GIVEN,
69
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
70
+ function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN,
71
+ functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN,
72
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
73
+ logprobs: Optional[bool] | NotGiven = NOT_GIVEN,
74
+ max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN,
75
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
76
+ metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN,
77
+ modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN,
78
+ n: Optional[int] | NotGiven = NOT_GIVEN,
79
+ parallel_tool_calls: bool | NotGiven = NOT_GIVEN,
80
+ prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN,
81
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
82
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
83
+ service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN,
84
+ stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN,
85
+ store: Optional[bool] | NotGiven = NOT_GIVEN,
86
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
87
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
88
+ tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN,
89
+ tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN,
90
+ top_logprobs: Optional[int] | NotGiven = NOT_GIVEN,
91
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
92
+ user: str | NotGiven = NOT_GIVEN,
93
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
94
+ # The extra values given here take precedence over values defined on the client or passed to this method.
95
+ extra_headers: Headers | None = None,
96
+ extra_query: Query | None = None,
97
+ extra_body: Body | None = None,
98
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
99
+ ) -> ParsedChatCompletion[ResponseFormatT]:
100
+ """Wrapper over the `client.chat.completions.create()` method that provides richer integrations with Python specific types
101
+ & returns a `ParsedChatCompletion` object, which is a subclass of the standard `ChatCompletion` class.
102
+
103
+ You can pass a pydantic model to this method and it will automatically convert the model
104
+ into a JSON schema, send it to the API and parse the response content back into the given model.
105
+
106
+ This method will also automatically parse `function` tool calls if:
107
+ - You use the `openai.pydantic_function_tool()` helper method
108
+ - You mark your tool schema with `"strict": True`
109
+
110
+ Example usage:
111
+ ```py
112
+ from pydantic import BaseModel
113
+ from openai import OpenAI
114
+
115
+
116
+ class Step(BaseModel):
117
+ explanation: str
118
+ output: str
119
+
120
+
121
+ class MathResponse(BaseModel):
122
+ steps: List[Step]
123
+ final_answer: str
124
+
125
+
126
+ client = OpenAI()
127
+ completion = client.beta.chat.completions.parse(
128
+ model="gpt-4o-2024-08-06",
129
+ messages=[
130
+ {"role": "system", "content": "You are a helpful math tutor."},
131
+ {"role": "user", "content": "solve 8x + 31 = 2"},
132
+ ],
133
+ response_format=MathResponse,
134
+ )
135
+
136
+ message = completion.choices[0].message
137
+ if message.parsed:
138
+ print(message.parsed.steps)
139
+ print("answer: ", message.parsed.final_answer)
140
+ ```
141
+ """
142
+ _validate_input_tools(tools)
143
+
144
+ extra_headers = {
145
+ "X-Stainless-Helper-Method": "beta.chat.completions.parse",
146
+ **(extra_headers or {}),
147
+ }
148
+
149
+ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseFormatT]:
150
+ return _parse_chat_completion(
151
+ response_format=response_format,
152
+ chat_completion=raw_completion,
153
+ input_tools=tools,
154
+ )
155
+
156
+ return self._post(
157
+ "/chat/completions",
158
+ body=maybe_transform(
159
+ {
160
+ "messages": messages,
161
+ "model": model,
162
+ "audio": audio,
163
+ "frequency_penalty": frequency_penalty,
164
+ "function_call": function_call,
165
+ "functions": functions,
166
+ "logit_bias": logit_bias,
167
+ "logprobs": logprobs,
168
+ "max_completion_tokens": max_completion_tokens,
169
+ "max_tokens": max_tokens,
170
+ "metadata": metadata,
171
+ "modalities": modalities,
172
+ "n": n,
173
+ "parallel_tool_calls": parallel_tool_calls,
174
+ "prediction": prediction,
175
+ "presence_penalty": presence_penalty,
176
+ "response_format": _type_to_response_format(response_format),
177
+ "seed": seed,
178
+ "service_tier": service_tier,
179
+ "stop": stop,
180
+ "store": store,
181
+ "stream": False,
182
+ "stream_options": stream_options,
183
+ "temperature": temperature,
184
+ "tool_choice": tool_choice,
185
+ "tools": tools,
186
+ "top_logprobs": top_logprobs,
187
+ "top_p": top_p,
188
+ "user": user,
189
+ },
190
+ completion_create_params.CompletionCreateParams,
191
+ ),
192
+ options=make_request_options(
193
+ extra_headers=extra_headers,
194
+ extra_query=extra_query,
195
+ extra_body=extra_body,
196
+ timeout=timeout,
197
+ post_parser=parser,
198
+ ),
199
+ # we turn the `ChatCompletion` instance into a `ParsedChatCompletion`
200
+ # in the `parser` function above
201
+ cast_to=cast(Type[ParsedChatCompletion[ResponseFormatT]], ChatCompletion),
202
+ stream=False,
203
+ )
204
+
205
+ def stream(
206
+ self,
207
+ *,
208
+ messages: Iterable[ChatCompletionMessageParam],
209
+ model: Union[str, ChatModel],
210
+ audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN,
211
+ response_format: completion_create_params.ResponseFormat | type[ResponseFormatT] | NotGiven = NOT_GIVEN,
212
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
213
+ function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN,
214
+ functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN,
215
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
216
+ logprobs: Optional[bool] | NotGiven = NOT_GIVEN,
217
+ max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN,
218
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
219
+ metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN,
220
+ modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN,
221
+ n: Optional[int] | NotGiven = NOT_GIVEN,
222
+ parallel_tool_calls: bool | NotGiven = NOT_GIVEN,
223
+ prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN,
224
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
225
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
226
+ service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN,
227
+ stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN,
228
+ store: Optional[bool] | NotGiven = NOT_GIVEN,
229
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
230
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
231
+ tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN,
232
+ tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN,
233
+ top_logprobs: Optional[int] | NotGiven = NOT_GIVEN,
234
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
235
+ user: str | NotGiven = NOT_GIVEN,
236
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
237
+ # The extra values given here take precedence over values defined on the client or passed to this method.
238
+ extra_headers: Headers | None = None,
239
+ extra_query: Query | None = None,
240
+ extra_body: Body | None = None,
241
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
242
+ ) -> ChatCompletionStreamManager[ResponseFormatT]:
243
+ """Wrapper over the `client.chat.completions.create(stream=True)` method that provides a more granular event API
244
+ and automatic accumulation of each delta.
245
+
246
+ This also supports all of the parsing utilities that `.parse()` does.
247
+
248
+ Unlike `.create(stream=True)`, the `.stream()` method requires usage within a context manager to prevent accidental leakage of the response:
249
+
250
+ ```py
251
+ with client.beta.chat.completions.stream(
252
+ model="gpt-4o-2024-08-06",
253
+ messages=[...],
254
+ ) as stream:
255
+ for event in stream:
256
+ if event.type == "content.delta":
257
+ print(event.delta, flush=True, end="")
258
+ ```
259
+
260
+ When the context manager is entered, a `ChatCompletionStream` instance is returned which, like `.create(stream=True)` is an iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events).
261
+
262
+ When the context manager exits, the response will be closed, however the `stream` instance is still available outside
263
+ the context manager.
264
+ """
265
+ extra_headers = {
266
+ "X-Stainless-Helper-Method": "beta.chat.completions.stream",
267
+ **(extra_headers or {}),
268
+ }
269
+
270
+ api_request: partial[Stream[ChatCompletionChunk]] = partial(
271
+ self._client.chat.completions.create,
272
+ messages=messages,
273
+ model=model,
274
+ audio=audio,
275
+ stream=True,
276
+ response_format=_type_to_response_format(response_format),
277
+ frequency_penalty=frequency_penalty,
278
+ function_call=function_call,
279
+ functions=functions,
280
+ logit_bias=logit_bias,
281
+ logprobs=logprobs,
282
+ max_completion_tokens=max_completion_tokens,
283
+ max_tokens=max_tokens,
284
+ metadata=metadata,
285
+ modalities=modalities,
286
+ n=n,
287
+ parallel_tool_calls=parallel_tool_calls,
288
+ prediction=prediction,
289
+ presence_penalty=presence_penalty,
290
+ seed=seed,
291
+ service_tier=service_tier,
292
+ store=store,
293
+ stop=stop,
294
+ stream_options=stream_options,
295
+ temperature=temperature,
296
+ tool_choice=tool_choice,
297
+ tools=tools,
298
+ top_logprobs=top_logprobs,
299
+ top_p=top_p,
300
+ user=user,
301
+ extra_headers=extra_headers,
302
+ extra_query=extra_query,
303
+ extra_body=extra_body,
304
+ timeout=timeout,
305
+ )
306
+ return ChatCompletionStreamManager(
307
+ api_request,
308
+ response_format=response_format,
309
+ input_tools=tools,
310
+ )
311
+
312
+
313
+ class AsyncCompletions(AsyncAPIResource):
314
+ @cached_property
315
+ def with_raw_response(self) -> AsyncCompletionsWithRawResponse:
316
+ """
317
+ This property can be used as a prefix for any HTTP method call to return the
318
+ the raw response object instead of the parsed content.
319
+
320
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
321
+ """
322
+ return AsyncCompletionsWithRawResponse(self)
323
+
324
+ @cached_property
325
+ def with_streaming_response(self) -> AsyncCompletionsWithStreamingResponse:
326
+ """
327
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
328
+
329
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
330
+ """
331
+ return AsyncCompletionsWithStreamingResponse(self)
332
+
333
+ async def parse(
334
+ self,
335
+ *,
336
+ messages: Iterable[ChatCompletionMessageParam],
337
+ model: Union[str, ChatModel],
338
+ audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN,
339
+ response_format: type[ResponseFormatT] | NotGiven = NOT_GIVEN,
340
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
341
+ function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN,
342
+ functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN,
343
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
344
+ logprobs: Optional[bool] | NotGiven = NOT_GIVEN,
345
+ max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN,
346
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
347
+ metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN,
348
+ modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN,
349
+ n: Optional[int] | NotGiven = NOT_GIVEN,
350
+ parallel_tool_calls: bool | NotGiven = NOT_GIVEN,
351
+ prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN,
352
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
353
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
354
+ service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN,
355
+ stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN,
356
+ store: Optional[bool] | NotGiven = NOT_GIVEN,
357
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
358
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
359
+ tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN,
360
+ tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN,
361
+ top_logprobs: Optional[int] | NotGiven = NOT_GIVEN,
362
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
363
+ user: str | NotGiven = NOT_GIVEN,
364
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
365
+ # The extra values given here take precedence over values defined on the client or passed to this method.
366
+ extra_headers: Headers | None = None,
367
+ extra_query: Query | None = None,
368
+ extra_body: Body | None = None,
369
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
370
+ ) -> ParsedChatCompletion[ResponseFormatT]:
371
+ """Wrapper over the `client.chat.completions.create()` method that provides richer integrations with Python specific types
372
+ & returns a `ParsedChatCompletion` object, which is a subclass of the standard `ChatCompletion` class.
373
+
374
+ You can pass a pydantic model to this method and it will automatically convert the model
375
+ into a JSON schema, send it to the API and parse the response content back into the given model.
376
+
377
+ This method will also automatically parse `function` tool calls if:
378
+ - You use the `openai.pydantic_function_tool()` helper method
379
+ - You mark your tool schema with `"strict": True`
380
+
381
+ Example usage:
382
+ ```py
383
+ from pydantic import BaseModel
384
+ from openai import AsyncOpenAI
385
+
386
+
387
+ class Step(BaseModel):
388
+ explanation: str
389
+ output: str
390
+
391
+
392
+ class MathResponse(BaseModel):
393
+ steps: List[Step]
394
+ final_answer: str
395
+
396
+
397
+ client = AsyncOpenAI()
398
+ completion = await client.beta.chat.completions.parse(
399
+ model="gpt-4o-2024-08-06",
400
+ messages=[
401
+ {"role": "system", "content": "You are a helpful math tutor."},
402
+ {"role": "user", "content": "solve 8x + 31 = 2"},
403
+ ],
404
+ response_format=MathResponse,
405
+ )
406
+
407
+ message = completion.choices[0].message
408
+ if message.parsed:
409
+ print(message.parsed.steps)
410
+ print("answer: ", message.parsed.final_answer)
411
+ ```
412
+ """
413
+ _validate_input_tools(tools)
414
+
415
+ extra_headers = {
416
+ "X-Stainless-Helper-Method": "beta.chat.completions.parse",
417
+ **(extra_headers or {}),
418
+ }
419
+
420
+ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseFormatT]:
421
+ return _parse_chat_completion(
422
+ response_format=response_format,
423
+ chat_completion=raw_completion,
424
+ input_tools=tools,
425
+ )
426
+
427
+ return await self._post(
428
+ "/chat/completions",
429
+ body=await async_maybe_transform(
430
+ {
431
+ "messages": messages,
432
+ "model": model,
433
+ "audio": audio,
434
+ "frequency_penalty": frequency_penalty,
435
+ "function_call": function_call,
436
+ "functions": functions,
437
+ "logit_bias": logit_bias,
438
+ "logprobs": logprobs,
439
+ "max_completion_tokens": max_completion_tokens,
440
+ "max_tokens": max_tokens,
441
+ "metadata": metadata,
442
+ "modalities": modalities,
443
+ "n": n,
444
+ "parallel_tool_calls": parallel_tool_calls,
445
+ "prediction": prediction,
446
+ "presence_penalty": presence_penalty,
447
+ "response_format": _type_to_response_format(response_format),
448
+ "seed": seed,
449
+ "service_tier": service_tier,
450
+ "store": store,
451
+ "stop": stop,
452
+ "stream": False,
453
+ "stream_options": stream_options,
454
+ "temperature": temperature,
455
+ "tool_choice": tool_choice,
456
+ "tools": tools,
457
+ "top_logprobs": top_logprobs,
458
+ "top_p": top_p,
459
+ "user": user,
460
+ },
461
+ completion_create_params.CompletionCreateParams,
462
+ ),
463
+ options=make_request_options(
464
+ extra_headers=extra_headers,
465
+ extra_query=extra_query,
466
+ extra_body=extra_body,
467
+ timeout=timeout,
468
+ post_parser=parser,
469
+ ),
470
+ # we turn the `ChatCompletion` instance into a `ParsedChatCompletion`
471
+ # in the `parser` function above
472
+ cast_to=cast(Type[ParsedChatCompletion[ResponseFormatT]], ChatCompletion),
473
+ stream=False,
474
+ )
475
+
476
+ def stream(
477
+ self,
478
+ *,
479
+ messages: Iterable[ChatCompletionMessageParam],
480
+ model: Union[str, ChatModel],
481
+ audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN,
482
+ response_format: completion_create_params.ResponseFormat | type[ResponseFormatT] | NotGiven = NOT_GIVEN,
483
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
484
+ function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN,
485
+ functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN,
486
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
487
+ logprobs: Optional[bool] | NotGiven = NOT_GIVEN,
488
+ max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN,
489
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
490
+ metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN,
491
+ modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN,
492
+ n: Optional[int] | NotGiven = NOT_GIVEN,
493
+ parallel_tool_calls: bool | NotGiven = NOT_GIVEN,
494
+ prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN,
495
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
496
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
497
+ service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN,
498
+ stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN,
499
+ store: Optional[bool] | NotGiven = NOT_GIVEN,
500
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
501
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
502
+ tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN,
503
+ tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN,
504
+ top_logprobs: Optional[int] | NotGiven = NOT_GIVEN,
505
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
506
+ user: str | NotGiven = NOT_GIVEN,
507
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
508
+ # The extra values given here take precedence over values defined on the client or passed to this method.
509
+ extra_headers: Headers | None = None,
510
+ extra_query: Query | None = None,
511
+ extra_body: Body | None = None,
512
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
513
+ ) -> AsyncChatCompletionStreamManager[ResponseFormatT]:
514
+ """Wrapper over the `client.chat.completions.create(stream=True)` method that provides a more granular event API
515
+ and automatic accumulation of each delta.
516
+
517
+ This also supports all of the parsing utilities that `.parse()` does.
518
+
519
+ Unlike `.create(stream=True)`, the `.stream()` method requires usage within a context manager to prevent accidental leakage of the response:
520
+
521
+ ```py
522
+ async with client.beta.chat.completions.stream(
523
+ model="gpt-4o-2024-08-06",
524
+ messages=[...],
525
+ ) as stream:
526
+ async for event in stream:
527
+ if event.type == "content.delta":
528
+ print(event.delta, flush=True, end="")
529
+ ```
530
+
531
+ When the context manager is entered, an `AsyncChatCompletionStream` instance is returned which, like `.create(stream=True)` is an async iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events).
532
+
533
+ When the context manager exits, the response will be closed, however the `stream` instance is still available outside
534
+ the context manager.
535
+ """
536
+ _validate_input_tools(tools)
537
+
538
+ extra_headers = {
539
+ "X-Stainless-Helper-Method": "beta.chat.completions.stream",
540
+ **(extra_headers or {}),
541
+ }
542
+
543
+ api_request = self._client.chat.completions.create(
544
+ messages=messages,
545
+ model=model,
546
+ audio=audio,
547
+ stream=True,
548
+ response_format=_type_to_response_format(response_format),
549
+ frequency_penalty=frequency_penalty,
550
+ function_call=function_call,
551
+ functions=functions,
552
+ logit_bias=logit_bias,
553
+ logprobs=logprobs,
554
+ max_completion_tokens=max_completion_tokens,
555
+ max_tokens=max_tokens,
556
+ metadata=metadata,
557
+ modalities=modalities,
558
+ n=n,
559
+ parallel_tool_calls=parallel_tool_calls,
560
+ prediction=prediction,
561
+ presence_penalty=presence_penalty,
562
+ seed=seed,
563
+ service_tier=service_tier,
564
+ stop=stop,
565
+ store=store,
566
+ stream_options=stream_options,
567
+ temperature=temperature,
568
+ tool_choice=tool_choice,
569
+ tools=tools,
570
+ top_logprobs=top_logprobs,
571
+ top_p=top_p,
572
+ user=user,
573
+ extra_headers=extra_headers,
574
+ extra_query=extra_query,
575
+ extra_body=extra_body,
576
+ timeout=timeout,
577
+ )
578
+ return AsyncChatCompletionStreamManager(
579
+ api_request,
580
+ response_format=response_format,
581
+ input_tools=tools,
582
+ )
583
+
584
+
585
+ class CompletionsWithRawResponse:
586
+ def __init__(self, completions: Completions) -> None:
587
+ self._completions = completions
588
+
589
+ self.parse = _legacy_response.to_raw_response_wrapper(
590
+ completions.parse,
591
+ )
592
+
593
+
594
+ class AsyncCompletionsWithRawResponse:
595
+ def __init__(self, completions: AsyncCompletions) -> None:
596
+ self._completions = completions
597
+
598
+ self.parse = _legacy_response.async_to_raw_response_wrapper(
599
+ completions.parse,
600
+ )
601
+
602
+
603
+ class CompletionsWithStreamingResponse:
604
+ def __init__(self, completions: Completions) -> None:
605
+ self._completions = completions
606
+
607
+ self.parse = to_streamed_response_wrapper(
608
+ completions.parse,
609
+ )
610
+
611
+
612
+ class AsyncCompletionsWithStreamingResponse:
613
+ def __init__(self, completions: AsyncCompletions) -> None:
614
+ self._completions = completions
615
+
616
+ self.parse = async_to_streamed_response_wrapper(
617
+ completions.parse,
618
+ )
vllm/lib/python3.10/site-packages/openai/resources/beta/threads/runs/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from .runs import (
4
+ Runs,
5
+ AsyncRuns,
6
+ RunsWithRawResponse,
7
+ AsyncRunsWithRawResponse,
8
+ RunsWithStreamingResponse,
9
+ AsyncRunsWithStreamingResponse,
10
+ )
11
+ from .steps import (
12
+ Steps,
13
+ AsyncSteps,
14
+ StepsWithRawResponse,
15
+ AsyncStepsWithRawResponse,
16
+ StepsWithStreamingResponse,
17
+ AsyncStepsWithStreamingResponse,
18
+ )
19
+
20
+ __all__ = [
21
+ "Steps",
22
+ "AsyncSteps",
23
+ "StepsWithRawResponse",
24
+ "AsyncStepsWithRawResponse",
25
+ "StepsWithStreamingResponse",
26
+ "AsyncStepsWithStreamingResponse",
27
+ "Runs",
28
+ "AsyncRuns",
29
+ "RunsWithRawResponse",
30
+ "AsyncRunsWithRawResponse",
31
+ "RunsWithStreamingResponse",
32
+ "AsyncRunsWithStreamingResponse",
33
+ ]
vllm/lib/python3.10/site-packages/openai/resources/beta/threads/runs/__pycache__/runs.cpython-310.pyc ADDED
Binary file (50.2 kB). View file
 
vllm/lib/python3.10/site-packages/openai/resources/beta/threads/runs/runs.py ADDED
The diff for this file is too large to render. See raw diff
 
vllm/lib/python3.10/site-packages/openai/resources/beta/threads/runs/steps.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List
6
+ from typing_extensions import Literal
7
+
8
+ import httpx
9
+
10
+ from ..... import _legacy_response
11
+ from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven
12
+ from ....._utils import (
13
+ maybe_transform,
14
+ async_maybe_transform,
15
+ )
16
+ from ....._compat import cached_property
17
+ from ....._resource import SyncAPIResource, AsyncAPIResource
18
+ from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
19
+ from .....pagination import SyncCursorPage, AsyncCursorPage
20
+ from ....._base_client import AsyncPaginator, make_request_options
21
+ from .....types.beta.threads.runs import step_list_params, step_retrieve_params
22
+ from .....types.beta.threads.runs.run_step import RunStep
23
+ from .....types.beta.threads.runs.run_step_include import RunStepInclude
24
+
25
+ __all__ = ["Steps", "AsyncSteps"]
26
+
27
+
28
+ class Steps(SyncAPIResource):
29
+ @cached_property
30
+ def with_raw_response(self) -> StepsWithRawResponse:
31
+ """
32
+ This property can be used as a prefix for any HTTP method call to return the
33
+ the raw response object instead of the parsed content.
34
+
35
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
36
+ """
37
+ return StepsWithRawResponse(self)
38
+
39
+ @cached_property
40
+ def with_streaming_response(self) -> StepsWithStreamingResponse:
41
+ """
42
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
43
+
44
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
45
+ """
46
+ return StepsWithStreamingResponse(self)
47
+
48
+ def retrieve(
49
+ self,
50
+ step_id: str,
51
+ *,
52
+ thread_id: str,
53
+ run_id: str,
54
+ include: List[RunStepInclude] | NotGiven = NOT_GIVEN,
55
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
56
+ # The extra values given here take precedence over values defined on the client or passed to this method.
57
+ extra_headers: Headers | None = None,
58
+ extra_query: Query | None = None,
59
+ extra_body: Body | None = None,
60
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
61
+ ) -> RunStep:
62
+ """
63
+ Retrieves a run step.
64
+
65
+ Args:
66
+ include: A list of additional fields to include in the response. Currently the only
67
+ supported value is `step_details.tool_calls[*].file_search.results[*].content`
68
+ to fetch the file search result content.
69
+
70
+ See the
71
+ [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)
72
+ for more information.
73
+
74
+ extra_headers: Send extra headers
75
+
76
+ extra_query: Add additional query parameters to the request
77
+
78
+ extra_body: Add additional JSON properties to the request
79
+
80
+ timeout: Override the client-level default timeout for this request, in seconds
81
+ """
82
+ if not thread_id:
83
+ raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
84
+ if not run_id:
85
+ raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}")
86
+ if not step_id:
87
+ raise ValueError(f"Expected a non-empty value for `step_id` but received {step_id!r}")
88
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
89
+ return self._get(
90
+ f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}",
91
+ options=make_request_options(
92
+ extra_headers=extra_headers,
93
+ extra_query=extra_query,
94
+ extra_body=extra_body,
95
+ timeout=timeout,
96
+ query=maybe_transform({"include": include}, step_retrieve_params.StepRetrieveParams),
97
+ ),
98
+ cast_to=RunStep,
99
+ )
100
+
101
+ def list(
102
+ self,
103
+ run_id: str,
104
+ *,
105
+ thread_id: str,
106
+ after: str | NotGiven = NOT_GIVEN,
107
+ before: str | NotGiven = NOT_GIVEN,
108
+ include: List[RunStepInclude] | NotGiven = NOT_GIVEN,
109
+ limit: int | NotGiven = NOT_GIVEN,
110
+ order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN,
111
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
112
+ # The extra values given here take precedence over values defined on the client or passed to this method.
113
+ extra_headers: Headers | None = None,
114
+ extra_query: Query | None = None,
115
+ extra_body: Body | None = None,
116
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
117
+ ) -> SyncCursorPage[RunStep]:
118
+ """
119
+ Returns a list of run steps belonging to a run.
120
+
121
+ Args:
122
+ after: A cursor for use in pagination. `after` is an object ID that defines your place
123
+ in the list. For instance, if you make a list request and receive 100 objects,
124
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
125
+ fetch the next page of the list.
126
+
127
+ before: A cursor for use in pagination. `before` is an object ID that defines your place
128
+ in the list. For instance, if you make a list request and receive 100 objects,
129
+ starting with obj_foo, your subsequent call can include before=obj_foo in order
130
+ to fetch the previous page of the list.
131
+
132
+ include: A list of additional fields to include in the response. Currently the only
133
+ supported value is `step_details.tool_calls[*].file_search.results[*].content`
134
+ to fetch the file search result content.
135
+
136
+ See the
137
+ [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)
138
+ for more information.
139
+
140
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
141
+ 100, and the default is 20.
142
+
143
+ order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending
144
+ order and `desc` for descending order.
145
+
146
+ extra_headers: Send extra headers
147
+
148
+ extra_query: Add additional query parameters to the request
149
+
150
+ extra_body: Add additional JSON properties to the request
151
+
152
+ timeout: Override the client-level default timeout for this request, in seconds
153
+ """
154
+ if not thread_id:
155
+ raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
156
+ if not run_id:
157
+ raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}")
158
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
159
+ return self._get_api_list(
160
+ f"/threads/{thread_id}/runs/{run_id}/steps",
161
+ page=SyncCursorPage[RunStep],
162
+ options=make_request_options(
163
+ extra_headers=extra_headers,
164
+ extra_query=extra_query,
165
+ extra_body=extra_body,
166
+ timeout=timeout,
167
+ query=maybe_transform(
168
+ {
169
+ "after": after,
170
+ "before": before,
171
+ "include": include,
172
+ "limit": limit,
173
+ "order": order,
174
+ },
175
+ step_list_params.StepListParams,
176
+ ),
177
+ ),
178
+ model=RunStep,
179
+ )
180
+
181
+
182
+ class AsyncSteps(AsyncAPIResource):
183
+ @cached_property
184
+ def with_raw_response(self) -> AsyncStepsWithRawResponse:
185
+ """
186
+ This property can be used as a prefix for any HTTP method call to return the
187
+ the raw response object instead of the parsed content.
188
+
189
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
190
+ """
191
+ return AsyncStepsWithRawResponse(self)
192
+
193
+ @cached_property
194
+ def with_streaming_response(self) -> AsyncStepsWithStreamingResponse:
195
+ """
196
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
197
+
198
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
199
+ """
200
+ return AsyncStepsWithStreamingResponse(self)
201
+
202
+ async def retrieve(
203
+ self,
204
+ step_id: str,
205
+ *,
206
+ thread_id: str,
207
+ run_id: str,
208
+ include: List[RunStepInclude] | NotGiven = NOT_GIVEN,
209
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
210
+ # The extra values given here take precedence over values defined on the client or passed to this method.
211
+ extra_headers: Headers | None = None,
212
+ extra_query: Query | None = None,
213
+ extra_body: Body | None = None,
214
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
215
+ ) -> RunStep:
216
+ """
217
+ Retrieves a run step.
218
+
219
+ Args:
220
+ include: A list of additional fields to include in the response. Currently the only
221
+ supported value is `step_details.tool_calls[*].file_search.results[*].content`
222
+ to fetch the file search result content.
223
+
224
+ See the
225
+ [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)
226
+ for more information.
227
+
228
+ extra_headers: Send extra headers
229
+
230
+ extra_query: Add additional query parameters to the request
231
+
232
+ extra_body: Add additional JSON properties to the request
233
+
234
+ timeout: Override the client-level default timeout for this request, in seconds
235
+ """
236
+ if not thread_id:
237
+ raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
238
+ if not run_id:
239
+ raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}")
240
+ if not step_id:
241
+ raise ValueError(f"Expected a non-empty value for `step_id` but received {step_id!r}")
242
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
243
+ return await self._get(
244
+ f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}",
245
+ options=make_request_options(
246
+ extra_headers=extra_headers,
247
+ extra_query=extra_query,
248
+ extra_body=extra_body,
249
+ timeout=timeout,
250
+ query=await async_maybe_transform({"include": include}, step_retrieve_params.StepRetrieveParams),
251
+ ),
252
+ cast_to=RunStep,
253
+ )
254
+
255
+ def list(
256
+ self,
257
+ run_id: str,
258
+ *,
259
+ thread_id: str,
260
+ after: str | NotGiven = NOT_GIVEN,
261
+ before: str | NotGiven = NOT_GIVEN,
262
+ include: List[RunStepInclude] | NotGiven = NOT_GIVEN,
263
+ limit: int | NotGiven = NOT_GIVEN,
264
+ order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN,
265
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
266
+ # The extra values given here take precedence over values defined on the client or passed to this method.
267
+ extra_headers: Headers | None = None,
268
+ extra_query: Query | None = None,
269
+ extra_body: Body | None = None,
270
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
271
+ ) -> AsyncPaginator[RunStep, AsyncCursorPage[RunStep]]:
272
+ """
273
+ Returns a list of run steps belonging to a run.
274
+
275
+ Args:
276
+ after: A cursor for use in pagination. `after` is an object ID that defines your place
277
+ in the list. For instance, if you make a list request and receive 100 objects,
278
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
279
+ fetch the next page of the list.
280
+
281
+ before: A cursor for use in pagination. `before` is an object ID that defines your place
282
+ in the list. For instance, if you make a list request and receive 100 objects,
283
+ starting with obj_foo, your subsequent call can include before=obj_foo in order
284
+ to fetch the previous page of the list.
285
+
286
+ include: A list of additional fields to include in the response. Currently the only
287
+ supported value is `step_details.tool_calls[*].file_search.results[*].content`
288
+ to fetch the file search result content.
289
+
290
+ See the
291
+ [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings)
292
+ for more information.
293
+
294
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
295
+ 100, and the default is 20.
296
+
297
+ order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending
298
+ order and `desc` for descending order.
299
+
300
+ extra_headers: Send extra headers
301
+
302
+ extra_query: Add additional query parameters to the request
303
+
304
+ extra_body: Add additional JSON properties to the request
305
+
306
+ timeout: Override the client-level default timeout for this request, in seconds
307
+ """
308
+ if not thread_id:
309
+ raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}")
310
+ if not run_id:
311
+ raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}")
312
+ extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})}
313
+ return self._get_api_list(
314
+ f"/threads/{thread_id}/runs/{run_id}/steps",
315
+ page=AsyncCursorPage[RunStep],
316
+ options=make_request_options(
317
+ extra_headers=extra_headers,
318
+ extra_query=extra_query,
319
+ extra_body=extra_body,
320
+ timeout=timeout,
321
+ query=maybe_transform(
322
+ {
323
+ "after": after,
324
+ "before": before,
325
+ "include": include,
326
+ "limit": limit,
327
+ "order": order,
328
+ },
329
+ step_list_params.StepListParams,
330
+ ),
331
+ ),
332
+ model=RunStep,
333
+ )
334
+
335
+
336
+ class StepsWithRawResponse:
337
+ def __init__(self, steps: Steps) -> None:
338
+ self._steps = steps
339
+
340
+ self.retrieve = _legacy_response.to_raw_response_wrapper(
341
+ steps.retrieve,
342
+ )
343
+ self.list = _legacy_response.to_raw_response_wrapper(
344
+ steps.list,
345
+ )
346
+
347
+
348
+ class AsyncStepsWithRawResponse:
349
+ def __init__(self, steps: AsyncSteps) -> None:
350
+ self._steps = steps
351
+
352
+ self.retrieve = _legacy_response.async_to_raw_response_wrapper(
353
+ steps.retrieve,
354
+ )
355
+ self.list = _legacy_response.async_to_raw_response_wrapper(
356
+ steps.list,
357
+ )
358
+
359
+
360
+ class StepsWithStreamingResponse:
361
+ def __init__(self, steps: Steps) -> None:
362
+ self._steps = steps
363
+
364
+ self.retrieve = to_streamed_response_wrapper(
365
+ steps.retrieve,
366
+ )
367
+ self.list = to_streamed_response_wrapper(
368
+ steps.list,
369
+ )
370
+
371
+
372
+ class AsyncStepsWithStreamingResponse:
373
+ def __init__(self, steps: AsyncSteps) -> None:
374
+ self._steps = steps
375
+
376
+ self.retrieve = async_to_streamed_response_wrapper(
377
+ steps.retrieve,
378
+ )
379
+ self.list = async_to_streamed_response_wrapper(
380
+ steps.list,
381
+ )
vllm/lib/python3.10/site-packages/openai/resources/beta/vector_stores/__init__.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from .files import (
4
+ Files,
5
+ AsyncFiles,
6
+ FilesWithRawResponse,
7
+ AsyncFilesWithRawResponse,
8
+ FilesWithStreamingResponse,
9
+ AsyncFilesWithStreamingResponse,
10
+ )
11
+ from .file_batches import (
12
+ FileBatches,
13
+ AsyncFileBatches,
14
+ FileBatchesWithRawResponse,
15
+ AsyncFileBatchesWithRawResponse,
16
+ FileBatchesWithStreamingResponse,
17
+ AsyncFileBatchesWithStreamingResponse,
18
+ )
19
+ from .vector_stores import (
20
+ VectorStores,
21
+ AsyncVectorStores,
22
+ VectorStoresWithRawResponse,
23
+ AsyncVectorStoresWithRawResponse,
24
+ VectorStoresWithStreamingResponse,
25
+ AsyncVectorStoresWithStreamingResponse,
26
+ )
27
+
28
+ __all__ = [
29
+ "Files",
30
+ "AsyncFiles",
31
+ "FilesWithRawResponse",
32
+ "AsyncFilesWithRawResponse",
33
+ "FilesWithStreamingResponse",
34
+ "AsyncFilesWithStreamingResponse",
35
+ "FileBatches",
36
+ "AsyncFileBatches",
37
+ "FileBatchesWithRawResponse",
38
+ "AsyncFileBatchesWithRawResponse",
39
+ "FileBatchesWithStreamingResponse",
40
+ "AsyncFileBatchesWithStreamingResponse",
41
+ "VectorStores",
42
+ "AsyncVectorStores",
43
+ "VectorStoresWithRawResponse",
44
+ "AsyncVectorStoresWithRawResponse",
45
+ "VectorStoresWithStreamingResponse",
46
+ "AsyncVectorStoresWithStreamingResponse",
47
+ ]