talonic 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.
- talonic/__init__.py +35 -0
- talonic/__main__.py +6 -0
- talonic/_config.py +45 -0
- talonic/_http.py +307 -0
- talonic/_models/__init__.py +4 -0
- talonic/_models/models.py +18263 -0
- talonic/_types/__init__.py +1 -0
- talonic/_types/cost.py +60 -0
- talonic/_types/extract_input.py +66 -0
- talonic/_types/rate_limit.py +59 -0
- talonic/_version.py +1 -0
- talonic/cli.py +191 -0
- talonic/client.py +325 -0
- talonic/errors.py +92 -0
- talonic/py.typed +0 -0
- talonic/resources/__init__.py +0 -0
- talonic/resources/_base.py +14 -0
- talonic/resources/credits.py +24 -0
- talonic/resources/documents.py +217 -0
- talonic/resources/extractions.py +157 -0
- talonic/resources/fields.py +79 -0
- talonic/resources/jobs.py +105 -0
- talonic/resources/pricing.py +31 -0
- talonic/resources/schemas.py +121 -0
- talonic/resources/usage.py +35 -0
- talonic-0.1.0.dist-info/METADATA +213 -0
- talonic-0.1.0.dist-info/RECORD +30 -0
- talonic-0.1.0.dist-info/WHEEL +4 -0
- talonic-0.1.0.dist-info/entry_points.txt +2 -0
- talonic-0.1.0.dist-info/licenses/LICENSE +21 -0
talonic/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Official Talonic SDK for Python."""
|
|
2
|
+
|
|
3
|
+
from talonic._types.cost import CostInfo
|
|
4
|
+
from talonic._types.extract_input import ExtractInputError
|
|
5
|
+
from talonic._types.rate_limit import RateLimitInfo, WithRateLimit
|
|
6
|
+
from talonic._version import __version__
|
|
7
|
+
from talonic.client import AsyncTalonic, Talonic
|
|
8
|
+
from talonic.errors import (
|
|
9
|
+
TalonicAuthError,
|
|
10
|
+
TalonicError,
|
|
11
|
+
TalonicNetworkError,
|
|
12
|
+
TalonicNotFoundError,
|
|
13
|
+
TalonicRateLimitError,
|
|
14
|
+
TalonicServerError,
|
|
15
|
+
TalonicTimeoutError,
|
|
16
|
+
TalonicValidationError,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"__version__",
|
|
21
|
+
"AsyncTalonic",
|
|
22
|
+
"Talonic",
|
|
23
|
+
"CostInfo",
|
|
24
|
+
"RateLimitInfo",
|
|
25
|
+
"WithRateLimit",
|
|
26
|
+
"ExtractInputError",
|
|
27
|
+
"TalonicAuthError",
|
|
28
|
+
"TalonicError",
|
|
29
|
+
"TalonicNetworkError",
|
|
30
|
+
"TalonicNotFoundError",
|
|
31
|
+
"TalonicRateLimitError",
|
|
32
|
+
"TalonicServerError",
|
|
33
|
+
"TalonicTimeoutError",
|
|
34
|
+
"TalonicValidationError",
|
|
35
|
+
]
|
talonic/__main__.py
ADDED
talonic/_config.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""TalonicConfig: client construction options with env-driven defaults."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from talonic.errors import TalonicValidationError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class TalonicConfig:
|
|
14
|
+
"""Configuration for a Talonic / AsyncTalonic client.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
api_key: Talonic API key (starts with "tlnc_"). Falls back to $TALONIC_API_KEY.
|
|
18
|
+
base_url: API base URL. Falls back to $TALONIC_BASE_URL, then "https://api.talonic.com".
|
|
19
|
+
timeout: Per-request timeout in seconds. Default 60.
|
|
20
|
+
max_retries: Retries on 429/500-504/network/timeout. Default 3.
|
|
21
|
+
transport: Optional httpx transport for testing (e.g. httpx.MockTransport).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
api_key: str | None = None
|
|
25
|
+
base_url: str | None = None
|
|
26
|
+
timeout: float = 60.0
|
|
27
|
+
max_retries: int = 3
|
|
28
|
+
transport: Any = None # httpx.BaseTransport | httpx.AsyncBaseTransport | None
|
|
29
|
+
|
|
30
|
+
def __post_init__(self) -> None:
|
|
31
|
+
# API key: explicit > env > error.
|
|
32
|
+
if not self.api_key:
|
|
33
|
+
env_key = os.environ.get("TALONIC_API_KEY", "").strip()
|
|
34
|
+
if not env_key:
|
|
35
|
+
raise TalonicValidationError(
|
|
36
|
+
message="TALONIC_API_KEY is required (pass api_key=... or set the env var).",
|
|
37
|
+
code="MISSING_API_KEY",
|
|
38
|
+
)
|
|
39
|
+
self.api_key = env_key
|
|
40
|
+
|
|
41
|
+
# Base URL: explicit > env > default. Strip trailing slashes.
|
|
42
|
+
if not self.base_url:
|
|
43
|
+
self.base_url = os.environ.get("TALONIC_BASE_URL", "https://api.talonic.com")
|
|
44
|
+
assert self.base_url is not None
|
|
45
|
+
self.base_url = self.base_url.rstrip("/")
|
talonic/_http.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""HTTP transport for the Talonic SDK.
|
|
2
|
+
|
|
3
|
+
BaseTransport holds pure, side-effect-free helpers shared between
|
|
4
|
+
SyncTransport (Task 11) and AsyncTransport (Task 12): header building,
|
|
5
|
+
retry-decision logic, exponential backoff with jitter, header parsing.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import json as _json_module
|
|
12
|
+
import random
|
|
13
|
+
import time
|
|
14
|
+
from typing import Any, cast
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
from talonic._config import TalonicConfig
|
|
19
|
+
from talonic._types.cost import parse_cost
|
|
20
|
+
from talonic._types.rate_limit import WithRateLimit, parse_rate_limit
|
|
21
|
+
from talonic._version import __version__
|
|
22
|
+
from talonic.errors import (
|
|
23
|
+
TalonicError,
|
|
24
|
+
TalonicNetworkError,
|
|
25
|
+
TalonicRateLimitError,
|
|
26
|
+
TalonicTimeoutError,
|
|
27
|
+
classify_http_error,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
_USER_AGENT = f"talonic-python/{__version__} httpx/{httpx.__version__}"
|
|
31
|
+
_BACKOFF_CAP_SECONDS = 16.0
|
|
32
|
+
_BACKOFF_BASE_SECONDS = 0.5
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class BaseTransport:
|
|
36
|
+
"""Pure helpers shared between sync + async transports.
|
|
37
|
+
|
|
38
|
+
Subclasses provide the actual `request()` method that does I/O.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, config: TalonicConfig) -> None:
|
|
42
|
+
self._config = config
|
|
43
|
+
|
|
44
|
+
def _build_headers(self) -> dict[str, str]:
|
|
45
|
+
return {
|
|
46
|
+
"Authorization": f"Bearer {self._config.api_key}",
|
|
47
|
+
"User-Agent": _USER_AGENT,
|
|
48
|
+
"Accept": "application/json",
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
def _should_retry_status(self, status: int, body: dict[str, Any] | None) -> bool:
|
|
52
|
+
"""Status alone says retryable; but the API can opt out with `retryable: false`."""
|
|
53
|
+
if body is not None:
|
|
54
|
+
nested = body.get("error")
|
|
55
|
+
flag = nested.get("retryable") if isinstance(nested, dict) else body.get("retryable")
|
|
56
|
+
if flag is False:
|
|
57
|
+
return False
|
|
58
|
+
return status == 429 or 500 <= status <= 504
|
|
59
|
+
|
|
60
|
+
def _should_retry_attempt(self, attempt: int) -> bool:
|
|
61
|
+
"""Attempt 0 is the first request; we retry up to max_retries times."""
|
|
62
|
+
return attempt < self._config.max_retries
|
|
63
|
+
|
|
64
|
+
def _backoff_delay(self, attempt: int) -> float:
|
|
65
|
+
"""Exponential backoff with full jitter, capped at _BACKOFF_CAP_SECONDS."""
|
|
66
|
+
ceiling = min(_BACKOFF_BASE_SECONDS * (2**attempt), _BACKOFF_CAP_SECONDS)
|
|
67
|
+
return random.uniform(0, ceiling)
|
|
68
|
+
|
|
69
|
+
def _retry_after_seconds(self, headers: httpx.Headers) -> float | None:
|
|
70
|
+
"""Parse `Retry-After` header as seconds.
|
|
71
|
+
|
|
72
|
+
Integer form only; HTTP-date parsing not implemented in v0.1.
|
|
73
|
+
"""
|
|
74
|
+
raw = headers.get("Retry-After")
|
|
75
|
+
if raw is None:
|
|
76
|
+
return None
|
|
77
|
+
try:
|
|
78
|
+
return float(raw)
|
|
79
|
+
except ValueError:
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _json_object(response: httpx.Response) -> dict[str, Any]:
|
|
84
|
+
"""Decode a response body as a JSON object; anything else yields an empty dict."""
|
|
85
|
+
try:
|
|
86
|
+
body = response.json()
|
|
87
|
+
except ValueError:
|
|
88
|
+
return {}
|
|
89
|
+
return body if isinstance(body, dict) else {}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _parse_success(response: httpx.Response) -> Any: # noqa: ANN401
|
|
93
|
+
"""Decode a 2xx body: JSON when the API sends JSON, raw text otherwise (e.g. CSV)."""
|
|
94
|
+
if not response.content:
|
|
95
|
+
return {}
|
|
96
|
+
content_type = response.headers.get("content-type", "").lower()
|
|
97
|
+
if content_type.startswith("text/"):
|
|
98
|
+
return response.text
|
|
99
|
+
try:
|
|
100
|
+
return response.json()
|
|
101
|
+
except ValueError:
|
|
102
|
+
return response.text
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _build_error(response: httpx.Response) -> TalonicError:
|
|
106
|
+
"""Map an HTTP response to the right TalonicError subclass.
|
|
107
|
+
|
|
108
|
+
Understands the flat production shape (`{code, message, request_id, ...}`),
|
|
109
|
+
the nested reference shape (`{error: {code, message, ...}}`) and the
|
|
110
|
+
endpoint-level shape (`{error: "missing_document", message: "..."}`).
|
|
111
|
+
"""
|
|
112
|
+
body = _json_object(response)
|
|
113
|
+
nested = body.get("error")
|
|
114
|
+
source: dict[str, Any] = nested if isinstance(nested, dict) else body
|
|
115
|
+
|
|
116
|
+
raw_message = source.get("message")
|
|
117
|
+
if isinstance(raw_message, list):
|
|
118
|
+
message = "; ".join(str(m) for m in raw_message)
|
|
119
|
+
elif isinstance(raw_message, str) and raw_message:
|
|
120
|
+
message = raw_message
|
|
121
|
+
else:
|
|
122
|
+
message = response.text or response.reason_phrase or f"HTTP {response.status_code}"
|
|
123
|
+
|
|
124
|
+
raw_code = source.get("code")
|
|
125
|
+
if isinstance(raw_code, str) and raw_code:
|
|
126
|
+
code = raw_code
|
|
127
|
+
elif isinstance(nested, str):
|
|
128
|
+
code = nested
|
|
129
|
+
else:
|
|
130
|
+
code = ""
|
|
131
|
+
|
|
132
|
+
request_id = (
|
|
133
|
+
source.get("request_id") or body.get("request_id") or response.headers.get("x-request-id")
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
cls = classify_http_error(response.status_code)
|
|
137
|
+
kwargs: dict[str, Any] = {
|
|
138
|
+
"message": message,
|
|
139
|
+
"status": response.status_code,
|
|
140
|
+
"code": code,
|
|
141
|
+
"request_id": request_id if isinstance(request_id, str) else None,
|
|
142
|
+
}
|
|
143
|
+
if cls is TalonicRateLimitError:
|
|
144
|
+
kwargs["rate_limit"] = parse_rate_limit(response.headers)
|
|
145
|
+
return cls(**kwargs)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class SyncTransport(BaseTransport):
|
|
149
|
+
"""Sync HTTP transport built on httpx.Client."""
|
|
150
|
+
|
|
151
|
+
def __init__(self, config: TalonicConfig) -> None:
|
|
152
|
+
super().__init__(config)
|
|
153
|
+
self._client = httpx.Client(
|
|
154
|
+
base_url=config.base_url or "",
|
|
155
|
+
timeout=config.timeout,
|
|
156
|
+
headers=self._build_headers(),
|
|
157
|
+
transport=config.transport,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def __enter__(self) -> SyncTransport:
|
|
161
|
+
return self
|
|
162
|
+
|
|
163
|
+
def __exit__(self, *exc: object) -> None:
|
|
164
|
+
self.close()
|
|
165
|
+
|
|
166
|
+
def close(self) -> None:
|
|
167
|
+
self._client.close()
|
|
168
|
+
|
|
169
|
+
def request(
|
|
170
|
+
self,
|
|
171
|
+
method: str,
|
|
172
|
+
path: str,
|
|
173
|
+
*,
|
|
174
|
+
params: dict[str, Any] | None = None,
|
|
175
|
+
json: dict[str, Any] | None = None,
|
|
176
|
+
files: Any = None, # noqa: ANN401 — httpx multipart: mapping or list of tuples
|
|
177
|
+
data: dict[str, Any] | None = None,
|
|
178
|
+
) -> WithRateLimit[Any]:
|
|
179
|
+
# Serialize JSON manually so we control formatting (spaces after separators).
|
|
180
|
+
content: bytes | None = None
|
|
181
|
+
extra_headers: dict[str, str] = {}
|
|
182
|
+
if json is not None:
|
|
183
|
+
content = _json_module.dumps(json).encode()
|
|
184
|
+
extra_headers["Content-Type"] = "application/json"
|
|
185
|
+
attempt = 0
|
|
186
|
+
last_exc: TalonicError | None = None
|
|
187
|
+
while True:
|
|
188
|
+
try:
|
|
189
|
+
response = self._client.request(
|
|
190
|
+
method,
|
|
191
|
+
path,
|
|
192
|
+
params=params,
|
|
193
|
+
content=content,
|
|
194
|
+
files=files,
|
|
195
|
+
data=data,
|
|
196
|
+
headers=extra_headers if extra_headers else None,
|
|
197
|
+
)
|
|
198
|
+
except httpx.TimeoutException as exc:
|
|
199
|
+
last_exc = TalonicTimeoutError(message=str(exc), code="TIMEOUT")
|
|
200
|
+
except httpx.NetworkError as exc:
|
|
201
|
+
last_exc = TalonicNetworkError(message=str(exc), code="NETWORK")
|
|
202
|
+
else:
|
|
203
|
+
if response.status_code < 400:
|
|
204
|
+
return WithRateLimit(
|
|
205
|
+
data=_parse_success(response),
|
|
206
|
+
rate_limit=parse_rate_limit(response.headers),
|
|
207
|
+
cost=parse_cost(response.headers),
|
|
208
|
+
)
|
|
209
|
+
body = _json_object(response)
|
|
210
|
+
if self._should_retry_status(
|
|
211
|
+
response.status_code, body
|
|
212
|
+
) and self._should_retry_attempt(attempt):
|
|
213
|
+
delay = self._retry_after_seconds(response.headers) or self._backoff_delay(
|
|
214
|
+
attempt
|
|
215
|
+
)
|
|
216
|
+
time.sleep(delay)
|
|
217
|
+
attempt += 1
|
|
218
|
+
continue
|
|
219
|
+
raise _build_error(response)
|
|
220
|
+
|
|
221
|
+
# Network/timeout fall-through:
|
|
222
|
+
if self._should_retry_attempt(attempt):
|
|
223
|
+
time.sleep(self._backoff_delay(attempt))
|
|
224
|
+
attempt += 1
|
|
225
|
+
continue
|
|
226
|
+
raise cast(TalonicError, last_exc)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class AsyncTransport(BaseTransport):
|
|
230
|
+
"""Async HTTP transport built on httpx.AsyncClient. Mirrors SyncTransport semantics exactly."""
|
|
231
|
+
|
|
232
|
+
def __init__(self, config: TalonicConfig) -> None:
|
|
233
|
+
super().__init__(config)
|
|
234
|
+
self._client = httpx.AsyncClient(
|
|
235
|
+
base_url=config.base_url or "",
|
|
236
|
+
timeout=config.timeout,
|
|
237
|
+
headers=self._build_headers(),
|
|
238
|
+
transport=config.transport,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
async def __aenter__(self) -> AsyncTransport:
|
|
242
|
+
return self
|
|
243
|
+
|
|
244
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
245
|
+
await self.aclose()
|
|
246
|
+
|
|
247
|
+
async def aclose(self) -> None:
|
|
248
|
+
await self._client.aclose()
|
|
249
|
+
|
|
250
|
+
async def request(
|
|
251
|
+
self,
|
|
252
|
+
method: str,
|
|
253
|
+
path: str,
|
|
254
|
+
*,
|
|
255
|
+
params: dict[str, Any] | None = None,
|
|
256
|
+
json: dict[str, Any] | None = None,
|
|
257
|
+
files: Any = None, # noqa: ANN401 — httpx multipart: mapping or list of tuples
|
|
258
|
+
data: dict[str, Any] | None = None,
|
|
259
|
+
) -> WithRateLimit[Any]:
|
|
260
|
+
# Serialize JSON manually so we control formatting (spaces after separators).
|
|
261
|
+
content: bytes | None = None
|
|
262
|
+
extra_headers: dict[str, str] = {}
|
|
263
|
+
if json is not None:
|
|
264
|
+
content = _json_module.dumps(json).encode()
|
|
265
|
+
extra_headers["Content-Type"] = "application/json"
|
|
266
|
+
attempt = 0
|
|
267
|
+
last_exc: TalonicError | None = None
|
|
268
|
+
while True:
|
|
269
|
+
try:
|
|
270
|
+
response = await self._client.request(
|
|
271
|
+
method,
|
|
272
|
+
path,
|
|
273
|
+
params=params,
|
|
274
|
+
content=content,
|
|
275
|
+
files=files,
|
|
276
|
+
data=data,
|
|
277
|
+
headers=extra_headers if extra_headers else None,
|
|
278
|
+
)
|
|
279
|
+
except httpx.TimeoutException as exc:
|
|
280
|
+
last_exc = TalonicTimeoutError(message=str(exc), code="TIMEOUT")
|
|
281
|
+
except httpx.NetworkError as exc:
|
|
282
|
+
last_exc = TalonicNetworkError(message=str(exc), code="NETWORK")
|
|
283
|
+
else:
|
|
284
|
+
if response.status_code < 400:
|
|
285
|
+
return WithRateLimit(
|
|
286
|
+
data=_parse_success(response),
|
|
287
|
+
rate_limit=parse_rate_limit(response.headers),
|
|
288
|
+
cost=parse_cost(response.headers),
|
|
289
|
+
)
|
|
290
|
+
body = _json_object(response)
|
|
291
|
+
if self._should_retry_status(
|
|
292
|
+
response.status_code, body
|
|
293
|
+
) and self._should_retry_attempt(attempt):
|
|
294
|
+
delay = self._retry_after_seconds(response.headers) or self._backoff_delay(
|
|
295
|
+
attempt
|
|
296
|
+
)
|
|
297
|
+
await asyncio.sleep(delay)
|
|
298
|
+
attempt += 1
|
|
299
|
+
continue
|
|
300
|
+
raise _build_error(response)
|
|
301
|
+
|
|
302
|
+
# Network/timeout fall-through:
|
|
303
|
+
if self._should_retry_attempt(attempt):
|
|
304
|
+
await asyncio.sleep(self._backoff_delay(attempt))
|
|
305
|
+
attempt += 1
|
|
306
|
+
continue
|
|
307
|
+
raise cast(TalonicError, last_exc)
|