lexapi-client 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.
- lexapi/__init__.py +132 -0
- lexapi/_base.py +122 -0
- lexapi/_meta.py +14 -0
- lexapi/_payloads.py +160 -0
- lexapi/_response.py +158 -0
- lexapi/_retry.py +148 -0
- lexapi/async_client.py +417 -0
- lexapi/citations.py +231 -0
- lexapi/client.py +491 -0
- lexapi/errors.py +261 -0
- lexapi/export.py +253 -0
- lexapi/models.py +1253 -0
- lexapi/py.typed +0 -0
- lexapi/webhooks.py +220 -0
- lexapi_client-0.1.0.dist-info/METADATA +310 -0
- lexapi_client-0.1.0.dist-info/RECORD +17 -0
- lexapi_client-0.1.0.dist-info/WHEEL +4 -0
lexapi/__init__.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Official Python SDK for LexAPI (https://lex-api.com)."""
|
|
2
|
+
|
|
3
|
+
from lexapi._meta import __version__
|
|
4
|
+
from lexapi._response import APIResponse, CreditsInfo, UsageInfo
|
|
5
|
+
from lexapi._retry import RetryConfig
|
|
6
|
+
from lexapi.async_client import AsyncLexAPI
|
|
7
|
+
from lexapi.client import LexAPI
|
|
8
|
+
from lexapi.errors import (
|
|
9
|
+
AuthenticationError,
|
|
10
|
+
CreditsExhaustedError,
|
|
11
|
+
InternalServerError,
|
|
12
|
+
InvalidCelexError,
|
|
13
|
+
InvalidParamsError,
|
|
14
|
+
InvalidURLError,
|
|
15
|
+
LexAPIConnectionError,
|
|
16
|
+
LexAPIError,
|
|
17
|
+
NotFoundError,
|
|
18
|
+
RateLimitedError,
|
|
19
|
+
RequestTimeoutError,
|
|
20
|
+
TierForbiddenError,
|
|
21
|
+
TimeoutError,
|
|
22
|
+
UpstreamError,
|
|
23
|
+
)
|
|
24
|
+
from lexapi.export import AsyncExportStream, ExportStream
|
|
25
|
+
from lexapi.models import (
|
|
26
|
+
Article,
|
|
27
|
+
BatchDocumentError,
|
|
28
|
+
CitationDocumentGroup,
|
|
29
|
+
CitationEdge,
|
|
30
|
+
CitationExtractResponse,
|
|
31
|
+
CitationNeighbour,
|
|
32
|
+
CitationNetworkResponse,
|
|
33
|
+
CitationPathNode,
|
|
34
|
+
CitationPathResponse,
|
|
35
|
+
CitationStatsEntry,
|
|
36
|
+
CitationStatsResponse,
|
|
37
|
+
CitedByResponse,
|
|
38
|
+
CitesResponse,
|
|
39
|
+
Document,
|
|
40
|
+
DocumentBatchResponse,
|
|
41
|
+
DocumentByUrlResponse,
|
|
42
|
+
DocumentContent,
|
|
43
|
+
DocumentMetadataResponse,
|
|
44
|
+
DocumentResponse,
|
|
45
|
+
DocumentVersionResponse,
|
|
46
|
+
DocumentVersionsResponse,
|
|
47
|
+
RecentDocumentsResponse,
|
|
48
|
+
Recital,
|
|
49
|
+
RelatedDocument,
|
|
50
|
+
RelatedDocumentsResponse,
|
|
51
|
+
ResolveResponse,
|
|
52
|
+
SearchHit,
|
|
53
|
+
SearchResponse,
|
|
54
|
+
Section,
|
|
55
|
+
SemanticCaseLawResult,
|
|
56
|
+
SemanticLegislationResponse,
|
|
57
|
+
SemanticLegislationResult,
|
|
58
|
+
SemanticSearchResponse,
|
|
59
|
+
VersionEntry,
|
|
60
|
+
Webhook,
|
|
61
|
+
WebhookDeliveriesResponse,
|
|
62
|
+
WebhookDelivery,
|
|
63
|
+
WebhookListResponse,
|
|
64
|
+
WebhookResponse,
|
|
65
|
+
WebhookTestResponse,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
__all__ = [
|
|
69
|
+
"APIResponse",
|
|
70
|
+
"Article",
|
|
71
|
+
"AsyncExportStream",
|
|
72
|
+
"AsyncLexAPI",
|
|
73
|
+
"AuthenticationError",
|
|
74
|
+
"BatchDocumentError",
|
|
75
|
+
"CitationDocumentGroup",
|
|
76
|
+
"CitationEdge",
|
|
77
|
+
"CitationExtractResponse",
|
|
78
|
+
"CitationNeighbour",
|
|
79
|
+
"CitationNetworkResponse",
|
|
80
|
+
"CitationPathNode",
|
|
81
|
+
"CitationPathResponse",
|
|
82
|
+
"CitationStatsEntry",
|
|
83
|
+
"CitationStatsResponse",
|
|
84
|
+
"CitedByResponse",
|
|
85
|
+
"CitesResponse",
|
|
86
|
+
"CreditsExhaustedError",
|
|
87
|
+
"CreditsInfo",
|
|
88
|
+
"Document",
|
|
89
|
+
"DocumentBatchResponse",
|
|
90
|
+
"DocumentByUrlResponse",
|
|
91
|
+
"DocumentContent",
|
|
92
|
+
"DocumentMetadataResponse",
|
|
93
|
+
"DocumentResponse",
|
|
94
|
+
"DocumentVersionResponse",
|
|
95
|
+
"DocumentVersionsResponse",
|
|
96
|
+
"ExportStream",
|
|
97
|
+
"InternalServerError",
|
|
98
|
+
"InvalidCelexError",
|
|
99
|
+
"InvalidParamsError",
|
|
100
|
+
"InvalidURLError",
|
|
101
|
+
"LexAPI",
|
|
102
|
+
"LexAPIConnectionError",
|
|
103
|
+
"LexAPIError",
|
|
104
|
+
"NotFoundError",
|
|
105
|
+
"RateLimitedError",
|
|
106
|
+
"RecentDocumentsResponse",
|
|
107
|
+
"Recital",
|
|
108
|
+
"RelatedDocument",
|
|
109
|
+
"RelatedDocumentsResponse",
|
|
110
|
+
"RequestTimeoutError",
|
|
111
|
+
"ResolveResponse",
|
|
112
|
+
"RetryConfig",
|
|
113
|
+
"SearchHit",
|
|
114
|
+
"SearchResponse",
|
|
115
|
+
"Section",
|
|
116
|
+
"SemanticCaseLawResult",
|
|
117
|
+
"SemanticLegislationResponse",
|
|
118
|
+
"SemanticLegislationResult",
|
|
119
|
+
"SemanticSearchResponse",
|
|
120
|
+
"TierForbiddenError",
|
|
121
|
+
"TimeoutError",
|
|
122
|
+
"UpstreamError",
|
|
123
|
+
"UsageInfo",
|
|
124
|
+
"Webhook",
|
|
125
|
+
"WebhookDeliveriesResponse",
|
|
126
|
+
"WebhookDelivery",
|
|
127
|
+
"WebhookListResponse",
|
|
128
|
+
"WebhookResponse",
|
|
129
|
+
"WebhookTestResponse",
|
|
130
|
+
"VersionEntry",
|
|
131
|
+
"__version__",
|
|
132
|
+
]
|
lexapi/_base.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Request core shared by the sync and async clients.
|
|
2
|
+
|
|
3
|
+
Everything here is transport-agnostic: header construction, response
|
|
4
|
+
parsing, error mapping, and retry decisions. The sync/async clients only
|
|
5
|
+
differ in how they send the request and how they sleep.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
from typing import Any, TypeVar
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from lexapi._meta import user_agent
|
|
16
|
+
from lexapi._response import APIResponse
|
|
17
|
+
from lexapi._retry import (
|
|
18
|
+
DEFAULT_RETRY_CONFIG,
|
|
19
|
+
RetryConfig,
|
|
20
|
+
compute_backoff,
|
|
21
|
+
is_retryable_exception,
|
|
22
|
+
retry_wait,
|
|
23
|
+
server_wait_hint,
|
|
24
|
+
)
|
|
25
|
+
from lexapi.errors import (
|
|
26
|
+
LexAPIConnectionError,
|
|
27
|
+
RequestTimeoutError,
|
|
28
|
+
error_from_response,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
DEFAULT_BASE_URL = "https://lex-api.com/api/v1"
|
|
32
|
+
|
|
33
|
+
R = TypeVar("R", bound=APIResponse)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def resolve_api_key(api_key: str | None) -> str:
|
|
37
|
+
key = api_key or os.environ.get("LEXAPI_API_KEY")
|
|
38
|
+
if not key:
|
|
39
|
+
raise ValueError("api_key is required (or set LEXAPI_API_KEY)")
|
|
40
|
+
return key
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def build_httpx_kwargs(
|
|
44
|
+
api_key: str | None,
|
|
45
|
+
base_url: str,
|
|
46
|
+
timeout: float | httpx.Timeout,
|
|
47
|
+
connect_timeout: float,
|
|
48
|
+
user_agent_suffix: str | None,
|
|
49
|
+
) -> dict[str, Any]:
|
|
50
|
+
"""Keyword arguments shared by ``httpx.Client`` and ``httpx.AsyncClient``."""
|
|
51
|
+
if isinstance(timeout, httpx.Timeout):
|
|
52
|
+
resolved_timeout = timeout
|
|
53
|
+
else:
|
|
54
|
+
resolved_timeout = httpx.Timeout(timeout, connect=connect_timeout)
|
|
55
|
+
return {
|
|
56
|
+
"base_url": base_url.rstrip("/"),
|
|
57
|
+
"timeout": resolved_timeout,
|
|
58
|
+
"headers": {
|
|
59
|
+
"x-api-key": resolve_api_key(api_key),
|
|
60
|
+
"user-agent": user_agent(user_agent_suffix),
|
|
61
|
+
"accept": "application/json",
|
|
62
|
+
},
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def decode_body(response: httpx.Response) -> Any:
|
|
67
|
+
"""Decode the JSON body, tolerating empty (204) and non-JSON bodies."""
|
|
68
|
+
if response.status_code == 204 or not response.content:
|
|
69
|
+
return {}
|
|
70
|
+
try:
|
|
71
|
+
return response.json()
|
|
72
|
+
except ValueError:
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def process_response(
|
|
77
|
+
response: httpx.Response, cast: type[R] = APIResponse # type: ignore[assignment]
|
|
78
|
+
) -> R:
|
|
79
|
+
"""Wrap a successful response, or raise the typed error for a failed one."""
|
|
80
|
+
body = decode_body(response)
|
|
81
|
+
if response.is_success:
|
|
82
|
+
return cast(body if body is not None else {}, response.headers)
|
|
83
|
+
raise error_from_response(
|
|
84
|
+
response.status_code,
|
|
85
|
+
body,
|
|
86
|
+
retry_after=server_wait_hint(response.headers, body),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def status_retry_wait(
|
|
91
|
+
method: str, response: httpx.Response, attempt: int, config: RetryConfig
|
|
92
|
+
) -> float | None:
|
|
93
|
+
"""Wait before retrying a non-2xx response, or ``None`` for "don't"."""
|
|
94
|
+
if response.is_success:
|
|
95
|
+
return None
|
|
96
|
+
return retry_wait(method, response, decode_body(response), attempt, config)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def exception_retry_wait(
|
|
100
|
+
exc: httpx.HTTPError, attempt: int, config: RetryConfig
|
|
101
|
+
) -> float | None:
|
|
102
|
+
"""Wait before retrying a transport failure, or ``None`` for "don't"."""
|
|
103
|
+
if attempt >= config.max_retries or not is_retryable_exception(exc):
|
|
104
|
+
return None
|
|
105
|
+
return compute_backoff(attempt, config)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def transport_error(exc: httpx.HTTPError) -> LexAPIConnectionError:
|
|
109
|
+
"""Map an httpx transport failure to the SDK's typed connection errors."""
|
|
110
|
+
if isinstance(exc, httpx.TimeoutException):
|
|
111
|
+
return RequestTimeoutError(f"Request timed out: {exc}")
|
|
112
|
+
return LexAPIConnectionError(f"Connection error: {exc}")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def make_retry_config(
|
|
116
|
+
max_retries: int | None, retry_config: RetryConfig | None
|
|
117
|
+
) -> RetryConfig:
|
|
118
|
+
if retry_config is not None:
|
|
119
|
+
return retry_config
|
|
120
|
+
if max_retries is None:
|
|
121
|
+
return DEFAULT_RETRY_CONFIG
|
|
122
|
+
return RetryConfig(max_retries=max_retries)
|
lexapi/_meta.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Package version and User-Agent construction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
|
|
7
|
+
_BASE_USER_AGENT = f"lexapi-python/{__version__}"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def user_agent(suffix: str | None = None) -> str:
|
|
11
|
+
"""Build the ``User-Agent`` header value, optionally with a caller suffix."""
|
|
12
|
+
if suffix:
|
|
13
|
+
return f"{_BASE_USER_AGENT} {suffix}"
|
|
14
|
+
return _BASE_USER_AGENT
|
lexapi/_payloads.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Request body / query-param builders shared by the sync and async clients.
|
|
2
|
+
|
|
3
|
+
``None`` values are always omitted so the server's own defaults apply and
|
|
4
|
+
older deployments never see parameters they don't know.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, Union
|
|
10
|
+
|
|
11
|
+
# Filters that accept a single value or a list (the API accepts both).
|
|
12
|
+
OneOrMany = Union[str, "list[str]"]
|
|
13
|
+
IntOrMany = Union[int, "list[int]"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def drop_none(mapping: dict[str, Any]) -> dict[str, Any]:
|
|
17
|
+
return {key: value for key, value in mapping.items() if value is not None}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def search_body(
|
|
21
|
+
query: str | None = None,
|
|
22
|
+
*,
|
|
23
|
+
text_scope: str | None = None,
|
|
24
|
+
date_from: str | None = None,
|
|
25
|
+
date_to: str | None = None,
|
|
26
|
+
year: IntOrMany | None = None,
|
|
27
|
+
month: IntOrMany | None = None,
|
|
28
|
+
document_type: OneOrMany | None = None,
|
|
29
|
+
author: OneOrMany | None = None,
|
|
30
|
+
procedure: OneOrMany | None = None,
|
|
31
|
+
domain: str | None = None,
|
|
32
|
+
subdomain: OneOrMany | None = None,
|
|
33
|
+
language: str | None = None,
|
|
34
|
+
max_pages: int | None = None,
|
|
35
|
+
) -> dict[str, Any]:
|
|
36
|
+
return drop_none(
|
|
37
|
+
{
|
|
38
|
+
"query": query,
|
|
39
|
+
"textScope": text_scope,
|
|
40
|
+
"dateFrom": date_from,
|
|
41
|
+
"dateTo": date_to,
|
|
42
|
+
"year": year,
|
|
43
|
+
"month": month,
|
|
44
|
+
"documentType": document_type,
|
|
45
|
+
"author": author,
|
|
46
|
+
"procedure": procedure,
|
|
47
|
+
"domain": domain,
|
|
48
|
+
"subdomain": subdomain,
|
|
49
|
+
"language": language,
|
|
50
|
+
"maxPages": max_pages,
|
|
51
|
+
}
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def document_content_body(
|
|
56
|
+
celex: str,
|
|
57
|
+
*,
|
|
58
|
+
bypass_corpus: bool | None = None,
|
|
59
|
+
language: str | None = None,
|
|
60
|
+
include: OneOrMany | None = None,
|
|
61
|
+
fields: OneOrMany | None = None,
|
|
62
|
+
article_id: str | None = None,
|
|
63
|
+
) -> dict[str, Any]:
|
|
64
|
+
return drop_none(
|
|
65
|
+
{
|
|
66
|
+
"celexNumber": celex,
|
|
67
|
+
"bypassCorpus": bypass_corpus,
|
|
68
|
+
"language": language,
|
|
69
|
+
"include": include,
|
|
70
|
+
"fields": fields,
|
|
71
|
+
"articleId": article_id,
|
|
72
|
+
}
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def document_batch_body(
|
|
77
|
+
celexes: list[str],
|
|
78
|
+
*,
|
|
79
|
+
bypass_corpus: bool | None = None,
|
|
80
|
+
language: str | None = None,
|
|
81
|
+
include: OneOrMany | None = None,
|
|
82
|
+
fields: OneOrMany | None = None,
|
|
83
|
+
article_id: str | None = None,
|
|
84
|
+
) -> dict[str, Any]:
|
|
85
|
+
return drop_none(
|
|
86
|
+
{
|
|
87
|
+
"celexNumbers": list(celexes),
|
|
88
|
+
"bypassCorpus": bypass_corpus,
|
|
89
|
+
"language": language,
|
|
90
|
+
"include": include,
|
|
91
|
+
"fields": fields,
|
|
92
|
+
"articleId": article_id,
|
|
93
|
+
}
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def document_by_url_body(
|
|
98
|
+
url: str,
|
|
99
|
+
*,
|
|
100
|
+
include: OneOrMany | None = None,
|
|
101
|
+
fields: OneOrMany | None = None,
|
|
102
|
+
article_id: str | None = None,
|
|
103
|
+
) -> dict[str, Any]:
|
|
104
|
+
return drop_none(
|
|
105
|
+
{"url": url, "include": include, "fields": fields, "articleId": article_id}
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def semantic_search_body(
|
|
110
|
+
query: str,
|
|
111
|
+
*,
|
|
112
|
+
hyde: bool = False,
|
|
113
|
+
min_score: float | None = None,
|
|
114
|
+
limit: int | None = None,
|
|
115
|
+
language: str | None = None,
|
|
116
|
+
include_text: bool = False,
|
|
117
|
+
filters: dict | None = None,
|
|
118
|
+
) -> dict[str, Any]:
|
|
119
|
+
"""Body for the semantic endpoints.
|
|
120
|
+
|
|
121
|
+
``hyde`` is only sent when True (additive param — older deployments
|
|
122
|
+
never see it); ``include_text=True`` maps to ``include: ["text"]``.
|
|
123
|
+
"""
|
|
124
|
+
body = drop_none(
|
|
125
|
+
{
|
|
126
|
+
"query": query,
|
|
127
|
+
"min_score": min_score,
|
|
128
|
+
"limit": limit,
|
|
129
|
+
"language": language,
|
|
130
|
+
"filters": filters,
|
|
131
|
+
}
|
|
132
|
+
)
|
|
133
|
+
if hyde:
|
|
134
|
+
body["hyde"] = True
|
|
135
|
+
if include_text:
|
|
136
|
+
body["include"] = ["text"]
|
|
137
|
+
return body
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def recent_documents_params(
|
|
141
|
+
*,
|
|
142
|
+
days: int | None = None,
|
|
143
|
+
document_type: str | None = None,
|
|
144
|
+
author: str | None = None,
|
|
145
|
+
domain: str | None = None,
|
|
146
|
+
subdomain: str | None = None,
|
|
147
|
+
language: str | None = None,
|
|
148
|
+
limit: int | None = None,
|
|
149
|
+
) -> dict[str, Any]:
|
|
150
|
+
return drop_none(
|
|
151
|
+
{
|
|
152
|
+
"days": days,
|
|
153
|
+
"documentType": document_type,
|
|
154
|
+
"author": author,
|
|
155
|
+
"domain": domain,
|
|
156
|
+
"subdomain": subdomain,
|
|
157
|
+
"language": language,
|
|
158
|
+
"limit": limit,
|
|
159
|
+
}
|
|
160
|
+
)
|
lexapi/_response.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Response wrapper with credit-visibility helpers (SDK contract §1.5).
|
|
2
|
+
|
|
3
|
+
Every successful call returns an :class:`APIResponse` (or a typed subclass).
|
|
4
|
+
It behaves like a read-only mapping over the raw JSON body — existing
|
|
5
|
+
``response["key"]`` code keeps working — and additionally exposes:
|
|
6
|
+
|
|
7
|
+
- ``credits`` — the pricing-v2 credit-pool block, typed (``None`` on legacy
|
|
8
|
+
daily-call accounts, which omit it)
|
|
9
|
+
- ``usage`` — the dual-mode usage block, typed
|
|
10
|
+
- ``units_charged`` — credits this request cost (``credits.operation_weight``;
|
|
11
|
+
0 for free operations such as ``/info`` and for legacy accounts)
|
|
12
|
+
- ``credits_remaining`` — ``credits.remaining`` falling back to ``usage.remaining``
|
|
13
|
+
- ``resets_at`` — when the quota window resets (ISO-8601 string)
|
|
14
|
+
- ``warning`` — the ``X-Warning`` response header, when present
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from collections.abc import Iterator, Mapping
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _opt_int(value: Any) -> int | None:
|
|
27
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
28
|
+
return None
|
|
29
|
+
return int(value)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class CreditsInfo:
|
|
34
|
+
"""Pricing-v2 credit-pool state (the response ``credits`` block)."""
|
|
35
|
+
|
|
36
|
+
operation_weight: int | None = None
|
|
37
|
+
current: int | None = None
|
|
38
|
+
limit: int | None = None
|
|
39
|
+
remaining: int | None = None
|
|
40
|
+
included: int | None = None
|
|
41
|
+
topup: int | None = None
|
|
42
|
+
resets_at: str | None = None
|
|
43
|
+
raw: dict = field(default_factory=dict)
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def from_dict(cls, data: Any) -> CreditsInfo | None:
|
|
47
|
+
if not isinstance(data, dict):
|
|
48
|
+
return None
|
|
49
|
+
return cls(
|
|
50
|
+
operation_weight=_opt_int(data.get("operation_weight")),
|
|
51
|
+
current=_opt_int(data.get("current")),
|
|
52
|
+
limit=_opt_int(data.get("limit")),
|
|
53
|
+
remaining=_opt_int(data.get("remaining")),
|
|
54
|
+
included=_opt_int(data.get("included")),
|
|
55
|
+
topup=_opt_int(data.get("topup")),
|
|
56
|
+
resets_at=data.get("resetsAt") if isinstance(data.get("resetsAt"), str) else None,
|
|
57
|
+
raw=data,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class UsageInfo:
|
|
63
|
+
"""Dual-mode usage counters (credits for v2 accounts, calls for legacy)."""
|
|
64
|
+
|
|
65
|
+
current: int | None = None
|
|
66
|
+
limit: int | None = None
|
|
67
|
+
remaining: int | None = None
|
|
68
|
+
unit: str | None = None
|
|
69
|
+
resets_at: str | None = None
|
|
70
|
+
raw: dict = field(default_factory=dict)
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_dict(cls, data: Any) -> UsageInfo | None:
|
|
74
|
+
if not isinstance(data, dict):
|
|
75
|
+
return None
|
|
76
|
+
return cls(
|
|
77
|
+
current=_opt_int(data.get("current")),
|
|
78
|
+
limit=_opt_int(data.get("limit")),
|
|
79
|
+
remaining=_opt_int(data.get("remaining")),
|
|
80
|
+
unit=data.get("unit") if isinstance(data.get("unit"), str) else None,
|
|
81
|
+
resets_at=data.get("resetsAt") if isinstance(data.get("resetsAt"), str) else None,
|
|
82
|
+
raw=data,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class APIResponse(Mapping):
|
|
87
|
+
"""Read-only mapping over the raw JSON body, plus typed helpers.
|
|
88
|
+
|
|
89
|
+
The raw body stays fully accessible (``response["usage"]``,
|
|
90
|
+
``response.data``) so no information is lost by the typed layer.
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(self, data: Any, headers: httpx.Headers | None = None) -> None:
|
|
94
|
+
self.data: Any = data
|
|
95
|
+
self._map: dict = data if isinstance(data, dict) else {}
|
|
96
|
+
self.headers: httpx.Headers = headers if headers is not None else httpx.Headers()
|
|
97
|
+
|
|
98
|
+
# -- Mapping protocol -------------------------------------------------
|
|
99
|
+
def __getitem__(self, key: str) -> Any:
|
|
100
|
+
return self._map[key]
|
|
101
|
+
|
|
102
|
+
def __iter__(self) -> Iterator[str]:
|
|
103
|
+
return iter(self._map)
|
|
104
|
+
|
|
105
|
+
def __len__(self) -> int:
|
|
106
|
+
return len(self._map)
|
|
107
|
+
|
|
108
|
+
def __repr__(self) -> str: # pragma: no cover - debug convenience
|
|
109
|
+
return f"{type(self).__name__}({self._map!r})"
|
|
110
|
+
|
|
111
|
+
# -- credit visibility (SDK contract §1.5) ----------------------------
|
|
112
|
+
@property
|
|
113
|
+
def credits(self) -> CreditsInfo | None:
|
|
114
|
+
"""The pricing-v2 ``credits`` block; ``None`` on legacy accounts."""
|
|
115
|
+
return CreditsInfo.from_dict(self._map.get("credits"))
|
|
116
|
+
|
|
117
|
+
@property
|
|
118
|
+
def usage(self) -> UsageInfo | None:
|
|
119
|
+
"""The dual-mode ``usage`` block; ``None`` when absent."""
|
|
120
|
+
return UsageInfo.from_dict(self._map.get("usage"))
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def units_charged(self) -> int:
|
|
124
|
+
"""Credits this request cost (0 for free ops and legacy accounts)."""
|
|
125
|
+
credits = self.credits
|
|
126
|
+
if credits is not None and credits.operation_weight is not None:
|
|
127
|
+
return credits.operation_weight
|
|
128
|
+
return 0
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def credits_remaining(self) -> int | None:
|
|
132
|
+
"""``credits.remaining``, falling back to ``usage.remaining``."""
|
|
133
|
+
credits = self.credits
|
|
134
|
+
if credits is not None and credits.remaining is not None:
|
|
135
|
+
return credits.remaining
|
|
136
|
+
usage = self.usage
|
|
137
|
+
return usage.remaining if usage is not None else None
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def resets_at(self) -> str | None:
|
|
141
|
+
"""When the quota window resets (ISO-8601), from credits or usage."""
|
|
142
|
+
credits = self.credits
|
|
143
|
+
if credits is not None and credits.resets_at is not None:
|
|
144
|
+
return credits.resets_at
|
|
145
|
+
usage = self.usage
|
|
146
|
+
return usage.resets_at if usage is not None else None
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def subscription(self) -> dict | None:
|
|
150
|
+
"""The raw ``subscription`` block, when present."""
|
|
151
|
+
value = self._map.get("subscription")
|
|
152
|
+
return value if isinstance(value, dict) else None
|
|
153
|
+
|
|
154
|
+
# -- header-borne signals ---------------------------------------------
|
|
155
|
+
@property
|
|
156
|
+
def warning(self) -> str | None:
|
|
157
|
+
"""The ``X-Warning`` header (tier clamping and similar), if any."""
|
|
158
|
+
return self.headers.get("x-warning")
|