datalab-python-sdk 0.11.0__tar.gz → 0.12.0__tar.gz

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.
Files changed (63) hide show
  1. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/CHANGELOG.md +32 -0
  2. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/PKG-INFO +3 -3
  3. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/README.md +2 -2
  4. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/datalab_sdk/client.py +154 -76
  5. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/datalab_sdk/models.py +19 -2
  6. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/pyproject.toml +1 -1
  7. datalab_python_sdk-0.12.0/tests/test_results.py +329 -0
  8. datalab_python_sdk-0.12.0/tests/test_streaming_retries.py +557 -0
  9. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/uv.lock +1 -1
  10. datalab_python_sdk-0.11.0/tests/test_results.py +0 -153
  11. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/.github/workflows/ci.yml +0 -0
  12. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/.gitignore +0 -0
  13. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/.pre-commit-config.yaml +0 -0
  14. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/.python-version +0 -0
  15. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/LICENSE +0 -0
  16. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/08-Lambda-Calculus.pptx +0 -0
  17. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/adversarial.pdf +0 -0
  18. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/bid_evaluation.docx +0 -0
  19. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/book_review.ppt +0 -0
  20. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/book_store.xls +0 -0
  21. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/chi_hind.png +0 -0
  22. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/how_to_read.doc +0 -0
  23. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/normandy.epub +0 -0
  24. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/sample-1-sheet.xlsx +0 -0
  25. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/thinkpython.pdf +0 -0
  26. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/data/vibe.html +0 -0
  27. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/datalab_sdk/__init__.py +0 -0
  28. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/datalab_sdk/auth.py +0 -0
  29. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/datalab_sdk/cli.py +0 -0
  30. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/datalab_sdk/exceptions.py +0 -0
  31. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/datalab_sdk/mimetypes.py +0 -0
  32. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/datalab_sdk/settings.py +0 -0
  33. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/integration/README.md +0 -0
  34. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/integration/__init__.py +0 -0
  35. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/integration/test_live_api.py +0 -0
  36. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/integration/test_readme_examples.py +0 -0
  37. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/pytest.ini +0 -0
  38. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/README.md +0 -0
  39. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/end_to_end_workflow.py +0 -0
  40. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_api_tutorial/1_get_step_types.py +0 -0
  41. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_api_tutorial/2_get_workflows.py +0 -0
  42. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_api_tutorial/3_create_workflow.py +0 -0
  43. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_api_tutorial/4_execute_workflow.py +0 -0
  44. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_api_tutorial/5_poll_workflow.py +0 -0
  45. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_api_tutorial/README.md +0 -0
  46. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_definitions/README.md +0 -0
  47. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_definitions/eval_segmentation.json +0 -0
  48. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_definitions/parse_segment.json +0 -0
  49. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_definitions/segment_parallel_extract.json +0 -0
  50. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/recipes/workflows/workflow_definitions/slack_alert.json +0 -0
  51. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/__init__.py +0 -0
  52. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/conftest.py +0 -0
  53. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_api_consistency.py +0 -0
  54. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_cli_options.py +0 -0
  55. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_cli_simple.py +0 -0
  56. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_client_methods.py +0 -0
  57. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_comparisons.py +0 -0
  58. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_device_login.py +0 -0
  59. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_errors.py +0 -0
  60. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_new_endpoints.py +0 -0
  61. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_progress.py +0 -0
  62. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_transport_audit.py +0 -0
  63. {datalab_python_sdk-0.11.0 → datalab_python_sdk-0.12.0}/tests/test_workflows.py +0 -0
@@ -3,6 +3,38 @@
3
3
  The newest release is at the top. Each export to this repository uses the
4
4
  top section as its commit message.
5
5
 
