interfaze 1.0.2__tar.gz → 1.0.5__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {interfaze-1.0.2 → interfaze-1.0.5}/PKG-INFO +13 -4
- {interfaze-1.0.2 → interfaze-1.0.5}/README.md +11 -2
- {interfaze-1.0.2 → interfaze-1.0.5}/pyproject.toml +1 -1
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/__init__.py +4 -2
- interfaze-1.0.5/src/interfaze/_client.py +184 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/_constants.py +6 -2
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_async.py +1 -8
- interfaze-1.0.5/tests/test_auth.py +332 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_chat.py +33 -6
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_inputs_and_client.py +0 -6
- {interfaze-1.0.2 → interfaze-1.0.5}/uv.lock +1 -1
- interfaze-1.0.2/src/interfaze/_client.py +0 -100
- {interfaze-1.0.2 → interfaze-1.0.5}/.github/workflows/ci.yml +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/.github/workflows/publish.yml +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/.github/workflows/qa-live.yml +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/.gitignore +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/LICENSE +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/scripts/qa_live.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/_chat.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/_errors.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/_guard.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/_inputs.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/_schema.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/_stream.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/_tasks.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/_types.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/src/interfaze/py.typed +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/assets.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/conftest.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_compliance.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_errors.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_guard.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_models.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_schema.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_stream.py +0 -0
- {interfaze-1.0.2 → interfaze-1.0.5}/tests/test_tasks.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: interfaze
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.5
|
|
4
4
|
Summary: Interfaze Python SDK.
|
|
5
5
|
Project-URL: Homepage, https://interfaze.ai
|
|
6
6
|
Project-URL: Repository, https://github.com/InterfazeAI/interfaze-python
|
|
@@ -45,6 +45,15 @@ interfaze = Interfaze(api_key="sk_...") # or set INTERFAZE_API_KEY and call Int
|
|
|
45
45
|
|
|
46
46
|
Async is identical via `AsyncInterfaze` - every call becomes `await`-able.
|
|
47
47
|
|
|
48
|
+
### Keyless access
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
# No API key: Interfaze applies per-IP keyless limits. Server-side code only.
|
|
52
|
+
client = Interfaze()
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
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.
|
|
56
|
+
|
|
48
57
|
## Your first request
|
|
49
58
|
|
|
50
59
|
This guide will get you started with your first request to Interfaze, which follows the Chat Completions API standard.
|
|
@@ -328,7 +337,7 @@ Set router, cache, and streaming behavior once on the client:
|
|
|
328
337
|
```python
|
|
329
338
|
interfaze = Interfaze(
|
|
330
339
|
show_additional_info=True, # stream <precontext> deltas as they're produced
|
|
331
|
-
|
|
340
|
+
bypass_moa=True, # skip the mixture-of-architecture router
|
|
332
341
|
bypass_cache=True, # skip the semantic cache
|
|
333
342
|
)
|
|
334
343
|
```
|
|
@@ -341,7 +350,7 @@ Interfaze re-exports typed error classes to catch and narrow on:
|
|
|
341
350
|
from interfaze import BadRequestError, InterfazeError, RateLimitError
|
|
342
351
|
```
|
|
343
352
|
|
|
344
|
-
`InterfazeError` is client-side (
|
|
353
|
+
`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.
|
|
345
354
|
|
|
346
355
|
## Capabilities
|
|
347
356
|
|
|
@@ -21,6 +21,15 @@ interfaze = Interfaze(api_key="sk_...") # or set INTERFAZE_API_KEY and call Int
|
|
|
21
21
|
|
|
22
22
|
Async is identical via `AsyncInterfaze` - every call becomes `await`-able.
|
|
23
23
|
|
|
24
|
+
### Keyless access
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
# No API key: Interfaze applies per-IP keyless limits. Server-side code only.
|
|
28
|
+
client = Interfaze()
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
24
33
|
## Your first request
|
|
25
34
|
|
|
26
35
|
This guide will get you started with your first request to Interfaze, which follows the Chat Completions API standard.
|
|
@@ -304,7 +313,7 @@ Set router, cache, and streaming behavior once on the client:
|
|
|
304
313
|
```python
|
|
305
314
|
interfaze = Interfaze(
|
|
306
315
|
show_additional_info=True, # stream <precontext> deltas as they're produced
|
|
307
|
-
|
|
316
|
+
bypass_moa=True, # skip the mixture-of-architecture router
|
|
308
317
|
bypass_cache=True, # skip the semantic cache
|
|
309
318
|
)
|
|
310
319
|
```
|
|
@@ -317,7 +326,7 @@ Interfaze re-exports typed error classes to catch and narrow on:
|
|
|
317
326
|
from interfaze import BadRequestError, InterfazeError, RateLimitError
|
|
318
327
|
```
|
|
319
328
|
|
|
320
|
-
`InterfazeError` is client-side (
|
|
329
|
+
`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.
|
|
321
330
|
|
|
322
331
|
## Capabilities
|
|
323
332
|
|
|
@@ -24,9 +24,11 @@ from ._schema import empty_task_schema, response_format
|
|
|
24
24
|
from ._stream import (
|
|
25
25
|
AsyncInterfazeStream,
|
|
26
26
|
InterfazeStream,
|
|
27
|
-
_SideChannelFilter as SideChannelFilter,
|
|
28
27
|
strip_side_channels,
|
|
29
28
|
)
|
|
29
|
+
from ._stream import (
|
|
30
|
+
_SideChannelFilter as SideChannelFilter,
|
|
31
|
+
)
|
|
30
32
|
from ._types import (
|
|
31
33
|
GuardCode,
|
|
32
34
|
InterfazeChatCompletion,
|
|
@@ -35,7 +37,7 @@ from ._types import (
|
|
|
35
37
|
TaskName,
|
|
36
38
|
)
|
|
37
39
|
|
|
38
|
-
__version__ = "1.0.
|
|
40
|
+
__version__ = "1.0.4"
|
|
39
41
|
|
|
40
42
|
__all__ = [
|
|
41
43
|
"Interfaze",
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import warnings
|
|
5
|
+
from typing import Any, Awaitable, Callable, Dict, Optional, Union
|
|
6
|
+
|
|
7
|
+
from openai import AsyncOpenAI, OpenAI
|
|
8
|
+
|
|
9
|
+
from ._chat import AsyncChat, Chat
|
|
10
|
+
from ._constants import (
|
|
11
|
+
DEFAULT_TIMEOUT,
|
|
12
|
+
HEADER_ADMIN_KEY,
|
|
13
|
+
HEADER_BYPASS_CACHE,
|
|
14
|
+
HEADER_BYPASS_MOA,
|
|
15
|
+
HEADER_SHOW_ADDITIONAL_INFO,
|
|
16
|
+
INTERFAZE_BASE_URL,
|
|
17
|
+
KEYLESS_WARNING,
|
|
18
|
+
)
|
|
19
|
+
from ._tasks import AsyncTasks, Tasks
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_KeyProvider = Callable[[], Any]
|
|
23
|
+
|
|
24
|
+
_keyless_warned = False
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# openai calls a key provider before each request, so the wrapper trims the key each time.
|
|
28
|
+
def _trimmed(provider: _KeyProvider) -> _KeyProvider:
|
|
29
|
+
return lambda: provider().strip()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _async_trimmed(provider: _KeyProvider) -> _KeyProvider:
|
|
33
|
+
async def trimmed() -> str:
|
|
34
|
+
return str((await provider()).strip())
|
|
35
|
+
|
|
36
|
+
return trimmed
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# Trims each string key, because an HTTP header value cannot end with a space or a newline.
|
|
40
|
+
def _resolve_key(
|
|
41
|
+
api_key: Union[str, _KeyProvider, None], trim_provider: Callable[[_KeyProvider], _KeyProvider]
|
|
42
|
+
) -> Union[str, _KeyProvider, None]:
|
|
43
|
+
if callable(api_key):
|
|
44
|
+
return trim_provider(api_key)
|
|
45
|
+
return (api_key or "").strip() or os.environ.get("INTERFAZE_API_KEY", "").strip() or None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# A caller Authorization header counts as a key.
|
|
49
|
+
def _has_authorization(headers: Dict[str, str]) -> bool:
|
|
50
|
+
return any(name.lower() == "authorization" for name in headers)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# Warns once per process; stacklevel=3 points at the code that built the client.
|
|
54
|
+
def _warn_if_keyless(key: Union[str, _KeyProvider, None], headers: Dict[str, str]) -> None:
|
|
55
|
+
global _keyless_warned
|
|
56
|
+
if key or _has_authorization(headers) or _keyless_warned:
|
|
57
|
+
return
|
|
58
|
+
_keyless_warned = True
|
|
59
|
+
warnings.warn(KEYLESS_WARNING, UserWarning, stacklevel=3)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# A key provider that returns "" stops OpenAI() from reading OPENAI_API_KEY and sends no Authorization header.
|
|
63
|
+
def _no_key() -> str:
|
|
64
|
+
return ""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
async def _async_no_key() -> str:
|
|
68
|
+
return ""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# openai>=2.34 refuses requests with no Authorization header; Interfaze allows keyless.
|
|
72
|
+
class InterfazeOpenAI(OpenAI):
|
|
73
|
+
# openai>=2.34 reads OPENAI_ADMIN_KEY; keep that credential off Interfaze requests.
|
|
74
|
+
@property
|
|
75
|
+
def _admin_api_key_auth(self) -> Dict[str, str]:
|
|
76
|
+
return {}
|
|
77
|
+
|
|
78
|
+
# Only the keyless stand-in skips the check, so a key callable returning a blank key still raises.
|
|
79
|
+
def _validate_headers(self, *args: Any, **kwargs: Any) -> None:
|
|
80
|
+
if getattr(self, "_api_key_provider", None) is not _no_key:
|
|
81
|
+
super()._validate_headers(*args, **kwargs)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class AsyncInterfazeOpenAI(AsyncOpenAI):
|
|
85
|
+
@property
|
|
86
|
+
def _admin_api_key_auth(self) -> Dict[str, str]:
|
|
87
|
+
return {}
|
|
88
|
+
|
|
89
|
+
def _validate_headers(self, *args: Any, **kwargs: Any) -> None:
|
|
90
|
+
if getattr(self, "_api_key_provider", None) is not _async_no_key:
|
|
91
|
+
super()._validate_headers(*args, **kwargs)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _build_headers(
|
|
95
|
+
default_headers: Optional[Dict[str, str]],
|
|
96
|
+
show_additional_info: bool,
|
|
97
|
+
bypass_moa: bool,
|
|
98
|
+
bypass_cache: bool,
|
|
99
|
+
admin_key: Optional[str],
|
|
100
|
+
) -> Dict[str, str]:
|
|
101
|
+
# A blank Authorization header counts as no key.
|
|
102
|
+
headers: Dict[str, str] = {
|
|
103
|
+
name: value
|
|
104
|
+
for name, value in (default_headers or {}).items()
|
|
105
|
+
if name.lower() != "authorization" or str(value).strip()
|
|
106
|
+
}
|
|
107
|
+
if show_additional_info:
|
|
108
|
+
headers[HEADER_SHOW_ADDITIONAL_INFO] = "true"
|
|
109
|
+
if bypass_moa:
|
|
110
|
+
headers[HEADER_BYPASS_MOA] = "true"
|
|
111
|
+
if bypass_cache:
|
|
112
|
+
headers[HEADER_BYPASS_CACHE] = "true"
|
|
113
|
+
if admin_key:
|
|
114
|
+
headers[HEADER_ADMIN_KEY] = admin_key
|
|
115
|
+
return headers
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# OpenAI() fills `organization` / `project` from OPENAI_ORG_ID / OPENAI_PROJECT_ID and sends them
|
|
119
|
+
# as OpenAI-Organization / OpenAI-Project headers. Those are OpenAI account ids, so keep them off
|
|
120
|
+
# Interfaze requests unless they were passed in explicitly.
|
|
121
|
+
# This only covers the client built here: one derived via client.openai.with_options(...) or
|
|
122
|
+
# .copy() goes back through the constructor with organization/project None, so it reads the
|
|
123
|
+
# env vars again and sends them.
|
|
124
|
+
def _drop_openai_env_ids(client: Union[OpenAI, AsyncOpenAI], kwargs: Dict[str, Any]) -> None:
|
|
125
|
+
client.organization = kwargs.get("organization")
|
|
126
|
+
client.project = kwargs.get("project")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Interfaze:
|
|
130
|
+
def __init__(
|
|
131
|
+
self,
|
|
132
|
+
*,
|
|
133
|
+
api_key: Union[str, Callable[[], str], None] = None,
|
|
134
|
+
base_url: Optional[str] = None,
|
|
135
|
+
show_additional_info: bool = False,
|
|
136
|
+
bypass_moa: bool = False,
|
|
137
|
+
bypass_cache: bool = False,
|
|
138
|
+
admin_key: Optional[str] = None,
|
|
139
|
+
default_headers: Optional[Dict[str, str]] = None,
|
|
140
|
+
**kwargs: Any,
|
|
141
|
+
) -> None:
|
|
142
|
+
kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
|
|
143
|
+
key = _resolve_key(api_key, _trimmed)
|
|
144
|
+
headers = _build_headers(default_headers, show_additional_info, bypass_moa, bypass_cache, admin_key)
|
|
145
|
+
_warn_if_keyless(key, headers)
|
|
146
|
+
self.openai: OpenAI = InterfazeOpenAI(
|
|
147
|
+
api_key=key or _no_key,
|
|
148
|
+
base_url=base_url or INTERFAZE_BASE_URL,
|
|
149
|
+
default_headers=headers,
|
|
150
|
+
**kwargs,
|
|
151
|
+
)
|
|
152
|
+
_drop_openai_env_ids(self.openai, kwargs)
|
|
153
|
+
self.chat = Chat(self.openai)
|
|
154
|
+
self.models = self.openai.models
|
|
155
|
+
self.tasks = Tasks(self.chat.completions)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class AsyncInterfaze:
|
|
159
|
+
def __init__(
|
|
160
|
+
self,
|
|
161
|
+
*,
|
|
162
|
+
api_key: Union[str, Callable[[], Awaitable[str]], None] = None,
|
|
163
|
+
base_url: Optional[str] = None,
|
|
164
|
+
show_additional_info: bool = False,
|
|
165
|
+
bypass_moa: bool = False,
|
|
166
|
+
bypass_cache: bool = False,
|
|
167
|
+
admin_key: Optional[str] = None,
|
|
168
|
+
default_headers: Optional[Dict[str, str]] = None,
|
|
169
|
+
**kwargs: Any,
|
|
170
|
+
) -> None:
|
|
171
|
+
kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
|
|
172
|
+
key = _resolve_key(api_key, _async_trimmed)
|
|
173
|
+
headers = _build_headers(default_headers, show_additional_info, bypass_moa, bypass_cache, admin_key)
|
|
174
|
+
_warn_if_keyless(key, headers)
|
|
175
|
+
self.openai: AsyncOpenAI = AsyncInterfazeOpenAI(
|
|
176
|
+
api_key=key or _async_no_key,
|
|
177
|
+
base_url=base_url or INTERFAZE_BASE_URL,
|
|
178
|
+
default_headers=headers,
|
|
179
|
+
**kwargs,
|
|
180
|
+
)
|
|
181
|
+
_drop_openai_env_ids(self.openai, kwargs)
|
|
182
|
+
self.chat = AsyncChat(self.openai)
|
|
183
|
+
self.models = self.openai.models
|
|
184
|
+
self.tasks = AsyncTasks(self.chat.completions)
|
|
@@ -3,6 +3,10 @@ from __future__ import annotations
|
|
|
3
3
|
INTERFAZE_BASE_URL = "https://api.interfaze.ai/v1"
|
|
4
4
|
INTERFAZE_MODEL = "interfaze-beta"
|
|
5
5
|
DEFAULT_TIMEOUT = 900.0
|
|
6
|
+
KEYLESS_WARNING = (
|
|
7
|
+
"Interfaze SDK is running in keyless mode. "
|
|
8
|
+
"For higher rate limits, get an API key at https://interfaze.ai/dashboard."
|
|
9
|
+
)
|
|
6
10
|
|
|
7
11
|
# Task names accepted in a <task>...</task> tag.
|
|
8
12
|
TASK_NAMES = (
|
|
@@ -43,6 +47,6 @@ BLACKLISTED_FORMATS = ("image/gif", "image/avif")
|
|
|
43
47
|
|
|
44
48
|
# Interfaze control-plane headers.
|
|
45
49
|
HEADER_SHOW_ADDITIONAL_INFO = "x-show-additional-info"
|
|
46
|
-
|
|
47
|
-
HEADER_BYPASS_CACHE = "x-bypass-cache"
|
|
50
|
+
HEADER_BYPASS_MOA = "x-interfaze-bypass-moa"
|
|
51
|
+
HEADER_BYPASS_CACHE = "x-interfaze-bypass-cache"
|
|
48
52
|
HEADER_ADMIN_KEY = "x-admin-key"
|
|
@@ -3,11 +3,10 @@ from __future__ import annotations
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import json
|
|
5
5
|
|
|
6
|
-
import pytest
|
|
7
6
|
import respx
|
|
8
7
|
from conftest import JSON_OBJECT, STREAM_CHUNKS, TASK_OCR, TOOL_CALL, last_body, mock_json, mock_sse
|
|
9
8
|
|
|
10
|
-
from interfaze import AsyncInterfaze
|
|
9
|
+
from interfaze import AsyncInterfaze
|
|
11
10
|
|
|
12
11
|
WEATHER_TOOL = [
|
|
13
12
|
{
|
|
@@ -69,12 +68,6 @@ def test_async_json_object_fence_stripped():
|
|
|
69
68
|
assert json.loads(content)["city"] == "Tokyo"
|
|
70
69
|
|
|
71
70
|
|
|
72
|
-
def test_async_missing_key_raises(monkeypatch):
|
|
73
|
-
monkeypatch.delenv("INTERFAZE_API_KEY", raising=False)
|
|
74
|
-
with pytest.raises(InterfazeError, match="INTERFAZE_API_KEY"):
|
|
75
|
-
AsyncInterfaze()
|
|
76
|
-
|
|
77
|
-
|
|
78
71
|
@respx.mock
|
|
79
72
|
def test_async_create_stream_true_returns_raw_openai_stream():
|
|
80
73
|
mock_sse(STREAM_CHUNKS)
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
"""Credentials at the request boundary: keyless, environment-key and explicit-key requests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
import json
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
import warnings
|
|
11
|
+
from functools import partial
|
|
12
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
13
|
+
from typing import Any, Callable, Dict, Iterator, List, Optional
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
import pytest
|
|
17
|
+
import respx
|
|
18
|
+
from conftest import completion
|
|
19
|
+
from openai import OpenAI
|
|
20
|
+
|
|
21
|
+
import interfaze._client as client_module
|
|
22
|
+
from interfaze import AsyncInterfaze, Interfaze, RateLimitError
|
|
23
|
+
|
|
24
|
+
API_HOST = "api.interfaze.ai"
|
|
25
|
+
MESSAGES = [{"role": "user", "content": "x"}]
|
|
26
|
+
MODELS_LIST = {
|
|
27
|
+
"object": "list",
|
|
28
|
+
"data": [{"id": "interfaze-beta", "object": "model", "owned_by": "interfaze"}],
|
|
29
|
+
}
|
|
30
|
+
PROJECTS_LIST = {"object": "list", "data": [], "has_more": False}
|
|
31
|
+
RESPONSE_BODIES = {"/models": MODELS_LIST, "/organization/projects": PROJECTS_LIST}
|
|
32
|
+
WEATHER = {"city": "Tokyo", "temp_c": 21}
|
|
33
|
+
|
|
34
|
+
ENV_KEY = "interfaze-env-key"
|
|
35
|
+
EXPLICIT_KEY = "interfaze-explicit-key"
|
|
36
|
+
NEW_KEY = "interfaze-new-key"
|
|
37
|
+
OPENAI_KEY = "openai-env-key"
|
|
38
|
+
OPENAI_ADMIN_KEY = "openai-admin-key"
|
|
39
|
+
|
|
40
|
+
SECONDS_IN_AN_HOUR = 3600
|
|
41
|
+
KEYLESS_DAILY_LIMIT_REQUESTS = 1000
|
|
42
|
+
KEYLESS_WARNING = (
|
|
43
|
+
"Interfaze SDK is running in keyless mode. "
|
|
44
|
+
"For higher rate limits, get an API key at https://interfaze.ai/dashboard."
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# The API builds these error bodies in InterfazeAI/interfaze src/helpers/keylessGuard.ts and apiKeyAuth.ts.
|
|
48
|
+
SIGNUP_HINT = (
|
|
49
|
+
"Get a free API key at https://interfaze.ai and send it as `Authorization: Bearer YOUR_API_KEY`."
|
|
50
|
+
)
|
|
51
|
+
REQUEST_ID = "req_keyless_test"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _error(message: str, type_: str, code: str) -> Dict[str, Any]:
|
|
55
|
+
return {"error": {"message": message, "type": type_, "code": code, "request_id": REQUEST_ID}}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
KEYLESS_DAILY_LIMIT = _error(
|
|
59
|
+
f"Keyless daily limit of {KEYLESS_DAILY_LIMIT_REQUESTS} requests reached. {SIGNUP_HINT}",
|
|
60
|
+
"rate_limit_error",
|
|
61
|
+
"keyless_daily_limit_exceeded",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# The API sends these headers with the keyless daily limit 429.
|
|
66
|
+
def _daily_headers() -> Dict[str, str]:
|
|
67
|
+
return {
|
|
68
|
+
"Retry-After": str(SECONDS_IN_AN_HOUR),
|
|
69
|
+
"X-RateLimit-Limit": str(KEYLESS_DAILY_LIMIT_REQUESTS),
|
|
70
|
+
"X-RateLimit-Remaining": "0",
|
|
71
|
+
"X-RateLimit-Reset": str(int(time.time()) + SECONDS_IN_AN_HOUR),
|
|
72
|
+
"x-should-retry": "false",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
CLIENTS = [Interfaze, AsyncInterfaze]
|
|
77
|
+
CLIENT_IDS = ["sync", "async"]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _chat(client: Any) -> Any:
|
|
81
|
+
return client.chat.completions.create(messages=MESSAGES)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _list_models(openai: Any) -> Any:
|
|
85
|
+
return openai.models.list()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
async def _wait(value: Any) -> Any:
|
|
89
|
+
return await value
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _call(client: Any, operation: Callable[[Any], Any]) -> Any:
|
|
93
|
+
result = operation(client)
|
|
94
|
+
return asyncio.run(_wait(result)) if inspect.isawaitable(result) else result
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _reply(request: httpx.Request) -> httpx.Response:
|
|
98
|
+
path = request.url.path
|
|
99
|
+
if path.endswith("/chat/completions"):
|
|
100
|
+
return httpx.Response(200, json=completion(json.dumps(WEATHER)))
|
|
101
|
+
return httpx.Response(200, json=RESPONSE_BODIES[path.removeprefix("/v1")])
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _authorizations(router: respx.MockRouter) -> List[Optional[str]]:
|
|
105
|
+
return [call.request.headers.get("authorization") for call in router.calls]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@pytest.fixture(autouse=True)
|
|
109
|
+
def isolated_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
110
|
+
monkeypatch.delenv("INTERFAZE_API_KEY", raising=False)
|
|
111
|
+
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
|
112
|
+
monkeypatch.delenv("OPENAI_ADMIN_KEY", raising=False)
|
|
113
|
+
monkeypatch.setattr(client_module, "_keyless_warned", False)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@pytest.fixture
|
|
117
|
+
def router() -> Iterator[respx.MockRouter]:
|
|
118
|
+
with respx.mock(assert_all_called=False) as mock_router:
|
|
119
|
+
yield mock_router
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@pytest.fixture
|
|
123
|
+
def api(router: respx.MockRouter) -> respx.MockRouter:
|
|
124
|
+
router.route(host=API_HOST).mock(side_effect=_reply)
|
|
125
|
+
return router
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _fail(router: respx.MockRouter, status: int, body: Dict[str, Any], headers: Dict[str, str]) -> None:
|
|
129
|
+
router.route(host=API_HOST).mock(return_value=httpx.Response(status, json=body, headers=headers))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# openai 2.34 and later have the admin resource, which reads OPENAI_ADMIN_KEY.
|
|
133
|
+
ADMIN = pytest.param(
|
|
134
|
+
lambda client: client.openai.admin.organization.projects.list(),
|
|
135
|
+
id="admin",
|
|
136
|
+
marks=pytest.mark.skipif(not hasattr(OpenAI, "admin"), reason="This openai has no admin resource."),
|
|
137
|
+
)
|
|
138
|
+
credential_operations = pytest.mark.parametrize("operation", [pytest.param(_chat, id="chat"), ADMIN])
|
|
139
|
+
clients = pytest.mark.parametrize("client_cls", CLIENTS, ids=CLIENT_IDS)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@credential_operations
|
|
143
|
+
@clients
|
|
144
|
+
def test_no_key_ignores_openai_credentials(api, monkeypatch, client_cls, operation):
|
|
145
|
+
monkeypatch.setenv("OPENAI_API_KEY", OPENAI_KEY)
|
|
146
|
+
monkeypatch.setenv("OPENAI_ADMIN_KEY", OPENAI_ADMIN_KEY)
|
|
147
|
+
_call(client_cls(), operation)
|
|
148
|
+
assert _authorizations(api) == [None]
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# Each case: explicit api_key, INTERFAZE_API_KEY, the Authorization header the request carries.
|
|
152
|
+
KEY_CASES = {
|
|
153
|
+
"env-key": (None, ENV_KEY, f"Bearer {ENV_KEY}"),
|
|
154
|
+
"explicit-key-over-env-key": (EXPLICIT_KEY, ENV_KEY, f"Bearer {EXPLICIT_KEY}"),
|
|
155
|
+
"padded-key-is-trimmed": (f" {EXPLICIT_KEY}\n", "", f"Bearer {EXPLICIT_KEY}"),
|
|
156
|
+
"blank-explicit-key-uses-env-key": (" \n", ENV_KEY, f"Bearer {ENV_KEY}"),
|
|
157
|
+
"blank-env-key-is-keyless": (None, " \n", None),
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@pytest.mark.parametrize("api_key,env_key,authorization", KEY_CASES.values(), ids=KEY_CASES.keys())
|
|
162
|
+
@clients
|
|
163
|
+
def test_request_sends_the_resolved_key(api, monkeypatch, client_cls, api_key, env_key, authorization):
|
|
164
|
+
monkeypatch.setenv("INTERFAZE_API_KEY", env_key)
|
|
165
|
+
_call(client_cls(api_key=api_key), _chat)
|
|
166
|
+
assert _authorizations(api) == [authorization]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _sync_key() -> str:
|
|
170
|
+
return EXPLICIT_KEY
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
async def _async_key() -> str:
|
|
174
|
+
return EXPLICIT_KEY
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
KEY_CALLABLES = {"sync": (Interfaze, _sync_key), "async": (AsyncInterfaze, _async_key)}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@pytest.mark.parametrize("client_cls,key_callable", KEY_CALLABLES.values(), ids=KEY_CALLABLES.keys())
|
|
181
|
+
def test_key_callable_takes_precedence_over_env_key(api, monkeypatch, client_cls, key_callable):
|
|
182
|
+
monkeypatch.setenv("INTERFAZE_API_KEY", ENV_KEY)
|
|
183
|
+
_call(client_cls(api_key=key_callable), _chat)
|
|
184
|
+
assert _authorizations(api) == [f"Bearer {EXPLICIT_KEY}"]
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# Each case: the value a key callable returns, and the Authorization header the request carries.
|
|
188
|
+
CALLABLE_KEY = "interfaze-callable-key"
|
|
189
|
+
KEY_CALLABLE_RESULTS = {
|
|
190
|
+
"padded-key-is-trimmed": (f" {CALLABLE_KEY}\n", f"Bearer {CALLABLE_KEY}"),
|
|
191
|
+
}
|
|
192
|
+
key_callable_results = pytest.mark.parametrize(
|
|
193
|
+
"result,authorization", KEY_CALLABLE_RESULTS.values(), ids=KEY_CALLABLE_RESULTS.keys()
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _key_callable(client_cls: Any, result: str) -> Callable[[], Any]:
|
|
198
|
+
async def async_key() -> str:
|
|
199
|
+
return result
|
|
200
|
+
|
|
201
|
+
return async_key if client_cls is AsyncInterfaze else lambda: result
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@key_callable_results
|
|
205
|
+
@clients
|
|
206
|
+
def test_key_callable_result_is_trimmed(api, client_cls, result, authorization):
|
|
207
|
+
_call(client_cls(api_key=_key_callable(client_cls, result)), _chat)
|
|
208
|
+
assert _authorizations(api) == [authorization]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@pytest.mark.parametrize("result", ["", " "], ids=["empty", "whitespace"])
|
|
212
|
+
@clients
|
|
213
|
+
def test_blank_key_callable_raises_before_the_request(api, client_cls, result):
|
|
214
|
+
with pytest.raises(TypeError, match="Could not resolve authentication method"):
|
|
215
|
+
_call(client_cls(api_key=_key_callable(client_cls, result)), _chat)
|
|
216
|
+
assert api.calls.call_count == 0
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class _RecordingHandler(BaseHTTPRequestHandler):
|
|
220
|
+
def __init__(self, authorizations: List[Optional[str]], *args: Any, **kwargs: Any) -> None:
|
|
221
|
+
self.authorizations = authorizations
|
|
222
|
+
super().__init__(*args, **kwargs)
|
|
223
|
+
|
|
224
|
+
def do_POST(self) -> None:
|
|
225
|
+
self.authorizations.append(self.headers.get("Authorization"))
|
|
226
|
+
self.rfile.read(int(self.headers.get("Content-Length", 0)))
|
|
227
|
+
body = json.dumps(completion(json.dumps(WEATHER))).encode()
|
|
228
|
+
self.send_response(200)
|
|
229
|
+
self.send_header("Content-Type", "application/json")
|
|
230
|
+
self.send_header("Content-Length", str(len(body)))
|
|
231
|
+
self.end_headers()
|
|
232
|
+
self.wfile.write(body)
|
|
233
|
+
|
|
234
|
+
def log_message(self, *args: Any) -> None:
|
|
235
|
+
return None
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
# A real socket, because respx does not run the h11 header validation.
|
|
239
|
+
@pytest.fixture
|
|
240
|
+
def local_api() -> Iterator[Dict[str, Any]]:
|
|
241
|
+
authorizations: List[Optional[str]] = []
|
|
242
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), partial(_RecordingHandler, authorizations))
|
|
243
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
244
|
+
thread.start()
|
|
245
|
+
yield {"base_url": f"http://127.0.0.1:{server.server_port}/v1", "authorizations": authorizations}
|
|
246
|
+
server.shutdown()
|
|
247
|
+
server.server_close()
|
|
248
|
+
thread.join()
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
@clients
|
|
252
|
+
def test_padded_key_callable_passes_header_validation(local_api, client_cls):
|
|
253
|
+
padded_key = _key_callable(client_cls, f" {CALLABLE_KEY}\n")
|
|
254
|
+
_call(client_cls(api_key=padded_key, base_url=local_api["base_url"]), _chat)
|
|
255
|
+
assert local_api["authorizations"] == [f"Bearer {CALLABLE_KEY}"]
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# Each case: how to derive a client from client.openai.
|
|
259
|
+
DERIVED = {
|
|
260
|
+
"with_options": lambda openai, **kwargs: openai.with_options(**kwargs),
|
|
261
|
+
"copy": lambda openai, **kwargs: openai.copy(**kwargs),
|
|
262
|
+
}
|
|
263
|
+
# Each case: the options of the derived client, and the Authorization header its request carries.
|
|
264
|
+
DERIVED_KEYS = {
|
|
265
|
+
"keyless": ({"max_retries": 0}, None),
|
|
266
|
+
"new-key": ({"api_key": NEW_KEY}, f"Bearer {NEW_KEY}"),
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@pytest.mark.parametrize("options,authorization", DERIVED_KEYS.values(), ids=DERIVED_KEYS.keys())
|
|
271
|
+
@pytest.mark.parametrize("derive", DERIVED.values(), ids=DERIVED.keys())
|
|
272
|
+
@clients
|
|
273
|
+
def test_derived_client_from_keyless_client(api, monkeypatch, client_cls, derive, options, authorization):
|
|
274
|
+
monkeypatch.setenv("OPENAI_API_KEY", OPENAI_KEY)
|
|
275
|
+
_call(derive(client_cls().openai, **options), _list_models)
|
|
276
|
+
assert _authorizations(api) == [authorization]
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
@clients
|
|
280
|
+
def test_keyless_daily_limit_raises_after_one_request(router, client_cls):
|
|
281
|
+
_fail(router, 429, KEYLESS_DAILY_LIMIT, _daily_headers())
|
|
282
|
+
with pytest.raises(RateLimitError) as exc_info:
|
|
283
|
+
_call(client_cls(), _chat)
|
|
284
|
+
assert router.calls.call_count == 1
|
|
285
|
+
assert exc_info.value.code == "keyless_daily_limit_exceeded"
|
|
286
|
+
assert SIGNUP_HINT in str(exc_info.value)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _keyless_warnings(recorded: List[warnings.WarningMessage]) -> List[warnings.WarningMessage]:
|
|
290
|
+
return [item for item in recorded if str(item.message) == KEYLESS_WARNING]
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
@clients
|
|
294
|
+
def test_first_keyless_client_warns_once(recwarn, client_cls):
|
|
295
|
+
client_cls()
|
|
296
|
+
client_cls()
|
|
297
|
+
(warning,) = _keyless_warnings(recwarn.list)
|
|
298
|
+
assert warning.category is UserWarning
|
|
299
|
+
assert warning.filename == __file__
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
# Each case: the constructor arguments and the INTERFAZE_API_KEY value of a client that has a key.
|
|
303
|
+
KEYED_CLIENTS = {
|
|
304
|
+
"explicit-key": ({"api_key": EXPLICIT_KEY}, ""),
|
|
305
|
+
"env-key": ({}, ENV_KEY),
|
|
306
|
+
"key-callable": ({"api_key": lambda: EXPLICIT_KEY}, ""),
|
|
307
|
+
"authorization-header": ({"default_headers": {"Authorization": f"Bearer {EXPLICIT_KEY}"}}, ""),
|
|
308
|
+
"lowercase-authorization-header": ({"default_headers": {"authorization": f"Bearer {EXPLICIT_KEY}"}}, ""),
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@pytest.mark.parametrize("kwargs,env_key", KEYED_CLIENTS.values(), ids=KEYED_CLIENTS.keys())
|
|
313
|
+
@clients
|
|
314
|
+
def test_keyed_client_does_not_warn(recwarn, monkeypatch, client_cls, kwargs, env_key):
|
|
315
|
+
monkeypatch.setenv("INTERFAZE_API_KEY", env_key)
|
|
316
|
+
client_cls(**kwargs)
|
|
317
|
+
assert _keyless_warnings(recwarn.list) == []
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
@pytest.mark.parametrize("value", ["", " "], ids=["empty", "whitespace"])
|
|
321
|
+
@clients
|
|
322
|
+
def test_blank_authorization_header_is_keyless(api, recwarn, client_cls, value):
|
|
323
|
+
_call(client_cls(default_headers={"Authorization": value}), _chat)
|
|
324
|
+
assert _authorizations(api) == [None]
|
|
325
|
+
assert len(_keyless_warnings(recwarn.list)) == 1
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
@clients
|
|
329
|
+
def test_keyed_client_does_not_use_up_the_warning(recwarn, client_cls):
|
|
330
|
+
client_cls(api_key=EXPLICIT_KEY)
|
|
331
|
+
client_cls()
|
|
332
|
+
assert len(_keyless_warnings(recwarn.list)) == 1
|
|
@@ -115,7 +115,7 @@ def test_control_headers():
|
|
|
115
115
|
messages=[{"role": "user", "content": "x"}]
|
|
116
116
|
)
|
|
117
117
|
h = last_headers(route)
|
|
118
|
-
assert h["x-show-additional-info"] == "true" and h["x-bypass-cache"] == "true"
|
|
118
|
+
assert h["x-show-additional-info"] == "true" and h["x-interfaze-bypass-cache"] == "true"
|
|
119
119
|
|
|
120
120
|
|
|
121
121
|
@respx.mock
|
|
@@ -124,14 +124,14 @@ def test_all_control_headers_present():
|
|
|
124
124
|
Interfaze(
|
|
125
125
|
api_key="t",
|
|
126
126
|
show_additional_info=True,
|
|
127
|
-
|
|
127
|
+
bypass_moa=True,
|
|
128
128
|
bypass_cache=True,
|
|
129
129
|
admin_key="admin-secret",
|
|
130
130
|
).chat.completions.create(messages=[{"role": "user", "content": "x"}])
|
|
131
131
|
h = last_headers(route)
|
|
132
132
|
assert h["x-show-additional-info"] == "true"
|
|
133
|
-
assert h["x-bypass-
|
|
134
|
-
assert h["x-bypass-cache"] == "true"
|
|
133
|
+
assert h["x-interfaze-bypass-moa"] == "true"
|
|
134
|
+
assert h["x-interfaze-bypass-cache"] == "true"
|
|
135
135
|
assert h["x-admin-key"] == "admin-secret"
|
|
136
136
|
|
|
137
137
|
|
|
@@ -141,11 +141,38 @@ def test_default_headers_omit_control_flags_when_unset():
|
|
|
141
141
|
Interfaze(api_key="t").chat.completions.create(messages=[{"role": "user", "content": "x"}])
|
|
142
142
|
h = last_headers(route)
|
|
143
143
|
assert "x-show-additional-info" not in h
|
|
144
|
-
assert "x-bypass-
|
|
145
|
-
assert "x-bypass-cache" not in h
|
|
144
|
+
assert "x-interfaze-bypass-moa" not in h
|
|
145
|
+
assert "x-interfaze-bypass-cache" not in h
|
|
146
146
|
assert "x-admin-key" not in h
|
|
147
147
|
|
|
148
148
|
|
|
149
|
+
@respx.mock
|
|
150
|
+
def test_openai_org_and_project_env_not_sent(monkeypatch):
|
|
151
|
+
monkeypatch.setenv("OPENAI_ORG_ID", "org-from-env")
|
|
152
|
+
monkeypatch.setenv("OPENAI_PROJECT_ID", "proj_from_env")
|
|
153
|
+
route = mock_json(BASIC)
|
|
154
|
+
Interfaze(api_key="t").chat.completions.create(messages=[{"role": "user", "content": "x"}])
|
|
155
|
+
h = last_headers(route)
|
|
156
|
+
assert "openai-organization" not in h and "openai-project" not in h
|
|
157
|
+
|
|
158
|
+
asyncio.run(
|
|
159
|
+
AsyncInterfaze(api_key="t").chat.completions.create(messages=[{"role": "user", "content": "x"}])
|
|
160
|
+
)
|
|
161
|
+
h = last_headers(route)
|
|
162
|
+
assert "openai-organization" not in h and "openai-project" not in h
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@respx.mock
|
|
166
|
+
def test_explicit_openai_org_and_project_still_sent(monkeypatch):
|
|
167
|
+
monkeypatch.setenv("OPENAI_ORG_ID", "org-from-env")
|
|
168
|
+
route = mock_json(BASIC)
|
|
169
|
+
Interfaze(api_key="t", organization="org-explicit", project="proj_explicit").chat.completions.create(
|
|
170
|
+
messages=[{"role": "user", "content": "x"}]
|
|
171
|
+
)
|
|
172
|
+
h = last_headers(route)
|
|
173
|
+
assert h["openai-organization"] == "org-explicit" and h["openai-project"] == "proj_explicit"
|
|
174
|
+
|
|
175
|
+
|
|
149
176
|
@respx.mock
|
|
150
177
|
def test_per_request_extra_headers_override_client_default():
|
|
151
178
|
route = mock_json(BASIC)
|
|
@@ -170,12 +170,6 @@ def test_curated_surface():
|
|
|
170
170
|
assert hasattr(c, "openai") # escape hatch
|
|
171
171
|
|
|
172
172
|
|
|
173
|
-
def test_missing_key_raises(monkeypatch):
|
|
174
|
-
monkeypatch.delenv("INTERFAZE_API_KEY", raising=False)
|
|
175
|
-
with pytest.raises(InterfazeError, match="INTERFAZE_API_KEY"):
|
|
176
|
-
Interfaze()
|
|
177
|
-
|
|
178
|
-
|
|
179
173
|
def test_default_timeout_covers_server_cap():
|
|
180
174
|
assert Interfaze(api_key="t").openai.timeout == 900.0
|
|
181
175
|
assert AsyncInterfaze(api_key="t").openai.timeout == 900.0
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import os
|
|
4
|
-
from typing import Any, Dict, Optional
|
|
5
|
-
|
|
6
|
-
from openai import AsyncOpenAI, OpenAI
|
|
7
|
-
|
|
8
|
-
from ._chat import AsyncChat, Chat
|
|
9
|
-
from ._constants import (
|
|
10
|
-
DEFAULT_TIMEOUT,
|
|
11
|
-
HEADER_ADMIN_KEY,
|
|
12
|
-
HEADER_BYPASS_CACHE,
|
|
13
|
-
HEADER_BYPASS_MOE,
|
|
14
|
-
HEADER_SHOW_ADDITIONAL_INFO,
|
|
15
|
-
INTERFAZE_BASE_URL,
|
|
16
|
-
)
|
|
17
|
-
from ._errors import InterfazeError
|
|
18
|
-
from ._tasks import AsyncTasks, Tasks
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
def _resolve_key(api_key: Optional[str]) -> str:
|
|
22
|
-
key = api_key or os.environ.get("INTERFAZE_API_KEY")
|
|
23
|
-
if not key:
|
|
24
|
-
raise InterfazeError(
|
|
25
|
-
"Missing API key. Pass Interfaze(api_key=...) or set the INTERFAZE_API_KEY environment variable."
|
|
26
|
-
)
|
|
27
|
-
return key
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
def _build_headers(
|
|
31
|
-
default_headers: Optional[Dict[str, str]],
|
|
32
|
-
show_additional_info: bool,
|
|
33
|
-
bypass_moe: bool,
|
|
34
|
-
bypass_cache: bool,
|
|
35
|
-
admin_key: Optional[str],
|
|
36
|
-
) -> Dict[str, str]:
|
|
37
|
-
headers: Dict[str, str] = dict(default_headers or {})
|
|
38
|
-
if show_additional_info:
|
|
39
|
-
headers[HEADER_SHOW_ADDITIONAL_INFO] = "true"
|
|
40
|
-
if bypass_moe:
|
|
41
|
-
headers[HEADER_BYPASS_MOE] = "true"
|
|
42
|
-
if bypass_cache:
|
|
43
|
-
headers[HEADER_BYPASS_CACHE] = "true"
|
|
44
|
-
if admin_key:
|
|
45
|
-
headers[HEADER_ADMIN_KEY] = admin_key
|
|
46
|
-
return headers
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
class Interfaze:
|
|
50
|
-
def __init__(
|
|
51
|
-
self,
|
|
52
|
-
*,
|
|
53
|
-
api_key: Optional[str] = None,
|
|
54
|
-
base_url: Optional[str] = None,
|
|
55
|
-
show_additional_info: bool = False,
|
|
56
|
-
bypass_moe: bool = False,
|
|
57
|
-
bypass_cache: bool = False,
|
|
58
|
-
admin_key: Optional[str] = None,
|
|
59
|
-
default_headers: Optional[Dict[str, str]] = None,
|
|
60
|
-
**kwargs: Any,
|
|
61
|
-
) -> None:
|
|
62
|
-
kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
|
|
63
|
-
self.openai = OpenAI(
|
|
64
|
-
api_key=_resolve_key(api_key),
|
|
65
|
-
base_url=base_url or INTERFAZE_BASE_URL,
|
|
66
|
-
default_headers=_build_headers(
|
|
67
|
-
default_headers, show_additional_info, bypass_moe, bypass_cache, admin_key
|
|
68
|
-
),
|
|
69
|
-
**kwargs,
|
|
70
|
-
)
|
|
71
|
-
self.chat = Chat(self.openai)
|
|
72
|
-
self.models = self.openai.models
|
|
73
|
-
self.tasks = Tasks(self.chat.completions)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
class AsyncInterfaze:
|
|
77
|
-
def __init__(
|
|
78
|
-
self,
|
|
79
|
-
*,
|
|
80
|
-
api_key: Optional[str] = None,
|
|
81
|
-
base_url: Optional[str] = None,
|
|
82
|
-
show_additional_info: bool = False,
|
|
83
|
-
bypass_moe: bool = False,
|
|
84
|
-
bypass_cache: bool = False,
|
|
85
|
-
admin_key: Optional[str] = None,
|
|
86
|
-
default_headers: Optional[Dict[str, str]] = None,
|
|
87
|
-
**kwargs: Any,
|
|
88
|
-
) -> None:
|
|
89
|
-
kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
|
|
90
|
-
self.openai = AsyncOpenAI(
|
|
91
|
-
api_key=_resolve_key(api_key),
|
|
92
|
-
base_url=base_url or INTERFAZE_BASE_URL,
|
|
93
|
-
default_headers=_build_headers(
|
|
94
|
-
default_headers, show_additional_info, bypass_moe, bypass_cache, admin_key
|
|
95
|
-
),
|
|
96
|
-
**kwargs,
|
|
97
|
-
)
|
|
98
|
-
self.chat = AsyncChat(self.openai)
|
|
99
|
-
self.models = self.openai.models
|
|
100
|
-
self.tasks = AsyncTasks(self.chat.completions)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|