visionai-sdk-python 2.2.0.dev6__py3-none-any.whl → 2.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.
@@ -1,16 +1,37 @@
1
+ from http import HTTPStatus
2
+ from typing import Any
3
+
1
4
  import httpx
2
5
 
6
+ # The longest `message` text an exception quotes; `APIError.body` keeps all of it.
7
+ _MESSAGE_LIMIT = 200
8
+
3
9
 
4
10
  class VisionaiSDKError(Exception):
5
11
  """Base exception for all SDK errors."""
6
12
 
7
13
 
8
14
  class APIError(VisionaiSDKError):
9
- """Base exception for all HTTP API errors (has status_code)."""
15
+ """Base exception for all HTTP API errors.
16
+
17
+ Attributes:
18
+ status_code: The response's HTTP status.
19
+ code: The error code in the body (e.g. ``postprocess_error``), None without one.
20
+ body: The response's JSON object, None when it is not one.
21
+ """
10
22
 
11
- def __init__(self, status_code: int, message: str) -> None:
23
+ def __init__(
24
+ self,
25
+ status_code: int,
26
+ message: str,
27
+ *,
28
+ code: str | None = None,
29
+ body: dict[str, Any] | None = None,
30
+ ) -> None:
12
31
  self.status_code = status_code
13
- super().__init__(f"[{status_code}] {message}")
32
+ self.code = code
33
+ self.body = body
34
+ super().__init__(f"[{_status_text(status_code)}] {message}")
14
35
 
15
36
 
16
37
  class ClientError(APIError):
@@ -20,22 +41,22 @@ class ClientError(APIError):
20
41
  class AuthenticationError(ClientError):
21
42
  """401 - Invalid credentials/password."""
22
43
 
23
- def __init__(self, message: str) -> None:
24
- super().__init__(401, message)
44
+ def __init__(self, message: str, **kwargs: Any) -> None:
45
+ super().__init__(401, message, **kwargs)
25
46
 
26
47
 
27
48
  class PermissionDeniedError(ClientError):
28
49
  """403 - Insufficient permissions."""
29
50
 
30
- def __init__(self, message: str) -> None:
31
- super().__init__(403, message)
51
+ def __init__(self, message: str, **kwargs: Any) -> None:
52
+ super().__init__(403, message, **kwargs)
32
53
 
33
54
 
34
55
  class RateLimitedError(ClientError):
35
56
  """429 - Too many requests; on client-token, Platform is rate limiting mints."""
36
57
 
37
- def __init__(self, message: str) -> None:
38
- super().__init__(429, message)
58
+ def __init__(self, message: str, **kwargs: Any) -> None:
59
+ super().__init__(429, message, **kwargs)
39
60
 
40
61
 
41
62
  class ServerError(APIError):
@@ -78,20 +99,52 @@ def raise_for_status(response: httpx.Response) -> httpx.Response:
78
99
  body = e.response.json()
79
100
  except Exception:
80
101
  pass
102
+ code = None
81
103
  if isinstance(body, dict):
82
104
  detail: str = body.get("detail") or body.get("message") or str(e)
105
+ # A VS chat result puts the error code in `error`, the relay in `code`.
106
+ # An `errors` list (VS's exceptions, Platform) is not read.
107
+ # TODO: read one shape once the services agree on an error body.
108
+ code = next(
109
+ (v for k in ("error", "code") if isinstance(v := body.get(k), str)),
110
+ None,
111
+ )
112
+ if code:
113
+ detail = _coded_detail(code, body)
83
114
  else:
115
+ body = None
84
116
  detail = str(e)
85
117
  status = e.response.status_code
86
118
  if status == 401:
87
- raise AuthenticationError(detail) from e
119
+ raise AuthenticationError(detail, code=code, body=body) from e
88
120
  if status == 403:
89
- raise PermissionDeniedError(detail) from e
121
+ raise PermissionDeniedError(detail, code=code, body=body) from e
90
122
  if status == 429:
91
- raise RateLimitedError(detail) from e
123
+ raise RateLimitedError(detail, code=code, body=body) from e
92
124
  if 400 <= status < 500:
93
- raise ClientError(status, detail) from e
125
+ raise ClientError(status, detail, code=code, body=body) from e
94
126
  if 500 <= status < 600:
