Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion src/openai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,18 @@
from . import types
from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes
from ._utils import file_from_path
from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions
from ._client import (
Client,
OpenAI,
Stream,
Timeout,
Transport,
AsyncClient,
AsyncOpenAI,
AsyncStream,
AuthProvider,
RequestOptions,
)
from ._models import BaseModel
from ._version import __title__, __version__
from ._response import APIResponse as APIResponse, AsyncAPIResponse as AsyncAPIResponse
Expand Down Expand Up @@ -119,6 +130,8 @@

api_key: str | None = None

auth_provider: AuthProvider | None = None

organization: str | None = None

project: str | None = None
Expand Down Expand Up @@ -165,6 +178,17 @@ def api_key(self, value: str | None) -> None: # type: ignore

api_key = value

@property # type: ignore
@override
def auth_provider(self) -> AuthProvider | None:
return auth_provider

@auth_provider.setter # type: ignore
def auth_provider(self, value: AuthProvider | None) -> None: # type: ignore
global auth_provider

auth_provider = value

@property # type: ignore
@override
def organization(self) -> str | None:
Expand Down Expand Up @@ -348,6 +372,7 @@ def _load_client() -> OpenAI: # type: ignore[reportUnusedFunction]

_client = _ModuleClient(
api_key=api_key,
auth_provider=auth_provider,
organization=organization,
project=project,
webhook_secret=webhook_secret,
Expand Down
87 changes: 70 additions & 17 deletions src/openai/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

import os
from typing import TYPE_CHECKING, Any, Union, Mapping
from typing import TYPE_CHECKING, Any, Union, Mapping, Callable, Awaitable
from typing_extensions import Self, override

import httpx
Expand All @@ -25,6 +25,7 @@
get_async_library,
)
from ._compat import cached_property
from ._models import FinalRequestOptions
from ._version import __version__
from ._streaming import Stream as Stream, AsyncStream as AsyncStream
from ._exceptions import OpenAIError, APIStatusError
Expand Down Expand Up @@ -73,6 +74,9 @@

__all__ = ["Timeout", "Transport", "ProxiesTypes", "RequestOptions", "OpenAI", "AsyncOpenAI", "Client", "AsyncClient"]

AuthProvider = Callable[[], "str | dict[str, str]"]
AsyncAuthProvider = Callable[[], Awaitable["str | dict[str, str]"]]


