openai/openai-python

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.78.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/openai/__init__.py

367lines · modecode

1# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
3from __future__ import annotations
4
5import os as _os
6from typing_extensions import override
7
8from . import types
9from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes
10from ._utils import file_from_path
11from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions
12from ._models import BaseModel
13from ._version import __title__, __version__
14from ._response import APIResponse as APIResponse, AsyncAPIResponse as AsyncAPIResponse
15from ._constants import DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_CONNECTION_LIMITS
16from ._exceptions import (
17 APIError,
18 OpenAIError,
19 ConflictError,
20 NotFoundError,
21 APIStatusError,
22 RateLimitError,
23 APITimeoutError,
24 BadRequestError,
25 APIConnectionError,
26 AuthenticationError,
27 InternalServerError,
28 PermissionDeniedError,
29 LengthFinishReasonError,
30 UnprocessableEntityError,
31 APIResponseValidationError,
32 ContentFilterFinishReasonError,
33)
34from ._base_client import DefaultHttpxClient, DefaultAsyncHttpxClient
35from ._utils._logs import setup_logging as _setup_logging
36from ._legacy_response import HttpxBinaryResponseContent as HttpxBinaryResponseContent
37
38__all__ = [
39 "types",
40 "__version__",
41 "__title__",
42 "NoneType",
43 "Transport",
44 "ProxiesTypes",
45 "NotGiven",
46 "NOT_GIVEN",
47 "Omit",
48 "OpenAIError",
49 "APIError",
50 "APIStatusError",
51 "APITimeoutError",
52 "APIConnectionError",
53 "APIResponseValidationError",
54 "BadRequestError",
55 "AuthenticationError",
56 "PermissionDeniedError",
57 "NotFoundError",
58 "ConflictError",
59 "UnprocessableEntityError",
60 "RateLimitError",
61 "InternalServerError",
62 "LengthFinishReasonError",
63 "ContentFilterFinishReasonError",
64 "Timeout",
65 "RequestOptions",
66 "Client",
67 "AsyncClient",
68 "Stream",
69 "AsyncStream",
70 "OpenAI",
71 "AsyncOpenAI",
72 "file_from_path",
73 "BaseModel",
74 "DEFAULT_TIMEOUT",
75 "DEFAULT_MAX_RETRIES",
76 "DEFAULT_CONNECTION_LIMITS",
77 "DefaultHttpxClient",
78 "DefaultAsyncHttpxClient",
79]
80
81from .lib import azure as _azure, pydantic_function_tool as pydantic_function_tool
82from .version import VERSION as VERSION
83from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI
84from .lib._old_api import *
85from .lib.streaming import (
86 AssistantEventHandler as AssistantEventHandler,
87 AsyncAssistantEventHandler as AsyncAssistantEventHandler,
88)
89
90_setup_logging()
91
92# Update the __module__ attribute for exported symbols so that
93# error messages point to this module instead of the module
94# it was originally defined in, e.g.
95# openai._exceptions.NotFoundError -> openai.NotFoundError
96__locals = locals()
97for __name in __all__:
98 if not __name.startswith("__"):
99 try:
100 __locals[__name].__module__ = "openai"
101 except (TypeError, AttributeError):
102 # Some of our exported symbols are builtins which we can't set attributes for.
103 pass
104
105# ------ Module level client ------
106import typing as _t
107import typing_extensions as _te
108
109import httpx as _httpx
110
111from ._base_client import DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES
112
113api_key: str | None = None
114
115organization: str | None = None
116
117project: str | None = None
118
119base_url: str | _httpx.URL | None = None
120
121timeout: float | Timeout | None = DEFAULT_TIMEOUT
122
123max_retries: int = DEFAULT_MAX_RETRIES
124
125default_headers: _t.Mapping[str, str] | None = None
126
127default_query: _t.Mapping[str, object] | None = None
128
129http_client: _httpx.Client | None = None
130
131_ApiType = _te.Literal["openai", "azure"]
132
133api_type: _ApiType | None = _t.cast(_ApiType, _os.environ.get("OPENAI_API_TYPE"))
134
135api_version: str | None = _os.environ.get("OPENAI_API_VERSION")
136
137azure_endpoint: str | None = _os.environ.get("AZURE_OPENAI_ENDPOINT")
138
139azure_ad_token: str | None = _os.environ.get("AZURE_OPENAI_AD_TOKEN")
140
141azure_ad_token_provider: _azure.AzureADTokenProvider | None = None
142
143
144class _ModuleClient(OpenAI):
145 # Note: we have to use type: ignores here as overriding class members
146 # with properties is technically unsafe but it is fine for our use case
147
148 @property # type: ignore
149 @override
150 def api_key(self) -> str | None:
151 return api_key
152
153 @api_key.setter # type: ignore
154 def api_key(self, value: str | None) -> None: # type: ignore
155 global api_key
156
157 api_key = value
158
159 @property # type: ignore
160 @override
161 def organization(self) -> str | None:
162 return organization
163
164 @organization.setter # type: ignore
165 def organization(self, value: str | None) -> None: # type: ignore
166 global organization
167
168 organization = value
169
170 @property # type: ignore
171 @override
172 def project(self) -> str | None:
173 return project
174
175 @project.setter # type: ignore
176 def project(self, value: str | None) -> None: # type: ignore
177 global project
178
179 project = value
180
181 @property
182 @override
183 def base_url(self) -> _httpx.URL:
184 if base_url is not None:
185 return _httpx.URL(base_url)
186
187 return super().base_url
188
189 @base_url.setter
190 def base_url(self, url: _httpx.URL | str) -> None:
191 super().base_url = url # type: ignore[misc]
192
193 @property # type: ignore
194 @override
195 def timeout(self) -> float | Timeout | None:
196 return timeout
197
198 @timeout.setter # type: ignore
199 def timeout(self, value: float | Timeout | None) -> None: # type: ignore
200 global timeout
201
202 timeout = value
203
204 @property # type: ignore
205 @override
206 def max_retries(self) -> int:
207 return max_retries
208
209 @max_retries.setter # type: ignore
210 def max_retries(self, value: int) -> None: # type: ignore
211 global max_retries
212
213 max_retries = value
214
215 @property # type: ignore
216 @override
217 def _custom_headers(self) -> _t.Mapping[str, str] | None:
218 return default_headers
219
220 @_custom_headers.setter # type: ignore
221 def _custom_headers(self, value: _t.Mapping[str, str] | None) -> None: # type: ignore
222 global default_headers
223
224 default_headers = value
225
226 @property # type: ignore
227 @override
228 def _custom_query(self) -> _t.Mapping[str, object] | None:
229 return default_query
230
231 @_custom_query.setter # type: ignore
232 def _custom_query(self, value: _t.Mapping[str, object] | None) -> None: # type: ignore
233 global default_query
234
235 default_query = value
236
237 @property # type: ignore
238 @override
239 def _client(self) -> _httpx.Client:
240 return http_client or super()._client
241
242 @_client.setter # type: ignore
243 def _client(self, value: _httpx.Client) -> None: # type: ignore
244 global http_client
245
246 http_client = value
247
248
249class _AzureModuleClient(_ModuleClient, AzureOpenAI): # type: ignore
250 ...
251
252
253class _AmbiguousModuleClientUsageError(OpenAIError):
254 def __init__(self) -> None:
255 super().__init__(
256 "Ambiguous use of module client; please set `openai.api_type` or the `OPENAI_API_TYPE` environment variable to `openai` or `azure`"
257 )
258
259
260def _has_openai_credentials() -> bool:
261 return _os.environ.get("OPENAI_API_KEY") is not None
262
263
264def _has_azure_credentials() -> bool:
265 return azure_endpoint is not None or _os.environ.get("AZURE_OPENAI_API_KEY") is not None
266
267
268def _has_azure_ad_credentials() -> bool:
269 return (
270 _os.environ.get("AZURE_OPENAI_AD_TOKEN") is not None
271 or azure_ad_token is not None
272 or azure_ad_token_provider is not None
273 )
274
275
276_client: OpenAI | None = None
277
278
279def _load_client() -> OpenAI: # type: ignore[reportUnusedFunction]
280 global _client
281
282 if _client is None:
283 global api_type, azure_endpoint, azure_ad_token, api_version
284
285 if azure_endpoint is None:
286 azure_endpoint = _os.environ.get("AZURE_OPENAI_ENDPOINT")
287
288 if azure_ad_token is None:
289 azure_ad_token = _os.environ.get("AZURE_OPENAI_AD_TOKEN")
290
291 if api_version is None:
292 api_version = _os.environ.get("OPENAI_API_VERSION")
293
294 if api_type is None:
295 has_openai = _has_openai_credentials()
296 has_azure = _has_azure_credentials()
297 has_azure_ad = _has_azure_ad_credentials()
298
299 if has_openai and (has_azure or has_azure_ad):
300 raise _AmbiguousModuleClientUsageError()
301
302 if (azure_ad_token is not None or azure_ad_token_provider is not None) and _os.environ.get(
303 "AZURE_OPENAI_API_KEY"
304 ) is not None:
305 raise _AmbiguousModuleClientUsageError()
306
307 if has_azure or has_azure_ad:
308 api_type = "azure"
309 else:
310 api_type = "openai"
311
312 if api_type == "azure":
313 _client = _AzureModuleClient( # type: ignore
314 api_version=api_version,
315 azure_endpoint=azure_endpoint,
316 api_key=api_key,
317 azure_ad_token=azure_ad_token,
318 azure_ad_token_provider=azure_ad_token_provider,
319 organization=organization,
320 base_url=base_url,
321 timeout=timeout,
322 max_retries=max_retries,
323 default_headers=default_headers,
324 default_query=default_query,
325 http_client=http_client,
326 )
327 return _client
328
329 _client = _ModuleClient(
330 api_key=api_key,
331 organization=organization,
332 project=project,
333 base_url=base_url,
334 timeout=timeout,
335 max_retries=max_retries,
336 default_headers=default_headers,
337 default_query=default_query,
338 http_client=http_client,
339 )
340 return _client
341
342 return _client
343
344
345def _reset_client() -> None: # type: ignore[reportUnusedFunction]
346 global _client
347
348 _client = None
349
350
351from ._module_client import (
352 beta as beta,
353 chat as chat,
354 audio as audio,
355 evals as evals,
356 files as files,
357 images as images,
358 models as models,
359 batches as batches,
360 uploads as uploads,
361 responses as responses,
362 embeddings as embeddings,
363 completions as completions,
364 fine_tuning as fine_tuning,
365 moderations as moderations,
366 vector_stores as vector_stores,
367)
368