main
   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 TYPE_CHECKING, Any, Mapping, Callable, Awaitable
   7from typing_extensions import Self, override
   8
   9import httpx
  10
  11from . import _exceptions
  12from ._qs import Querystring
  13from ._types import (
  14    Omit,
  15    Timeout,
  16    NotGiven,
  17    Transport,
  18    ProxiesTypes,
  19    RequestOptions,
  20    not_given,
  21)
  22from ._utils import (
  23    is_given,
  24    is_mapping,
  25    get_async_library,
  26)
  27from ._compat import cached_property
  28from ._models import FinalRequestOptions
  29from ._version import __version__
  30from ._streaming import Stream as Stream, AsyncStream as AsyncStream
  31from ._exceptions import OpenAIError, APIStatusError
  32from ._base_client import (
  33    DEFAULT_MAX_RETRIES,
  34    SyncAPIClient,
  35    AsyncAPIClient,
  36)
  37
  38if TYPE_CHECKING:
  39    from .resources import (
  40        beta,
  41        chat,
  42        audio,
  43        evals,
  44        files,
  45        images,
  46        models,
  47        videos,
  48        batches,
  49        uploads,
  50        realtime,
  51        responses,
  52        containers,
  53        embeddings,
  54        completions,
  55        fine_tuning,
  56        moderations,
  57        conversations,
  58        vector_stores,
  59    )
  60    from .resources.files import Files, AsyncFiles
  61    from .resources.images import Images, AsyncImages
  62    from .resources.models import Models, AsyncModels
  63    from .resources.videos import Videos, AsyncVideos
  64    from .resources.batches import Batches, AsyncBatches
  65    from .resources.webhooks import Webhooks, AsyncWebhooks
  66    from .resources.beta.beta import Beta, AsyncBeta
  67    from .resources.chat.chat import Chat, AsyncChat
  68    from .resources.embeddings import Embeddings, AsyncEmbeddings
  69    from .resources.audio.audio import Audio, AsyncAudio
  70    from .resources.completions import Completions, AsyncCompletions
  71    from .resources.evals.evals import Evals, AsyncEvals
  72    from .resources.moderations import Moderations, AsyncModerations
  73    from .resources.uploads.uploads import Uploads, AsyncUploads
  74    from .resources.realtime.realtime import Realtime, AsyncRealtime
  75    from .resources.responses.responses import Responses, AsyncResponses
  76    from .resources.containers.containers import Containers, AsyncContainers
  77    from .resources.fine_tuning.fine_tuning import FineTuning, AsyncFineTuning
  78    from .resources.conversations.conversations import Conversations, AsyncConversations
  79    from .resources.vector_stores.vector_stores import VectorStores, AsyncVectorStores
  80
  81__all__ = ["Timeout", "Transport", "ProxiesTypes", "RequestOptions", "OpenAI", "AsyncOpenAI", "Client", "AsyncClient"]
  82
  83
  84class OpenAI(SyncAPIClient):
  85    # client options
  86    api_key: str
  87    organization: str | None
  88    project: str | None
  89    webhook_secret: str | None
  90
  91    websocket_base_url: str | httpx.URL | None
  92    """Base URL for WebSocket connections.
  93
  94    If not specified, the default base URL will be used, with 'wss://' replacing the
  95    'http://' or 'https://' scheme. For example: 'http://example.com' becomes
  96    'wss://example.com'
  97    """
  98
  99    def __init__(
 100        self,
 101        *,
 102        api_key: str | None | Callable[[], str] = None,
 103        organization: str | None = None,
 104        project: str | None = None,
 105        webhook_secret: str | None = None,
 106        base_url: str | httpx.URL | None = None,
 107        websocket_base_url: str | httpx.URL | None = None,
 108        timeout: float | Timeout | None | NotGiven = not_given,
 109        max_retries: int = DEFAULT_MAX_RETRIES,
 110        default_headers: Mapping[str, str] | None = None,
 111        default_query: Mapping[str, object] | None = None,
 112        # Configure a custom httpx client.
 113        # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
 114        # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details.
 115        http_client: httpx.Client | None = None,
 116        # Enable or disable schema validation for data returned by the API.
 117        # When enabled an error APIResponseValidationError is raised
 118        # if the API responds with invalid data for the expected schema.
 119        #
 120        # This parameter may be removed or changed in the future.
 121        # If you rely on this feature, please open a GitHub issue
 122        # outlining your use-case to help us decide if it should be
 123        # part of our public interface in the future.
 124        _strict_response_validation: bool = False,
 125    ) -> None:
 126        """Construct a new synchronous OpenAI client instance.
 127
 128        This automatically infers the following arguments from their corresponding environment variables if they are not provided:
 129        - `api_key` from `OPENAI_API_KEY`
 130        - `organization` from `OPENAI_ORG_ID`
 131        - `project` from `OPENAI_PROJECT_ID`
 132        - `webhook_secret` from `OPENAI_WEBHOOK_SECRET`
 133        """
 134        if api_key is None:
 135            api_key = os.environ.get("OPENAI_API_KEY")
 136        if api_key is None:
 137            raise OpenAIError(
 138                "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"
 139            )
 140        if callable(api_key):
 141            self.api_key = ""
 142            self._api_key_provider: Callable[[], str] | None = api_key
 143        else:
 144            self.api_key = api_key
 145            self._api_key_provider = None
 146
 147        if organization is None:
 148            organization = os.environ.get("OPENAI_ORG_ID")
 149        self.organization = organization
 150
 151        if project is None:
 152            project = os.environ.get("OPENAI_PROJECT_ID")
 153        self.project = project
 154
 155        if webhook_secret is None:
 156            webhook_secret = os.environ.get("OPENAI_WEBHOOK_SECRET")
 157        self.webhook_secret = webhook_secret
 158
 159        self.websocket_base_url = websocket_base_url
 160
 161        if base_url is None:
 162            base_url = os.environ.get("OPENAI_BASE_URL")
 163        if base_url is None:
 164            base_url = f"https://api.openai.com/v1"
 165
 166        super().__init__(
 167            version=__version__,
 168            base_url=base_url,
 169            max_retries=max_retries,
 170            timeout=timeout,
 171            http_client=http_client,
 172            custom_headers=default_headers,
 173            custom_query=default_query,
 174            _strict_response_validation=_strict_response_validation,
 175        )
 176
 177        self._default_stream_cls = Stream
 178
 179    @cached_property
 180    def completions(self) -> Completions:
 181        from .resources.completions import Completions
 182
 183        return Completions(self)
 184
 185    @cached_property
 186    def chat(self) -> Chat:
 187        from .resources.chat import Chat
 188
 189        return Chat(self)
 190
 191    @cached_property
 192    def embeddings(self) -> Embeddings:
 193        from .resources.embeddings import Embeddings
 194
 195        return Embeddings(self)
 196
 197    @cached_property
 198    def files(self) -> Files:
 199        from .resources.files import Files
 200
 201        return Files(self)
 202
 203    @cached_property
 204    def images(self) -> Images:
 205        from .resources.images import Images
 206
 207        return Images(self)
 208
 209    @cached_property
 210    def audio(self) -> Audio:
 211        from .resources.audio import Audio
 212
 213        return Audio(self)
 214
 215    @cached_property
 216    def moderations(self) -> Moderations:
 217        from .resources.moderations import Moderations
 218
 219        return Moderations(self)
 220
 221    @cached_property
 222    def models(self) -> Models:
 223        from .resources.models import Models
 224
 225        return Models(self)
 226
 227    @cached_property
 228    def fine_tuning(self) -> FineTuning:
 229        from .resources.fine_tuning import FineTuning
 230
 231        return FineTuning(self)
 232
 233    @cached_property
 234    def vector_stores(self) -> VectorStores:
 235        from .resources.vector_stores import VectorStores
 236
 237        return VectorStores(self)
 238
 239    @cached_property
 240    def webhooks(self) -> Webhooks:
 241        from .resources.webhooks import Webhooks
 242
 243        return Webhooks(self)
 244
 245    @cached_property
 246    def beta(self) -> Beta:
 247        from .resources.beta import Beta
 248
 249        return Beta(self)
 250
 251    @cached_property
 252    def batches(self) -> Batches:
 253        from .resources.batches import Batches
 254
 255        return Batches(self)
 256
 257    @cached_property
 258    def uploads(self) -> Uploads:
 259        from .resources.uploads import Uploads
 260
 261        return Uploads(self)
 262
 263    @cached_property
 264    def responses(self) -> Responses:
 265        from .resources.responses import Responses
 266
 267        return Responses(self)
 268
 269    @cached_property
 270    def realtime(self) -> Realtime:
 271        from .resources.realtime import Realtime
 272
 273        return Realtime(self)
 274
 275    @cached_property
 276    def conversations(self) -> Conversations:
 277        from .resources.conversations import Conversations
 278
 279        return Conversations(self)
 280
 281    @cached_property
 282    def evals(self) -> Evals:
 283        from .resources.evals import Evals
 284
 285        return Evals(self)
 286
 287    @cached_property
 288    def containers(self) -> Containers:
 289        from .resources.containers import Containers
 290
 291        return Containers(self)
 292
 293    @cached_property
 294    def videos(self) -> Videos:
 295        from .resources.videos import Videos
 296
 297        return Videos(self)
 298
 299    @cached_property
 300    def with_raw_response(self) -> OpenAIWithRawResponse:
 301        return OpenAIWithRawResponse(self)
 302
 303    @cached_property
 304    def with_streaming_response(self) -> OpenAIWithStreamedResponse:
 305        return OpenAIWithStreamedResponse(self)
 306
 307    @property
 308    @override
 309    def qs(self) -> Querystring:
 310        return Querystring(array_format="brackets")
 311
 312    def _refresh_api_key(self) -> None:
 313        if self._api_key_provider:
 314            self.api_key = self._api_key_provider()
 315
 316    @override
 317    def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
 318        self._refresh_api_key()
 319        return super()._prepare_options(options)
 320
 321    @property
 322    @override
 323    def auth_headers(self) -> dict[str, str]:
 324        api_key = self.api_key
 325        if not api_key:
 326            # if the api key is an empty string, encoding the header will fail
 327            return {}
 328        return {"Authorization": f"Bearer {api_key}"}
 329
 330    @property
 331    @override
 332    def default_headers(self) -> dict[str, str | Omit]:
 333        return {
 334            **super().default_headers,
 335            "X-Stainless-Async": "false",
 336            "OpenAI-Organization": self.organization if self.organization is not None else Omit(),
 337            "OpenAI-Project": self.project if self.project is not None else Omit(),
 338            **self._custom_headers,
 339        }
 340
 341    def copy(
 342        self,
 343        *,
 344        api_key: str | Callable[[], str] | None = None,
 345        organization: str | None = None,
 346        project: str | None = None,
 347        webhook_secret: str | None = None,
 348        websocket_base_url: str | httpx.URL | None = None,
 349        base_url: str | httpx.URL | None = None,
 350        timeout: float | Timeout | None | NotGiven = not_given,
 351        http_client: httpx.Client | None = None,
 352        max_retries: int | NotGiven = not_given,
 353        default_headers: Mapping[str, str] | None = None,
 354        set_default_headers: Mapping[str, str] | None = None,
 355        default_query: Mapping[str, object] | None = None,
 356        set_default_query: Mapping[str, object] | None = None,
 357        _extra_kwargs: Mapping[str, Any] = {},
 358    ) -> Self:
 359        """
 360        Create a new client instance re-using the same options given to the current client with optional overriding.
 361        """
 362        if default_headers is not None and set_default_headers is not None:
 363            raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
 364
 365        if default_query is not None and set_default_query is not None:
 366            raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
 367
 368        headers = self._custom_headers
 369        if default_headers is not None:
 370            headers = {**headers, **default_headers}
 371        elif set_default_headers is not None:
 372            headers = set_default_headers
 373
 374        params = self._custom_query
 375        if default_query is not None:
 376            params = {**params, **default_query}
 377        elif set_default_query is not None:
 378            params = set_default_query
 379
 380        http_client = http_client or self._client
 381        return self.__class__(
 382            api_key=api_key or self._api_key_provider or self.api_key,
 383            organization=organization or self.organization,
 384            project=project or self.project,
 385            webhook_secret=webhook_secret or self.webhook_secret,
 386            websocket_base_url=websocket_base_url or self.websocket_base_url,
 387            base_url=base_url or self.base_url,
 388            timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
 389            http_client=http_client,
 390            max_retries=max_retries if is_given(max_retries) else self.max_retries,
 391            default_headers=headers,
 392            default_query=params,
 393            **_extra_kwargs,
 394        )
 395
 396    # Alias for `copy` for nicer inline usage, e.g.
 397    # client.with_options(timeout=10).foo.create(...)
 398    with_options = copy
 399
 400    @override
 401    def _make_status_error(
 402        self,
 403        err_msg: str,
 404        *,
 405        body: object,
 406        response: httpx.Response,
 407    ) -> APIStatusError:
 408        data = body.get("error", body) if is_mapping(body) else body
 409        if response.status_code == 400:
 410            return _exceptions.BadRequestError(err_msg, response=response, body=data)
 411
 412        if response.status_code == 401:
 413            return _exceptions.AuthenticationError(err_msg, response=response, body=data)
 414
 415        if response.status_code == 403:
 416            return _exceptions.PermissionDeniedError(err_msg, response=response, body=data)
 417
 418        if response.status_code == 404:
 419            return _exceptions.NotFoundError(err_msg, response=response, body=data)
 420
 421        if response.status_code == 409:
 422            return _exceptions.ConflictError(err_msg, response=response, body=data)
 423
 424        if response.status_code == 422:
 425            return _exceptions.UnprocessableEntityError(err_msg, response=response, body=data)
 426
 427        if response.status_code == 429:
 428            return _exceptions.RateLimitError(err_msg, response=response, body=data)
 429
 430        if response.status_code >= 500:
 431            return _exceptions.InternalServerError(err_msg, response=response, body=data)
 432        return APIStatusError(err_msg, response=response, body=data)
 433
 434
 435class AsyncOpenAI(AsyncAPIClient):
 436    # client options
 437    api_key: str
 438    organization: str | None
 439    project: str | None
 440    webhook_secret: str | None
 441
 442    websocket_base_url: str | httpx.URL | None
 443    """Base URL for WebSocket connections.
 444
 445    If not specified, the default base URL will be used, with 'wss://' replacing the
 446    'http://' or 'https://' scheme. For example: 'http://example.com' becomes
 447    'wss://example.com'
 448    """
 449
 450    def __init__(
 451        self,
 452        *,
 453        api_key: str | Callable[[], Awaitable[str]] | None = None,
 454        organization: str | None = None,
 455        project: str | None = None,
 456        webhook_secret: str | None = None,
 457        base_url: str | httpx.URL | None = None,
 458        websocket_base_url: str | httpx.URL | None = None,
 459        timeout: float | Timeout | None | NotGiven = not_given,
 460        max_retries: int = DEFAULT_MAX_RETRIES,
 461        default_headers: Mapping[str, str] | None = None,
 462        default_query: Mapping[str, object] | None = None,
 463        # Configure a custom httpx client.
 464        # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`.
 465        # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details.
 466        http_client: httpx.AsyncClient | None = None,
 467        # Enable or disable schema validation for data returned by the API.
 468        # When enabled an error APIResponseValidationError is raised
 469        # if the API responds with invalid data for the expected schema.
 470        #
 471        # This parameter may be removed or changed in the future.
 472        # If you rely on this feature, please open a GitHub issue
 473        # outlining your use-case to help us decide if it should be
 474        # part of our public interface in the future.
 475        _strict_response_validation: bool = False,
 476    ) -> None:
 477        """Construct a new async AsyncOpenAI client instance.
 478
 479        This automatically infers the following arguments from their corresponding environment variables if they are not provided:
 480        - `api_key` from `OPENAI_API_KEY`
 481        - `organization` from `OPENAI_ORG_ID`
 482        - `project` from `OPENAI_PROJECT_ID`
 483        - `webhook_secret` from `OPENAI_WEBHOOK_SECRET`
 484        """
 485        if api_key is None:
 486            api_key = os.environ.get("OPENAI_API_KEY")
 487        if api_key is None:
 488            raise OpenAIError(
 489                "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"
 490            )
 491        if callable(api_key):
 492            self.api_key = ""
 493            self._api_key_provider: Callable[[], Awaitable[str]] | None = api_key
 494        else:
 495            self.api_key = api_key
 496            self._api_key_provider = None
 497
 498        if organization is None:
 499            organization = os.environ.get("OPENAI_ORG_ID")
 500        self.organization = organization
 501
 502        if project is None:
 503            project = os.environ.get("OPENAI_PROJECT_ID")
 504        self.project = project
 505
 506        if webhook_secret is None:
 507            webhook_secret = os.environ.get("OPENAI_WEBHOOK_SECRET")
 508        self.webhook_secret = webhook_secret
 509
 510        self.websocket_base_url = websocket_base_url
 511
 512        if base_url is None:
 513            base_url = os.environ.get("OPENAI_BASE_URL")
 514        if base_url is None:
 515            base_url = f"https://api.openai.com/v1"
 516
 517        super().__init__(
 518            version=__version__,
 519            base_url=base_url,
 520            max_retries=max_retries,
 521            timeout=timeout,
 522            http_client=http_client,
 523            custom_headers=default_headers,
 524            custom_query=default_query,
 525            _strict_response_validation=_strict_response_validation,
 526        )
 527
 528        self._default_stream_cls = AsyncStream
 529
 530    @cached_property
 531    def completions(self) -> AsyncCompletions:
 532        from .resources.completions import AsyncCompletions
 533
 534        return AsyncCompletions(self)
 535
 536    @cached_property
 537    def chat(self) -> AsyncChat:
 538        from .resources.chat import AsyncChat
 539
 540        return AsyncChat(self)
 541
 542    @cached_property
 543    def embeddings(self) -> AsyncEmbeddings:
 544        from .resources.embeddings import AsyncEmbeddings
 545
 546        return AsyncEmbeddings(self)
 547
 548    @cached_property
 549    def files(self) -> AsyncFiles:
 550        from .resources.files import AsyncFiles
 551
 552        return AsyncFiles(self)
 553
 554    @cached_property
 555    def images(self) -> AsyncImages:
 556        from .resources.images import AsyncImages
 557
 558        return AsyncImages(self)
 559
 560    @cached_property
 561    def audio(self) -> AsyncAudio:
 562        from .resources.audio import AsyncAudio
 563
 564        return AsyncAudio(self)
 565
 566    @cached_property
 567    def moderations(self) -> AsyncModerations:
 568        from .resources.moderations import AsyncModerations
 569
 570        return AsyncModerations(self)
 571
 572    @cached_property
 573    def models(self) -> AsyncModels:
 574        from .resources.models import AsyncModels
 575
 576        return AsyncModels(self)
 577
 578    @cached_property
 579    def fine_tuning(self) -> AsyncFineTuning:
 580        from .resources.fine_tuning import AsyncFineTuning
 581
 582        return AsyncFineTuning(self)
 583
 584    @cached_property
 585    def vector_stores(self) -> AsyncVectorStores:
 586        from .resources.vector_stores import AsyncVectorStores
 587
 588        return AsyncVectorStores(self)
 589
 590    @cached_property
 591    def webhooks(self) -> AsyncWebhooks:
 592        from .resources.webhooks import AsyncWebhooks
 593
 594        return AsyncWebhooks(self)
 595
 596    @cached_property
 597    def beta(self) -> AsyncBeta:
 598        from .resources.beta import AsyncBeta
 599
 600        return AsyncBeta(self)
 601
 602    @cached_property
 603    def batches(self) -> AsyncBatches:
 604        from .resources.batches import AsyncBatches
 605
 606        return AsyncBatches(self)
 607
 608    @cached_property
 609    def uploads(self) -> AsyncUploads:
 610        from .resources.uploads import AsyncUploads
 611
 612        return AsyncUploads(self)
 613
 614    @cached_property
 615    def responses(self) -> AsyncResponses:
 616        from .resources.responses import AsyncResponses
 617
 618        return AsyncResponses(self)
 619
 620    @cached_property
 621    def realtime(self) -> AsyncRealtime:
 622        from .resources.realtime import AsyncRealtime
 623
 624        return AsyncRealtime(self)
 625
 626    @cached_property
 627    def conversations(self) -> AsyncConversations:
 628        from .resources.conversations import AsyncConversations
 629
 630        return AsyncConversations(self)
 631
 632    @cached_property
 633    def evals(self) -> AsyncEvals:
 634        from .resources.evals import AsyncEvals
 635
 636        return AsyncEvals(self)
 637
 638    @cached_property
 639    def containers(self) -> AsyncContainers:
 640        from .resources.containers import AsyncContainers
 641
 642        return AsyncContainers(self)
 643
 644    @cached_property
 645    def videos(self) -> AsyncVideos:
 646        from .resources.videos import AsyncVideos
 647
 648        return AsyncVideos(self)
 649
 650    @cached_property
 651    def with_raw_response(self) -> AsyncOpenAIWithRawResponse:
 652        return AsyncOpenAIWithRawResponse(self)
 653
 654    @cached_property
 655    def with_streaming_response(self) -> AsyncOpenAIWithStreamedResponse:
 656        return AsyncOpenAIWithStreamedResponse(self)
 657
 658    @property
 659    @override
 660    def qs(self) -> Querystring:
 661        return Querystring(array_format="brackets")
 662
 663    async def _refresh_api_key(self) -> None:
 664        if self._api_key_provider:
 665            self.api_key = await self._api_key_provider()
 666
 667    @override
 668    async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
 669        await self._refresh_api_key()
 670        return await super()._prepare_options(options)
 671
 672    @property
 673    @override
 674    def auth_headers(self) -> dict[str, str]:
 675        api_key = self.api_key
 676        if not api_key:
 677            # if the api key is an empty string, encoding the header will fail
 678            return {}
 679        return {"Authorization": f"Bearer {api_key}"}
 680
 681    @property
 682    @override
 683    def default_headers(self) -> dict[str, str | Omit]:
 684        return {
 685            **super().default_headers,
 686            "X-Stainless-Async": f"async:{get_async_library()}",
 687            "OpenAI-Organization": self.organization if self.organization is not None else Omit(),
 688            "OpenAI-Project": self.project if self.project is not None else Omit(),
 689            **self._custom_headers,
 690        }
 691
 692    def copy(
 693        self,
 694        *,
 695        api_key: str | Callable[[], Awaitable[str]] | None = None,
 696        organization: str | None = None,
 697        project: str | None = None,
 698        webhook_secret: str | None = None,
 699        websocket_base_url: str | httpx.URL | None = None,
 700        base_url: str | httpx.URL | None = None,
 701        timeout: float | Timeout | None | NotGiven = not_given,
 702        http_client: httpx.AsyncClient | None = None,
 703        max_retries: int | NotGiven = not_given,
 704        default_headers: Mapping[str, str] | None = None,
 705        set_default_headers: Mapping[str, str] | None = None,
 706        default_query: Mapping[str, object] | None = None,
 707        set_default_query: Mapping[str, object] | None = None,
 708        _extra_kwargs: Mapping[str, Any] = {},
 709    ) -> Self:
 710        """
 711        Create a new client instance re-using the same options given to the current client with optional overriding.
 712        """
 713        if default_headers is not None and set_default_headers is not None:
 714            raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive")
 715
 716        if default_query is not None and set_default_query is not None:
 717            raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive")
 718
 719        headers = self._custom_headers
 720        if default_headers is not None:
 721            headers = {**headers, **default_headers}
 722        elif set_default_headers is not None:
 723            headers = set_default_headers
 724
 725        params = self._custom_query
 726        if default_query is not None:
 727            params = {**params, **default_query}
 728        elif set_default_query is not None:
 729            params = set_default_query
 730
 731        http_client = http_client or self._client
 732        return self.__class__(
 733            api_key=api_key or self._api_key_provider or self.api_key,
 734            organization=organization or self.organization,
 735            project=project or self.project,
 736            webhook_secret=webhook_secret or self.webhook_secret,
 737            websocket_base_url=websocket_base_url or self.websocket_base_url,
 738            base_url=base_url or self.base_url,
 739            timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
 740            http_client=http_client,
 741            max_retries=max_retries if is_given(max_retries) else self.max_retries,
 742            default_headers=headers,
 743            default_query=params,
 744            **_extra_kwargs,
 745        )
 746
 747    # Alias for `copy` for nicer inline usage, e.g.
 748    # client.with_options(timeout=10).foo.create(...)
 749    with_options = copy
 750
 751    @override
 752    def _make_status_error(
 753        self,
 754        err_msg: str,
 755        *,
 756        body: object,
 757        response: httpx.Response,
 758    ) -> APIStatusError:
 759        data = body.get("error", body) if is_mapping(body) else body
 760        if response.status_code == 400:
 761            return _exceptions.BadRequestError(err_msg, response=response, body=data)
 762
 763        if response.status_code == 401:
 764            return _exceptions.AuthenticationError(err_msg, response=response, body=data)
 765
 766        if response.status_code == 403:
 767            return _exceptions.PermissionDeniedError(err_msg, response=response, body=data)
 768
 769        if response.status_code == 404:
 770            return _exceptions.NotFoundError(err_msg, response=response, body=data)
 771
 772        if response.status_code == 409:
 773            return _exceptions.ConflictError(err_msg, response=response, body=data)
 774
 775        if response.status_code == 422:
 776            return _exceptions.UnprocessableEntityError(err_msg, response=response, body=data)
 777
 778        if response.status_code == 429:
 779            return _exceptions.RateLimitError(err_msg, response=response, body=data)
 780
 781        if response.status_code >= 500:
 782            return _exceptions.InternalServerError(err_msg, response=response, body=data)
 783        return APIStatusError(err_msg, response=response, body=data)
 784
 785
 786class OpenAIWithRawResponse:
 787    _client: OpenAI
 788
 789    def __init__(self, client: OpenAI) -> None:
 790        self._client = client
 791
 792    @cached_property
 793    def completions(self) -> completions.CompletionsWithRawResponse:
 794        from .resources.completions import CompletionsWithRawResponse
 795
 796        return CompletionsWithRawResponse(self._client.completions)
 797
 798    @cached_property
 799    def chat(self) -> chat.ChatWithRawResponse:
 800        from .resources.chat import ChatWithRawResponse
 801
 802        return ChatWithRawResponse(self._client.chat)
 803
 804    @cached_property
 805    def embeddings(self) -> embeddings.EmbeddingsWithRawResponse:
 806        from .resources.embeddings import EmbeddingsWithRawResponse
 807
 808        return EmbeddingsWithRawResponse(self._client.embeddings)
 809
 810    @cached_property
 811    def files(self) -> files.FilesWithRawResponse:
 812        from .resources.files import FilesWithRawResponse
 813
 814        return FilesWithRawResponse(self._client.files)
 815
 816    @cached_property
 817    def images(self) -> images.ImagesWithRawResponse:
 818        from .resources.images import ImagesWithRawResponse
 819
 820        return ImagesWithRawResponse(self._client.images)
 821
 822    @cached_property
 823    def audio(self) -> audio.AudioWithRawResponse:
 824        from .resources.audio import AudioWithRawResponse
 825
 826        return AudioWithRawResponse(self._client.audio)
 827
 828    @cached_property
 829    def moderations(self) -> moderations.ModerationsWithRawResponse:
 830        from .resources.moderations import ModerationsWithRawResponse
 831
 832        return ModerationsWithRawResponse(self._client.moderations)
 833
 834    @cached_property
 835    def models(self) -> models.ModelsWithRawResponse:
 836        from .resources.models import ModelsWithRawResponse
 837
 838        return ModelsWithRawResponse(self._client.models)
 839
 840    @cached_property
 841    def fine_tuning(self) -> fine_tuning.FineTuningWithRawResponse:
 842        from .resources.fine_tuning import FineTuningWithRawResponse
 843
 844        return FineTuningWithRawResponse(self._client.fine_tuning)
 845
 846    @cached_property
 847    def vector_stores(self) -> vector_stores.VectorStoresWithRawResponse:
 848        from .resources.vector_stores import VectorStoresWithRawResponse
 849
 850        return VectorStoresWithRawResponse(self._client.vector_stores)
 851
 852    @cached_property
 853    def beta(self) -> beta.BetaWithRawResponse:
 854        from .resources.beta import BetaWithRawResponse
 855
 856        return BetaWithRawResponse(self._client.beta)
 857
 858    @cached_property
 859    def batches(self) -> batches.BatchesWithRawResponse:
 860        from .resources.batches import BatchesWithRawResponse
 861
 862        return BatchesWithRawResponse(self._client.batches)
 863
 864    @cached_property
 865    def uploads(self) -> uploads.UploadsWithRawResponse:
 866        from .resources.uploads import UploadsWithRawResponse
 867
 868        return UploadsWithRawResponse(self._client.uploads)
 869
 870    @cached_property
 871    def responses(self) -> responses.ResponsesWithRawResponse:
 872        from .resources.responses import ResponsesWithRawResponse
 873
 874        return ResponsesWithRawResponse(self._client.responses)
 875
 876    @cached_property
 877    def realtime(self) -> realtime.RealtimeWithRawResponse:
 878        from .resources.realtime import RealtimeWithRawResponse
 879
 880        return RealtimeWithRawResponse(self._client.realtime)
 881
 882    @cached_property
 883    def conversations(self) -> conversations.ConversationsWithRawResponse:
 884        from .resources.conversations import ConversationsWithRawResponse
 885
 886        return ConversationsWithRawResponse(self._client.conversations)
 887
 888    @cached_property
 889    def evals(self) -> evals.EvalsWithRawResponse:
 890        from .resources.evals import EvalsWithRawResponse
 891
 892        return EvalsWithRawResponse(self._client.evals)
 893
 894    @cached_property
 895    def containers(self) -> containers.ContainersWithRawResponse:
 896        from .resources.containers import ContainersWithRawResponse
 897
 898        return ContainersWithRawResponse(self._client.containers)
 899
 900    @cached_property
 901    def videos(self) -> videos.VideosWithRawResponse:
 902        from .resources.videos import VideosWithRawResponse
 903
 904        return VideosWithRawResponse(self._client.videos)
 905
 906
 907class AsyncOpenAIWithRawResponse:
 908    _client: AsyncOpenAI
 909
 910    def __init__(self, client: AsyncOpenAI) -> None:
 911        self._client = client
 912
 913    @cached_property
 914    def completions(self) -> completions.AsyncCompletionsWithRawResponse:
 915        from .resources.completions import AsyncCompletionsWithRawResponse
 916
 917        return AsyncCompletionsWithRawResponse(self._client.completions)
 918
 919    @cached_property
 920    def chat(self) -> chat.AsyncChatWithRawResponse:
 921        from .resources.chat import AsyncChatWithRawResponse
 922
 923        return AsyncChatWithRawResponse(self._client.chat)
 924
 925    @cached_property
 926    def embeddings(self) -> embeddings.AsyncEmbeddingsWithRawResponse:
 927        from .resources.embeddings import AsyncEmbeddingsWithRawResponse
 928
 929        return AsyncEmbeddingsWithRawResponse(self._client.embeddings)
 930
 931    @cached_property
 932    def files(self) -> files.AsyncFilesWithRawResponse:
 933        from .resources.files import AsyncFilesWithRawResponse
 934
 935        return AsyncFilesWithRawResponse(self._client.files)
 936
 937    @cached_property
 938    def images(self) -> images.AsyncImagesWithRawResponse:
 939        from .resources.images import AsyncImagesWithRawResponse
 940
 941        return AsyncImagesWithRawResponse(self._client.images)
 942
 943    @cached_property
 944    def audio(self) -> audio.AsyncAudioWithRawResponse:
 945        from .resources.audio import AsyncAudioWithRawResponse
 946
 947        return AsyncAudioWithRawResponse(self._client.audio)
 948
 949    @cached_property
 950    def moderations(self) -> moderations.AsyncModerationsWithRawResponse:
 951        from .resources.moderations import AsyncModerationsWithRawResponse
 952
 953        return AsyncModerationsWithRawResponse(self._client.moderations)
 954
 955    @cached_property
 956    def models(self) -> models.AsyncModelsWithRawResponse:
 957        from .resources.models import AsyncModelsWithRawResponse
 958
 959        return AsyncModelsWithRawResponse(self._client.models)
 960
 961    @cached_property
 962    def fine_tuning(self) -> fine_tuning.AsyncFineTuningWithRawResponse:
 963        from .resources.fine_tuning import AsyncFineTuningWithRawResponse
 964
 965        return AsyncFineTuningWithRawResponse(self._client.fine_tuning)
 966
 967    @cached_property
 968    def vector_stores(self) -> vector_stores.AsyncVectorStoresWithRawResponse:
 969        from .resources.vector_stores import AsyncVectorStoresWithRawResponse
 970
 971        return AsyncVectorStoresWithRawResponse(self._client.vector_stores)
 972
 973    @cached_property
 974    def beta(self) -> beta.AsyncBetaWithRawResponse:
 975        from .resources.beta import AsyncBetaWithRawResponse
 976
 977        return AsyncBetaWithRawResponse(self._client.beta)
 978
 979    @cached_property
 980    def batches(self) -> batches.AsyncBatchesWithRawResponse:
 981        from .resources.batches import AsyncBatchesWithRawResponse
 982
 983        return AsyncBatchesWithRawResponse(self._client.batches)
 984
 985    @cached_property
 986    def uploads(self) -> uploads.AsyncUploadsWithRawResponse:
 987        from .resources.uploads import AsyncUploadsWithRawResponse
 988
 989        return AsyncUploadsWithRawResponse(self._client.uploads)
 990
 991    @cached_property
 992    def responses(self) -> responses.AsyncResponsesWithRawResponse:
 993        from .resources.responses import AsyncResponsesWithRawResponse
 994
 995        return AsyncResponsesWithRawResponse(self._client.responses)
 996
 997    @cached_property
 998    def realtime(self) -> realtime.AsyncRealtimeWithRawResponse:
 999        from .resources.realtime import AsyncRealtimeWithRawResponse
