> ## Documentation Index
> Fetch the complete documentation index at: https://docs.datalab.to/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> The Datalab Python SDK provides a simple interface for document conversion, pipelines, structured extraction, form fields, form filling, and file management.

## Installation

```bash theme={null}
pip install datalab-python-sdk
```

Requires Python 3.11 or higher.

## Authentication

Set your API key as an environment variable (recommended):

```bash theme={null}
export DATALAB_API_KEY=your_api_key_here
```

Or pass it directly to the client:

```python theme={null}
from datalab_sdk import DatalabClient

client = DatalabClient(api_key="your_api_key_here")
```

Get your API key from the [API Keys dashboard](https://www.datalab.to/app/keys).

Or sign in from a terminal, which also works for coding agents:

```bash theme={null}
datalab login
```

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>`.

> [!NOTE]
>
> `datalab login` needs SDK 0.7.0 or newer. On an older version, set `DATALAB_API_KEY`.

## Quick Example

```python theme={null}
from pathlib import Path

from datalab_sdk import DatalabClient

client = DatalabClient()

# Convert a document to markdown
result = client.convert("document.pdf")
print(result.markdown)

# Save output and images. The path is a file stem, not a folder: this writes
# output/document.md and output/document.metadata.json, with the images in output/.
Path("output").mkdir(exist_ok=True)
result.save_output("output/document")
```

## Client Options

Both sync and async clients accept the same configuration options:

```python theme={null}
from datalab_sdk import DatalabClient, AsyncDatalabClient

# Synchronous client (blocking)
client = DatalabClient(
    api_key="your_key",           # Or DATALAB_API_KEY, or the `datalab login` key
    base_url="https://www.datalab.to",  # API endpoint
    timeout=300,                  # Request timeout in seconds
)

# Asynchronous client (non-blocking)
async_client = AsyncDatalabClient(
    api_key="your_key",
    base_url="https://www.datalab.to",
    timeout=300,
)
```

| Parameter | Type | Default | Description |
| - | - | - | - |
| `api_key` | str | `DATALAB_API_KEY`, then the key saved by `datalab login` for this host | Your Datalab API key |
| `base_url` | str | `https://www.datalab.to` | API base URL |
| `timeout` | int | `300` | Request timeout in seconds |

## Async Support

For high-throughput applications, use `AsyncDatalabClient`:

```python theme={null}
import asyncio
from datalab_sdk import AsyncDatalabClient

async def process_documents():
    async with AsyncDatalabClient() as client:
        result = await client.convert("document.pdf")
        print(result.markdown)

asyncio.run(process_documents())
```

The async client is recommended when processing multiple documents concurrently.

## Error Handling

The SDK raises specific exceptions for different error types:

```python theme={null}
from datalab_sdk import DatalabClient
from datalab_sdk.exceptions import (
    DatalabAPIError,
    DatalabTimeoutError,
    DatalabFileError,
    DatalabValidationError,
)

client = DatalabClient()

try:
    result = client.convert("document.pdf")
except DatalabAPIError as e:
    print(f"API error {e.status_code}: {e.response_data}")
except DatalabTimeoutError as e:
    print(f"Timed out; request ID: {e.request_id}")
except DatalabFileError as e:
    print(f"File error: {e}")
except DatalabValidationError as e:
    print(f"Invalid input: {e}")
```

| Exception | Description |
| - | - |
| `DatalabAPIError` | API returned an error response (includes `status_code` and `response_data`) |
| `DatalabTimeoutError` | A request or the polling budget timed out. See [Timeouts](#timeouts) |
| `DatalabFileError` | File not found or cannot be read |
| `DatalabValidationError` | The SDK rejected the call before sending it, such as no file or checkpoint given, or options that can't be combined. A missing or empty file raises `DatalabFileError` |

### 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.

```python theme={null}
import json

from datalab_sdk import DatalabClient, ExtractOptions
from datalab_sdk.exceptions import DatalabAPIError

client = DatalabClient()
options = ExtractOptions(
    page_schema=json.dumps({"type": "object", "properties": {"total": {"type": "number"}}})
)

try:
    result = client.extract("invoice.pdf", options=options)
except DatalabAPIError as e:
    # status_code is 4xx for a rejected request, None for a failure while processing.
    # request_id is set once the API accepted the request.
    print(f"Failed: {e} (status {e.status_code}, request {e.request_id})")
    raise

if not result.success:
    print(f"Finished without a result: {result.error}")
```

From SDK 0.13.0, an error that the document-processing methods (`convert()`, `extract()`, `run_agent()` and the others in the [Method Summary](#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:

| Exception | `request_id` | What happened to the request |
| - | - | - |
| `DatalabTimeoutError` | `None` | The submission timed out. The API may still have accepted the request. |
| `DatalabPollingTimeoutError` | Set | The polling budget ran out. The request is still running and is charged. `status` and `progress_percent` come from the last poll. |
| `DatalabTransferTimeoutError` | Set | The request finished, but its result timed out while it downloaded. Raise the client `timeout` before you fetch it again. |

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:

```python theme={null}
from datalab_sdk import DatalabClient, DatalabPollingTimeoutError

client = DatalabClient()

try:
    result = client.convert("big.pdf", max_polls=60)
except DatalabPollingTimeoutError as e:
    result = client.get_result(e.check_url, max_polls=600)
```

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.

> [!WARNING]
>
> 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.

> [!NOTE]
>
> 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](https://docs.datalab.to/docs/welcome/api.md#progress-percentages) for availability, completion semantics, and callback error handling. Percentages are estimates, not time remaining.

## SDK Features

> [card] [Document Conversion](https://docs.datalab.to/docs/welcome/sdk/conversion.md)
>
> Convert PDFs, images, and documents to Markdown, HTML, JSON, or chunks.

> [card] [Structured Extraction](https://docs.datalab.to/docs/welcome/sdk/extraction.md)
>
> Extract structured data from documents using JSON schemas.

> [card] [Document Segmentation](https://docs.datalab.to/docs/welcome/sdk/segmentation.md)
>
> Segment documents into logical sections.

> [card] [Form Fields](https://docs.datalab.to/docs/welcome/sdk/form-fields.md)
>
> Find the fillable fields on each page of a PDF or image.

> [card] [Form Filling](https://docs.datalab.to/docs/welcome/sdk/form-filling.md)
>
> Fill PDF and image forms with structured field data.

> [card] [Pipelines](https://docs.datalab.to/docs/welcome/sdk/pipelines.md)
>
> Chain processors into versioned, reusable pipelines.

> [card] [File Management](https://docs.datalab.to/docs/welcome/sdk/file-management.md)
>
> Upload, list, and manage files in Datalab storage.

> [card] [CLI](https://docs.datalab.to/docs/welcome/sdk/cli.md)
>
> Command-line interface for document conversion.

> [card] [Compare](https://docs.datalab.to/docs/recipes/compare/sdk.md)
>
> Compare pipeline variants and read which one wins (open beta).

## Method Summary

| Method | Description |
| - | - |
| `convert()` | Convert documents to markdown, HTML, JSON, or chunks |
| `extract()` | Extract structured data from documents using JSON schemas |
| `segment()` | Segment documents into sections using a schema |
| `track_changes()` | Extract tracked changes from DOCX, PDF, and image files |
| `create_document()` | Create DOCX from markdown with track changes |
| `run_agent()` | Run an existing published processor (open beta; the API may change) |
| `form_fields()` | Find the fillable fields on each page of a PDF or image |
| `fill()` | Fill PDF or image forms with field data |
| `redact()` | Redact documents (beta; SDK 0.9.0+); see [verification guidance](https://docs.datalab.to/docs/recipes/redaction/redaction-api-overview.md#python-sdk) |
| `get_redaction_presets()` | Retrieve redaction starting points (SDK 0.9.0+) |
| `get_result()` | Wait for the result of a request that was already submitted (SDK 0.13.0+) |
| `delete_result()` | Delete the stored result of a finished request as soon as you've downloaded it. Results are otherwise removed after about a day |
| `upload_files()` | Upload files to Datalab storage |
| `list_files()` | List uploaded files |
| `get_file_metadata()` | Get metadata for a specific file |
| `get_file_download_url()` | Generate presigned download URL |
| `delete_file()` | Delete an uploaded file |
| `create_pipeline()` | Create a new pipeline |
| `list_pipelines()` | List pipelines for your team |
| `get_pipeline()` | Get a pipeline by ID |
| `update_pipeline()` | Update pipeline steps (creates a draft) |
| `save_pipeline()` | Name a pipeline and mark it saved. Does not publish: call `create_pipeline_version()` |
| `archive_pipeline()` | Archive a pipeline |
| `unarchive_pipeline()` | Restore an archived pipeline |
| `create_pipeline_version()` | Snapshot the current pipeline steps as an immutable version |
| `list_pipeline_versions()` | List all versions of a pipeline |
| `discard_pipeline_draft()` | Reset the draft to the active version. With `version=N`, load version N and make it the active version |
| `get_pipeline_rate()` | Get per-page rate for a pipeline |
| `run_pipeline()` | Execute a pipeline on a file |
| `get_pipeline_execution()` | Poll pipeline execution status |
| `list_pipeline_executions()` | List recent executions for a pipeline |
| `get_step_result()` | Fetch the result of a specific pipeline step |
| `create_comparison()` | Run and compare 2 to 4 pipeline variants on files or a collection (open beta, SDK 0.11.0+; the API may change) |
| `get_comparison()` | Get a comparison's status, each variant's share, and each document (open beta) |
| `list_comparisons()` | List the team's comparisons, newest first (open beta) |
| `get_comparison_differences()` | Get where a comparison's variants read one document differently (open beta) |
| `wait_for_comparison()` | Poll a comparison until it completes or fails (open beta) |
| `create_eval()`, `get_eval()`, `list_evals()`, `get_eval_differences()`, `wait_for_eval()` | *(Deprecated)* The SDK 0.10.0 names of the comparison methods; see [Moving from Evals](https://docs.datalab.to/docs/recipes/compare/sdk.md#moving-from-evals) |
| `create_extraction_schema()` | Create a reusable extraction schema |
| `list_extraction_schemas()` | List saved extraction schemas |
| `get_extraction_schema()` | Get a schema by ID |
| `update_extraction_schema()` | Update schema fields or create a new version |
| `delete_extraction_schema()` | Archive (soft-delete) an extraction schema |
| `ocr()` | *(Deprecated)* Use `convert()` instead |

### 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

> [card] [Document Conversion](https://docs.datalab.to/docs/welcome/sdk/conversion.md)
>
> Convert PDFs, images, and documents to Markdown, HTML, JSON, or chunks.

> [card] [Structured Extraction](https://docs.datalab.to/docs/welcome/sdk/extraction.md)
>
> Extract structured data from documents using JSON schemas.

> [card] [Document Segmentation](https://docs.datalab.to/docs/welcome/sdk/segmentation.md)
>
> Segment documents into logical sections.

> [card] [Form Fields](https://docs.datalab.to/docs/welcome/sdk/form-fields.md)
>
> Find the fillable fields on each page of a PDF or image.

> [card] [Form Filling](https://docs.datalab.to/docs/welcome/sdk/form-filling.md)
>
> Fill PDF and image forms with structured field data.

> [card] [Pipelines](https://docs.datalab.to/docs/welcome/sdk/pipelines.md)
>
> Chain processors into versioned, reusable pipelines.

> [card] [File Management](https://docs.datalab.to/docs/welcome/sdk/file-management.md)
>
> Upload, list, and manage files in Datalab storage.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.