95
- raise ServerError(status, detail) from e
96
- raise APIError(status, detail) from e
127
+ raise ServerError(status, detail, code=code, body=body) from e
128
+ raise APIError(status, detail, code=code, body=body) from e
97
129
  return response
130
+
131
+
132
+ def _status_text(status_code: int) -> str:
133
+ """The status with its standard phrase (400 Bad Request); the number alone without one."""
134
+ try:
135
+ return f"{status_code} {HTTPStatus(status_code).phrase}"
136
+ except ValueError:
137
+ return str(status_code)
138
+
139
+
140
+ def _coded_detail(code: str, body: dict[str, Any]) -> str:
141
+ """The message of an error with a code: the code, then what the body says about it."""
142
+ if body.get("detail"):
143
+ return f"{code}: {body['detail']}"
144
+ if body.get("message"):
145
+ # VS's `message` is the model's output, not a description: quote it, cut short.
146
+ text = str(body["message"])
147
+ if len(text) > _MESSAGE_LIMIT:
148
+ text = f"{text[:_MESSAGE_LIMIT]}..."
149
+ return f"{code} (message={text!r})"
150
+ return code
@@ -8,8 +8,8 @@ should receive the header::
8
8
  allowed_destination_hosts=["vlm-inference-server", "*.svc.cluster.local"],
9
9
  )
10
10
 
11
- Every request through ``requests``, ``httpx`` (sync and async) and ``aiohttp``
12
- then carries ``X-Request-Source`` -- including third-party code, module-level
11
+ Every request through ``requests``, ``httpx``/``httpx2`` (sync and async) and
12
+ ``aiohttp`` then carries ``X-Request-Source`` -- including third-party code, module-level
13
13
  one-shots (``requests.get()``), and clients built before ``instrument()`` ran,
14
14
  since injection patches a request-dispatch method on the class rather than
15
15
  ``__init__``.
