Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
8545f26
feat: send requests without a key when no key is set
jade-interfaze Nov 24, 2026
e56029f
fix: trim whitespace around the API key
jade-interfaze Nov 24, 2026
5a6dda3
fix(client): stop retrying the keyless daily limit and accept key cal…
jade-interfaze Nov 24, 2026
4041eca
docs(readme): describe keyless access and the daily limit
jade-interfaze Nov 24, 2026
1e915dd
fix(client): retry keyed 429 responses like openai and survive a brok…
jade-interfaze Nov 25, 2026
467bf12
fix(client): never send OPENAI_ADMIN_KEY to Interfaze
jade-interfaze Nov 25, 2026
44e19ad
refactor(client): name the openai subclasses after Interfaze
jade-interfaze Nov 25, 2026
14eaea0
docs(client): describe the daily limit retry rule and the async guess
jade-interfaze Nov 25, 2026
95974f2
test(keyless): trim duplicate keyless tests
jade-interfaze Nov 25, 2026
355602a
docs(keyless): describe the daily-limit retry rule that every client …
jade-interfaze Nov 25, 2026
0082e5b
refactor(keyless): remove the SDK retry check and the Authorization d…
jade-interfaze Nov 25, 2026
c15919e
test(keyless): drop the User-Agent and keyed 401 tests
jade-interfaze Nov 25, 2026
396bf23
fix(keyless): trim the result of a key callable
jade-interfaze Nov 25, 2026
eb37576
docs(keyless): replace the keyless paragraph with an example and a do…
jade-interfaze Nov 25, 2026
58afe32
refactor(keyless): shorten the comment blocks in _client.py to one line
jade-interfaze Nov 25, 2026
f39be22
feat(keyless): warn once per process when a client goes keyless
jade-interfaze Nov 25, 2026
899bd98
fix(keyless): treat a blank authorization header as no key
Abhinavexist Nov 27, 2026
33013ef
fix(keyless): raise when a key callable returns a blank key
Abhinavexist Nov 27, 2026
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
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ interfaze = Interfaze(api_key="sk_...") # or set INTERFAZE_API_KEY and call Int

Async is identical via `AsyncInterfaze` - every call becomes `await`-able.

### Keyless access

```python
# No API key: Interfaze applies per-IP keyless limits. Server-side code only.
client = Interfaze()
```

See [Try Interfaze without an API key](https://interfaze.ai/docs#try-interfaze-without-an-api-key) for the limits and rules. Keyless access needs a release of `interfaze` later than 1.0.3.

## Your first request

This guide will get you started with your first request to Interfaze, which follows the Chat Completions API standard.
Expand Down Expand Up @@ -317,7 +326,7 @@ Interfaze re-exports typed error classes to catch and narrow on:
from interfaze import BadRequestError, InterfazeError, RateLimitError
```

`InterfazeError` is client-side (missing key, invalid guard code, stream misuse). Everything else is an `APIError` subclass carrying `status_code` and `code` - `BadRequestError` (400), `AuthenticationError` (401), `RateLimitError` (429), and so on.
`InterfazeError` is client-side (invalid guard code, stream misuse). Everything else is an `APIError` subclass carrying `status_code` and `code` - `BadRequestError` (400), `AuthenticationError` (401), `RateLimitError` (429), and so on. When a keyless request reaches a limit, the `RateLimitError` message tells you how to get an API key.

## Capabilities

Expand Down
115 changes: 93 additions & 22 deletions src/interfaze/_client.py
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

Expand All @@ -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()

Copy link
Copy Markdown
Collaborator

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.



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):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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 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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.



# 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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.



# 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):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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. _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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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(
Expand All @@ -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:
Expand All @@ -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,
Expand All @@ -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)
Expand All @@ -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,
Expand All @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions src/interfaze/_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
INTERFAZE_BASE_URL = "https://api.interfaze.ai/v1"
INTERFAZE_MODEL = "interfaze-beta"
DEFAULT_TIMEOUT = 900.0
KEYLESS_WARNING = (
"Interfaze SDK is running in keyless mode. "
"For higher rate limits, get an API key at https://interfaze.ai/dashboard."
)

# Task names accepted in a <task>...</task> tag.
TASK_NAMES = (
Expand Down
9 changes: 1 addition & 8 deletions tests/test_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
import asyncio
import json

import pytest
import respx
from conftest import JSON_OBJECT, STREAM_CHUNKS, TASK_OCR, TOOL_CALL, last_body, mock_json, mock_sse

from interfaze import AsyncInterfaze, InterfazeError
from interfaze import AsyncInterfaze

WEATHER_TOOL = [
{
Expand Down Expand Up @@ -69,12 +68,6 @@ async def go():
assert json.loads(content)["city"] == "Tokyo"


def test_async_missing_key_raises(monkeypatch):
monkeypatch.delenv("INTERFAZE_API_KEY", raising=False)
with pytest.raises(InterfazeError, match="INTERFAZE_API_KEY"):
AsyncInterfaze()


@respx.mock
def test_async_create_stream_true_returns_raw_openai_stream():
mock_sse(STREAM_CHUNKS)
Expand Down
Loading