6
+ ## 0.12.0
7
+
8
+ New:
9
+
10
+ - `FileResult`, the result of a call with `stream_response_to`, now has
11
+ `request_id`, `page_count`, `parse_quality_score`, `versions`, `runtime`,
12
+ and `cost_breakdown`. They come from the poll response and are `None` when
13
+ it does not send them; `request_id` falls back to the submit response. For
14
+ a result from a signed `result_url`, the poll response has no `versions`,
15
+ and `runtime` or cost can be unset on an early poll. The saved file can
16
+ contain `versions` and `runtime`.
17
+
18
+ Fixed:
19
+
20
+ - With `stream_response_to`, a result from a signed `result_url` (for example
21
+ with `processing_location`) lost the cost, page count and quality score,
22
+ because the download does not contain them. `FileResult` now returns them
23
+ from the poll response. The download is still copied to disk without
24
+ parsing.
25
+ - With `stream_response_to`, a connection that dropped while the result
26
+ streamed ended the call without a retry. The SDK now retries the poll as it
27
+ does for other poll errors; it does not submit the document again. An error
28
+ response whose body is cut off or stalls keeps its HTTP status, so a 404
29
+ still fails at once.
30
+ - With `stream_response_to`, a timeout while the result streamed surfaced as
31
+ a raw `asyncio.CancelledError`. It now raises `DatalabTimeoutError`. As
32
+ before, it is not retried: `timeout` limits the whole request, so a result
33
+ too large to transfer within it would time out again.
34
+ - Without `stream_response_to`, a failed download of a signed `result_url` is
35
+ now retried on a connection error or HTTP 408, 429 or 5xx, and honors
36
+ `Retry-After`. A timeout, or an expired URL (HTTP 403), still fails at once.
37
+
6
38
  ## 0.11.0
7
39
 
8
40
  Comparisons (open beta):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: datalab-python-sdk
3
- Version: 0.11.0
3
+ Version: 0.12.0
4
4
  Summary: SDK for the Datalab document intelligence API
5
5
  Project-URL: Homepage, https://www.datalab.to
6
6
  Project-URL: Documentation, https://documentation.datalab.to
@@ -182,8 +182,8 @@ Published-agent execution is in open beta; the API may change. Processor design
182
182
  ## Inputs, polling and errors
183
183
 
184
184
  - Send a local file with `file_path`, or a URL or a `datalab://file-...` reference with `file_url`. When you set `processing_location`, send the document as `file_url`.
185
- - Processing methods poll until the result is ready. The first 8 seconds poll every 0.3 seconds. Set `max_polls` and `poll_interval` to change the limit (default: 300 polls, 1 second apart). Use `stream_response_to` to write a large result straight to disk.
186
- - The SDK retries a submission that gets HTTP 429 or 503, and polls that get 408, 429, 5xx or a connection error. It waits for the `Retry-After` header when the API sends one.
185
+ - Processing methods poll until the result is ready. The first 8 seconds poll every 0.3 seconds. Set `max_polls` and `poll_interval` to change the limit (default: 300 polls, 1 second apart). Use `stream_response_to` to write a large result straight to disk. It returns a `FileResult` with the status, `output_path` and, when the poll response sends them, `request_id`, `page_count`, `parse_quality_score`, `versions`, `runtime` and `cost_breakdown`.
186
+ - The SDK retries a submission that gets HTTP 429 or 503, and polls or result downloads that get 408, 429, 5xx or a connection error, including one that happens while a result streams. It waits for the `Retry-After` header when the API sends one.
187
187
  - API errors raise `DatalabAPIError` (with `status_code` and `response_data`) or one of its subclasses: `DatalabAuthenticationError` (401, 403), `DatalabPaymentRequiredError` (402), `DatalabNotFoundError` (404), `DatalabRateLimitError` (429) and `DatalabServerError` (5xx). Invalid arguments raise `DatalabValidationError`, which is also a `ValueError`.
188
188
 
189
189
  With SDK 0.9.0, `upload_files(paths, max_concurrency=5)` streams
@@ -161,8 +161,8 @@ Published-agent execution is in open beta; the API may change. Processor design
161
161
  ## Inputs, polling and errors
162
162
 
163
163
  - Send a local file with `file_path`, or a URL or a `datalab://file-...` reference with `file_url`. When you set `processing_location`, send the document as `file_url`.
