Repository navigation
feat(keyless): send requests without an API key when none is set #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
8545f26
e56029f
5a6dda3
4041eca
1e915dd
467bf12
44e19ad
14eaea0
95974f2
355602a
0082e5b
c15919e
396bf23
eb37576
58afe32
f39be22
899bd98
33013ef
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,8 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from typing import Any, Dict, Optional, Union | ||
| import warnings | ||
| from typing import Any, Awaitable, Callable, Dict, Optional, Union | ||
|
|
||
| from openai import AsyncOpenAI, OpenAI | ||
|
|
||
|
|
@@ -13,18 +14,81 @@ | |
| HEADER_BYPASS_MOA, | ||
| HEADER_SHOW_ADDITIONAL_INFO, | ||
| INTERFAZE_BASE_URL, | ||
| KEYLESS_WARNING, | ||
| ) | ||
| from ._errors import InterfazeError | ||
| from ._tasks import AsyncTasks, Tasks | ||
|
|
||
|
|
||
| def _resolve_key(api_key: Optional[str]) -> str: | ||
| key = api_key or os.environ.get("INTERFAZE_API_KEY") | ||
| if not key: | ||
| raise InterfazeError( | ||
| "Missing API key. Pass Interfaze(api_key=...) or set the INTERFAZE_API_KEY environment variable." | ||
| ) | ||
| return key | ||
| _KeyProvider = Callable[[], Any] | ||
|
|
||
| _keyless_warned = False | ||
|
|
||
|
|
||
| # openai calls a key provider before each request, so the wrapper trims the key each time. | ||
| def _trimmed(provider: _KeyProvider) -> _KeyProvider: | ||
| return lambda: provider().strip() | ||
|
|
||
|
|
||
| def _async_trimmed(provider: _KeyProvider) -> _KeyProvider: | ||
| async def trimmed() -> str: | ||
| return str((await provider()).strip()) | ||
|
|
||
| return trimmed | ||
|
|
||
|
|
||
| # Trims each string key, because an HTTP header value cannot end with a space or a newline. | ||
| def _resolve_key( | ||
| api_key: Union[str, _KeyProvider, None], trim_provider: Callable[[_KeyProvider], _KeyProvider] | ||
| ) -> Union[str, _KeyProvider, None]: | ||
| if callable(api_key): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bug: a key provider's value isn't trimmed. String keys are now stripped because "an HTTP header value cannot end with a space or a newline", but a callable passes through untouched, so openai puts its raw return value in Example: Fix: wrap a callable so its result is
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 396bf23. The client trims the value that a key callable returns, sync and async. A key file with a trailing newline now sends a valid header. |
||
| return trim_provider(api_key) | ||
| return (api_key or "").strip() or os.environ.get("INTERFAZE_API_KEY", "").strip() or None | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: a missing or misspelt key now fails late and silently. Before, Fix: log a warning once when the client falls back to keyless.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added in f39be22. A keyless client warns once per process with a |
||
|
|
||
|
|
||
| # A caller Authorization header counts as a key. | ||
| def _has_authorization(headers: Dict[str, str]) -> bool: | ||
| return any(name.lower() == "authorization" for name in headers) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: a blank Fix: drop the header in |
||
|
|
||
|
|
||
| # Warns once per process; stacklevel=3 points at the code that built the client. | ||
| def _warn_if_keyless(key: Union[str, _KeyProvider, None], headers: Dict[str, str]) -> None: | ||
| global _keyless_warned | ||
| if key or _has_authorization(headers) or _keyless_warned: | ||
| return | ||
| _keyless_warned = True | ||
| warnings.warn(KEYLESS_WARNING, UserWarning, stacklevel=3) | ||
|
|
||
|
|
||
| # A key provider that returns "" stops OpenAI() from reading OPENAI_API_KEY and sends no Authorization header. | ||
| def _no_key() -> str: | ||
| return "" | ||
|
|
||
|
|
||
| async def _async_no_key() -> str: | ||
| return "" | ||
|
|
||
|
|
||
| # openai>=2.34 refuses requests with no Authorization header; Interfaze allows keyless. | ||
| class InterfazeOpenAI(OpenAI): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bug from before this PR: a derived client still sends the caller's OpenAI org/project ids to Interfaze. Example: Fix: now that these subclasses exist, clear
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We will keep openai's default behavior for these variables. A caller sets them on purpose, and the SDK passes them through as openai does. |
||
| # openai>=2.34 reads OPENAI_ADMIN_KEY; keep that credential off Interfaze requests. | ||
| @property | ||
| def _admin_api_key_auth(self) -> Dict[str, str]: | ||
| return {} | ||
|
|
||
| # Only the keyless stand-in skips the check, so a key callable returning a blank key still raises. | ||
| def _validate_headers(self, *args: Any, **kwargs: Any) -> None: | ||
| if getattr(self, "_api_key_provider", None) is not _no_key: | ||
| super()._validate_headers(*args, **kwargs) | ||
|
|
||
|
|
||
| class AsyncInterfazeOpenAI(AsyncOpenAI): | ||
| @property | ||
| def _admin_api_key_auth(self) -> Dict[str, str]: | ||
| return {} | ||
|
|
||
| def _validate_headers(self, *args: Any, **kwargs: Any) -> None: | ||
| if getattr(self, "_api_key_provider", None) is not _async_no_key: | ||
| super()._validate_headers(*args, **kwargs) | ||
|
|
||
|
|
||
| def _build_headers( | ||
|
|
@@ -34,7 +98,12 @@ def _build_headers( | |
| bypass_cache: bool, | ||
| admin_key: Optional[str], | ||
| ) -> Dict[str, str]: | ||
| headers: Dict[str, str] = dict(default_headers or {}) | ||
| # A blank Authorization header counts as no key. | ||
| headers: Dict[str, str] = { | ||
| name: value | ||
| for name, value in (default_headers or {}).items() | ||
| if name.lower() != "authorization" or str(value).strip() | ||
| } | ||
| if show_additional_info: | ||
| headers[HEADER_SHOW_ADDITIONAL_INFO] = "true" | ||
| if bypass_moa: | ||
|
|
@@ -61,7 +130,7 @@ class Interfaze: | |
| def __init__( | ||
| self, | ||
| *, | ||
| api_key: Optional[str] = None, | ||
| api_key: Union[str, Callable[[], str], None] = None, | ||
| base_url: Optional[str] = None, | ||
| show_additional_info: bool = False, | ||
| bypass_moa: bool = False, | ||
|
|
@@ -71,12 +140,13 @@ def __init__( | |
| **kwargs: Any, | ||
| ) -> None: | ||
| kwargs.setdefault("timeout", DEFAULT_TIMEOUT) | ||
| self.openai = OpenAI( | ||
| api_key=_resolve_key(api_key), | ||
| key = _resolve_key(api_key, _trimmed) | ||
| headers = _build_headers(default_headers, show_additional_info, bypass_moa, bypass_cache, admin_key) | ||
| _warn_if_keyless(key, headers) | ||
| self.openai: OpenAI = InterfazeOpenAI( | ||
| api_key=key or _no_key, | ||
| base_url=base_url or INTERFAZE_BASE_URL, | ||
| default_headers=_build_headers( | ||
| default_headers, show_additional_info, bypass_moa, bypass_cache, admin_key | ||
| ), | ||
| default_headers=headers, | ||
| **kwargs, | ||
| ) | ||
| _drop_openai_env_ids(self.openai, kwargs) | ||
|
|
@@ -89,7 +159,7 @@ class AsyncInterfaze: | |
| def __init__( | ||
| self, | ||
| *, | ||
| api_key: Optional[str] = None, | ||
| api_key: Union[str, Callable[[], Awaitable[str]], None] = None, | ||
| base_url: Optional[str] = None, | ||
| show_additional_info: bool = False, | ||
| bypass_moa: bool = False, | ||
|
|
@@ -99,12 +169,13 @@ def __init__( | |
| **kwargs: Any, | ||
| ) -> None: | ||
| kwargs.setdefault("timeout", DEFAULT_TIMEOUT) | ||
| self.openai = AsyncOpenAI( | ||
| api_key=_resolve_key(api_key), | ||
| key = _resolve_key(api_key, _async_trimmed) | ||
| headers = _build_headers(default_headers, show_additional_info, bypass_moa, bypass_cache, admin_key) | ||
| _warn_if_keyless(key, headers) | ||
| self.openai: AsyncOpenAI = AsyncInterfazeOpenAI( | ||
| api_key=key or _async_no_key, | ||
| base_url=base_url or INTERFAZE_BASE_URL, | ||
| default_headers=_build_headers( | ||
| default_headers, show_additional_info, bypass_moa, bypass_cache, admin_key | ||
| ), | ||
| default_headers=headers, | ||
| **kwargs, | ||
| ) | ||
| _drop_openai_env_ids(self.openai, kwargs) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: a key function that returns
""(or only whitespace, now that it's trimmed) silently sends a keyless request, with no warning. langchain-interfaze#5 now raises for this case, which reads better for a secret store that comes back empty.Fix: skip the header check only for
_no_key/_async_no_key, the same way langchain does with_api_key_provider is not _keyless_api_key.