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
23 changes: 21 additions & 2 deletions src/openai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing_extensions import override

from . import types
from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes
from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, TokenAuth, Transport, ProxiesTypes
from ._utils import file_from_path
from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions
from ._models import BaseModel
Expand Down Expand Up @@ -87,7 +87,12 @@

from .lib import azure as _azure, pydantic_function_tool as pydantic_function_tool
from .version import VERSION as VERSION
from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI
from .lib.azure import (
AzureAuth as AzureAuth,
AzureOpenAI as AzureOpenAI,
AsyncAzureAuth as AsyncAzureAuth,
AsyncAzureOpenAI as AsyncAzureOpenAI,
)
from .lib._old_api import *
from .lib.streaming import (
AssistantEventHandler as AssistantEventHandler,
Expand Down Expand Up @@ -119,6 +124,8 @@

api_key: str | None = None

auth: TokenAuth | None = None

organization: str | None = None

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

api_key = value

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

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

auth = value

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

_client = _ModuleClient(
api_key=api_key,
auth=auth,
organization=organization,
project=project,
webhook_secret=webhook_secret,
Expand Down
80 changes: 64 additions & 16 deletions src/openai/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
Omit,
Timeout,
NotGiven,
TokenAuth,
Transport,
ProxiesTypes,
AsyncTokenAuth,
RequestOptions,
)
from ._utils import (
Expand All @@ -25,6 +27,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 @@ -93,6 +96,7 @@ def __init__(
self,
*,
api_key: str | None = None,
auth: TokenAuth | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
Expand Down Expand Up @@ -124,13 +128,16 @@ def __init__(
- `project` from `OPENAI_PROJECT_ID`
- `webhook_secret` from `OPENAI_WEBHOOK_SECRET`
"""
if api_key and auth:
raise ValueError("The `api_key` and `auth` 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 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 client option must be set either by passing api_key or auth to the client or by setting the OPENAI_API_KEY environment variable"
)
self.api_key = api_key
self.auth = auth
self.api_key = api_key or ""

if organization is None:
organization = os.environ.get("OPENAI_ORG_ID")
Expand Down Expand Up @@ -163,6 +170,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 +287,25 @@ def with_streaming_response(self) -> OpenAIWithStreamedResponse:
def qs(self) -> Querystring:
return Querystring(array_format="brackets")

def refresh_auth_headers(self) -> None:
secret = self.auth.get_token() if self.auth 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 = {}
else:
self._auth_headers = {"Authorization": f"Bearer {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 +322,7 @@ def copy(
self,
*,
api_key: str | None = None,
auth: TokenAuth | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
Expand Down Expand Up @@ -338,6 +358,10 @@ def copy(
elif set_default_query is not None:
params = set_default_query

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

http_client = http_client or self._client
return self.__class__(
api_key=api_key or self.api_key,
Expand Down Expand Up @@ -412,6 +436,7 @@ def __init__(
self,
*,
api_key: str | None = None,
auth: AsyncTokenAuth | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
Expand Down Expand Up @@ -443,13 +468,16 @@ def __init__(
- `project` from `OPENAI_PROJECT_ID`
- `webhook_secret` from `OPENAI_WEBHOOK_SECRET`
"""
if api_key and auth:
raise ValueError("The `api_key` and `auth` 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 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 client option must be set either by passing api_key or auth to the client or by setting the OPENAI_API_KEY environment variable"
)
self.api_key = api_key
self.auth = auth
self.api_key = api_key or ""

if organization is None:
organization = os.environ.get("OPENAI_ORG_ID")
Expand Down Expand Up @@ -482,6 +510,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 +627,28 @@ 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:
secret = await self.auth.get_token()
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 = {}
else:
self._auth_headers = {"Authorization": f"Bearer {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 +665,7 @@ def copy(
self,
*,
api_key: str | None = None,
auth: AsyncTokenAuth | None = None,
organization: str | None = None,
project: str | None = None,
webhook_secret: str | None = None,
Expand Down Expand Up @@ -657,6 +701,10 @@ def copy(
elif set_default_query is not None:
params = set_default_query

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

http_client = http_client or self._client
return self.__class__(
api_key=api_key or self.api_key,
Expand Down
8 changes: 8 additions & 0 deletions src/openai/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,11 @@ class _GenericAlias(Protocol):
class HttpxSendArgs(TypedDict, total=False):
auth: httpx.Auth
follow_redirects: bool


class TokenAuth(Protocol):
def get_token(self) -> str: ...


class AsyncTokenAuth(Protocol):
async def get_token(self) -> str: ...
Loading