openai/openai-python

Public

mirrored from https://github.com/openai/openai-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
22bbd4a092b5248a4a96a08750ca613117fc1a38

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/openai/_client.py

543lines · modecode

1# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
3from __future__ import annotations
4
5import os
6from typing import Any, Union, Mapping
7from typing_extensions import Self, override
8
9import httpx
10
11from . import resources, _exceptions
12from ._qs import Querystring
13from ._types import (
14 NOT_GIVEN,
15 Omit,
16 Timeout,
17 NotGiven,
18 Transport,
19 ProxiesTypes,
20 RequestOptions,
21)
22from ._utils import (
23 is_given,
24 is_mapping,
25 get_async_library,
26)
27from ._version import __version__
28from ._streaming import Stream as Stream, AsyncStream as AsyncStream
29from ._exceptions import OpenAIError, APIStatusError
30from ._base_client import (
31 DEFAULT_MAX_RETRIES,
32 SyncAPIClient,
33 AsyncAPIClient,
34)
35
36__all__ = [
37 "Timeout",
38 "Transport",
39 "ProxiesTypes",
40 "RequestOptions",
41 "resources",
42 "OpenAI",
43 "AsyncOpenAI",
44 "Client",
45 "AsyncClient",
46]
47
48
49class OpenAI(SyncAPIClient):
50 completions: resources.Completions
51 chat: resources.Chat
52 embeddings: resources.Embeddings
53 files: resources.Files
54 images: resources.Images
55 audio: resources.Audio
56 moderations: resources.Moderations
57 models: resources.Models
58 fine_tuning: resources.FineTuning
59 beta: resources.Beta
60 batches: resources.Batches
61 uploads: resources.Uploads
62 with_raw_response: OpenAIWithRawResponse
63 with_streaming_response: OpenAIWithStreamedResponse
64
65 # client options
66 api_key: str
67 organization: str | None
68 project: str | None
69
70 def __init__(
71 self,
72 *,
73 api_key: str | None = None,
74 organization: str | None = None,
75 project: str | None = None,
76 base_url: str | httpx.URL | None = None,
77 timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
78 max_retries: int = DEFAULT_MAX_RETRIES,
79 default_headers: Mapping[str, str] | None = None,
80 default_query: Mapping[str, object] | None = None,
81 # Configure a custom httpx client.
82 # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
83 # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details.
84 http_client: httpx.Client | None = None,
85 # Enable or disable schema validation for data returned by the API.
86 # When enabled an error APIResponseValidationError is raised
87 # if the API responds with invalid data for the expected schema.
88 #
89 # This parameter may be removed or changed in the future.
90 # If you rely on this feature, please open a GitHub issue
91 # outlining your use-case to help us decide if it should be
92 # part of our public interface in the future.
93 _strict_response_validation: bool = False,
94 ) -> None:
95 """Construct a new synchronous openai client instance.
96
97 This automatically infers the following arguments from their corresponding environment variables if they are not provided:
98 - `api_key` from `OPENAI_API_KEY`
99 - `organization` from `OPENAI_ORG_ID`
100 - `project` from `OPENAI_PROJECT_ID`
101 """
102 if api_key is None:
103 api_key = os.environ.get("OPENAI_API_KEY")
104 if api_key is None:
105 raise OpenAIError(
106 "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"
107 )
108 self.api_key = api_key
109
110 if organization is None:
111 organization = os.environ.get("OPENAI_ORG_ID")
112 self.organization = organization
113
114 if project is None:
115 project = os.environ.get("OPENAI_PROJECT_ID")
116 self.project = project
117
118 if base_url is None:
119 base_url = os.environ.get("OPENAI_BASE_URL")
120 if base_url is None:
121 base_url = f"https://api.openai.com/v1"
122
123 super().__init__(
124 version=__version__,
125 base_url=base_url,
126 max_retries=max_retries,
127 timeout=timeout,
128 http_client=http_client,
129 custom_headers=default_headers,
130 custom_query=default_query,
131 _strict_response_validation=_strict_response_validation,
132 )
133
134 self._default_stream_cls = Stream
135
136 self.completions = resources.Completions(self)
137 self.chat = resources.Chat(self)
138 self.embeddings = resources.Embeddings(self)
139 self.files = resources.Files(self)
140 self.images = resources.Images(self)
141 self.audio = resources.Audio(self)
142 self.moderations = resources.Moderations(self)
143 self.models = resources.Models(self)
144 self.fine_tuning = resources.FineTuning(self)
145 self.beta = resources.Beta(self)
146 self.batches = resources.Batches(self)
147 self.uploads = resources.Uploads(self)
148 self.with_raw_response = OpenAIWithRawResponse(self)
149 self.with_streaming_response = OpenAIWithStreamedResponse(self)
150
151 @property
152 @override
153 def qs(self) -> Querystring:
154 return Querystring(array_format="brackets")
155
156 @property
157 @override
158 def auth_headers(self) -> dict[str, str]:
159 api_key = self.api_key
160 return {"Authorization": f"Bearer {api_key}"}
161
162 @property
163 @override
164 def default_headers(self) -> dict[str, str | Omit]:
165 return {
166 **super().default_headers,
167 "X-Stainless-Async": "false",
168 "OpenAI-Organization": self.organization if self.organization is not None else Omit(),
169 "OpenAI-Project": self.project if self.project is not None else Omit(),
170 **self._custom_headers,
171 }
172
173 def copy(
174 self,
175 *,
176 api_key: str | None = None,
177 organization: str | None = None,
178 project: str | None = None,
179 base_url: str | httpx.URL | None = None,
180 timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
181 http_client: httpx.Client | None = None,
182 max_retries: int | NotGiven = NOT_GIVEN,
183 default_headers: Mapping[str, str] | None = None,
184 set_default_headers: Mapping[str, str] | None = None,
185 default_query: Mapping[str, object] | None = None,
186 set_default_query: Mapping[str, object] | None = None,
187 _extra_kwargs: Mapping[str, Any] = {},
188 ) -> Self:
189 """
190 Create a new client instance re-using the same options given to the current client with optional overriding.
191 """
192 if default_headers is not None and set_default_headers is not None:
193 raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
194
195 if default_query is not None and set_default_query is not None:
196 raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
197
198 headers = self._custom_headers
199 if default_headers is not None:
200 headers = {**headers, **default_headers}
201 elif set_default_headers is not None:
202 headers = set_default_headers
203
204 params = self._custom_query
205 if default_query is not None:
206 params = {**params, **default_query}
207 elif set_default_query is not None:
208 params = set_default_query
209
210 http_client = http_client or self._client
211 return self.__class__(
212 api_key=api_key or self.api_key,
213 organization=organization or self.organization,
214 project=project or self.project,
215 base_url=base_url or self.base_url,
216 timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
217 http_client=http_client,
218 max_retries=max_retries if is_given(max_retries) else self.max_retries,
219 default_headers=headers,
220 default_query=params,
221 **_extra_kwargs,
222 )
223
224 # Alias for `copy` for nicer inline usage, e.g.
225 # client.with_options(timeout=10).foo.create(...)
226 with_options = copy
227
228 @override
229 def _make_status_error(
230 self,
231 err_msg: str,
232 *,
233 body: object,
234 response: httpx.Response,
235 ) -> APIStatusError:
236 data = body.get("error", body) if is_mapping(body) else body
237 if response.status_code == 400:
238 return _exceptions.BadRequestError(err_msg, response=response, body=data)
239
240 if response.status_code == 401:
241 return _exceptions.AuthenticationError(err_msg, response=response, body=data)
242
243 if response.status_code == 403:
244 return _exceptions.PermissionDeniedError(err_msg, response=response, body=data)
245
246 if response.status_code == 404:
247 return _exceptions.NotFoundError(err_msg, response=response, body=data)
248
249 if response.status_code == 409:
250 return _exceptions.ConflictError(err_msg, response=response, body=data)
251
252 if response.status_code == 422:
253 return _exceptions.UnprocessableEntityError(err_msg, response=response, body=data)
254
255 if response.status_code == 429:
256 return _exceptions.RateLimitError(err_msg, response=response, body=data)
257
258 if response.status_code >= 500:
259 return _exceptions.InternalServerError(err_msg, response=response, body=data)
260 return APIStatusError(err_msg, response=response, body=data)
261
262
263class AsyncOpenAI(AsyncAPIClient):
264 completions: resources.AsyncCompletions
265 chat: resources.AsyncChat
266 embeddings: resources.AsyncEmbeddings
267 files: resources.AsyncFiles
268 images: resources.AsyncImages
269 audio: resources.AsyncAudio
270 moderations: resources.AsyncModerations
271 models: resources.AsyncModels
272 fine_tuning: resources.AsyncFineTuning
273 beta: resources.AsyncBeta
274 batches: resources.AsyncBatches
275 uploads: resources.AsyncUploads
276 with_raw_response: AsyncOpenAIWithRawResponse
277 with_streaming_response: AsyncOpenAIWithStreamedResponse
278
279 # client options
280 api_key: str
281 organization: str | None
282 project: str | None
283
284 def __init__(
285 self,
286 *,
287 api_key: str | None = None,
288 organization: str | None = None,
289 project: str | None = None,
290 base_url: str | httpx.URL | None = None,
291 timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
292 max_retries: int = DEFAULT_MAX_RETRIES,
293 default_headers: Mapping[str, str] | None = None,
294 default_query: Mapping[str, object] | None = None,
295 # Configure a custom httpx client.
296 # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
297 # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details.
298 http_client: httpx.AsyncClient | None = None,
299 # Enable or disable schema validation for data returned by the API.
300 # When enabled an error APIResponseValidationError is raised
301 # if the API responds with invalid data for the expected schema.
302 #
303 # This parameter may be removed or changed in the future.
304 # If you rely on this feature, please open a GitHub issue
305 # outlining your use-case to help us decide if it should be
306 # part of our public interface in the future.
307 _strict_response_validation: bool = False,
308 ) -> None:
309 """Construct a new async openai client instance.
310
311 This automatically infers the following arguments from their corresponding environment variables if they are not provided:
312 - `api_key` from `OPENAI_API_KEY`
313 - `organization` from `OPENAI_ORG_ID`
314 - `project` from `OPENAI_PROJECT_ID`
315 """
316 if api_key is None:
317 api_key = os.environ.get("OPENAI_API_KEY")
318 if api_key is None:
319 raise OpenAIError(
320 "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"
321 )
322 self.api_key = api_key
323
324 if organization is None:
325 organization = os.environ.get("OPENAI_ORG_ID")
326 self.organization = organization
327
328 if project is None:
329 project = os.environ.get("OPENAI_PROJECT_ID")
330 self.project = project
331
332 if base_url is None:
333 base_url = os.environ.get("OPENAI_BASE_URL")
334 if base_url is None:
335 base_url = f"https://api.openai.com/v1"
336
337 super().__init__(
338 version=__version__,
339 base_url=base_url,
340 max_retries=max_retries,
341 timeout=timeout,
342 http_client=http_client,
343 custom_headers=default_headers,
344 custom_query=default_query,
345 _strict_response_validation=_strict_response_validation,
346 )
347
348 self._default_stream_cls = AsyncStream
349
350 self.completions = resources.AsyncCompletions(self)
351 self.chat = resources.AsyncChat(self)
352 self.embeddings = resources.AsyncEmbeddings(self)
353 self.files = resources.AsyncFiles(self)
354 self.images = resources.AsyncImages(self)
355 self.audio = resources.AsyncAudio(self)
356 self.moderations = resources.AsyncModerations(self)
357 self.models = resources.AsyncModels(self)
358 self.fine_tuning = resources.AsyncFineTuning(self)
359 self.beta = resources.AsyncBeta(self)
360 self.batches = resources.AsyncBatches(self)
361 self.uploads = resources.AsyncUploads(self)
362 self.with_raw_response = AsyncOpenAIWithRawResponse(self)
363 self.with_streaming_response = AsyncOpenAIWithStreamedResponse(self)
364
365 @property
366 @override
367 def qs(self) -> Querystring:
368 return Querystring(array_format="brackets")
369
370 @property
371 @override
372 def auth_headers(self) -> dict[str, str]:
373 api_key = self.api_key
374 return {"Authorization": f"Bearer {api_key}"}
375
376 @property
377 @override
378 def default_headers(self) -> dict[str, str | Omit]:
379 return {
380 **super().default_headers,
381 "X-Stainless-Async": f"async:{get_async_library()}",
382 "OpenAI-Organization": self.organization if self.organization is not None else Omit(),
383 "OpenAI-Project": self.project if self.project is not None else Omit(),
384 **self._custom_headers,
385 }
386
387 def copy(
388 self,
389 *,
390 api_key: str | None = None,
391 organization: str | None = None,
392 project: str | None = None,
393 base_url: str | httpx.URL | None = None,
394 timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
395 http_client: httpx.AsyncClient | None = None,
396 max_retries: int | NotGiven = NOT_GIVEN,
397 default_headers: Mapping[str, str] | None = None,
398 set_default_headers: Mapping[str, str] | None = None,
399 default_query: Mapping[str, object] | None = None,
400 set_default_query: Mapping[str, object] | None = None,
401 _extra_kwargs: Mapping[str, Any] = {},
402 ) -> Self:
403 """
404 Create a new client instance re-using the same options given to the current client with optional overriding.
405 """
406 if default_headers is not None and set_default_headers is not None:
407 raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
408
409 if default_query is not None and set_default_query is not None:
410 raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
411
412 headers = self._custom_headers
413 if default_headers is not None:
414 headers = {**headers, **default_headers}
415 elif set_default_headers is not None:
416 headers = set_default_headers
417
418 params = self._custom_query
419 if default_query is not None:
420 params = {**params, **default_query}
421 elif set_default_query is not None:
422 params = set_default_query
423
424 http_client = http_client or self._client
425 return self.__class__(
426 api_key=api_key or self.api_key,
427 organization=organization or self.organization,
428 project=project or self.project,
429 base_url=base_url or self.base_url,
430 timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
431 http_client=http_client,
432 max_retries=max_retries if is_given(max_retries) else self.max_retries,
433 default_headers=headers,
434 default_query=params,
435 **_extra_kwargs,
436 )
437
438 # Alias for `copy` for nicer inline usage, e.g.
439 # client.with_options(timeout=10).foo.create(...)
440 with_options = copy
441
442 @override
443 def _make_status_error(
444 self,
445 err_msg: str,
446 *,
447 body: object,
448 response: httpx.Response,
449 ) -> APIStatusError:
450 data = body.get("error", body) if is_mapping(body) else body
451 if response.status_code == 400:
452 return _exceptions.BadRequestError(err_msg, response=response, body=data)
453
454 if response.status_code == 401:
455 return _exceptions.AuthenticationError(err_msg, response=response, body=data)
456
457 if response.status_code == 403:
458 return _exceptions.PermissionDeniedError(err_msg, response=response, body=data)
459
460 if response.status_code == 404:
461 return _exceptions.NotFoundError(err_msg, response=response, body=data)
462
463 if response.status_code == 409:
464 return _exceptions.ConflictError(err_msg, response=response, body=data)
465
466 if response.status_code == 422:
467 return _exceptions.UnprocessableEntityError(err_msg, response=response, body=data)
468
469 if response.status_code == 429:
470 return _exceptions.RateLimitError(err_msg, response=response, body=data)
471
472 if response.status_code >= 500:
473 return _exceptions.InternalServerError(err_msg, response=response, body=data)
474 return APIStatusError(err_msg, response=response, body=data)
475
476
477class OpenAIWithRawResponse:
478 def __init__(self, client: OpenAI) -> None:
479 self.completions = resources.CompletionsWithRawResponse(client.completions)
480 self.chat = resources.ChatWithRawResponse(client.chat)
481 self.embeddings = resources.EmbeddingsWithRawResponse(client.embeddings)
482 self.files = resources.FilesWithRawResponse(client.files)
483 self.images = resources.ImagesWithRawResponse(client.images)
484 self.audio = resources.AudioWithRawResponse(client.audio)
485 self.moderations = resources.ModerationsWithRawResponse(client.moderations)
486 self.models = resources.ModelsWithRawResponse(client.models)
487 self.fine_tuning = resources.FineTuningWithRawResponse(client.fine_tuning)
488 self.beta = resources.BetaWithRawResponse(client.beta)
489 self.batches = resources.BatchesWithRawResponse(client.batches)
490 self.uploads = resources.UploadsWithRawResponse(client.uploads)
491
492
493class AsyncOpenAIWithRawResponse:
494 def __init__(self, client: AsyncOpenAI) -> None:
495 self.completions = resources.AsyncCompletionsWithRawResponse(client.completions)
496 self.chat = resources.AsyncChatWithRawResponse(client.chat)
497 self.embeddings = resources.AsyncEmbeddingsWithRawResponse(client.embeddings)
498 self.files = resources.AsyncFilesWithRawResponse(client.files)
499 self.images = resources.AsyncImagesWithRawResponse(client.images)
500 self.audio = resources.AsyncAudioWithRawResponse(client.audio)
501 self.moderations = resources.AsyncModerationsWithRawResponse(client.moderations)
502 self.models = resources.AsyncModelsWithRawResponse(client.models)
503 self.fine_tuning = resources.AsyncFineTuningWithRawResponse(client.fine_tuning)
504 self.beta = resources.AsyncBetaWithRawResponse(client.beta)
505 self.batches = resources.AsyncBatchesWithRawResponse(client.batches)
506 self.uploads = resources.AsyncUploadsWithRawResponse(client.uploads)
507
508
509class OpenAIWithStreamedResponse:
510 def __init__(self, client: OpenAI) -> None:
511 self.completions = resources.CompletionsWithStreamingResponse(client.completions)
512 self.chat = resources.ChatWithStreamingResponse(client.chat)
513 self.embeddings = resources.EmbeddingsWithStreamingResponse(client.embeddings)
514 self.files = resources.FilesWithStreamingResponse(client.files)
515 self.images = resources.ImagesWithStreamingResponse(client.images)
516 self.audio = resources.AudioWithStreamingResponse(client.audio)
517 self.moderations = resources.ModerationsWithStreamingResponse(client.moderations)
518 self.models = resources.ModelsWithStreamingResponse(client.models)
519 self.fine_tuning = resources.FineTuningWithStreamingResponse(client.fine_tuning)
520 self.beta = resources.BetaWithStreamingResponse(client.beta)
521 self.batches = resources.BatchesWithStreamingResponse(client.batches)
522 self.uploads = resources.UploadsWithStreamingResponse(client.uploads)
523
524
525class AsyncOpenAIWithStreamedResponse:
526 def __init__(self, client: AsyncOpenAI) -> None:
527 self.completions = resources.AsyncCompletionsWithStreamingResponse(client.completions)
528 self.chat = resources.AsyncChatWithStreamingResponse(client.chat)
529 self.embeddings = resources.AsyncEmbeddingsWithStreamingResponse(client.embeddings)
530 self.files = resources.AsyncFilesWithStreamingResponse(client.files)
531 self.images = resources.AsyncImagesWithStreamingResponse(client.images)
532 self.audio = resources.AsyncAudioWithStreamingResponse(client.audio)
533 self.moderations = resources.AsyncModerationsWithStreamingResponse(client.moderations)
534 self.models = resources.AsyncModelsWithStreamingResponse(client.models)
535 self.fine_tuning = resources.AsyncFineTuningWithStreamingResponse(client.fine_tuning)
536 self.beta = resources.AsyncBetaWithStreamingResponse(client.beta)
537 self.batches = resources.AsyncBatchesWithStreamingResponse(client.batches)
538 self.uploads = resources.AsyncUploadsWithStreamingResponse(client.uploads)
539
540
541Client = OpenAI
542
543AsyncClient = AsyncOpenAI
544