164
- - Processing methods poll until the result is ready. The first 8 seconds poll every 0.3 seconds. Set `max_polls` and `poll_interval` to change the limit (default: 300 polls, 1 second apart). Use `stream_response_to` to write a large result straight to disk.
165
- - The SDK retries a submission that gets HTTP 429 or 503, and polls that get 408, 429, 5xx or a connection error. It waits for the `Retry-After` header when the API sends one.
164
+ - Processing methods poll until the result is ready. The first 8 seconds poll every 0.3 seconds. Set `max_polls` and `poll_interval` to change the limit (default: 300 polls, 1 second apart). Use `stream_response_to` to write a large result straight to disk. It returns a `FileResult` with the status, `output_path` and, when the poll response sends them, `request_id`, `page_count`, `parse_quality_score`, `versions`, `runtime` and `cost_breakdown`.
165
+ - The SDK retries a submission that gets HTTP 429 or 503, and polls or result downloads that get 408, 429, 5xx or a connection error, including one that happens while a result streams. It waits for the `Retry-After` header when the API sends one.
166
166
  - API errors raise `DatalabAPIError` (with `status_code` and `response_data`) or one of its subclasses: `DatalabAuthenticationError` (401, 403), `DatalabPaymentRequiredError` (402), `DatalabNotFoundError` (404), `DatalabRateLimitError` (429) and `DatalabServerError` (5xx). Invalid arguments raise `DatalabValidationError`, which is also a `ValueError`.
167
167
 
168
168
  With SDK 0.9.0, `upload_files(paths, max_concurrency=5)` streams
@@ -3,6 +3,8 @@ Datalab API client - async core with sync wrapper
3
3
  """
4
4
 
5
5
  import asyncio
6
+ import dataclasses
7
+ import decimal
6
8
  import inspect
7
9
  import json as jsonlib
8
10
  import mimetypes
@@ -17,6 +19,7 @@ from tenacity import (
17
19
  retry,
18
20
  retry_if_exception,
19
21
  retry_if_exception_type,
22
+ retry_if_not_exception_type,
20
23
  stop_after_attempt,
21
24
  wait_exponential_jitter,
22
25
  )
@@ -157,6 +160,39 @@ def _is_retryable_poll_error(e: BaseException) -> bool:
157
160
  )
158
161
 
159
162
 
163
+ # Polls are GETs, so a transient failure can be retried without submitting
164
+ # the request again.
165
+ class _TransferTimeoutError(DatalabTimeoutError):
166
+ """A timeout while a result body transfers. It is not retried: the
167
+ timeout limits the whole request, so a result too large to transfer
168
+ within it would time out again on every attempt."""
169
+
170
+
171
+ _poll_retry = retry(
172
+ retry=(
173
+ (
174
+ retry_if_exception_type(DatalabTimeoutError)
175
+ & retry_if_not_exception_type(_TransferTimeoutError)
176
+ )
177
+ | retry_if_exception(_is_retryable_poll_error)
178
+ ),
179
+ stop=stop_after_attempt(10),
180
+ wait=_wait_retry_after_or_backoff,
181
+ reraise=True,
182
+ )
183
+
184
+ # Top-level fields of a poll response that a streamed call returns on
185
+ # FileResult. A signed result_url download does not contain them.
186
+ _FILE_RESULT_FIELDS = (
187
+ "request_id",
188
+ "page_count",
189
+ "parse_quality_score",
190
+ "versions",
191
+ "runtime",
192
+ "cost_breakdown",
193
+ )
194
+
195
+
160
196
  def _error_message_from_body(error_data: Any, fallback: str) -> str:
161
197
  """Make a readable message from an API error body.
162
198
 
@@ -228,19 +264,71 @@ def _warn_eval_renamed(old: str, new: str) -> None:
228
264
  )
229
265
 
230
266
 
231
- class _AsyncIterableReader:
232
- """Adapts an async iterable of bytes into an async file-like object for ijson."""
267
+ def _floats(value: Any) -> Any:
268
+ """Turn the Decimals that ijson returns for fractions into floats."""
269
+ if isinstance(value, decimal.Decimal):
270
+ return float(value)
271
+ if isinstance(value, dict):
272
+ return {k: _floats(v) for k, v in value.items()}
273
+ if isinstance(value, list):
274
+ return [_floats(v) for v in value]
275
+ return value
233
276
 