@@ -387,12 +387,20 @@ async def _inject_httpx_send_async(
387
387
  return await wrapped(*args, **kwargs)
388
388
 
389
389
 
390
- # (module, attribute path, wrapper). Missing modules are skipped: requests and
391
- # aiohttp are optional extras, httpx is a core dependency.
390
+ # (module, attribute path, wrapper). Missing modules are skipped: requests,
391
+ # aiohttp and httpx2 are optional extras, httpx is a core dependency. httpx2 is
392
+ # the fork Starlette's TestClient prefers from 1.2.0 on, deprecating httpx
393
+ # (https://github.com/Kludex/starlette/pull/3291) -- a separate class
394
+ # hierarchy under its own import name (not a subclass of httpx's), so it needs
395
+ # its own targets, but its redirect loop and _build_redirect_request
396
+ # (extensions passed by reference) match httpx's, so the same wrappers apply
397
+ # unchanged.
392
398
  _TARGETS = (
393
399
  ("requests", "Session.send", _inject_requests_send),
394
400
  ("httpx", "Client._send_single_request", _inject_httpx_send),
395
401
  ("httpx", "AsyncClient._send_single_request", _inject_httpx_send_async),
402
+ ("httpx2", "Client._send_single_request", _inject_httpx_send),
403
+ ("httpx2", "AsyncClient._send_single_request", _inject_httpx_send_async),
396
404
  ("aiohttp", "ClientRequest.__init__", _inject_aiohttp_request),
397
405
  )
398
406
 
@@ -1,7 +1,8 @@
1
1
  """The platform-relay wire protocol, shared by platform-relay and platform-edge-agent.
2
2
 
3
- Internal to the platform; the spec is platform-service's
4
- ``docs/adr/0001-relay-protocol.md``. See :mod:`.protocol`.
3
+ Internal to the platform. The wire format is specified in ``docs/relay-protocol.md``
4
+ of this repository; platform-service's ``docs/adr/0001-relay-protocol.md`` records the
5
+ decisions around it. See :mod:`.protocol`.
5
6
  """
6
7
 
7
8
  from .protocol import (
@@ -1,4 +1,4 @@
1
- """The ADR's JSON examples, shipped so every implementation tests against the same frames.
1
+ """The wire-format spec's JSON examples, shipped so every implementation tests against the same frames.
2
2
 
3
3
  ``example("register")`` is the parsed object, ``example_text("register")`` the wire text.
4
4
  """
@@ -19,7 +19,7 @@ NAMES = (
19
19
 
20
20
 
21
21
  def example_text(name: str) -> str:
22
- """One ADR example as the text that goes over the wire."""
22
+ """One spec example as the text that goes over the wire."""
23
23
  return (files(__package__) / f"{name}.json").read_text(encoding="utf-8")
24
24
 
25
25
 
@@ -1,7 +1,7 @@
1
1
  """Wire format between platform-relay and platform-edge-agent.
2
2
 
3
- The spec is platform-service's ``docs/adr/0001-relay-protocol.md``; this module is
4
- the one implementation both sides import. Frames are JSON objects told apart by
3
+ The spec is ``docs/relay-protocol.md`` in this repository (the decisions behind it:
4
+ platform-service's ADR 0001); this module is the one implementation both sides import. Frames are JSON objects told apart by
5
5
  ``type``. Receivers ignore unknown fields, and the string-typed ``reason`` /
6
6
  ``code`` fields accept values they do not know, so either side can be upgraded
7
7
  first.
@@ -71,8 +71,7 @@ class Frame(BaseModel):
71
71
  class ModelEntry(Frame):
72
72
  name: str
73
73
  version: str
74
- # Required by the ADR. A receiver counts None as 0 and logs it: the sender has a bug.
75
- replicas: int | None = Field(default=None, ge=0)
74
+ replicas: int = Field(ge=0)
76
75
 
77
76
 
78
77
  class WorkspaceEntry(Frame):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: visionai-sdk-python
3
- Version: 2.2.0.dev6
3
+ Version: 2.3.0
4
4
  Summary: VisionAI SDK for Python
5
5
  Author-email: Tony Yang <tonyyang@linkervision.com>
6
6
  Requires-Python: >=3.11
@@ -13,6 +13,8 @@ Provides-Extra: requests
13
13
  Requires-Dist: requests<3,>=2.31; extra == "requests"
14
14
  Provides-Extra: aiohttp
15
15
  Requires-Dist: aiohttp<4,>=3.9; extra == "aiohttp"
16
+ Provides-Extra: httpx2
17
+ Requires-Dist: httpx2<3,>=2.13; extra == "httpx2"
16
18
  Provides-Extra: instrumentation
17
19
  Requires-Dist: wrapt<3,>=1.16; extra == "instrumentation"
18
20
 
@@ -43,6 +45,7 @@ Attributing direct `requests`/`aiohttp` calls, or using `instrumentation.instrum
43
45
  ```bash
44
46
  pip install visionai-sdk-python[requests]
45
47
  pip install visionai-sdk-python[aiohttp]
48
+ pip install visionai-sdk-python[httpx2]
46
49
  pip install visionai-sdk-python[instrumentation] # needed for instrument() itself
47
50
  ```
48
51
 
@@ -177,11 +180,13 @@ authentication wins. `vlm_url` is optional for clients that only authenticate.
177
180
  `visionai_sdk_python.relay` holds the wire format between platform-relay and
178
181
  platform-edge-agent: the frame models, the constants and `parse_agent_frame()` /
179
182
  `parse_relay_frame()` (text frames only: `bytes` or `None` is an `InvalidFrame`) /
180
- `dump_frame()` (which refuses a frame over `MAX_FRAME_BYTES`). The spec is platform-service's
181
- `docs/adr/0001-relay-protocol.md`; both sides import this module instead of keeping a
182
- copy. The ADR's JSON examples ship with it (`visionai_sdk_python.relay.examples`:
183
- `example(name)` / `example_text(name)`), so every implementation tests against the same
184
- frames. It is internal to the platform and not a public API.
183
+ `dump_frame()` (which refuses a frame over `MAX_FRAME_BYTES`). The spec is
184
+ [`docs/relay-protocol.md`](docs/relay-protocol.md); both sides import this module instead of
185
+ keeping a copy, and a protocol change edits the spec and the module in one PR. The spec's
186
+ JSON examples ship with it (`visionai_sdk_python.relay.examples`: `example(name)` /
187
+ `example_text(name)`), so every implementation tests against the same frames. The decisions
188
+ behind the protocol are platform-service's `docs/adr/0001-relay-protocol.md`. It is internal
189
+ to the platform and not a public API.
185
190
 
186
191
  ## VLM Inference
187
192
 
@@ -338,6 +343,25 @@ except VisionaiSDKError as e:
338
343
  - `NetworkError`: Connection/timeout errors
339
344
  - `JwksDiscoveryError`: OIDC discovery failures
340
345
 
346
+ Every HTTP error (`ClientError`, `ServerError` and their subclasses) carries
347
+ `status_code`, `code` and `body`; `body` is the whole JSON body. `code` is set for two
348
+ bodies only: a VS chat result (its `error`) and the relay's own errors (their `code`).
349
+ It is `None` for every other body, including the ones that list their errors under
350
+ `errors` (VS's `invalid_credentials` or `workspace_mismatch`, Platform's errors): read
351
+ `body` there. Where `code` is set, branch on it, not on the message text:
352
+
353
+ ```python
354
+ try:
355
+ result = client.vlm.chat(request)
356
+ except ClientError as e:
357
+ # [400 Bad Request] postprocess_error (message='Yes')
358
+ if e.code == "postprocess_error":
359
+ raw_output = e.body["message"]
360
+ ```
361
+
362
+ VS answers a failed chat with 200 and `status: "failed"` (read `result.error`), except
363
+ `postprocess_error` (400) and a timeout (408), which raise `ClientError`.
364
+
341
365
  ## Context Manager Usage
342
366
 
343
367
  Recommended for automatic resource cleanup:
@@ -422,7 +446,10 @@ instrumentation.instrument(
422
446
  ```
423
447
 
424
448
  This wraps a request-dispatch method of `requests.Session`, `httpx.Client`/
425
- `AsyncClient` and `aiohttp.ClientSession` in place, so it also covers calls made
449
+ `AsyncClient`, `httpx2.Client`/`AsyncClient` (the httpx fork Starlette prefers
450
+ from 1.2.0 on, see
451
+ [Kludex/starlette#3291](https://github.com/Kludex/starlette/pull/3291)) and
452
+ `aiohttp.ClientSession` in place, so it also covers calls made
426
453
  by third-party packages you cannot edit, module-level one-shots like
427
454
  `requests.get()`, and requests sent through a client instance that already
428
455
  existed before `instrument()` ran (see "Call it any time" below).
@@ -434,6 +461,7 @@ it patches are separately optional, and whichever is not installed is skipped:
434
461
  pip install visionai-sdk-python[instrumentation]
435
462
  pip install visionai-sdk-python[requests] # httpx is already a core dependency
436
463
  pip install visionai-sdk-python[aiohttp]
464
+ pip install visionai-sdk-python[httpx2]
437
465
  ```
438
466
 
439
467
  ### Destination scoping
@@ -7,8 +7,8 @@ visionai_sdk_python/async_client.py,sha256=03iWCg_MIxentqT8dZJw4YSnZUp4-ZRli_I8v
7
7
  visionai_sdk_python/client.py,sha256=oKRVrHVxHkN5IrfkLJBRpXPEv158_zs7Q2T6ujTr-gE,6272
8
8
  visionai_sdk_python/constants.py,sha256=KWhoxZdlwqXwhUJDqERStq2mrms-MA8aRDqBwbIvNO0,1471
9
9
  visionai_sdk_python/endpoints.py,sha256=CC-AoxXzg39sMAhqx1CTS3gRWKx_H7VOqBANRLVotoU,183
10
- visionai_sdk_python/exceptions.py,sha256=BUpcoTgILc3z68lIQGyTYs7PCvu_BTSi228YMTx7ZWs,3020
11
- visionai_sdk_python/instrumentation.py,sha256=tTTL5Op0fZULpmoOKW8dw8-2ReOQUEpMvHrf-R5C_yg,24512
10
+ visionai_sdk_python/exceptions.py,sha256=NljiRMEHEE2UUl5Ye8aaYdzb86uZNx5tj73hFqcC080,5062
11
+ visionai_sdk_python/instrumentation.py,sha256=K2HV290TwO9a-wqltp7hrmJU77mgW_hnPsrA08ApFdY,25069
12
12
  visionai_sdk_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
13
  visionai_sdk_python/auth/__init__.py,sha256=sWtanqUos5Q8P80IvjoyvOzXv6gYNkflop9qwDwsZk8,400
14
14
  visionai_sdk_python/auth/_mixin.py,sha256=EDDhEB9jHc_7wEoLx_MprhToTVLekL5CyJuLTK8GhNM,5022
@@ -16,9 +16,9 @@ visionai_sdk_python/auth/async_resource.py,sha256=V6O51i7KyYSBkiQeKAbmw-EIKMVZIo
16
16
  visionai_sdk_python/auth/credentials.py,sha256=hxigy3hB09lWqmhhcw_QFqYVD-8fHIyvupZYowCIycw,13360
17
17
  visionai_sdk_python/auth/models.py,sha256=u6MDFYaWMyf08XCrGZzwPHv43d6AElH9XO2QSjRsb3Q,449
18
18
  visionai_sdk_python/auth/resource.py,sha256=3PgcxH8N6unKTs2jSQhMeJT_lg6bTce0hz0bzuID12U,5446
19
- visionai_sdk_python/relay/__init__.py,sha256=yqYdedHUBCo-E9wmVY9Xfa5r9zbOLeii-p6HYTdgzvY,1384
20
- visionai_sdk_python/relay/protocol.py,sha256=8KvMActRq2iwk8XF94v0Ze3VFAAl6-fAb64BJUDKL7I,7128
21
- visionai_sdk_python/relay/examples/__init__.py,sha256=GvjlP-EtrhDVgqReOYqcf1mObND61vO6Q8CT_YFfgDM,732
19
+ visionai_sdk_python/relay/__init__.py,sha256=Z6iJ_Cd-VQVWAF5Tpr_N4oYl13V8eRyp-r22siXz3Uc,1483
20
+ visionai_sdk_python/relay/protocol.py,sha256=LljyVBx9WA4vd-zDKERAkZ7hB8jh7emcZCMULx4n-2U,7063
21
+ visionai_sdk_python/relay/examples/__init__.py,sha256=g3N3XGIUPE8iDGxb0DD4cPm6dt56o9z6Rqnf9PjRBIs,746
22
22
  visionai_sdk_python/relay/examples/error_connection.json,sha256=stjkXo27Vkhoy0rNtPUti2OEXzioxJ8Aqgyq2hAdquA,81
23
23
  visionai_sdk_python/relay/examples/error_request.json,sha256=iUB11sSf1vuBAdzvoiHAoUoifZoG4-wGBK6gb0ConjA,228
24
24
  visionai_sdk_python/relay/examples/heartbeat.json,sha256=CZKMBTkVxtLzY05bQW7AkCULJAIu-7RUVjgc7hTgg9I,22
@@ -33,7 +33,7 @@ visionai_sdk_python/vlm/async_resource.py,sha256=meMUfBDa0g1hk7vFZq2fDuIQ1-QUpU0
33
33
  visionai_sdk_python/vlm/models.py,sha256=yDFjo4LfAxqXYBnl6ZW7YUJQoKKRkQWtqBJi2ruI6Jw,984
34
34
  visionai_sdk_python/vlm/preprocess.py,sha256=ZpJJa13h8_YKwh_P7Pn8WIXV0x-r2xJi-ETgCFsGw-Y,7892
35
35
  visionai_sdk_python/vlm/resource.py,sha256=4eMQ4ACcgd7nUfdRyADWmPd8yZ--uqQC4zwzBft68lg,3386
36
- visionai_sdk_python-2.2.0.dev6.dist-info/METADATA,sha256=gPr3oj2wON5pearcb_fq_-FGNQ6fL7oOup3f0tLX9jM,31131
37
- visionai_sdk_python-2.2.0.dev6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
38
- visionai_sdk_python-2.2.0.dev6.dist-info/top_level.txt,sha256=79a5MCSLLv6Mbfun-8RS-G6O927hahBwDqJjeuWLdvM,20
39
- visionai_sdk_python-2.2.0.dev6.dist-info/RECORD,,
36
+ visionai_sdk_python-2.3.0.dist-info/METADATA,sha256=6Z-HzJBJNOBZuwOsFXKJizY7o1yWKAnyeFxWxFj4Z5E,32465
37
+ visionai_sdk_python-2.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
38
+ visionai_sdk_python-2.3.0.dist-info/top_level.txt,sha256=79a5MCSLLv6Mbfun-8RS-G6O927hahBwDqJjeuWLdvM,20
39
+ visionai_sdk_python-2.3.0.dist-info/RECORD,,