visionai-sdk-python 2.2.0.dev7__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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: visionai-sdk-python
3
- Version: 2.2.0.dev7
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
 
@@ -340,6 +343,25 @@ except VisionaiSDKError as e:
340
343
  - `NetworkError`: Connection/timeout errors
341
344
  - `JwksDiscoveryError`: OIDC discovery failures
342
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
+
343
365
  ## Context Manager Usage
344
366
 
345
367
  Recommended for automatic resource cleanup:
@@ -424,7 +446,10 @@ instrumentation.instrument(
424
446
  ```
425
447
 
426
448
  This wraps a request-dispatch method of `requests.Session`, `httpx.Client`/
427
- `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
428
453
  by third-party packages you cannot edit, module-level one-shots like
429
454
  `requests.get()`, and requests sent through a client instance that already
430
455
  existed before `instrument()` ran (see "Call it any time" below).
@@ -436,6 +461,7 @@ it patches are separately optional, and whichever is not installed is skipped:
436
461
  pip install visionai-sdk-python[instrumentation]
437
462
  pip install visionai-sdk-python[requests] # httpx is already a core dependency
438
463
  pip install visionai-sdk-python[aiohttp]
464
+ pip install visionai-sdk-python[httpx2]
439
465
  ```
440
466
 
441
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
@@ -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.dev7.dist-info/METADATA,sha256=5d969v2YO3Lk-1KEAPZyrmpzgdFNaus8ad16fay-6so,31285
37
- visionai_sdk_python-2.2.0.dev7.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
38
- visionai_sdk_python-2.2.0.dev7.dist-info/top_level.txt,sha256=79a5MCSLLv6Mbfun-8RS-G6O927hahBwDqJjeuWLdvM,20
39
- visionai_sdk_python-2.2.0.dev7.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,,