zeriq-team 0.1.0__py3-none-any.whl
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.
- zeriq_team/__init__.py +36 -0
- zeriq_team/_client.py +116 -0
- zeriq_team/_core.py +356 -0
- zeriq_team/_errors.py +107 -0
- zeriq_team/_resources.py +511 -0
- zeriq_team/_version.py +1 -0
- zeriq_team/py.typed +0 -0
- zeriq_team/types.py +617 -0
- zeriq_team/webhooks.py +57 -0
- zeriq_team-0.1.0.dist-info/METADATA +118 -0
- zeriq_team-0.1.0.dist-info/RECORD +12 -0
- zeriq_team-0.1.0.dist-info/WHEEL +4 -0
zeriq_team/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Zeriq Teams API — official Python SDK.
|
|
2
|
+
|
|
3
|
+
from zeriq_team import Zeriq
|
|
4
|
+
|
|
5
|
+
zq = Zeriq() # reads ZERIQ_TEAM_API_KEY
|
|
6
|
+
answer = zq.personas.ask("prs_…", input="What changed in our refund policy?")
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from ._client import AsyncZeriq, Zeriq
|
|
10
|
+
from ._core import AsyncPager, Page, SyncPage, ZeriqObject
|
|
11
|
+
from ._errors import (
|
|
12
|
+
APIConnectionError,
|
|
13
|
+
APIError,
|
|
14
|
+
APITimeoutError,
|
|
15
|
+
AuthenticationError,
|
|
16
|
+
ConflictError,
|
|
17
|
+
CreditsExhaustedError,
|
|
18
|
+
InsufficientScopeError,
|
|
19
|
+
InternalServerError,
|
|
20
|
+
InvalidRequestError,
|
|
21
|
+
NotFoundError,
|
|
22
|
+
PermissionDeniedError,
|
|
23
|
+
PlanLimitError,
|
|
24
|
+
RateLimitError,
|
|
25
|
+
ToolNotPermittedError,
|
|
26
|
+
ZeriqError,
|
|
27
|
+
)
|
|
28
|
+
from ._version import __version__
|
|
29
|
+
from .webhooks import WebhookVerificationError
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"APIConnectionError", "APIError", "APITimeoutError", "AsyncPager", "AsyncZeriq", "AuthenticationError",
|
|
33
|
+
"ConflictError", "CreditsExhaustedError", "InsufficientScopeError", "InternalServerError", "InvalidRequestError",
|
|
34
|
+
"NotFoundError", "Page", "PermissionDeniedError", "PlanLimitError", "RateLimitError", "SyncPage",
|
|
35
|
+
"ToolNotPermittedError", "WebhookVerificationError", "Zeriq", "ZeriqError", "ZeriqObject", "__version__",
|
|
36
|
+
]
|
zeriq_team/_client.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""The sync (``Zeriq``) and async (``AsyncZeriq``) clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Mapping, Optional
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._core import DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, AsyncCore, SyncCore
|
|
10
|
+
from ._resources import (
|
|
11
|
+
ActionItems,
|
|
12
|
+
AsyncBots,
|
|
13
|
+
AsyncDocuments,
|
|
14
|
+
AsyncRooms,
|
|
15
|
+
Bots,
|
|
16
|
+
Conversations,
|
|
17
|
+
Documents,
|
|
18
|
+
Knowledge,
|
|
19
|
+
Meetings,
|
|
20
|
+
Personas,
|
|
21
|
+
RoomMessages,
|
|
22
|
+
Rooms,
|
|
23
|
+
Webhooks,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from .types import Me
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Zeriq:
|
|
31
|
+
"""Zeriq Teams API client.
|
|
32
|
+
|
|
33
|
+
>>> zq = Zeriq() # reads ZERIQ_TEAM_API_KEY
|
|
34
|
+
>>> zq.personas.ask("prs_…", input="What changed in our refund policy?")["answer"]
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
*,
|
|
40
|
+
api_key: Optional[str] = None,
|
|
41
|
+
base_url: Optional[str] = None,
|
|
42
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
43
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
44
|
+
default_headers: Optional[Mapping[str, str]] = None,
|
|
45
|
+
http_client: Optional[httpx.Client] = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
self._core = SyncCore(api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries,
|
|
48
|
+
default_headers=default_headers, http_client=http_client)
|
|
49
|
+
self.knowledge = Knowledge(self._core, Documents(self._core))
|
|
50
|
+
self.personas = Personas(self._core)
|
|
51
|
+
self.conversations = Conversations(self._core)
|
|
52
|
+
self.rooms = Rooms(self._core, RoomMessages(self._core))
|
|
53
|
+
self.action_items = ActionItems(self._core)
|
|
54
|
+
self.meetings = Meetings(Bots(self._core))
|
|
55
|
+
self.webhooks = Webhooks(self._core)
|
|
56
|
+
|
|
57
|
+
def me(self) -> "Me":
|
|
58
|
+
"""The workspace, key, scopes and tool access behind this API key."""
|
|
59
|
+
return self._core.request("GET", "/v1/me") # type: ignore[no-any-return]
|
|
60
|
+
|
|
61
|
+
def request(self, method: str, path: str, **kwargs: Any) -> Any:
|
|
62
|
+
"""Low-level access for endpoints the SDK doesn't wrap yet."""
|
|
63
|
+
return self._core.request(method, path, **kwargs)
|
|
64
|
+
|
|
65
|
+
def close(self) -> None:
|
|
66
|
+
self._core.close()
|
|
67
|
+
|
|
68
|
+
def __enter__(self) -> "Zeriq":
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
def __exit__(self, *exc: object) -> None:
|
|
72
|
+
self.close()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class AsyncZeriq:
|
|
76
|
+
"""Async Zeriq Teams API client: the same API, awaited.
|
|
77
|
+
|
|
78
|
+
>>> async with AsyncZeriq() as zq:
|
|
79
|
+
... async for item in zq.action_items.list(status="open"):
|
|
80
|
+
... print(item["title"])
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
*,
|
|
86
|
+
api_key: Optional[str] = None,
|
|
87
|
+
base_url: Optional[str] = None,
|
|
88
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
89
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
90
|
+
default_headers: Optional[Mapping[str, str]] = None,
|
|
91
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
92
|
+
) -> None:
|
|
93
|
+
self._core = AsyncCore(api_key=api_key, base_url=base_url, timeout=timeout, max_retries=max_retries,
|
|
94
|
+
default_headers=default_headers, http_client=http_client)
|
|
95
|
+
self.knowledge = Knowledge(self._core, AsyncDocuments(self._core))
|
|
96
|
+
self.personas = Personas(self._core)
|
|
97
|
+
self.conversations = Conversations(self._core)
|
|
98
|
+
self.rooms = AsyncRooms(self._core, RoomMessages(self._core))
|
|
99
|
+
self.action_items = ActionItems(self._core)
|
|
100
|
+
self.meetings = Meetings(AsyncBots(self._core))
|
|
101
|
+
self.webhooks = Webhooks(self._core)
|
|
102
|
+
|
|
103
|
+
async def me(self) -> "Me":
|
|
104
|
+
return await self._core.request("GET", "/v1/me") # type: ignore[no-any-return]
|
|
105
|
+
|
|
106
|
+
async def request(self, method: str, path: str, **kwargs: Any) -> Any:
|
|
107
|
+
return await self._core.request(method, path, **kwargs)
|
|
108
|
+
|
|
109
|
+
async def close(self) -> None:
|
|
110
|
+
await self._core.close()
|
|
111
|
+
|
|
112
|
+
async def __aenter__(self) -> "AsyncZeriq":
|
|
113
|
+
return self
|
|
114
|
+
|
|
115
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
116
|
+
await self.close()
|
zeriq_team/_core.py
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
"""HTTP core shared by the sync and async clients: auth, retries, idempotency keys, timeouts, pagination."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import email.utils
|
|
7
|
+
import os
|
|
8
|
+
import random
|
|
9
|
+
import time
|
|
10
|
+
import uuid
|
|
11
|
+
from typing import Any, AsyncIterator, Awaitable, Callable, Dict, Generic, Iterator, List, Mapping, Optional, TypeVar
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from ._errors import APIConnectionError, APITimeoutError, ZeriqError, error_for
|
|
16
|
+
from ._version import __version__
|
|
17
|
+
|
|
18
|
+
DEFAULT_BASE_URL = "https://api.zeriq.app"
|
|
19
|
+
DEFAULT_TIMEOUT = 60.0
|
|
20
|
+
DEFAULT_MAX_RETRIES = 2
|
|
21
|
+
RETRY_STATUSES = frozenset({408, 429, 500, 502, 503, 504})
|
|
22
|
+
|
|
23
|
+
T = TypeVar("T")
|
|
24
|
+
Query = Mapping[str, Any]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ZeriqObject(dict): # type: ignore[type-arg]
|
|
28
|
+
"""A JSON object from the API: a plain dict, plus the response's ``request_id``."""
|
|
29
|
+
|
|
30
|
+
request_id: Optional[str] = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _wrap(body: Any, request_id: Optional[str]) -> Any:
|
|
34
|
+
if isinstance(body, dict):
|
|
35
|
+
obj = ZeriqObject(body)
|
|
36
|
+
obj.request_id = request_id
|
|
37
|
+
return obj
|
|
38
|
+
return body
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _clean(query: Optional[Query]) -> Dict[str, Any]:
|
|
42
|
+
out: Dict[str, Any] = {}
|
|
43
|
+
for key, value in (query or {}).items():
|
|
44
|
+
if value is None:
|
|
45
|
+
continue
|
|
46
|
+
if hasattr(value, "isoformat"):
|
|
47
|
+
value = value.isoformat()
|
|
48
|
+
elif isinstance(value, bool):
|
|
49
|
+
value = "true" if value else "false"
|
|
50
|
+
out[key] = value
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _drop_none(body: Optional[Mapping[str, Any]]) -> Optional[Dict[str, Any]]:
|
|
55
|
+
"""Leave out arguments the caller didn't set, so server defaults apply."""
|
|
56
|
+
if body is None:
|
|
57
|
+
return None
|
|
58
|
+
return {k: v for k, v in body.items() if v is not None}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _Base:
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
*,
|
|
65
|
+
api_key: Optional[str],
|
|
66
|
+
base_url: Optional[str],
|
|
67
|
+
timeout: float,
|
|
68
|
+
max_retries: int,
|
|
69
|
+
default_headers: Optional[Mapping[str, str]],
|
|
70
|
+
) -> None:
|
|
71
|
+
api_key = api_key if api_key is not None else os.environ.get("ZERIQ_TEAM_API_KEY")
|
|
72
|
+
if not api_key:
|
|
73
|
+
raise ZeriqError("Missing API key: pass api_key=... or set ZERIQ_TEAM_API_KEY.")
|
|
74
|
+
self.api_key = api_key
|
|
75
|
+
self.base_url = (base_url or os.environ.get("ZERIQ_TEAM_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
76
|
+
self.timeout = timeout
|
|
77
|
+
self.max_retries = max_retries
|
|
78
|
+
self._default_headers = dict(default_headers or {})
|
|
79
|
+
|
|
80
|
+
def _headers(self, method: str, idempotency_key: Optional[str], extra: Optional[Mapping[str, str]]) -> Dict[str, str]:
|
|
81
|
+
headers = {
|
|
82
|
+
"Accept": "application/json",
|
|
83
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
84
|
+
"User-Agent": f"zeriq-team-python/{__version__}",
|
|
85
|
+
**self._default_headers,
|
|
86
|
+
**(extra or {}),
|
|
87
|
+
}
|
|
88
|
+
if method == "POST":
|
|
89
|
+
headers["Idempotency-Key"] = idempotency_key or f"sdk-{uuid.uuid4()}"
|
|
90
|
+
return headers
|
|
91
|
+
|
|
92
|
+
@staticmethod
|
|
93
|
+
def _backoff(attempt: int) -> float:
|
|
94
|
+
return min(0.5 * 2**attempt, 8.0) * (0.75 + random.random() * 0.5)
|
|
95
|
+
|
|
96
|
+
@staticmethod
|
|
97
|
+
def _retry_after(response: httpx.Response) -> Optional[float]:
|
|
98
|
+
header = response.headers.get("retry-after")
|
|
99
|
+
if not header:
|
|
100
|
+
return None
|
|
101
|
+
try:
|
|
102
|
+
return min(float(header), 60.0)
|
|
103
|
+
except ValueError:
|
|
104
|
+
parsed = email.utils.parsedate_to_datetime(header) if header else None
|
|
105
|
+
return None if parsed is None else max(0.0, min(parsed.timestamp() - time.time(), 60.0))
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def _raise_for(response: httpx.Response) -> None:
|
|
109
|
+
try:
|
|
110
|
+
body = response.json().get("error")
|
|
111
|
+
except Exception: # noqa: BLE001 — not JSON
|
|
112
|
+
body = None
|
|
113
|
+
raise error_for(response.status_code, body, response.headers)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class SyncCore(_Base):
|
|
117
|
+
def __init__(self, *, http_client: Optional[httpx.Client] = None, **kwargs: Any) -> None:
|
|
118
|
+
super().__init__(**kwargs)
|
|
119
|
+
self._http = http_client or httpx.Client()
|
|
120
|
+
self._owns_http = http_client is None
|
|
121
|
+
|
|
122
|
+
def request(
|
|
123
|
+
self,
|
|
124
|
+
method: str,
|
|
125
|
+
path: str,
|
|
126
|
+
*,
|
|
127
|
+
query: Optional[Query] = None,
|
|
128
|
+
json: Optional[Mapping[str, Any]] = None,
|
|
129
|
+
files: Any = None,
|
|
130
|
+
data: Optional[Mapping[str, Any]] = None,
|
|
131
|
+
timeout: Optional[float] = None,
|
|
132
|
+
max_retries: Optional[int] = None,
|
|
133
|
+
idempotency_key: Optional[str] = None,
|
|
134
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
135
|
+
) -> Any:
|
|
136
|
+
retries = self.max_retries if max_retries is None else max_retries
|
|
137
|
+
hdrs = self._headers(method, idempotency_key, headers)
|
|
138
|
+
attempt = 0
|
|
139
|
+
while True:
|
|
140
|
+
try:
|
|
141
|
+
response = self._http.request(
|
|
142
|
+
method, self.base_url + path, params=_clean(query), json=_drop_none(json), files=files, data=data,
|
|
143
|
+
headers=hdrs, timeout=self.timeout if timeout is None else timeout,
|
|
144
|
+
)
|
|
145
|
+
except httpx.TimeoutException as exc:
|
|
146
|
+
if attempt < retries:
|
|
147
|
+
time.sleep(self._backoff(attempt))
|
|
148
|
+
attempt += 1
|
|
149
|
+
continue
|
|
150
|
+
raise APITimeoutError("Request timed out") from exc
|
|
151
|
+
except httpx.TransportError as exc:
|
|
152
|
+
if attempt < retries:
|
|
153
|
+
time.sleep(self._backoff(attempt))
|
|
154
|
+
attempt += 1
|
|
155
|
+
continue
|
|
156
|
+
raise APIConnectionError(str(exc) or "Connection error") from exc
|
|
157
|
+
if response.is_success:
|
|
158
|
+
return _wrap(response.json() if response.content else {}, response.headers.get("x-request-id"))
|
|
159
|
+
if response.status_code in RETRY_STATUSES and attempt < retries:
|
|
160
|
+
delay = self._retry_after(response)
|
|
161
|
+
time.sleep(self._backoff(attempt) if delay is None else delay)
|
|
162
|
+
attempt += 1
|
|
163
|
+
continue
|
|
164
|
+
self._raise_for(response)
|
|
165
|
+
|
|
166
|
+
def paginate(self, fetch: Callable[[Optional[str]], Any]) -> Any:
|
|
167
|
+
return SyncPage(fetch)
|
|
168
|
+
|
|
169
|
+
def stream_events(self, path: str, *, query: Optional[Query] = None, headers: Optional[Mapping[str, str]] = None) -> Iterator["SSEMessage"]:
|
|
170
|
+
"""A streaming GET (server-sent events): yields messages until the server ends the stream."""
|
|
171
|
+
hdrs = {**self._headers("GET", None, headers), "Accept": "text/event-stream"}
|
|
172
|
+
try:
|
|
173
|
+
with self._http.stream("GET", self.base_url + path, params=_clean(query), headers=hdrs,
|
|
174
|
+
timeout=httpx.Timeout(self.timeout, read=None)) as response:
|
|
175
|
+
if not response.is_success:
|
|
176
|
+
response.read()
|
|
177
|
+
self._raise_for(response)
|
|
178
|
+
yield from parse_sse(response.iter_lines())
|
|
179
|
+
except httpx.TransportError as exc:
|
|
180
|
+
raise APIConnectionError(str(exc) or "Connection error") from exc
|
|
181
|
+
|
|
182
|
+
def close(self) -> None:
|
|
183
|
+
if self._owns_http:
|
|
184
|
+
self._http.close()
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class AsyncCore(_Base):
|
|
188
|
+
def __init__(self, *, http_client: Optional[httpx.AsyncClient] = None, **kwargs: Any) -> None:
|
|
189
|
+
super().__init__(**kwargs)
|
|
190
|
+
self._http = http_client or httpx.AsyncClient()
|
|
191
|
+
self._owns_http = http_client is None
|
|
192
|
+
|
|
193
|
+
async def request(
|
|
194
|
+
self,
|
|
195
|
+
method: str,
|
|
196
|
+
path: str,
|
|
197
|
+
*,
|
|
198
|
+
query: Optional[Query] = None,
|
|
199
|
+
json: Optional[Mapping[str, Any]] = None,
|
|
200
|
+
files: Any = None,
|
|
201
|
+
data: Optional[Mapping[str, Any]] = None,
|
|
202
|
+
timeout: Optional[float] = None,
|
|
203
|
+
max_retries: Optional[int] = None,
|
|
204
|
+
idempotency_key: Optional[str] = None,
|
|
205
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
206
|
+
) -> Any:
|
|
207
|
+
retries = self.max_retries if max_retries is None else max_retries
|
|
208
|
+
hdrs = self._headers(method, idempotency_key, headers)
|
|
209
|
+
attempt = 0
|
|
210
|
+
while True:
|
|
211
|
+
try:
|
|
212
|
+
response = await self._http.request(
|
|
213
|
+
method, self.base_url + path, params=_clean(query), json=_drop_none(json), files=files, data=data,
|
|
214
|
+
headers=hdrs, timeout=self.timeout if timeout is None else timeout,
|
|
215
|
+
)
|
|
216
|
+
except httpx.TimeoutException as exc:
|
|
217
|
+
if attempt < retries:
|
|
218
|
+
await asyncio.sleep(self._backoff(attempt))
|
|
219
|
+
attempt += 1
|
|
220
|
+
continue
|
|
221
|
+
raise APITimeoutError("Request timed out") from exc
|
|
222
|
+
except httpx.TransportError as exc:
|
|
223
|
+
if attempt < retries:
|
|
224
|
+
await asyncio.sleep(self._backoff(attempt))
|
|
225
|
+
attempt += 1
|
|
226
|
+
continue
|
|
227
|
+
raise APIConnectionError(str(exc) or "Connection error") from exc
|
|
228
|
+
if response.is_success:
|
|
229
|
+
return _wrap(response.json() if response.content else {}, response.headers.get("x-request-id"))
|
|
230
|
+
if response.status_code in RETRY_STATUSES and attempt < retries:
|
|
231
|
+
delay = self._retry_after(response)
|
|
232
|
+
await asyncio.sleep(self._backoff(attempt) if delay is None else delay)
|
|
233
|
+
attempt += 1
|
|
234
|
+
continue
|
|
235
|
+
self._raise_for(response)
|
|
236
|
+
|
|
237
|
+
def paginate(self, fetch: Callable[[Optional[str]], Awaitable[Any]]) -> Any:
|
|
238
|
+
return AsyncPager(fetch)
|
|
239
|
+
|
|
240
|
+
async def stream_events(
|
|
241
|
+
self, path: str, *, query: Optional[Query] = None, headers: Optional[Mapping[str, str]] = None
|
|
242
|
+
) -> AsyncIterator["SSEMessage"]:
|
|
243
|
+
hdrs = {**self._headers("GET", None, headers), "Accept": "text/event-stream"}
|
|
244
|
+
try:
|
|
245
|
+
async with self._http.stream("GET", self.base_url + path, params=_clean(query), headers=hdrs,
|
|
246
|
+
timeout=httpx.Timeout(self.timeout, read=None)) as response:
|
|
247
|
+
if not response.is_success:
|
|
248
|
+
await response.aread()
|
|
249
|
+
self._raise_for(response)
|
|
250
|
+
parser = SSEParser()
|
|
251
|
+
async for line in response.aiter_lines():
|
|
252
|
+
message = parser.feed(line)
|
|
253
|
+
if message is not None:
|
|
254
|
+
yield message
|
|
255
|
+
except httpx.TransportError as exc:
|
|
256
|
+
raise APIConnectionError(str(exc) or "Connection error") from exc
|
|
257
|
+
|
|
258
|
+
async def close(self) -> None:
|
|
259
|
+
if self._owns_http:
|
|
260
|
+
await self._http.aclose()
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class SSEMessage:
|
|
264
|
+
__slots__ = ("id", "event", "data")
|
|
265
|
+
|
|
266
|
+
def __init__(self, id: Optional[str], event: str, data: str) -> None: # noqa: A002
|
|
267
|
+
self.id, self.event, self.data = id, event, data
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class SSEParser:
|
|
271
|
+
"""Feed lines of a text/event-stream; a complete message comes back on its blank line."""
|
|
272
|
+
|
|
273
|
+
def __init__(self) -> None:
|
|
274
|
+
self._reset()
|
|
275
|
+
|
|
276
|
+
def _reset(self) -> None:
|
|
277
|
+
self._id: Optional[str] = None
|
|
278
|
+
self._event: Optional[str] = None
|
|
279
|
+
self._data: List[str] = []
|
|
280
|
+
|
|
281
|
+
def feed(self, line: str) -> Optional[SSEMessage]:
|
|
282
|
+
line = line.rstrip("\r")
|
|
283
|
+
if line == "":
|
|
284
|
+
message = SSEMessage(self._id, self._event or "message", "\n".join(self._data)) if self._data else None
|
|
285
|
+
self._reset()
|
|
286
|
+
return message
|
|
287
|
+
if line.startswith(":"):
|
|
288
|
+
return None
|
|
289
|
+
name, _, value = line.partition(":")
|
|
290
|
+
value = value[1:] if value.startswith(" ") else value
|
|
291
|
+
if name == "id":
|
|
292
|
+
self._id = value
|
|
293
|
+
elif name == "event":
|
|
294
|
+
self._event = value
|
|
295
|
+
elif name == "data":
|
|
296
|
+
self._data.append(value)
|
|
297
|
+
return None
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def parse_sse(lines: Any) -> Iterator[SSEMessage]:
|
|
301
|
+
parser = SSEParser()
|
|
302
|
+
for line in lines:
|
|
303
|
+
message = parser.feed(line)
|
|
304
|
+
if message is not None:
|
|
305
|
+
yield message
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
class Page(Generic[T]):
|
|
309
|
+
"""One page of a list: ``.data`` and ``.next_cursor`` (None on the last page)."""
|
|
310
|
+
|
|
311
|
+
def __init__(self, body: Mapping[str, Any]) -> None:
|
|
312
|
+
self.data: List[T] = list(body.get("data") or [])
|
|
313
|
+
self.next_cursor: Optional[str] = body.get("next_cursor")
|
|
314
|
+
self.request_id: Optional[str] = getattr(body, "request_id", None)
|
|
315
|
+
|
|
316
|
+
def __repr__(self) -> str:
|
|
317
|
+
return f"Page(data=[{len(self.data)} items], next_cursor={self.next_cursor!r})"
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class SyncPage(Page[T]):
|
|
321
|
+
"""The first page; iterating it walks every item across pages."""
|
|
322
|
+
|
|
323
|
+
def __init__(self, fetch: Callable[[Optional[str]], Any]) -> None:
|
|
324
|
+
super().__init__(fetch(None))
|
|
325
|
+
self._fetch = fetch
|
|
326
|
+
|
|
327
|
+
def __iter__(self) -> Iterator[T]:
|
|
328
|
+
page: Page[T] = self
|
|
329
|
+
while True:
|
|
330
|
+
yield from page.data
|
|
331
|
+
if not page.next_cursor:
|
|
332
|
+
return
|
|
333
|
+
page = Page(self._fetch(page.next_cursor))
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
class AsyncPager(Generic[T]):
|
|
337
|
+
"""``await`` it for the first page, or ``async for`` it to walk every item across pages."""
|
|
338
|
+
|
|
339
|
+
def __init__(self, fetch: Callable[[Optional[str]], Awaitable[Any]]) -> None:
|
|
340
|
+
self._fetch = fetch
|
|
341
|
+
|
|
342
|
+
def __await__(self): # type: ignore[no-untyped-def]
|
|
343
|
+
return self._first().__await__()
|
|
344
|
+
|
|
345
|
+
async def _first(self) -> Page[T]:
|
|
346
|
+
return Page(await self._fetch(None))
|
|
347
|
+
|
|
348
|
+
async def __aiter__(self) -> AsyncIterator[T]:
|
|
349
|
+
cursor: Optional[str] = None
|
|
350
|
+
while True:
|
|
351
|
+
page = Page[T](await self._fetch(cursor))
|
|
352
|
+
for item in page.data:
|
|
353
|
+
yield item
|
|
354
|
+
cursor = page.next_cursor
|
|
355
|
+
if not cursor:
|
|
356
|
+
return
|
zeriq_team/_errors.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Errors the SDK raises. API errors carry the API's ``type``, ``code``, ``param`` and ``request_id``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Mapping, Optional
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ZeriqError(Exception):
|
|
11
|
+
"""Base class for everything the SDK raises."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class APIError(ZeriqError):
|
|
15
|
+
"""The API answered with an error status."""
|
|
16
|
+
|
|
17
|
+
def __init__(self, status: int, body: Optional[Mapping[str, Any]], headers: httpx.Headers) -> None:
|
|
18
|
+
body = body or {}
|
|
19
|
+
self.status = status
|
|
20
|
+
self.type: str = body.get("type") or "api_error"
|
|
21
|
+
self.code: str = body.get("code") or "unknown"
|
|
22
|
+
self.param: Optional[str] = body.get("param")
|
|
23
|
+
self.request_id: Optional[str] = body.get("request_id") or headers.get("x-request-id")
|
|
24
|
+
self.headers = headers
|
|
25
|
+
self.message: str = body.get("message") or f"Request failed with status {status}"
|
|
26
|
+
super().__init__(self.message)
|
|
27
|
+
|
|
28
|
+
def __repr__(self) -> str:
|
|
29
|
+
return f"{type(self).__name__}(status={self.status}, code={self.code!r}, request_id={self.request_id!r})"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class InvalidRequestError(APIError):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class AuthenticationError(APIError):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class CreditsExhaustedError(APIError):
|
|
41
|
+
"""402: out of credits. Retry with ``allow_downgrade=True`` to use the free model."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class PlanLimitError(APIError):
|
|
45
|
+
"""402: the workspace's plan doesn't include this."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class PermissionDeniedError(APIError):
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class InsufficientScopeError(PermissionDeniedError):
|
|
53
|
+
"""403: the API key lacks a scope; ``param`` names it."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ToolNotPermittedError(PermissionDeniedError):
|
|
57
|
+
"""403: the key's tool policy doesn't allow what was asked."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class NotFoundError(APIError):
|
|
61
|
+
"""404, also for objects in other workspaces."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class ConflictError(APIError):
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class RateLimitError(APIError):
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class InternalServerError(APIError):
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class APIConnectionError(ZeriqError):
|
|
77
|
+
"""The request never got an answer (DNS, connection reset, …)."""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class APITimeoutError(APIConnectionError):
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def error_for(status: int, body: Optional[Mapping[str, Any]], headers: httpx.Headers) -> APIError:
|
|
85
|
+
code = (body or {}).get("code")
|
|
86
|
+
cls: type[APIError]
|
|
87
|
+
if status == 402:
|
|
88
|
+
cls = CreditsExhaustedError if code == "credits_exhausted" else PlanLimitError
|
|
89
|
+
elif status == 403:
|
|
90
|
+
cls = {"insufficient_scope": InsufficientScopeError, "tool_not_permitted": ToolNotPermittedError}.get(
|
|
91
|
+
code or "", PermissionDeniedError
|
|
92
|
+
)
|
|
93
|
+
elif status in (400, 413, 422):
|
|
94
|
+
cls = InvalidRequestError
|
|
95
|
+
elif status == 401:
|
|
96
|
+
cls = AuthenticationError
|
|
97
|
+
elif status == 404:
|
|
98
|
+
cls = NotFoundError
|
|
99
|
+
elif status == 409:
|
|
100
|
+
cls = ConflictError
|
|
101
|
+
elif status == 429:
|
|
102
|
+
cls = RateLimitError
|
|
103
|
+
elif status >= 500:
|
|
104
|
+
cls = InternalServerError
|
|
105
|
+
else:
|
|
106
|
+
cls = APIError
|
|
107
|
+
return cls(status, body, headers)
|