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

# Structured Extraction

> Extract structured data from documents using JSON schemas with the Datalab SDK.

> [!WARNING]
>
> A completed request can return `success=False` and `error` without raising an SDK exception. Check `result.success` before reading the output.
>
> SDK 0.6.0 and later downloads signed regional results automatically. Upgrade older SDKs or use the [REST polling and download flow](https://docs.datalab.to/docs/recipes/conversion/conversion-api-overview.md#regional-result-downloads).

## Basic Usage

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

client = DatalabClient()

# Define a JSON schema for extraction
page_schema = json.dumps({
    "type": "object",
    "properties": {
        "invoice_number": {"type": "string", "description": "Invoice number"},
        "total": {"type": "number", "description": "Total amount due"},
        "vendor": {"type": "string", "description": "Vendor or company name"},
        "items": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "description": {"type": "string"},
                    "amount": {"type": "number"}
                }
            }
        }
    },
})

options = ExtractOptions(page_schema=page_schema)
result = client.extract("invoice.pdf", options=options)
if not result.success:
    raise RuntimeError(result.error or "Document processing failed")

# Access the extracted data
extracted = json.loads(result.extraction_schema_json)
print(extracted)
```

## Extract Options

Use `ExtractOptions` to configure extraction behavior:

| Option | Type | Default | Description |
| - | - | - | - |
| `page_schema` | str | Required unless using `schema_id` | JSON schema with `type="object"` and a root `properties` object. Mutually exclusive with `schema_id`. |
| `schema_id` | str | None | ID of a saved extraction schema (e.g. `sch_k8Hx9mP2nQ4v`). Mutually exclusive with `page_schema`. |
| `schema_version` | int | None | Schema version to pin to. Only valid with `schema_id`. |
| `checkpoint_id` | str | None | Checkpoint ID from a previous `convert()` call |
| `mode` | str | None | Parse mode: `"fast"`, `"balanced"`, `"accurate"`. Omit it to let the API match parsing to the extraction mode; Turbo skips parsing. |
| `extraction_mode` | str | None | `"turbo"`, `"fast"`, `"balanced"`, or `"accurate"`. When omitted, the team default applies. Turbo returns JSON without parsed output or citations and cannot reuse checkpoints. |
| `citation_granularity` | str | None | `"block"` (the API default) returns block IDs. `"phrase"` (open beta; the API may change) returns the matching words, their position and a match score, with a box only when the phrase can be located. See [Phrase-level citations](https://docs.datalab.to/docs/recipes/structured-extraction/api-overview.md#phrase-level-citations). |
| `output_format` | str | `"markdown"` | Output format: `"markdown"`, `"html"`, `"json"`, `"chunks"` |
| `save_checkpoint` | bool | `False` | Save checkpoint for reuse with subsequent calls |
| `max_pages` | int | None | Maximum number of pages to process |
| `page_range` | str | None | Specific pages to process (e.g., `"0-5,10"`). For spreadsheets, filters by sheet index. |
| `skip_cache` | bool | `False` | Skip cached results, force reprocessing |
| `webhook_url` | str | None | Webhook URL for completion notification |

> [!NOTE]
>
> Since SDK 0.6.0, `ExtractOptions.mode` defaults to `None` and is omitted from the request. The API uses accurate parsing for balanced and accurate extraction, and fast parsing for fast extraction; Turbo skips parsing. Set `extraction_mode` explicitly when you need repeatable behavior across teams. See [Balanced and Accurate Extraction Modes](https://docs.datalab.to/docs/recipes/structured-extraction/balanced-mode.md).

## Checkpoint Reuse

Use checkpoints to avoid re-parsing a document when running extraction after conversion. First convert with `save_checkpoint=True`, then extract using the returned `checkpoint_id`:

```python theme={null}
import json
from datalab_sdk import DatalabClient, ConvertOptions, ExtractOptions

client = DatalabClient()

# Step 1: Convert and save a checkpoint
convert_options = ConvertOptions(
    mode="accurate",
    save_checkpoint=True,
)
convert_result = client.convert("report.pdf", options=convert_options)
print(convert_result.markdown)

# Step 2: Extract using the checkpoint (no re-parsing needed)
page_schema = json.dumps({
    "type": "object",
    "properties": {
        "title": {"type": "string", "description": "Document title"},
        "author": {"type": "string", "description": "Author name"},
        "date": {"type": "string", "description": "Publication date"},
        "summary": {"type": "string", "description": "Brief summary of the document"},
    },
})

extract_options = ExtractOptions(
    page_schema=page_schema,
    checkpoint_id=convert_result.checkpoint_id,
)
extract_result = client.extract(options=extract_options)
extracted = json.loads(extract_result.extraction_schema_json)
print(extracted)
```

## Extraction Result

The result object contains the extracted data alongside standard conversion fields:

```python theme={null}
result = client.extract("invoice.pdf", options=options)

# Extracted structured data (JSON string)
extracted = json.loads(result.extraction_schema_json)
print(extracted["invoice_number"])
print(extracted["total"])

# Standard conversion fields are also available
print(result.success)
print(result.markdown)
print(result.page_count)
print(result.cost_breakdown)
```

`extraction_schema_json` is JSON text on this result. A pipeline's extract step result (`get_step_result()`) is a dict, and there `extraction_schema_json` is already a dict.

`extract()` reuses a checkpoint only when you pass `checkpoint_id`, so its `checkpoint_reused` is always `None`. Only [`segment()`](https://docs.datalab.to/docs/welcome/sdk/segmentation) reuses one on its own.

### Confidence Scores

Only `extraction_mode="fast"` produces confidence scores, and they arrive after the extraction itself. `extract()` returns as soon as the extraction is complete, so `extraction_score_average` is usually still `None`. To wait for the scores, poll the same request again with `get_result()`:

```python theme={null}
import time

result = client.extract(
    "invoice.pdf", options=ExtractOptions(page_schema=page_schema, extraction_mode="fast")
)
for _ in range(12):  # wait up to about a minute
    # The status stays None while scoring runs; complete, partial and failed are final.
    if result.extraction_scoring_status is not None:
        break
    time.sleep(5)
    result = client.get_result(result.request_id, endpoint="extract")

print(result.extraction_scoring_status, result.extraction_score_average)
```

`extraction_score_average` can be set only when the status is `complete`. A `complete` status with no scored fields, such as when every field came back empty, has no average. With `partial`, some fields have a `_score` in `extraction_schema_json` but there's no average; with `failed`, there are no scores. A missing score means no score, not zero confidence. See [Confidence scoring](https://docs.datalab.to/docs/recipes/structured-extraction/confidence-scoring.md) for the `_score` fields.

## Async Usage

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

async def extract_data():
    async with AsyncDatalabClient() as client:
        page_schema = json.dumps({
            "type": "object",
            "properties": {
                "title": {"type": "string", "description": "Document title"},
                "author": {"type": "string", "description": "Author name"},
            },
        })
        options = ExtractOptions(page_schema=page_schema)
        result = await client.extract("document.pdf", options=options)
        return json.loads(result.extraction_schema_json)

extracted = asyncio.run(extract_data())
print(extracted)
```

## Next Steps

> [card] [Extraction Recipe](https://docs.datalab.to/docs/recipes/structured-extraction/api-overview.md)
>
> Learn more about structured extraction patterns and best practices.

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

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

> [card] [Batch Processing](https://docs.datalab.to/docs/recipes/conversion/batch-documents.md)
>
> Process multiple documents efficiently in parallel.


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