open-agent-docs 0.3.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.
- open_agent_docs/__init__.py +86 -0
- open_agent_docs/_base_client.py +667 -0
- open_agent_docs/_client.py +112 -0
- open_agent_docs/_embed.py +83 -0
- open_agent_docs/_errors.py +206 -0
- open_agent_docs/_files.py +51 -0
- open_agent_docs/_generated/__init__.py +2 -0
- open_agent_docs/_generated/models.py +1378 -0
- open_agent_docs/_generated/resources.py +4300 -0
- open_agent_docs/_models.py +17 -0
- open_agent_docs/_pagination.py +132 -0
- open_agent_docs/_server.py +330 -0
- open_agent_docs/_sse.py +335 -0
- open_agent_docs/_types.py +35 -0
- open_agent_docs/_utils.py +15 -0
- open_agent_docs/_version.py +1 -0
- open_agent_docs/_webhook.py +85 -0
- open_agent_docs/py.typed +0 -0
- open_agent_docs/types.py +3 -0
- open_agent_docs-0.3.0.dist-info/METADATA +266 -0
- open_agent_docs-0.3.0.dist-info/RECORD +22 -0
- open_agent_docs-0.3.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,667 @@
|
|
|
1
|
+
"""客户端的底子:配置、认证头(token / with_user 的 header、JWT)、重试、错误、翻页、事件流。
|
|
2
|
+
生成的资源类(_generated/resources.py)只调这里的 _call / _call_or_none / _call_page / _stream。"""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import random
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from functools import cached_property, lru_cache
|
|
12
|
+
from typing import (
|
|
13
|
+
Any,
|
|
14
|
+
Awaitable,
|
|
15
|
+
Dict,
|
|
16
|
+
List,
|
|
17
|
+
Mapping,
|
|
18
|
+
Optional,
|
|
19
|
+
Sequence,
|
|
20
|
+
Tuple,
|
|
21
|
+
Type,
|
|
22
|
+
TypeVar,
|
|
23
|
+
Union,
|
|
24
|
+
cast,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
import httpx
|
|
28
|
+
import pydantic
|
|
29
|
+
|
|
30
|
+
from ._embed import WorkspaceClaim, sign_jwt
|
|
31
|
+
from ._errors import (
|
|
32
|
+
APIConnectionError,
|
|
33
|
+
APIError,
|
|
34
|
+
APITimeoutError,
|
|
35
|
+
ConfigurationError,
|
|
36
|
+
NotFoundError,
|
|
37
|
+
OADError,
|
|
38
|
+
error_from_response,
|
|
39
|
+
parse_retry_after,
|
|
40
|
+
)
|
|
41
|
+
from ._models import BaseModel
|
|
42
|
+
from ._pagination import AsyncCursorPage, AsyncPaginator, CursorPage
|
|
43
|
+
from ._sse import AsyncEventStream, EventStream
|
|
44
|
+
from ._types import NOT_GIVEN, NotGiven
|
|
45
|
+
from ._utils import encode_uri_component
|
|
46
|
+
from ._version import __version__
|
|
47
|
+
|
|
48
|
+
__all__ = ["SyncAPIClient", "AsyncAPIClient", "Headers", "Query", "Body", "TimeoutTypes"]
|
|
49
|
+
|
|
50
|
+
DEFAULT_BASE_URL = "http://127.0.0.1:8848"
|
|
51
|
+
DEFAULT_TIMEOUT = 60.0
|
|
52
|
+
DEFAULT_MAX_RETRIES = 2
|
|
53
|
+
RETRY_AFTER_MAX = 60.0
|
|
54
|
+
BACKOFF_INITIAL = 0.5
|
|
55
|
+
BACKOFF_MAX = 8.0
|
|
56
|
+
JWT_REFRESH_BEFORE = 60
|
|
57
|
+
USER_AGENT = f"open-agent-docs-python/{__version__}"
|
|
58
|
+
|
|
59
|
+
Headers = Mapping[str, str]
|
|
60
|
+
Query = Mapping[str, object]
|
|
61
|
+
Body = Mapping[str, object]
|
|
62
|
+
TimeoutTypes = Union[float, httpx.Timeout, None]
|
|
63
|
+
|
|
64
|
+
_T = TypeVar("_T")
|
|
65
|
+
_M = TypeVar("_M", bound=BaseModel)
|
|
66
|
+
_C = TypeVar("_C", bound="_BaseClient")
|
|
67
|
+
|
|
68
|
+
# 请求没发出去的错误:什么方法都能重试
|
|
69
|
+
_NOT_SENT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)
|
|
70
|
+
# 连接被断:只有 GET、PUT、DELETE(幂等)重试
|
|
71
|
+
_IDEMPOTENT = {"GET", "HEAD", "OPTIONS", "PUT", "DELETE"}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@lru_cache(maxsize=None)
|
|
75
|
+
def _adapter(t: Any) -> pydantic.TypeAdapter[Any]:
|
|
76
|
+
return pydantic.TypeAdapter(t)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _validate(t: Any, data: Any) -> Any:
|
|
80
|
+
if isinstance(t, type) and issubclass(t, pydantic.BaseModel):
|
|
81
|
+
return t.model_validate(data)
|
|
82
|
+
if t is object:
|
|
83
|
+
return data
|
|
84
|
+
adapter: pydantic.TypeAdapter[Any] = _adapter(cast(object, t))
|
|
85
|
+
return adapter.validate_python(data)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _jsonable(v: Any) -> Any:
|
|
89
|
+
"""请求体里的值:模型转 dict(用接口里的名字,没设的字段不发),NOT_GIVEN 去掉"""
|
|
90
|
+
if isinstance(v, pydantic.BaseModel):
|
|
91
|
+
return v.model_dump(mode="json", by_alias=True, exclude_unset=True)
|
|
92
|
+
if isinstance(v, Mapping):
|
|
93
|
+
m = cast(Mapping[Any, Any], v)
|
|
94
|
+
return {k: _jsonable(x) for k, x in m.items() if not isinstance(x, NotGiven)}
|
|
95
|
+
if isinstance(v, (list, tuple)):
|
|
96
|
+
seq = cast(Sequence[Any], v)
|
|
97
|
+
return [_jsonable(x) for x in seq]
|
|
98
|
+
return v
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _query(q: Optional[Mapping[str, object]], extra: Optional[Mapping[str, object]]) -> Dict[str, str]:
|
|
102
|
+
"""查询参数:没给的(NOT_GIVEN、None)不带;布尔写成 true / false"""
|
|
103
|
+
out: Dict[str, str] = {}
|
|
104
|
+
for src in (q, extra):
|
|
105
|
+
if not src:
|
|
106
|
+
continue
|
|
107
|
+
for k, v in src.items():
|
|
108
|
+
if isinstance(v, NotGiven) or v is None:
|
|
109
|
+
continue
|
|
110
|
+
if isinstance(v, bool):
|
|
111
|
+
out[k] = "true" if v else "false"
|
|
112
|
+
elif isinstance(v, (list, tuple)):
|
|
113
|
+
out[k] = ",".join(str(x) for x in cast(Sequence[Any], v))
|
|
114
|
+
else:
|
|
115
|
+
out[k] = str(v)
|
|
116
|
+
return out
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _retry_delay(attempt: int, resp: Optional[httpx.Response]) -> float:
|
|
120
|
+
"""第 attempt 次重试(从 0 起)前等多久:Retry-After(秒,最多 60),没有就 0.5 × 2^n(最多 8)加 0–25% 随机"""
|
|
121
|
+
if resp is not None:
|
|
122
|
+
ra = parse_retry_after(resp.headers.get("retry-after"))
|
|
123
|
+
if ra is not None:
|
|
124
|
+
return min(ra, RETRY_AFTER_MAX)
|
|
125
|
+
d = min(BACKOFF_INITIAL * (2**attempt), BACKOFF_MAX)
|
|
126
|
+
return d * (1 + random.random() * 0.25)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _retry_status(method: str, status: int) -> bool:
|
|
130
|
+
if status == 429:
|
|
131
|
+
return True
|
|
132
|
+
if status in (502, 503, 504):
|
|
133
|
+
# POST、PATCH 可能已经生效了:不重试
|
|
134
|
+
return method not in ("POST", "PATCH")
|
|
135
|
+
return False
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _retry_exc(method: str, e: Exception) -> bool:
|
|
139
|
+
if isinstance(e, _NOT_SENT):
|
|
140
|
+
return True
|
|
141
|
+
if isinstance(e, (httpx.ReadTimeout, httpx.WriteTimeout)):
|
|
142
|
+
return False
|
|
143
|
+
if isinstance(e, (httpx.RemoteProtocolError, httpx.ReadError, httpx.WriteError, httpx.CloseError)):
|
|
144
|
+
return method in _IDEMPOTENT
|
|
145
|
+
return False
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _wrap_exc(e: Exception, req: Optional[httpx.Request]) -> APIConnectionError:
|
|
149
|
+
if isinstance(e, httpx.TimeoutException):
|
|
150
|
+
return APITimeoutError(f"请求超时:{e}", request=req)
|
|
151
|
+
return APIConnectionError(f"连不上服务器:{e}", request=req)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class _User:
|
|
155
|
+
__slots__ = ("id", "name", "email", "workspaces")
|
|
156
|
+
|
|
157
|
+
def __init__(self, id: str, name: Optional[str], email: Optional[str], workspaces: Optional[Sequence[WorkspaceClaim]]) -> None:
|
|
158
|
+
self.id = id
|
|
159
|
+
self.name = name
|
|
160
|
+
self.email = email
|
|
161
|
+
self.workspaces = workspaces
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class _BaseClient:
|
|
165
|
+
base_url: str
|
|
166
|
+
"""服务器地址(不带 /api/v1)"""
|
|
167
|
+
token: Optional[str]
|
|
168
|
+
timeout: float
|
|
169
|
+
max_retries: int
|
|
170
|
+
locale: Optional[str]
|
|
171
|
+
|
|
172
|
+
def __init__(
|
|
173
|
+
self,
|
|
174
|
+
*,
|
|
175
|
+
base_url: Optional[str] = None,
|
|
176
|
+
token: Optional[str] = None,
|
|
177
|
+
header_secret: Optional[str] = None,
|
|
178
|
+
jwt_secret: Optional[str] = None,
|
|
179
|
+
jwt_issuer: Optional[str] = None,
|
|
180
|
+
jwt_audience: Optional[str] = None,
|
|
181
|
+
jwt_ttl: int = 3600,
|
|
182
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
183
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
184
|
+
locale: Optional[str] = None,
|
|
185
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
186
|
+
) -> None:
|
|
187
|
+
url = base_url or os.environ.get("OAD_BASE_URL") or DEFAULT_BASE_URL
|
|
188
|
+
self.base_url = url.rstrip("/")
|
|
189
|
+
self.token = token if token is not None else (os.environ.get("OAD_TOKEN") or None)
|
|
190
|
+
self._header_secret = header_secret
|
|
191
|
+
self._jwt_secret = jwt_secret
|
|
192
|
+
self._jwt_issuer = jwt_issuer
|
|
193
|
+
self._jwt_audience = jwt_audience
|
|
194
|
+
self._jwt_ttl = int(jwt_ttl)
|
|
195
|
+
self.timeout = float(timeout)
|
|
196
|
+
self.max_retries = max(0, int(max_retries))
|
|
197
|
+
self.locale = locale
|
|
198
|
+
self._headers: Dict[str, str] = dict(headers or {})
|
|
199
|
+
self._user: Optional[_User] = None
|
|
200
|
+
self._jwt: Optional[Tuple[str, float]] = None
|
|
201
|
+
self._lock = threading.Lock()
|
|
202
|
+
self._ws: Optional[str] = None
|
|
203
|
+
|
|
204
|
+
# ---------- with_user
|
|
205
|
+
|
|
206
|
+
def _child(self: _C, user: _User) -> _C:
|
|
207
|
+
mode = self._auth_mode()
|
|
208
|
+
if user.workspaces is not None and mode == "header":
|
|
209
|
+
raise ConfigurationError("header 模式不支持 workspaces(要指定工作区用 jwt_secret)")
|
|
210
|
+
c = self.__class__.__new__(self.__class__)
|
|
211
|
+
c.__dict__.update(self.__dict__)
|
|
212
|
+
# 每个客户端自己的:用户、JWT 缓存、默认工作区、资源(cached_property 存在 __dict__ 里,要重新建)
|
|
213
|
+
for klass in type(self).__mro__:
|
|
214
|
+
for name, attr in vars(klass).items():
|
|
215
|
+
if isinstance(attr, cached_property):
|
|
216
|
+
c.__dict__.pop(name, None)
|
|
217
|
+
c._user = user
|
|
218
|
+
c._jwt = None
|
|
219
|
+
c._ws = None
|
|
220
|
+
c._lock = threading.Lock()
|
|
221
|
+
c.__dict__["_owns_http"] = False # 连接池是父客户端的
|
|
222
|
+
return c
|
|
223
|
+
|
|
224
|
+
def _auth_mode(self) -> str:
|
|
225
|
+
if self._header_secret and self._jwt_secret:
|
|
226
|
+
raise ConfigurationError("header_secret 和 jwt_secret 只能配一个")
|
|
227
|
+
if self._header_secret:
|
|
228
|
+
return "header"
|
|
229
|
+
if self._jwt_secret:
|
|
230
|
+
return "jwt"
|
|
231
|
+
raise ConfigurationError("with_user 要先配 header_secret(OAD_AUTH=header)或 jwt_secret(OAD_AUTH=jwt)")
|
|
232
|
+
|
|
233
|
+
def with_user(
|
|
234
|
+
self: _C,
|
|
235
|
+
user_id: str,
|
|
236
|
+
name: Optional[str] = None,
|
|
237
|
+
email: Optional[str] = None,
|
|
238
|
+
workspaces: Optional[Sequence[WorkspaceClaim]] = None,
|
|
239
|
+
) -> _C:
|
|
240
|
+
"""以某个用户的身份调(宿主后端用):返回一个新的客户端(共享连接池和配置),原来的不变。
|
|
241
|
+
|
|
242
|
+
- 配了 header_secret:带 X-OAD-Secret、X-OAD-User-Id / -Name(百分号编码)/ -Email
|
|
243
|
+
- 配了 jwt_secret:签一个 JWT(缓存到过期前 60 秒再换),workspaces 写进 claims
|
|
244
|
+
"""
|
|
245
|
+
return self._child(_User(user_id, name, email, workspaces))
|
|
246
|
+
|
|
247
|
+
def _jwt_token(self, user: _User) -> str:
|
|
248
|
+
now = time.time()
|
|
249
|
+
with self._lock:
|
|
250
|
+
if self._jwt is not None and self._jwt[1] - JWT_REFRESH_BEFORE > now:
|
|
251
|
+
return self._jwt[0]
|
|
252
|
+
assert self._jwt_secret is not None
|
|
253
|
+
tok = sign_jwt(
|
|
254
|
+
self._jwt_secret,
|
|
255
|
+
user.id,
|
|
256
|
+
name=user.name,
|
|
257
|
+
email=user.email,
|
|
258
|
+
workspaces=user.workspaces,
|
|
259
|
+
ttl=self._jwt_ttl,
|
|
260
|
+
issuer=self._jwt_issuer,
|
|
261
|
+
audience=self._jwt_audience,
|
|
262
|
+
now=now,
|
|
263
|
+
)
|
|
264
|
+
self._jwt = (tok, int(now) + self._jwt_ttl)
|
|
265
|
+
return tok
|
|
266
|
+
|
|
267
|
+
def _auth_headers(self) -> Dict[str, str]:
|
|
268
|
+
u = self._user
|
|
269
|
+
if u is None:
|
|
270
|
+
return {"authorization": f"Bearer {self.token}"} if self.token else {}
|
|
271
|
+
if self._auth_mode() == "header":
|
|
272
|
+
assert self._header_secret is not None
|
|
273
|
+
h = {"x-oad-secret": self._header_secret, "x-oad-user-id": u.id}
|
|
274
|
+
if u.name is not None:
|
|
275
|
+
h["x-oad-user-name"] = encode_uri_component(u.name)
|
|
276
|
+
if u.email is not None:
|
|
277
|
+
h["x-oad-user-email"] = u.email
|
|
278
|
+
return h
|
|
279
|
+
return {"authorization": f"Bearer {self._jwt_token(u)}"}
|
|
280
|
+
|
|
281
|
+
def _build_headers(self, extra: Optional[Mapping[str, str]], json_body: bool) -> Dict[str, str]:
|
|
282
|
+
h: Dict[str, str] = {"user-agent": USER_AGENT}
|
|
283
|
+
if self.locale:
|
|
284
|
+
h["accept-language"] = {"zh": "zh-CN", "en": "en"}.get(self.locale, self.locale)
|
|
285
|
+
if json_body:
|
|
286
|
+
h["content-type"] = "application/json"
|
|
287
|
+
h.update({k.lower(): v for k, v in self._headers.items()})
|
|
288
|
+
h.update(self._auth_headers())
|
|
289
|
+
if extra:
|
|
290
|
+
h.update({k.lower(): v for k, v in extra.items()})
|
|
291
|
+
return h
|
|
292
|
+
|
|
293
|
+
def _timeout(self, t: Union[TimeoutTypes, NotGiven]) -> httpx.Timeout:
|
|
294
|
+
if isinstance(t, NotGiven):
|
|
295
|
+
return httpx.Timeout(self.timeout)
|
|
296
|
+
if isinstance(t, httpx.Timeout):
|
|
297
|
+
return t
|
|
298
|
+
return httpx.Timeout(t)
|
|
299
|
+
|
|
300
|
+
def _url(self, path: str) -> str:
|
|
301
|
+
return f"{self.base_url}/api/v1{path}"
|
|
302
|
+
|
|
303
|
+
def _prepare(
|
|
304
|
+
self,
|
|
305
|
+
method: str,
|
|
306
|
+
path: str,
|
|
307
|
+
*,
|
|
308
|
+
query: Optional[Mapping[str, object]],
|
|
309
|
+
body: object,
|
|
310
|
+
extra_body: Optional[Mapping[str, object]],
|
|
311
|
+
content: Optional[bytes],
|
|
312
|
+
files: Optional[Mapping[str, Any]],
|
|
313
|
+
headers: Optional[Mapping[str, str]],
|
|
314
|
+
extra_headers: Optional[Mapping[str, str]],
|
|
315
|
+
extra_query: Optional[Mapping[str, object]],
|
|
316
|
+
) -> Dict[str, Any]:
|
|
317
|
+
"""→ httpx.build_request 的参数"""
|
|
318
|
+
kw: Dict[str, Any] = {"params": _query(query, extra_query)}
|
|
319
|
+
is_json = False
|
|
320
|
+
if not isinstance(body, NotGiven):
|
|
321
|
+
data = _jsonable(body)
|
|
322
|
+
if extra_body:
|
|
323
|
+
if not isinstance(data, dict):
|
|
324
|
+
raise ConfigurationError("extra_body 只能用在正文是对象的接口上")
|
|
325
|
+
cast(Dict[str, Any], data).update(_jsonable(extra_body))
|
|
326
|
+
kw["content"] = json.dumps(data, ensure_ascii=False).encode("utf-8")
|
|
327
|
+
is_json = True
|
|
328
|
+
elif content is not None:
|
|
329
|
+
kw["content"] = content
|
|
330
|
+
if files is not None:
|
|
331
|
+
kw["files"] = files
|
|
332
|
+
h = dict(headers or {})
|
|
333
|
+
if extra_headers:
|
|
334
|
+
h.update(extra_headers)
|
|
335
|
+
kw["headers"] = self._build_headers(h, is_json)
|
|
336
|
+
return kw
|
|
337
|
+
|
|
338
|
+
def _parse(self, resp: httpx.Response, cast_to: Any, unwrap: Optional[str]) -> Any:
|
|
339
|
+
if cast_to is type(None):
|
|
340
|
+
return None
|
|
341
|
+
if cast_to is bytes:
|
|
342
|
+
return resp.content
|
|
343
|
+
if resp.status_code == 204 or not resp.content:
|
|
344
|
+
data: Any = None
|
|
345
|
+
else:
|
|
346
|
+
try:
|
|
347
|
+
data = json.loads(resp.content)
|
|
348
|
+
except ValueError as e:
|
|
349
|
+
raise APIError(resp.status_code, "invalid_json", f"响应不是 JSON:{resp.text[:200]}", response=resp) from e
|
|
350
|
+
if unwrap is not None:
|
|
351
|
+
if not isinstance(data, dict) or unwrap not in data:
|
|
352
|
+
raise APIError(resp.status_code, "invalid_response", f"响应里没有 {unwrap}", response=resp)
|
|
353
|
+
data = cast(Dict[str, Any], data)[unwrap]
|
|
354
|
+
return _validate(cast_to, data)
|
|
355
|
+
|
|
356
|
+
def _stream_params(self, query: Optional[Mapping[str, object]], last_id: Optional[str]) -> Tuple[Dict[str, str], Dict[str, str]]:
|
|
357
|
+
q = _query(query, None)
|
|
358
|
+
h: Dict[str, str] = {"accept": "text/event-stream", "cache-control": "no-cache"}
|
|
359
|
+
if last_id is not None:
|
|
360
|
+
# 服务器先看 ?after=:重连时去掉,用 Last-Event-ID 接着收
|
|
361
|
+
q.pop("after", None)
|
|
362
|
+
q.pop("cursor", None)
|
|
363
|
+
h["last-event-id"] = last_id
|
|
364
|
+
return q, h
|
|
365
|
+
|
|
366
|
+
def __repr__(self) -> str:
|
|
367
|
+
who = f" user={self._user.id!r}" if self._user else ""
|
|
368
|
+
return f"<{type(self).__name__} {self.base_url}{who}>"
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
class SyncAPIClient(_BaseClient):
|
|
372
|
+
_http: httpx.Client
|
|
373
|
+
_owns_http: bool
|
|
374
|
+
|
|
375
|
+
def __init__(self, *, http_client: Optional[httpx.Client] = None, **kw: Any) -> None:
|
|
376
|
+
super().__init__(**kw)
|
|
377
|
+
self._owns_http = http_client is None
|
|
378
|
+
self._http = http_client or httpx.Client(timeout=self.timeout, follow_redirects=True)
|
|
379
|
+
|
|
380
|
+
def close(self) -> None:
|
|
381
|
+
"""关掉连接池(自己建的才关;with_user 出来的客户端不关父客户端的)"""
|
|
382
|
+
if self._owns_http:
|
|
383
|
+
self._http.close()
|
|
384
|
+
|
|
385
|
+
def __enter__(self: _C) -> _C:
|
|
386
|
+
return self
|
|
387
|
+
|
|
388
|
+
def __exit__(self, *exc: object) -> None:
|
|
389
|
+
self.close()
|
|
390
|
+
|
|
391
|
+
def _send(self, method: str, path: str, timeout: Union[TimeoutTypes, NotGiven], stream: bool = False, **kw: Any) -> httpx.Response:
|
|
392
|
+
attempt = 0
|
|
393
|
+
while True:
|
|
394
|
+
req = self._http.build_request(method, self._url(path), timeout=self._timeout(timeout), **kw)
|
|
395
|
+
try:
|
|
396
|
+
resp = self._http.send(req, stream=stream)
|
|
397
|
+
except httpx.TransportError as e:
|
|
398
|
+
if attempt < self.max_retries and _retry_exc(method, e):
|
|
399
|
+
time.sleep(_retry_delay(attempt, None))
|
|
400
|
+
attempt += 1
|
|
401
|
+
continue
|
|
402
|
+
raise _wrap_exc(e, req) from e
|
|
403
|
+
if resp.status_code >= 400:
|
|
404
|
+
if attempt < self.max_retries and _retry_status(method, resp.status_code):
|
|
405
|
+
delay = _retry_delay(attempt, resp)
|
|
406
|
+
resp.close()
|
|
407
|
+
time.sleep(delay)
|
|
408
|
+
attempt += 1
|
|
409
|
+
continue
|
|
410
|
+
try:
|
|
411
|
+
resp.read()
|
|
412
|
+
finally:
|
|
413
|
+
resp.close()
|
|
414
|
+
raise error_from_response(resp)
|
|
415
|
+
return resp
|
|
416
|
+
|
|
417
|
+
def _call(
|
|
418
|
+
self,
|
|
419
|
+
method: str,
|
|
420
|
+
path: str,
|
|
421
|
+
*,
|
|
422
|
+
cast: Type[_T],
|
|
423
|
+
query: Optional[Mapping[str, object]] = None,
|
|
424
|
+
body: object = NOT_GIVEN,
|
|
425
|
+
extra_body: Optional[Mapping[str, object]] = None,
|
|
426
|
+
content: Optional[bytes] = None,
|
|
427
|
+
files: Optional[Mapping[str, Any]] = None,
|
|
428
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
429
|
+
unwrap: Optional[str] = None,
|
|
430
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
431
|
+
extra_query: Optional[Mapping[str, object]] = None,
|
|
432
|
+
timeout: Union[TimeoutTypes, NotGiven] = NOT_GIVEN,
|
|
433
|
+
) -> _T:
|
|
434
|
+
kw = self._prepare(
|
|
435
|
+
method, path, query=query, body=body, extra_body=extra_body, content=content, files=files,
|
|
436
|
+
headers=headers, extra_headers=extra_headers, extra_query=extra_query,
|
|
437
|
+
)
|
|
438
|
+
resp = self._send(method, path, timeout, **kw)
|
|
439
|
+
return self._parse(resp, cast, unwrap)
|
|
440
|
+
|
|
441
|
+
def _call_or_none(self, method: str, path: str, *, cast: Type[_T], **kw: Any) -> Optional[_T]:
|
|
442
|
+
"""404 不算错,返回 None"""
|
|
443
|
+
try:
|
|
444
|
+
return self._call(method, path, cast=cast, **kw)
|
|
445
|
+
except NotFoundError:
|
|
446
|
+
return None
|
|
447
|
+
|
|
448
|
+
def _call_page(
|
|
449
|
+
self,
|
|
450
|
+
method: str,
|
|
451
|
+
path: str,
|
|
452
|
+
*,
|
|
453
|
+
model: Type[_M],
|
|
454
|
+
items: str,
|
|
455
|
+
item: Type[_T],
|
|
456
|
+
query: Optional[Mapping[str, object]] = None,
|
|
457
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
458
|
+
extra_query: Optional[Mapping[str, object]] = None,
|
|
459
|
+
timeout: Union[TimeoutTypes, NotGiven] = NOT_GIVEN,
|
|
460
|
+
) -> CursorPage[_T]:
|
|
461
|
+
base = dict(query or {})
|
|
462
|
+
|
|
463
|
+
def fetch(cursor: Optional[str]) -> CursorPage[_T]:
|
|
464
|
+
q = dict(base)
|
|
465
|
+
if cursor is not None:
|
|
466
|
+
q["cursor"] = cursor
|
|
467
|
+
r = self._call(method, path, cast=model, query=q, extra_headers=extra_headers, extra_query=extra_query, timeout=timeout)
|
|
468
|
+
got = cast(List[_T], list(getattr(r, items) or []))
|
|
469
|
+
return CursorPage(items=got, next_cursor=getattr(r, "next_cursor", None), response=r, cursor=cursor, fetch=fetch)
|
|
470
|
+
|
|
471
|
+
start = base.get("cursor")
|
|
472
|
+
return fetch(start if isinstance(start, str) else None)
|
|
473
|
+
|
|
474
|
+
def _stream(
|
|
475
|
+
self,
|
|
476
|
+
path: str,
|
|
477
|
+
*,
|
|
478
|
+
kind: str,
|
|
479
|
+
query: Optional[Mapping[str, object]] = None,
|
|
480
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
481
|
+
extra_query: Optional[Mapping[str, object]] = None,
|
|
482
|
+
timeout: Union[TimeoutTypes, NotGiven] = NOT_GIVEN,
|
|
483
|
+
) -> EventStream:
|
|
484
|
+
t = self._timeout(timeout)
|
|
485
|
+
# 事件流没有总超时:只有连接超时
|
|
486
|
+
t = httpx.Timeout(t.connect, read=None, write=t.write, pool=t.pool)
|
|
487
|
+
merged = dict(query or {})
|
|
488
|
+
merged.update(extra_query or {})
|
|
489
|
+
|
|
490
|
+
def connect(last_id: Optional[str]) -> httpx.Response:
|
|
491
|
+
q, h = self._stream_params(merged, last_id)
|
|
492
|
+
h.update(extra_headers or {})
|
|
493
|
+
req = self._http.build_request("GET", self._url(path), params=q, headers=self._build_headers(h, False), timeout=t)
|
|
494
|
+
try:
|
|
495
|
+
resp = self._http.send(req, stream=True)
|
|
496
|
+
except httpx.TransportError as e:
|
|
497
|
+
raise _wrap_exc(e, req) from e
|
|
498
|
+
if resp.status_code >= 400:
|
|
499
|
+
try:
|
|
500
|
+
resp.read()
|
|
501
|
+
finally:
|
|
502
|
+
resp.close()
|
|
503
|
+
raise error_from_response(resp)
|
|
504
|
+
return resp
|
|
505
|
+
|
|
506
|
+
return EventStream(connect, kind)
|
|
507
|
+
|
|
508
|
+
def default_workspace(self) -> str:
|
|
509
|
+
"""/me 里第一个工作区的 id(每个客户端只取一次)"""
|
|
510
|
+
if self._ws is None:
|
|
511
|
+
me = self._call("GET", "/me", cast=object)
|
|
512
|
+
self._ws = _first_ws(me)
|
|
513
|
+
return self._ws
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
class AsyncAPIClient(_BaseClient):
|
|
517
|
+
_http: httpx.AsyncClient
|
|
518
|
+
_owns_http: bool
|
|
519
|
+
|
|
520
|
+
def __init__(self, *, http_client: Optional[httpx.AsyncClient] = None, **kw: Any) -> None:
|
|
521
|
+
super().__init__(**kw)
|
|
522
|
+
self._owns_http = http_client is None
|
|
523
|
+
self._http = http_client or httpx.AsyncClient(timeout=self.timeout, follow_redirects=True)
|
|
524
|
+
|
|
525
|
+
async def close(self) -> None:
|
|
526
|
+
if self._owns_http:
|
|
527
|
+
await self._http.aclose()
|
|
528
|
+
|
|
529
|
+
async def __aenter__(self: _C) -> _C:
|
|
530
|
+
return self
|
|
531
|
+
|
|
532
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
533
|
+
await self.close()
|
|
534
|
+
|
|
535
|
+
async def _send(self, method: str, path: str, timeout: Union[TimeoutTypes, NotGiven], stream: bool = False, **kw: Any) -> httpx.Response:
|
|
536
|
+
attempt = 0
|
|
537
|
+
while True:
|
|
538
|
+
req = self._http.build_request(method, self._url(path), timeout=self._timeout(timeout), **kw)
|
|
539
|
+
try:
|
|
540
|
+
resp = await self._http.send(req, stream=stream)
|
|
541
|
+
except httpx.TransportError as e:
|
|
542
|
+
if attempt < self.max_retries and _retry_exc(method, e):
|
|
543
|
+
await asyncio.sleep(_retry_delay(attempt, None))
|
|
544
|
+
attempt += 1
|
|
545
|
+
continue
|
|
546
|
+
raise _wrap_exc(e, req) from e
|
|
547
|
+
if resp.status_code >= 400:
|
|
548
|
+
if attempt < self.max_retries and _retry_status(method, resp.status_code):
|
|
549
|
+
delay = _retry_delay(attempt, resp)
|
|
550
|
+
await resp.aclose()
|
|
551
|
+
await asyncio.sleep(delay)
|
|
552
|
+
attempt += 1
|
|
553
|
+
continue
|
|
554
|
+
try:
|
|
555
|
+
await resp.aread()
|
|
556
|
+
finally:
|
|
557
|
+
await resp.aclose()
|
|
558
|
+
raise error_from_response(resp)
|
|
559
|
+
return resp
|
|
560
|
+
|
|
561
|
+
async def _call(
|
|
562
|
+
self,
|
|
563
|
+
method: str,
|
|
564
|
+
path: str,
|
|
565
|
+
*,
|
|
566
|
+
cast: Type[_T],
|
|
567
|
+
query: Optional[Mapping[str, object]] = None,
|
|
568
|
+
body: object = NOT_GIVEN,
|
|
569
|
+
extra_body: Optional[Mapping[str, object]] = None,
|
|
570
|
+
content: Optional[bytes] = None,
|
|
571
|
+
files: Optional[Mapping[str, Any]] = None,
|
|
572
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
573
|
+
unwrap: Optional[str] = None,
|
|
574
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
575
|
+
extra_query: Optional[Mapping[str, object]] = None,
|
|
576
|
+
timeout: Union[TimeoutTypes, NotGiven] = NOT_GIVEN,
|
|
577
|
+
) -> _T:
|
|
578
|
+
kw = self._prepare(
|
|
579
|
+
method, path, query=query, body=body, extra_body=extra_body, content=content, files=files,
|
|
580
|
+
headers=headers, extra_headers=extra_headers, extra_query=extra_query,
|
|
581
|
+
)
|
|
582
|
+
resp = await self._send(method, path, timeout, **kw)
|
|
583
|
+
return self._parse(resp, cast, unwrap)
|
|
584
|
+
|
|
585
|
+
async def _call_or_none(self, method: str, path: str, *, cast: Type[_T], **kw: Any) -> Optional[_T]:
|
|
586
|
+
try:
|
|
587
|
+
return await self._call(method, path, cast=cast, **kw)
|
|
588
|
+
except NotFoundError:
|
|
589
|
+
return None
|
|
590
|
+
|
|
591
|
+
def _call_page(
|
|
592
|
+
self,
|
|
593
|
+
method: str,
|
|
594
|
+
path: str,
|
|
595
|
+
*,
|
|
596
|
+
model: Type[_M],
|
|
597
|
+
items: str,
|
|
598
|
+
item: Type[_T],
|
|
599
|
+
query: Optional[Mapping[str, object]] = None,
|
|
600
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
601
|
+
extra_query: Optional[Mapping[str, object]] = None,
|
|
602
|
+
timeout: Union[TimeoutTypes, NotGiven] = NOT_GIVEN,
|
|
603
|
+
) -> AsyncPaginator[_T]:
|
|
604
|
+
base = dict(query or {})
|
|
605
|
+
|
|
606
|
+
async def fetch(cursor: Optional[str]) -> AsyncCursorPage[_T]:
|
|
607
|
+
q = dict(base)
|
|
608
|
+
if cursor is not None:
|
|
609
|
+
q["cursor"] = cursor
|
|
610
|
+
r = await self._call(method, path, cast=model, query=q, extra_headers=extra_headers, extra_query=extra_query, timeout=timeout)
|
|
611
|
+
got = cast(List[_T], list(getattr(r, items) or []))
|
|
612
|
+
return AsyncCursorPage(items=got, next_cursor=getattr(r, "next_cursor", None), response=r, cursor=cursor, fetch=fetch)
|
|
613
|
+
|
|
614
|
+
start = base.get("cursor")
|
|
615
|
+
|
|
616
|
+
def first() -> Awaitable[AsyncCursorPage[_T]]:
|
|
617
|
+
return fetch(start if isinstance(start, str) else None)
|
|
618
|
+
|
|
619
|
+
return AsyncPaginator(first)
|
|
620
|
+
|
|
621
|
+
def _stream(
|
|
622
|
+
self,
|
|
623
|
+
path: str,
|
|
624
|
+
*,
|
|
625
|
+
kind: str,
|
|
626
|
+
query: Optional[Mapping[str, object]] = None,
|
|
627
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
628
|
+
extra_query: Optional[Mapping[str, object]] = None,
|
|
629
|
+
timeout: Union[TimeoutTypes, NotGiven] = NOT_GIVEN,
|
|
630
|
+
) -> AsyncEventStream:
|
|
631
|
+
t = self._timeout(timeout)
|
|
632
|
+
t = httpx.Timeout(t.connect, read=None, write=t.write, pool=t.pool)
|
|
633
|
+
merged = dict(query or {})
|
|
634
|
+
merged.update(extra_query or {})
|
|
635
|
+
|
|
636
|
+
async def connect(last_id: Optional[str]) -> httpx.Response:
|
|
637
|
+
q, h = self._stream_params(merged, last_id)
|
|
638
|
+
h.update(extra_headers or {})
|
|
639
|
+
req = self._http.build_request("GET", self._url(path), params=q, headers=self._build_headers(h, False), timeout=t)
|
|
640
|
+
try:
|
|
641
|
+
resp = await self._http.send(req, stream=True)
|
|
642
|
+
except httpx.TransportError as e:
|
|
643
|
+
raise _wrap_exc(e, req) from e
|
|
644
|
+
if resp.status_code >= 400:
|
|
645
|
+
try:
|
|
646
|
+
await resp.aread()
|
|
647
|
+
finally:
|
|
648
|
+
await resp.aclose()
|
|
649
|
+
raise error_from_response(resp)
|
|
650
|
+
return resp
|
|
651
|
+
|
|
652
|
+
return AsyncEventStream(connect, kind)
|
|
653
|
+
|
|
654
|
+
async def default_workspace(self) -> str:
|
|
655
|
+
"""/me 里第一个工作区的 id(每个客户端只取一次)"""
|
|
656
|
+
if self._ws is None:
|
|
657
|
+
me = await self._call("GET", "/me", cast=object)
|
|
658
|
+
self._ws = _first_ws(me)
|
|
659
|
+
return self._ws
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _first_ws(me: Any) -> str:
|
|
663
|
+
try:
|
|
664
|
+
return str(me["workspaces"][0]["id"])
|
|
665
|
+
except (KeyError, IndexError, TypeError):
|
|
666
|
+
raise OADError("这个用户不在任何工作区里(/me 的 workspaces 是空的)") from None
|
|
667
|
+
|