Skip to content

Commit 89d9f9b

Browse files
committed
feat: expose the API's declared error verdict as typed attributes
1 parent 24fadc4 commit 89d9f9b

7 files changed

Lines changed: 209 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
## 0.47.0
2+
3+
### Features
4+
* Expose the verdict the API declares on an error as typed attributes on every HTTP error: `retryable`, `error_type`, `error_reason` and `audience`. Errors the API raises deliberately publish these fields next to `detail`, eg a 503 OCR timeout with `"retryable": false`. Callers no longer need to parse `err.body` to read them. Each attribute is `None` when the body is not JSON, the field is absent, or its value has the wrong type. The retry loop reads `retryable` with the same parser.
5+
16
## 0.46.4
27

38
### Fixes

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,10 @@ with UnstructuredClient(
156156
| `err.body` | `str` | HTTP body. Can be empty string if no body is returned. |
157157
| `err.raw_response` | `httpx.Response` | Raw HTTP response |
158158
| `err.data` | | Optional. Some errors may contain structured data. [See Error Classes](#error-classes). |
159+
| `err.retryable` | `Optional[bool]` | Whether the API declared that sending the same request again can succeed. `None` if it declared nothing. |
160+
| `err.error_type` | `Optional[str]` | The kind of failure the API declared, eg `timeout`. `None` if it declared nothing. |
161+
| `err.error_reason` | `Optional[str]` | A stable name for the failure the API declared. `None` if it declared nothing. |
162+
| `err.audience` | `Optional[str]` | Whose fault the API declared the failure to be, `user` or `platform`. `None` if it declared nothing. |
159163

160164
### Example
161165
```python
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import asyncio
2+
3+
import httpx
4+
import pytest
5+
6+
from unstructured_client import UnstructuredClient
7+
from unstructured_client.models.errors import (
8+
HTTPValidationError,
9+
HTTPValidationErrorData,
10+
SDKError,
11+
ServerError,
12+
ServerErrorData,
13+
)
14+
from unstructured_client.utils import BackoffStrategy, RetryConfig
15+
from unstructured_client.utils.declared_errors import (
16+
DeclaredErrorFields,
17+
parse_declared_error_fields,
18+
)
19+
20+
DECLARED_BODY = {
21+
"detail": "OCR timed out",
22+
"retryable": False,
23+
"error_type": "timeout",
24+
"error_reason": "ocr_timeout",
25+
"audience": "platform",
26+
}
27+
DECLARED_FIELDS = DeclaredErrorFields(
28+
retryable=False, error_type="timeout", error_reason="ocr_timeout", audience="platform"
29+
)
30+
31+
32+
def _response(status_code: int, **kwargs) -> httpx.Response:
33+
return httpx.Response(
34+
status_code,
35+
request=httpx.Request("POST", "http://test.invalid/general/v0/general"),
36+
**kwargs,
37+
)
38+
39+
40+
def _declared(error) -> DeclaredErrorFields:
41+
return DeclaredErrorFields(
42+
retryable=error.retryable,
43+
error_type=error.error_type,
44+
error_reason=error.error_reason,
45+
audience=error.audience,
46+
)
47+
48+
49+
@pytest.mark.parametrize(
50+
"text,expected",
51+
[
52+
('{"detail":"x","retryable":false,"error_type":"timeout",'
53+
'"error_reason":"ocr_timeout","audience":"platform"}', DECLARED_FIELDS),
54+
('{"retryable":true}', DeclaredErrorFields(retryable=True)),
55+
('{"detail":"x","retryable":false,"audience":null}', DeclaredErrorFields(retryable=False)),
56+
('{"detail":"Internal server error"}', DeclaredErrorFields()),
57+
('{"retryable":"false","error_type":5,"error_reason":" ","audience":[]}',
58+
DeclaredErrorFields()),
59+
('{"retryable":0}', DeclaredErrorFields()),
60+
('[{"retryable":false}]', DeclaredErrorFields()),
61+
("false", DeclaredErrorFields()),
62+
("{broken", DeclaredErrorFields()),
63+
("upstream error", DeclaredErrorFields()),
64+
("", DeclaredErrorFields()),
65+
(None, DeclaredErrorFields()),
66+
pytest.param(
67+
'{"retryable":false,"detail":' + "[" * 100_000 + "]" * 100_000 + "}",
68+
DeclaredErrorFields(),
69+
id="deeply-nested",
70+
),
71+
],
72+
)
73+
def test_parse_declared_error_fields(text, expected):
74+
assert parse_declared_error_fields(text) == expected
75+
76+
77+
def test_server_error_exposes_declared_fields():
78+
response = _response(503, json=DECLARED_BODY)
79+
error = ServerError(ServerErrorData(detail="OCR timed out"), response)
80+
81+
assert _declared(error) == DECLARED_FIELDS
82+
assert error.data.detail == "OCR timed out"
83+
84+
85+
def test_sdk_error_exposes_declared_fields():
86+
response = _response(400, json=DECLARED_BODY)
87+
error = SDKError("API error occurred", response, response.text)
88+
89+
assert _declared(error) == DECLARED_FIELDS
90+
91+
92+
def test_http_validation_error_exposes_declared_fields():
93+
response = _response(422, json=DECLARED_BODY)
94+
error = HTTPValidationError(HTTPValidationErrorData(detail="OCR timed out"), response)
95+
96+
assert _declared(error) == DECLARED_FIELDS
97+
98+
99+
def test_explicit_body_takes_precedence_over_response_text():
100+
response = _response(500, json={"detail": "x"})
101+
error = SDKError("API error occurred", response, '{"retryable":false}')
102+
103+
assert error.retryable is False
104+
105+
106+
def test_undeclared_error_reads_none():
107+
response = _response(500, json={"detail": "Internal server error"})
108+
error = ServerError(ServerErrorData(detail="Internal server error"), response)
109+
110+
assert _declared(error) == DeclaredErrorFields()
111+
112+
113+
@pytest.mark.parametrize("async_mode", [False, True])
114+
@pytest.mark.parametrize("status_code,error_class", [(400, SDKError), (503, ServerError)])
115+
def test_public_partition_raises_declared_fields(async_mode, status_code, error_class):
116+
def respond(request):
117+
return httpx.Response(status_code, json=DECLARED_BODY)
118+
119+
async def run():
120+
transport = httpx.MockTransport(respond)
121+
with httpx.Client(transport=transport) as client:
122+
async with httpx.AsyncClient(transport=transport) as async_client:
123+
sdk = UnstructuredClient(
124+
server_url="http://test.invalid", client=client, async_client=async_client
125+
)
126+
request = {"partition_parameters": {
127+
"files": {"content": b"hello", "file_name": "test.txt"},
128+
"split_pdf_page": False,
129+
}}
130+
retries = RetryConfig("none", BackoffStrategy(1, 1, 1.0, 1), False)
131+
with pytest.raises(error_class) as exc:
132+
if async_mode:
133+
await sdk.general.partition_async(request=request, retries=retries)
134+
else:
135+
sdk.general.partition(request=request, retries=retries)
136+
return exc.value
137+
138+
error = asyncio.run(run())
139+
assert _declared(error) == DECLARED_FIELDS

‎src/unstructured_client/_version.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
import importlib.metadata
44

55
__title__: str = "unstructured-client"
6-
__version__: str = "0.46.4"
6+
__version__: str = "0.47.0"
77
__openapi_doc_version__: str = "1.2.31"
88
__gen_version__: str = "2.680.0"
9-
__user_agent__: str = "speakeasy-sdk/python 0.46.4 2.680.0 1.2.31 unstructured-client"
9+
__user_agent__: str = "speakeasy-sdk/python 0.47.0 2.680.0 1.2.31 unstructured-client"
1010

1111
try:
1212
if __package__ is not None:

‎src/unstructured_client/models/errors/unstructuredclienterror.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import httpx
44
from typing import Optional
55

6+
from unstructured_client.utils.declared_errors import parse_declared_error_fields
7+
68

79
class UnstructuredClientError(Exception):
810
"""The base class for all HTTP error responses."""
@@ -12,6 +14,10 @@ class UnstructuredClientError(Exception):
1214
body: str
1315
headers: httpx.Headers
1416
raw_response: httpx.Response
17+
retryable: Optional[bool]
18+
error_type: Optional[str]
19+
error_reason: Optional[str]
20+
audience: Optional[str]
1521

1622
def __init__(
1723
self, message: str, raw_response: httpx.Response, body: Optional[str] = None
@@ -22,5 +28,11 @@ def __init__(
2228
self.headers = raw_response.headers
2329
self.raw_response = raw_response
2430

31+
declared = parse_declared_error_fields(self.body)
32+
self.retryable = declared.retryable
33+
self.error_type = declared.error_type
34+
self.error_reason = declared.error_reason
35+
self.audience = declared.audience
36+
2537
def __str__(self):
2638
return self.message
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""The verdict the Unstructured API declares beside ``detail`` in an error body.
2+
3+
Errors the API raises deliberately carry ``retryable``, ``error_type``,
4+
``error_reason`` and ``audience`` next to ``detail``. Errors it did not classify
5+
carry only ``detail``, and every field reads as ``None``.
6+
"""
7+
8+
import json
9+
from dataclasses import dataclass
10+
from typing import Any, Optional
11+
12+
13+
@dataclass(frozen=True)
14+
class DeclaredErrorFields:
15+
retryable: Optional[bool] = None
16+
error_type: Optional[str] = None
17+
error_reason: Optional[str] = None
18+
audience: Optional[str] = None
19+
20+
21+
def _non_empty_str(value: Any) -> Optional[str]:
22+
return value if isinstance(value, str) and value.strip() else None
23+
24+
25+
def declared_error_fields(body: Any) -> DeclaredErrorFields:
26+
"""Read the declared fields from a decoded body, dropping any of the wrong type."""
27+
if not isinstance(body, dict):
28+
return DeclaredErrorFields()
29+
retryable = body.get("retryable")
30+
return DeclaredErrorFields(
31+
retryable=retryable if isinstance(retryable, bool) else None,
32+
error_type=_non_empty_str(body.get("error_type")),
33+
error_reason=_non_empty_str(body.get("error_reason")),
34+
audience=_non_empty_str(body.get("audience")),
35+
)
36+
37+
38+
def parse_declared_error_fields(text: Optional[str]) -> DeclaredErrorFields:
39+
"""Read the declared fields from a raw body; a non-JSON body declares nothing."""
40+
try:
41+
body = json.loads(text) if text else None
42+
except (ValueError, TypeError, RecursionError):
43+
return DeclaredErrorFields()
44+
return declared_error_fields(body)

‎src/unstructured_client/utils/retries.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
import httpx
99

10+
from unstructured_client.utils.declared_errors import declared_error_fields
11+
1012

1113
class BackoffStrategy:
1214
initial_interval: int
@@ -93,7 +95,7 @@ def _declares_non_retryable(response: httpx.Response) -> bool:
9395
body = response.json()
9496
except (ValueError, RecursionError, httpx.ResponseNotRead):
9597
return False
96-
return isinstance(body, dict) and body.get("retryable") is False
98+
return declared_error_fields(body).retryable is False
9799

98100

99101
def _is_retry_status(response: httpx.Response, status_codes: List[str]) -> bool:

0 commit comments

Comments
 (0)