1000
1001        return AsyncRealtimeWithRawResponse(self._client.realtime)
1002
1003    @cached_property
1004    def conversations(self) -> conversations.AsyncConversationsWithRawResponse:
1005        from .resources.conversations import AsyncConversationsWithRawResponse
1006
1007        return AsyncConversationsWithRawResponse(self._client.conversations)
1008
1009    @cached_property
1010    def evals(self) -> evals.AsyncEvalsWithRawResponse:
1011        from .resources.evals import AsyncEvalsWithRawResponse
1012
1013        return AsyncEvalsWithRawResponse(self._client.evals)
1014
1015    @cached_property
1016    def containers(self) -> containers.AsyncContainersWithRawResponse:
1017        from .resources.containers import AsyncContainersWithRawResponse
1018
1019        return AsyncContainersWithRawResponse(self._client.containers)
1020
1021    @cached_property
1022    def videos(self) -> videos.AsyncVideosWithRawResponse:
1023        from .resources.videos import AsyncVideosWithRawResponse
1024
1025        return AsyncVideosWithRawResponse(self._client.videos)
1026
1027
1028class OpenAIWithStreamedResponse:
1029    _client: OpenAI
1030
1031    def __init__(self, client: OpenAI) -> None:
1032        self._client = client
1033
1034    @cached_property
1035    def completions(self) -> completions.CompletionsWithStreamingResponse:
1036        from .resources.completions import CompletionsWithStreamingResponse
1037
1038        return CompletionsWithStreamingResponse(self._client.completions)
1039
1040    @cached_property
1041    def chat(self) -> chat.ChatWithStreamingResponse:
1042        from .resources.chat import ChatWithStreamingResponse
1043
1044        return ChatWithStreamingResponse(self._client.chat)
1045
1046    @cached_property
1047    def embeddings(self) -> embeddings.EmbeddingsWithStreamingResponse:
1048        from .resources.embeddings import EmbeddingsWithStreamingResponse
1049
1050        return EmbeddingsWithStreamingResponse(self._client.embeddings)
1051
1052    @cached_property
1053    def files(self) -> files.FilesWithStreamingResponse:
1054        from .resources.files import FilesWithStreamingResponse
1055
1056        return FilesWithStreamingResponse(self._client.files)
1057
1058    @cached_property
1059    def images(self) -> images.ImagesWithStreamingResponse:
1060        from .resources.images import ImagesWithStreamingResponse
1061
1062        return ImagesWithStreamingResponse(self._client.images)
1063
1064    @cached_property
1065    def audio(self) -> audio.AudioWithStreamingResponse:
1066        from .resources.audio import AudioWithStreamingResponse
1067
1068        return AudioWithStreamingResponse(self._client.audio)
1069
1070    @cached_property
1071    def moderations(self) -> moderations.ModerationsWithStreamingResponse:
1072        from .resources.moderations import ModerationsWithStreamingResponse
1073
1074        return ModerationsWithStreamingResponse(self._client.moderations)
1075
1076    @cached_property
1077    def models(self) -> models.ModelsWithStreamingResponse:
1078        from .resources.models import ModelsWithStreamingResponse
1079
1080        return ModelsWithStreamingResponse(self._client.models)
1081
1082    @cached_property
1083    def fine_tuning(self) -> fine_tuning.FineTuningWithStreamingResponse:
1084        from .resources.fine_tuning import FineTuningWithStreamingResponse
1085
1086        return FineTuningWithStreamingResponse(self._client.fine_tuning)
1087
1088    @cached_property
1089    def vector_stores(self) -> vector_stores.VectorStoresWithStreamingResponse:
1090        from .resources.vector_stores import VectorStoresWithStreamingResponse
1091
1092        return VectorStoresWithStreamingResponse(self._client.vector_stores)
1093
1094    @cached_property
1095    def beta(self) -> beta.BetaWithStreamingResponse:
1096        from .resources.beta import BetaWithStreamingResponse
1097
1098        return BetaWithStreamingResponse(self._client.beta)
1099
1100    @cached_property
1101    def batches(self) -> batches.BatchesWithStreamingResponse:
1102        from .resources.batches import BatchesWithStreamingResponse
1103
1104        return BatchesWithStreamingResponse(self._client.batches)
1105
1106    @cached_property
1107    def uploads(self) -> uploads.UploadsWithStreamingResponse:
1108        from .resources.uploads import UploadsWithStreamingResponse
1109
1110        return UploadsWithStreamingResponse(self._client.uploads)
1111
1112    @cached_property
1113    def responses(self) -> responses.ResponsesWithStreamingResponse:
1114        from .resources.responses import ResponsesWithStreamingResponse
1115
1116        return ResponsesWithStreamingResponse(self._client.responses)
1117
1118    @cached_property
1119    def realtime(self) -> realtime.RealtimeWithStreamingResponse:
1120        from .resources.realtime import RealtimeWithStreamingResponse
1121
1122        return RealtimeWithStreamingResponse(self._client.realtime)
1123
1124    @cached_property
1125    def conversations(self) -> conversations.ConversationsWithStreamingResponse:
1126        from .resources.conversations import ConversationsWithStreamingResponse
1127
1128        return ConversationsWithStreamingResponse(self._client.conversations)
1129
1130    @cached_property
1131    def evals(self) -> evals.EvalsWithStreamingResponse:
1132        from .resources.evals import EvalsWithStreamingResponse
1133
1134        return EvalsWithStreamingResponse(self._client.evals)
1135
1136    @cached_property
1137    def containers(self) -> containers.ContainersWithStreamingResponse:
1138        from .resources.containers import ContainersWithStreamingResponse
1139
1140        return ContainersWithStreamingResponse(self._client.containers)
1141
1142    @cached_property
1143    def videos(self) -> videos.VideosWithStreamingResponse:
1144        from .resources.videos import VideosWithStreamingResponse
1145
1146        return VideosWithStreamingResponse(self._client.videos)
1147
1148
1149class AsyncOpenAIWithStreamedResponse:
1150    _client: AsyncOpenAI
1151
1152    def __init__(self, client: AsyncOpenAI) -> None:
1153        self._client = client
1154
1155    @cached_property
1156    def completions(self) -> completions.AsyncCompletionsWithStreamingResponse:
1157        from .resources.completions import AsyncCompletionsWithStreamingResponse
1158
1159        return AsyncCompletionsWithStreamingResponse(self._client.completions)
1160
1161    @cached_property
1162    def chat(self) -> chat.AsyncChatWithStreamingResponse:
1163        from .resources.chat import AsyncChatWithStreamingResponse
1164
1165        return AsyncChatWithStreamingResponse(self._client.chat)
1166
1167    @cached_property
1168    def embeddings(self) -> embeddings.AsyncEmbeddingsWithStreamingResponse:
1169        from .resources.embeddings import AsyncEmbeddingsWithStreamingResponse
1170
1171        return AsyncEmbeddingsWithStreamingResponse(self._client.embeddings)
1172
1173    @cached_property
1174    def files(self) -> files.AsyncFilesWithStreamingResponse:
1175        from .resources.files import AsyncFilesWithStreamingResponse
1176
1177        return AsyncFilesWithStreamingResponse(self._client.files)
1178
1179    @cached_property
1180    def images(self) -> images.AsyncImagesWithStreamingResponse:
1181        from .resources.images import AsyncImagesWithStreamingResponse
1182
1183        return AsyncImagesWithStreamingResponse(self._client.images)
1184
1185    @cached_property
1186    def audio(self) -> audio.AsyncAudioWithStreamingResponse:
1187        from .resources.audio import AsyncAudioWithStreamingResponse
1188
1189        return AsyncAudioWithStreamingResponse(self._client.audio)
1190
1191    @cached_property
1192    def moderations(self) -> moderations.AsyncModerationsWithStreamingResponse:
1193        from .resources.moderations import AsyncModerationsWithStreamingResponse
1194
1195        return AsyncModerationsWithStreamingResponse(self._client.moderations)
1196
1197    @cached_property
1198    def models(self) -> models.AsyncModelsWithStreamingResponse:
1199        from .resources.models import AsyncModelsWithStreamingResponse
1200
1201        return AsyncModelsWithStreamingResponse(self._client.models)
1202
1203    @cached_property
1204    def fine_tuning(self) -> fine_tuning.AsyncFineTuningWithStreamingResponse:
1205        from .resources.fine_tuning import AsyncFineTuningWithStreamingResponse
1206
1207        return AsyncFineTuningWithStreamingResponse(self._client.fine_tuning)
1208
1209    @cached_property
1210    def vector_stores(self) -> vector_stores.AsyncVectorStoresWithStreamingResponse:
1211        from .resources.vector_stores import AsyncVectorStoresWithStreamingResponse
1212
1213        return AsyncVectorStoresWithStreamingResponse(self._client.vector_stores)
1214
1215    @cached_property
1216    def beta(self) -> beta.AsyncBetaWithStreamingResponse:
1217        from .resources.beta import AsyncBetaWithStreamingResponse
1218
1219        return AsyncBetaWithStreamingResponse(self._client.beta)
1220
1221    @cached_property
1222    def batches(self) -> batches.AsyncBatchesWithStreamingResponse:
1223        from .resources.batches import AsyncBatchesWithStreamingResponse
1224
1225        return AsyncBatchesWithStreamingResponse(self._client.batches)
1226
1227    @cached_property
1228    def uploads(self) -> uploads.AsyncUploadsWithStreamingResponse:
1229        from .resources.uploads import AsyncUploadsWithStreamingResponse
1230
1231        return AsyncUploadsWithStreamingResponse(self._client.uploads)
1232
1233    @cached_property
1234    def responses(self) -> responses.AsyncResponsesWithStreamingResponse:
1235        from .resources.responses import AsyncResponsesWithStreamingResponse
1236
1237        return AsyncResponsesWithStreamingResponse(self._client.responses)
1238
1239    @cached_property
1240    def realtime(self) -> realtime.AsyncRealtimeWithStreamingResponse:
1241        from .resources.realtime import AsyncRealtimeWithStreamingResponse
1242
1243        return AsyncRealtimeWithStreamingResponse(self._client.realtime)
1244
1245    @cached_property
1246    def conversations(self) -> conversations.AsyncConversationsWithStreamingResponse:
1247        from .resources.conversations import AsyncConversationsWithStreamingResponse
1248
1249        return AsyncConversationsWithStreamingResponse(self._client.conversations)
1250
1251    @cached_property
1252    def evals(self) -> evals.AsyncEvalsWithStreamingResponse:
1253        from .resources.evals import AsyncEvalsWithStreamingResponse
1254
1255        return AsyncEvalsWithStreamingResponse(self._client.evals)
1256
1257    @cached_property
1258    def containers(self) -> containers.AsyncContainersWithStreamingResponse:
1259        from .resources.containers import AsyncContainersWithStreamingResponse
1260
1261        return AsyncContainersWithStreamingResponse(self._client.containers)
1262
1263    @cached_property
1264    def videos(self) -> videos.AsyncVideosWithStreamingResponse:
1265        from .resources.videos import AsyncVideosWithStreamingResponse
1266
1267        return AsyncVideosWithStreamingResponse(self._client.videos)
1268
1269
1270Client = OpenAI
1271
1272AsyncClient = AsyncOpenAI