Repository navigation
feat(keyless): send requests without an API key when none is set - #25
Conversation
Interfaze() and AsyncInterfaze() no longer raise InterfazeError when no api_key is passed and INTERFAZE_API_KEY is not set. A keyless client gives the openai client a key provider that returns an empty string, so it sends no Authorization header and does not read OPENAI_API_KEY. The _OpenAI and _AsyncOpenAI subclasses skip the header check that openai 2.34 and later run before each request. Adds request-boundary tests for keyless, environment-key and explicit-key requests over chat, streaming, raw streaming and model listing (sync and async), a rejected key (401) and a keyless 429.
A key with a trailing space or newline, for example a key read from a
file, made h11 reject the Authorization header. The request never left,
and the caller got APIConnectionError ("Connection error."). An explicit
blank api_key also hid a valid INTERFAZE_API_KEY.
_resolve_key now trims the explicit key and INTERFAZE_API_KEY before it
chooses one. A blank key gives a keyless request, as the API already
reads a bare Bearer header as keyless.
…lables Pass a key callable to openai untouched and strip string keys only. Override _should_retry so a keyless 429 with code keyless_daily_limit_exceeded reaches the caller after one request. A streamed async body is unread at that point, so a keyless 429 with a Retry-After above 60 seconds counts too. Keep the last Authorization header when openai joins the key and a caller header with another letter case. Accept *args and **kwargs in _validate_headers. Cover chat, stream, raw stream, parse, models, embeddings, moderations and batches on the sync and async clients with the real error shapes.
…follows Every client throws a keyless daily-limit 429 without a retry while the reset is more than a minute away. Some clients can retry in the last minute before the reset, when the retry succeeds.
…edupe Remove the SDK-side check for the keyless daily limit 429 (_error_code, _retry_after_seconds, _is_keyless_daily_limit, both _should_retry overrides and their constants). The API sends `x-should-retry: false` with that 429 (InterfazeAI/interfaze#346), and openai obeys the header before it checks the status. One test pins that a 429 with the header raises after one request. Remove _keep_last_authorization and both _build_headers overrides. A caller Authorization header next to the key is a case from before keyless access and is out of scope for this PR. Cut tests/test_auth.py to one test for each rule. Key resolution uses one table. The derived client test covers with_options and copy, keyless and with a new key. The other tests cover callable keys, OpenAI credentials on a keyless client, the User-Agent, a 401 and the daily limit 429.
Abhinavexist
left a comment
There was a problem hiding this comment.
Requesting changes for the untrimmed key provider below (line 27), and the org/project id leak on derived clients (line 48), which predates this PR but is a small fix now that the subclasses exist. The other inline comments are nits.
| # key, because an HTTP header value cannot end with a space or a newline. A key provider passes | ||
| # through untouched, because openai calls it before each request. | ||
| def _resolve_key(api_key: Union[str, _KeyProvider, None]) -> Union[str, _KeyProvider, None]: | ||
| if callable(api_key): |
There was a problem hiding this comment.
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 Authorization.
Example: Interfaze(api_key=lambda: open("/run/secrets/key").read()) with a file ending in a newline sends Bearer sk_...\n, and httpx/h11 raises LocalProtocolError: Illegal header value on the first request. The same key passed as a string works. Reproduced on this branch.
Fix: wrap a callable so its result is .strip()ped (sync and async variants).
There was a problem hiding this comment.
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.
| # The *args signature keeps the override working when openai changes its private signature. | ||
| # openai 2.34 and later read OPENAI_ADMIN_KEY for client.openai.admin.*. The empty _admin_api_key_auth | ||
| # keeps that OpenAI credential off Interfaze requests, and older openai versions never read it. | ||
| class InterfazeOpenAI(OpenAI): |
There was a problem hiding this comment.
Bug from before this PR: a derived client still sends the caller's OpenAI org/project ids to Interfaze. _drop_openai_env_ids (line 91) only clears them on the first client; client.openai.with_options(...) and .copy() go back through the constructor, which reads OPENAI_ORG_ID / OPENAI_PROJECT_ID again. The comment on lines 88-90 already notes this.
Example: OPENAI_ORG_ID=org_x OPENAI_PROJECT_ID=proj_x, then Interfaze().openai.with_options(max_retries=0).models.list() sends OpenAI-Organization: org_x and OpenAI-Project: proj_x (the base client sends neither). Reproduced on this branch.
Fix: now that these subclasses exist, clear organization / project in their __init__ unless they were passed in, which covers derived clients and replaces _drop_openai_env_ids. Fine as a follow-up if you'd rather keep this PR scoped.
There was a problem hiding this comment.
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.
| def _resolve_key(api_key: Union[str, _KeyProvider, None]) -> Union[str, _KeyProvider, None]: | ||
| if callable(api_key): | ||
| return api_key | ||
| return (api_key or "").strip() or os.environ.get("INTERFAZE_API_KEY", "").strip() or None |
There was a problem hiding this comment.
nit: a missing or misspelt key now fails late and silently. Before, Interfaze() raised at construction; now a deploy with INTERFAZE_APIKEY (typo) runs keyless under the per-IP limits until the daily cap, then raises RateLimitError in production. Checked: no warning is emitted.
Fix: log a warning once when the client falls back to keyless.
There was a problem hiding this comment.
Added in f39be22. A keyless client warns once per process with a UserWarning that links the dashboard. A wrong key value still gets a 401 from the API.
| return "" | ||
|
|
||
|
|
||
| # openai 2.34 and later raise before they send a request with no Authorization header. |
There was a problem hiding this comment.
nit: these comment blocks (here, 23-25, 32-34) could each be one line, e.g. # openai>=2.34 refuses requests with no Authorization header; Interfaze allows keyless. The first sentence of the _resolve_key comment restates the return line.
A key callable that returned a trailing newline sent an illegal Authorization header value. The client now wraps sync and async callables so each result is stripped. A blank result sends no Authorization header.
Abhinavexist
left a comment
There was a problem hiding this comment.
LGTM @jade-interfaze. Re-checked on f39be22: sync and async key functions returning "sk_...\n" now send a trimmed header, the keyless warning fires once per process, and the tests pass. Two nits below for parity with langchain-interfaze#5, neither blocking. Fine to keep openai's default for the OPENAI_* env vars.
|
|
||
| # 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) |
There was a problem hiding this comment.
nit: a blank Authorization default header counts as a key here, so Interfaze(default_headers={"Authorization": ""}) sends authorization: (empty) and skips the keyless warning, instead of going keyless. langchain-interfaze#5 now drops a blank one.
Fix: drop the header in _build_headers when value.strip() is empty, and check the value here, not only the name.
|
|
||
| # 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() |
There was a problem hiding this comment.
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.
With no
api_keyand noINTERFAZE_API_KEY,Interfaze()andAsyncInterfaze()send requests without anAuthorizationheader. This lets server-side code use the API's keyless access. Onmain, both clients raiseInterfazeErrorwhen the caller sets no key.A keyless client gives the openai client a key provider that returns an empty string, so it sends no
Authorizationheader and never readsOPENAI_API_KEY. TheInterfazeOpenAIandAsyncInterfazeOpenAIsubclasses skip openai's check for anAuthorizationheader before each request, and never sendOPENAI_ADMIN_KEY(_client.py#L72-L90). These overrides depend on openai internals. The tests pass with openai 2.0.0, 2.33.0, 2.34.0, 2.46.0 (locked) and 2.54.0.An explicit key wins over
INTERFAZE_API_KEY, and a blank key counts as no key. A keyless client warns once per process with aUserWarning: "Interfaze SDK is running in keyless mode. For higher rate limits, get an API key at https://interfaze.ai/dashboard." A key callable passes through, and the client trims its result (_client.py#L28-L47).The API sends
x-should-retry: falsewith the keyless daily-limit429, and openai does not retry a response with that header. This PR depends on InterfazeAI/interfaze#346 for that header, so #346 must merge first.tests/test_auth.pychecks the request headers withrespx, with the API's real429body and headers. It covers chat, model listing, the openai admin resource,with_optionsandcopy, with sync and async clients. The README says that keyless access needs a release later than 1.0.3.Authorizationheader and got a200.