234
- def __init__(self, async_iterable):
235
- self._iter = async_iterable.__aiter__()
236
277
 
237
- async def read(self, n=-1):
238
- if n == 0:
239
- return b""
240
- try:
241
- return await self._iter.__anext__()
242
- except StopAsyncIteration:
243
- return b""
278
+ async def _read_error_body(resp: aiohttp.ClientResponse) -> bytes:
279
+ """Read an error body, or return b"" if it fails.
280
+
281
+ The status is already known, so a cut-off or stalled error body must not
282
+ change whether the error is retried.
283
+ """
284
+ try:
285
+ return await resp.read()
286
+ except (aiohttp.ClientError, asyncio.TimeoutError):
287
+ return b""
288
+
289
+
290
+ class _StreamedPollFields:
291
+ """Reads the top-level fields of a streamed poll response from ijson events.
292
+
293
+ Only the small fields are kept; the output itself stays on disk.
294
+ """
295
+
296
+ def __init__(self):
297
+ self.status = None
298
+ self.success = None
299
+ self.error = None
300
+ self.result_url = None
301
+ self.progress_percent = None
302
+ self.fields: Dict[str, Any] = {}
303
+ self._builder = None
304
+ self._builder_key = None
305
+
306
+ def feed(self, events) -> None:
307
+ for prefix, event, value in events:
308
+ if self._builder is not None:
309
+ # Build an object or array field, such as cost_breakdown,
310
+ # until its closing event.
311
+ self._builder.event(event, value)
312
+ if prefix == self._builder_key and event in ("end_map", "end_array"):
313
+ self.fields[self._builder_key] = _floats(self._builder.value)
314
+ self._builder = None
315
+ elif prefix in _FILE_RESULT_FIELDS:
316
+ if event in ("start_map", "start_array"):
317
+ self._builder = ijson.ObjectBuilder()
318
+ self._builder.event(event, value)
319
+ self._builder_key = prefix
320
+ else:
321
+ self.fields[prefix] = _floats(value)
322
+ elif prefix == "status" and event == "string":
323
+ self.status = value
324
+ elif prefix == "success" and event == "boolean":
325
+ self.success = value
326
+ elif prefix == "error" and event in ("string", "null"):
327
+ self.error = value
328
+ elif prefix == "result_url" and event == "string":
329
+ self.result_url = value
330
+ elif prefix == "progress_percent" and event == "number":
331
+ self.progress_percent = value
244
332
 
245
333
 
246
334
  class AsyncDatalabClient:
@@ -415,15 +503,7 @@ class AsyncDatalabClient:
415
503
  f"Polling timed out after {max_polls * poll_interval} seconds"
416
504
  )
417
505
 
418
- @retry(
419
- retry=(
420
- retry_if_exception_type(DatalabTimeoutError)
421
- | retry_if_exception(_is_retryable_poll_error)
422
- ),
423
- stop=stop_after_attempt(10),
424
- wait=_wait_retry_after_or_backoff,
425
- reraise=True,
426
- )
506
+ @_poll_retry
427
507
  async def _poll_get_with_retry(self, url: str) -> Dict[str, Any]:
428
508
  """GET wrapper for polling with scoped retries for transient failures"""
429
509
  return await self._make_request("GET", url)
@@ -435,6 +515,7 @@ class AsyncDatalabClient:
435
515
  headers={"User-Agent": f"datalab-python-sdk/{settings.VERSION}"},
436
516
  )
437
517
 
518
+ @_poll_retry
438
519
  async def _fetch_signed_result(self, url: str) -> Dict[str, Any]:
439
520
  """Download a result JSON from a signed result_url"""
440
521
  try:
@@ -442,24 +523,34 @@ class AsyncDatalabClient:
442
523
  async with session.get(url) as resp:
443
524
  if resp.status >= 400:
444
525
  raise _api_error_from_body(
445
- resp.status, await resp.read(), resp.reason, None
526
+ resp.status,
527
+ await _read_error_body(resp),
528
+ resp.reason,
529
+ resp.headers.get("Retry-After"),
446
530
  )
