Skip to main content

Installation

Requires Python 3.11 or higher.

Authentication

Set your API key as an environment variable (recommended):
Or pass it directly to the client:
Get your API key from the API Keys dashboard. Or sign in from a terminal, which also works for coding agents:
The command prints a link and a code. Open the link, sign in or sign up, check that the code matches, approve it, and type the 6-digit code that Datalab emails you. The SDK saves the key to ~/.config/datalab/config.json, readable only by your user, together with the host you signed in to. Run datalab logout to delete it. The client and the CLI pick a key in this order: the api_key you pass, then DATALAB_API_KEY, then the saved key. They send the saved key only to the host it was saved for, so a client with another base_url does not use it. To sign in to another host, run datalab login --host <url>.
datalab login needs SDK 0.7.0 or newer. On an older version, set DATALAB_API_KEY.

Quick Example

Client Options

Both sync and async clients accept the same configuration options:

Async Support

For high-throughput applications, use AsyncDatalabClient:
The async client is recommended when processing multiple documents concurrently.

Error Handling

The SDK raises specific exceptions for different error types:

How Failures Arrive

A failed request reaches you in one of three ways, so check the result as well as catching exceptions:
  1. A finished request with success=False. The method returns the result instead of raising. Check result.success and read result.error. For example, an extraction that runs but produces no result arrives this way. save_output saves nothing for a failed result, with one exception: a redaction that fails verification still returns the redacted PDF with success=False, and save_output saves it so that you can review it (see verdict and failing_checks).
  2. A DatalabAPIError while polling. When a poll reports success=False before the request is complete, the SDK raises DatalabAPIError("Processing failed: ..."). Its status_code is None.
  3. A DatalabAPIError for a rejected request. The API rejects an invalid option or schema with HTTP 400 or 422, which the SDK raises as DatalabAPIError with status_code and response_data, not as DatalabValidationError. A saved extraction schema (schema_id) fails this way too: an unknown schema or version is a 404 (DatalabNotFoundError), an archived schema is a 400, and a stored schema that fails the schema check is a 400 whose message names the schema and version.
From SDK 0.13.0, an error that the document-processing methods (convert(), extract(), run_agent() and the others in the Method Summary) or get_result() raise after the API accepted the request has request_id and check_url. Use them to fetch the result instead of submitting the document again. For run_pipeline(), request_id holds the execution ID; resume with get_pipeline_execution(e.request_id).

Timeouts

For the document-processing methods, each DatalabTimeoutError says what happened to the request: A polling request that times out 10 times also raises DatalabTimeoutError, with request_id set. To resume a request, pass the error’s check_url to get_result(). It polls the same request and returns the same result type as the method that submitted it, so the document is not processed or charged twice:
After a DatalabTransferTimeoutError, create a client with a larger timeout before you call get_result(); with the same timeout, the download times out again. With a request ID, also pass the endpoint that received it, for example client.get_result(request_id, endpoint="agent"). get_result() accepts the same save_output, stream_response_to, max_polls, poll_interval and on_progress arguments as the processing methods. Its result has no checkpoint_reused, because only the submission response sends it. If the response omits output_format, a conversion result reports markdown. An exception from an on_progress callback also ends the call while the request keeps running, but it is your own exception and has no request_id. Catch errors inside the callback to keep polling.

Automatic Retries

Document-processing submissions retry HTTP 429 and 503 responses. Polling and result downloads retry HTTP 408, 429, and 5xx responses, plus connection errors and poll timeouts, including a connection that drops while a result streams to disk. Each request is tried at most 10 times. A timeout while a finished result downloads from a signed result_url, or streams to disk with stream_response_to, is not retried, because timeout limits each whole request, and the same download would time out again. Retries use exponential backoff and honor Retry-After up to 120 seconds.
A submission timeout or other server error can happen after the server accepted the document. The SDK leaves these errors to your application instead of automatically submitting a second job. Check any known request ID before resubmitting.
Control polling with max_polls and poll_interval on individual methods. Since SDK 0.9.1, processing requests poll more frequently during the first eight seconds when poll_interval is positive and at most one second, then use that interval; the total polling budget stays max_polls * poll_interval. The client timeout applies to each HTTP request, including the whole download of a result; it is not a deadline for the whole processing job. Raise it for a large result. Pass stream_response_to to write a large result straight to disk. The call returns a FileResult with status, success, and output_path. Since SDK 0.12.0, it also has request_id, page_count, parse_quality_score, versions, runtime, and cost_breakdown when the poll response sends them, including when the result comes from a signed result_url. For a signed result, versions is not in the poll response; read it from the saved file.
SDK 0.8.0 and later supports on_progress callbacks on document-processing helpers such as convert() and extract(), including streamed results, and on pipeline polling. Callbacks receive increasing overall percentages from existing polls; async callbacks are supported too. Result models expose optional progress_percent. See progress percentages and examples for availability, completion semantics, and callback error handling. Percentages are estimates, not time remaining.

SDK Features

Document Conversion

Convert PDFs, images, and documents to Markdown, HTML, JSON, or chunks.

Structured Extraction

Extract structured data from documents using JSON schemas.

Document Segmentation

Segment documents into logical sections.

Form Fields

Find the fillable fields on each page of a PDF or image.

Form Filling

Fill PDF and image forms with structured field data.

Pipelines

Chain processors into versioned, reusable pipelines.

File Management

Upload, list, and manage files in Datalab storage.

CLI

Command-line interface for document conversion.

Compare

Compare pipeline variants and read which one wins (open beta).

Method Summary

Result Types

The processing methods return typed results, such as ConversionResult from convert() and extract(). A few methods return plain dicts instead: get_step_result() (a step’s raw result) and delete_result(). The same data can differ in type between the two: extraction_schema_json is JSON text on ConversionResult and a dict in a pipeline’s extract step result. IDs keep the API’s types: comparison_id and file_id are integers, and pipeline_id and execution_id are strings. request_id is a string on processing results, but an integer on each variant’s per-document results in a comparison (ComparisonDocumentResult).

Next Steps

Document Conversion

Convert PDFs, images, and documents to Markdown, HTML, JSON, or chunks.

Structured Extraction

Extract structured data from documents using JSON schemas.

Document Segmentation

Segment documents into logical sections.

Form Fields

Find the fillable fields on each page of a PDF or image.

Form Filling

Fill PDF and image forms with structured field data.

Pipelines

Chain processors into versioned, reusable pipelines.

File Management

Upload, list, and manage files in Datalab storage.