class OpenAI(SyncAPIClient):
# client options
Expand All @@ -93,6 +97,7 @@ def __init__(
self,
*,
api_key: str | None = None,
auth_provider: AuthProvider | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
Expand Down Expand Up @@ -124,13 +129,16 @@ def __init__(
- `project` from `OPENAI_PROJECT_ID`
- `webhook_secret` from `OPENAI_WEBHOOK_SECRET`
"""
if api_key and auth_provider:
raise ValueError("The `api_key` and `auth_provider` arguments are mutually exclusive")
if api_key is None:
api_key = os.environ.get("OPENAI_API_KEY")
if api_key is None:
if api_key is None and auth_provider is None:
raise OpenAIError(
"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"
"The api_key or auth_provider client option must be set either by passing api_key or auth_provider to the client or by setting the OPENAI_API_KEY environment variable"
)
self.api_key = api_key
self.auth_provider = auth_provider
self.api_key = api_key or ""

if organization is None:
organization = os.environ.get("OPENAI_ORG_ID")
Expand Down Expand Up @@ -163,6 +171,7 @@ def __init__(
)

self._default_stream_cls = Stream
self._auth_headers: dict[str, str] = {}

@cached_property
def completions(self) -> Completions:
Expand Down Expand Up @@ -279,14 +288,27 @@ def with_streaming_response(self) -> OpenAIWithStreamedResponse:
def qs(self) -> Querystring:
return Querystring(array_format="brackets")

def refresh_auth_headers(self) -> None:
secret = self.auth_provider() if self.auth_provider else self.api_key
if not secret:
# if secret is an empty string, encoding the header will fail
# so we set it to an empty dict
# this is to avoid sending an invalid Authorization header
self._auth_headers = {}
elif isinstance(secret, str):
self._auth_headers = {"Authorization": f"Bearer {secret}"}
else:
self._auth_headers = secret

@override
def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
self.refresh_auth_headers()
return super()._prepare_options(options)

@property
@override
def auth_headers(self) -> dict[str, str]:
api_key = self.api_key
if not api_key:
# if the api key is an empty string, encoding the header will fail
return {}
return {"Authorization": f"Bearer {api_key}"}
return self._auth_headers

@property
@override
Expand All @@ -303,6 +325,7 @@ def copy(
self,
*,
api_key: str | None = None,
auth_provider: AuthProvider | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
Expand Down Expand Up @@ -338,6 +361,10 @@ def copy(
elif set_default_query is not None:
params = set_default_query

auth_provider = auth_provider or self.auth_provider
if auth_provider is not None:
_extra_kwargs = {**_extra_kwargs, "auth_provider": auth_provider}

http_client = http_client or self._client
return self.__class__(
api_key=api_key or self.api_key,
Expand Down Expand Up @@ -412,6 +439,7 @@ def __init__(
self,
*,
api_key: str | None = None,
auth_provider: AsyncAuthProvider | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
Expand Down Expand Up @@ -443,13 +471,16 @@ def __init__(
- `project` from `OPENAI_PROJECT_ID`
- `webhook_secret` from `OPENAI_WEBHOOK_SECRET`
"""
if api_key and auth_provider:
raise ValueError("The `api_key` and `auth_provider` arguments are mutually exclusive")
if api_key is None:
api_key = os.environ.get("OPENAI_API_KEY")
if api_key is None:
if api_key is None and auth_provider is None:
raise OpenAIError(
"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"
"The api_key or auth_provider client option must be set either by passing api_key or auth_provider to the client or by setting the OPENAI_API_KEY environment variable"
)
self.api_key = api_key
self.auth_provider = auth_provider
self.api_key = api_key or ""

if organization is None:
organization = os.environ.get("OPENAI_ORG_ID")
Expand Down Expand Up @@ -482,6 +513,7 @@ def __init__(
)

self._default_stream_cls = AsyncStream
self._auth_headers: dict[str, str] = {}

@cached_property
def completions(self) -> AsyncCompletions:
Expand Down Expand Up @@ -598,14 +630,30 @@ def with_streaming_response(self) -> AsyncOpenAIWithStreamedResponse:
def qs(self) -> Querystring:
return Querystring(array_format="brackets")

async def refresh_auth_headers(self) -> None:
if self.auth_provider:
secret = await self.auth_provider()
else:
secret = self.api_key
if not secret:
# if the secret is an empty string, encoding the header will fail
# so we set it to an empty dict
# this is to avoid sending an invalid Authorization header
self._auth_headers = {}
elif isinstance(secret, str):
self._auth_headers = {"Authorization": f"Bearer {secret}"}
else:
self._auth_headers = secret

@override
async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
await self.refresh_auth_headers()
return await super()._prepare_options(options)

@property
@override
def auth_headers(self) -> dict[str, str]:
api_key = self.api_key
if not api_key:
# if the api key is an empty string, encoding the header will fail
return {}
return {"Authorization": f"Bearer {api_key}"}
return self._auth_headers

@property
@override
Expand All @@ -622,6 +670,7 @@ def copy(
self,
*,
api_key: str | None = None,
auth_provider: AsyncAuthProvider | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
Expand Down Expand Up @@ -657,6 +706,10 @@ def copy(
elif set_default_query is not None:
params = set_default_query

auth_provider = auth_provider or self.auth_provider
if auth_provider is not None:
_extra_kwargs = {**_extra_kwargs, "auth_provider": auth_provider}

http_client = http_client or self._client
return self.__class__(
api_key=api_key or self.api_key,
Expand Down
8 changes: 4 additions & 4 deletions src/openai/lib/azure.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ def __init__(
self._azure_endpoint = httpx.___URL(azure_endpoint) if azure_endpoint else None

@override
def copy(
def copy( # type: ignore
self,
*,
api_key: str | None = None,
Expand Down Expand Up @@ -301,7 +301,7 @@ def copy(
},
)

with_options = copy
with_options = copy # type: ignore

def _get_azure_ad_token(self) -> str | None:
if self._azure_ad_token is not None:
Expand Down Expand Up @@ -536,7 +536,7 @@ def __init__(
self._azure_endpoint = httpx.___URL(azure_endpoint) if azure_endpoint else None

@override
def copy(
def copy( # type: ignore
self,
*,
api_key: str | None = None,
Expand Down Expand Up @@ -582,7 +582,7 @@ def copy(
},
)

with_options = copy
with_options = copy # type: ignore

async def _get_azure_ad_token(self) -> str | None:
if self._azure_ad_token is not None:
Expand Down
2 changes: 2 additions & 0 deletions src/openai/resources/beta/realtime/realtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ async def __aenter__(self) -> AsyncRealtimeConnection:
raise OpenAIError("You need to install `openai[realtime]` to use this method") from exc

extra_query = self.__extra_query
await self.__client.refresh_auth_headers()
auth_headers = self.__client.auth_headers
if is_async_azure_client(self.__client):
url, auth_headers = await self.__client._configure_realtime(self.__model, extra_query)
Expand Down Expand Up @@ -540,6 +541,7 @@ def __enter__(self) -> RealtimeConnection:
raise OpenAIError("You need to install `openai[realtime]` to use this method") from exc

extra_query = self.__extra_query
self.__client.refresh_auth_headers()
auth_headers = self.__client.auth_headers
if is_azure_client(self.__client):
url, auth_headers = self.__client._configure_realtime(self.__model, extra_query)
Expand Down
Loading