447
531
  return await resp.json(content_type=None)
448
532
  except asyncio.TimeoutError:
449
- raise DatalabTimeoutError(
533
+ raise _TransferTimeoutError(
450
534
  f"Result download timed out after {self.timeout} seconds"
451
535
  )
452
536
  except aiohttp.ClientError as e:
453
537
  raise DatalabAPIError(f"Result download failed: {str(e)}")
454
538
 
455
539
  async def _download_signed_url_to_file(self, url: str, path: Path) -> None:
456
- """Stream a signed result_url to a file on disk"""
540
+ """Stream a signed result_url to a file on disk.
541
+
542
+ The bytes are copied without parsing, so the result is never held in
543
+ memory.
544
+ """
457
545
  try:
458
546
  async with self._signed_url_session() as session:
459
547
  async with session.get(url) as resp:
460
548
  if resp.status >= 400:
461
549
  raise _api_error_from_body(
462
- resp.status, await resp.read(), resp.reason, None
550
+ resp.status,
551
+ await _read_error_body(resp),
552
+ resp.reason,
553
+ resp.headers.get("Retry-After"),
463
554
  )
464
555
  with open(path, "wb") as f:
465
556
  async for chunk in resp.content.iter_any():
@@ -490,22 +581,7 @@ class AsyncDatalabClient:
490
581
  merged.update({k: v for k, v in data.items() if v is not None})
491
582
  return merged
492
583
 
493
- @staticmethod
494
- async def _tee_stream_to_file(content, fd):
495
- """Async generator that writes each chunk to fd and yields it for ijson."""
496
- async for chunk in content.iter_any():
497
- os.write(fd, chunk)
498
- yield chunk
499
-
500
- @retry(
501
- retry=(
502
- retry_if_exception_type(DatalabTimeoutError)
503
- | retry_if_exception(_is_retryable_poll_error)
504
- ),
505
- stop=stop_after_attempt(10),
506
- wait=_wait_retry_after_or_backoff,
507
- reraise=True,
508
- )
584
+ @_poll_retry
509
585
  async def _poll_get_streaming(
510
586
  self, url: str, stream_response_to: Path
511
587
  ) -> FileResult:
@@ -530,34 +606,38 @@ class AsyncDatalabClient:
530
606
  if resp.status >= 400:
531
607
  raise _api_error_from_body(
532
608
  resp.status,
533
- await resp.read(),
609
+ await _read_error_body(resp),
534
610
  resp.reason,
535
611
  resp.headers.get("Retry-After"),
536
612
  )
537
613
 
538
- status = None
539
- success = None
540
- error = None
541
- result_url = None
542
- progress_percent = None
543
-
544
- tee_reader = _AsyncIterableReader(
545
- self._tee_stream_to_file(resp.content, fd)
614
+ # Push each chunk to ijson from this task. ijson.parse_async
615
+ # reads in another task, which turns an aiohttp timeout into
616
+ # a CancelledError.
617
+ poll = _StreamedPollFields()
618
+ events = ijson.sendable_list()
619
+ parser = ijson.parse_coro(events)
620
+ async for chunk in resp.content.iter_any():
621
+ os.write(fd, chunk)
622
+ parser.send(chunk)
623
+ poll.feed(events)
624
+ del events[:]
625
+ parser.close()
626
+ poll.feed(events)
627
+ except asyncio.TimeoutError:
628
+ raise _TransferTimeoutError(
629
+ f"Result transfer timed out after {self.timeout} seconds"
546
630
  )
547
- async for prefix, event, value in ijson.parse_async(tee_reader):
548
- if prefix == "status" and event == "string":
549
- status = value
550
- elif prefix == "success" and event == "boolean":
551
- success = value
552
- elif prefix == "error" and event in ("string", "null"):
553
- error = value
554
- elif prefix == "result_url" and event == "string":
555
- result_url = value
556
- elif prefix == "progress_percent" and event == "number":
557
- progress_percent = value
631
+ except aiohttp.ClientError as e:
632
+ # The body can fail after the headers arrive.
633
+ raise DatalabAPIError(f"Request failed: {str(e)}") from e
558
634
  finally:
559
635
  resp.release()
560
636
 
637
+ status, success, error = poll.status, poll.success, poll.error
638
+ result_url, progress_percent = poll.result_url, poll.progress_percent
639
+ fields = poll.fields
640
+
561
641
  if status is None:
562
642
  raise DatalabAPIError("Response missing 'status' field")
563
643
 
@@ -570,27 +650,21 @@ class AsyncDatalabClient:
570
650
 
571
651
  if status == "complete" and result_url:
572
652
  # The API sent a signed URL instead of the full result.
573
- # Stream the full result from that URL into the file.
653
+ # Stream the full result from that URL into the file. The
654
+ # FileResult fields come from the poll response only.
574
655
  await self._download_signed_url_to_file(result_url, Path(tmp_path))
575
656
 
576
657
  if status == "complete":
577
658
  shutil.move(tmp_path, stream_response_to)
578
659
  tmp_path = None
579
- return FileResult(
580
- success=success,
581
- status=status,
582
- output_path=stream_response_to,
583
- error=error,
584
- progress_percent=progress_percent,
585
- )
586
- else:
587
- return FileResult(
588
- success=success,
589
- status=status,
590
- output_path=stream_response_to,
591
- error=error,
592
- progress_percent=progress_percent,
593
- )
660
+ return FileResult(
661
+ success=success,
662
+ status=status,
663
+ output_path=stream_response_to,
664
+ error=error,
665
+ progress_percent=progress_percent,
666
+ **fields,
667
+ )
594
668
  finally:
595
669
  if fd is not None:
596
670
  try:
@@ -735,6 +809,10 @@ class AsyncDatalabClient:
735
809
  for key in ("request_id", "checkpoint_reused"):
736
810
  if result.get(key) is None and initial_data.get(key) is not None:
737
811
  result[key] = initial_data[key]
812
+ elif isinstance(result, FileResult) and result.request_id is None:
813
+ result = dataclasses.replace(
814
+ result, request_id=initial_data.get("request_id")
815
+ )
738
816
  return result
739
817
 
740
818
  @staticmethod
@@ -879,14 +879,31 @@ class ExtractionSchemaSuggestions:
879
879
  @dataclass
880
880
  class FileResult:
881
881
  """Lightweight result returned when stream_response_to is used.
882
- The full JSON response is written directly to disk at output_path,
883
- never fully loaded into memory."""
882
+ The full JSON response is written directly to disk at output_path, and
883
+ the parsed result is never built in memory. While a poll response
884
+ streams, the SDK decodes each JSON string value whole, so peak memory is
885
+ at least the size of the largest text field, such as markdown. A result
886
+ from a signed result_url is copied to disk without parsing.
887
+
888
+ The page_count, parse_quality_score, versions, runtime and
889
+ cost_breakdown fields come from the poll response, and are None when it
890
+ does not send them. request_id comes from the poll response, or else
891
+ from the submit response. For a result from a signed result_url, the
892
+ poll response has no versions, and cost or runtime can be unset on an
893
+ early poll. The saved file can contain versions and runtime, but not
894
+ cost."""
884
895
 
885
896
  success: bool
886
897
  status: str
887
898
  output_path: Path
888
899
  error: Optional[str] = None
889
900
  progress_percent: Optional[int] = None
901
+ request_id: Optional[str] = None
902
+ page_count: Optional[int] = None
903
+ parse_quality_score: Optional[float] = None
904
+ versions: Optional[Union[Dict[str, Any], str]] = None
905
+ runtime: Optional[float] = None
906
+ cost_breakdown: Optional[Dict[str, Any]] = None
890
907
 
891
908
 
892
909
  # --- Extraction Schema models ---
@@ -7,7 +7,7 @@ readme = "README.md"
7
7
  license = "MIT"
8
8
  repository = "https://github.com/datalab-to/sdk"
9
9
  keywords = ["datalab", "sdk", "document-intelligence", "api"]
10
- version = "0.11.0"
10
+ version = "0.12.0"
11
11
  description = "SDK for the Datalab document intelligence API"
12
12
  requires-python = ">=3.11"
13
13
  dependencies = [