Skip to main content

unstract-python-client

PyPI - Downloads Python Version from PEP 621 TOML PyPI - Version

Python client for the Unstract LLM-powered structured data extraction platform

Installation

You can install the Unstract Python Client using pip:

pip install unstract-client

Usage

First, import the APIDeploymentsClient from the client module:

from unstract.api_deployments.client import APIDeploymentsClient

Then, create an instance of the APIDeploymentsClient:

client = APIDeploymentsClient(api_url="url", api_key="your_api_key")

Note: Pass the raw API key without the "Bearer " prefix — the client adds it automatically.

Now, you can use the client to interact with the Unstract API deployments API:

try:
    adc = APIDeploymentsClient(
        api_url=os.getenv("UNSTRACT_API_URL"),
        api_key=os.getenv("UNSTRACT_API_DEPLOYMENT_KEY"),
        api_timeout=10,
        logging_level="DEBUG",
        include_metadata=False # optional
    )
    # Replace files with pdfs
    response = adc.structure_file(
        ["<files>"]
    )
    print(response)
    if response["pending"]:
        while True:
            p_response = adc.check_execution_status(
                response["status_check_api_endpoint"]
            )
            print(p_response)
            if not p_response["pending"]:
                break
            print("Sleeping and checking again in 5 seconds..")
            time.sleep(5)
except APIDeploymentsClientException as e:
    print(e)

Parameter Details

api_url: The URL of the Unstract API deployment. api_key: Your raw API key. Do not include the "Bearer " prefix — the client adds it automatically. api_timeout: Backend execution mode sent with the request (see timeout on structure_file). 0 or below queues the execution and returns immediately; above it the call runs synchronously and the value bounds how long the backend waits. This is not a socket timeout — pass transport_timeout for that. logging_level: Set logging verbosity (e.g., "DEBUG"). include_metadata: If set to True, the response will include additional metadata (cost, tokens consumed and context) for each call made by the Prompt Studio exported tool. transport_timeout: Socket timeout in seconds (keyword-only). Left unset, a stalled connection blocks forever, which is what earlier releases did.

Closing the client

The client reuses connections between calls, so release them when you are done with it — either by calling close(), or by using it as a context manager:

with APIDeploymentsClient(api_url="url", api_key="your_api_key") as adc:
    response = adc.structure_file(["<file>"])

A long-lived client can be left open; one built per job should be closed.

Retry Configuration

The client includes built-in exponential backoff retry with the following behavior:

  • Async mode (api_timeout of 0 or below): POST requests are retried on transient failures (5xx, 429) and connection errors, since the server returns immediately after queuing.
  • Sync mode (api_timeout > 0, the default): POST requests are not retried, because the server blocks during processing — a failure may mean the request was processed but the response was lost.
  • Status polling (check_execution_status): GET requests are always retried, as they are idempotent.

Retries are enabled by default and can be customized:

client = APIDeploymentsClient(
    api_url="url",
    api_key="your_api_key",
    max_retries=4,       # Max retry attempts (default: 4, set to 0 to disable)
    initial_delay=2.0,   # Initial delay in seconds (default: 2.0)
    max_delay=60.0,      # Maximum delay cap in seconds (default: 60.0)
    backoff_factor=2.0,  # Multiplier per retry (default: 2.0)
)
Parameter Default Description
max_retries 4 Maximum number of retry attempts. Set to 0 to disable retries.
initial_delay 2.0 Initial delay in seconds before the first retry.
max_delay 60.0 Maximum delay cap in seconds between retries.
backoff_factor 2.0 Multiplier applied to the delay for each subsequent retry.

The retry logic uses exponential backoff with full jitter and respects the Retry-After header on 429 responses.

Listing deployments with a platform key

PlatformKeyClient takes a platform API key, not a deployment key, and reads the account that key belongs to. It cannot run a deployment.

from unstract.api_deployments import PlatformKeyClient

with PlatformKeyClient("https://us-central.unstract.com", "your_platform_key") as client:
    org_id = client.whoami()["organization_id"]
    page = client.list_deployments(org_id, page_size=50)
    for deployment in page["results"]:
        print(deployment["api_name"], deployment["api_endpoint"])

Follow next for further pages. api_key falls back to $UNSTRACT_PLATFORM_KEY.

Errors

Every error either client raises derives from UnstractError:

Exception Raised by
UnstractError base of both — catch this to catch everything
APIDeploymentError APIDeploymentsClient
PlatformClientError PlatformKeyClient

APIDeploymentsClientException is an alias of UnstractError, so existing except clauses keep working.

Transport failures are raised as the requests exception types (ConnectionError, Timeout, and friends) rather than the httpx ones.

Internals

unstract.api_deployments._sdk_docstudio is generated from the deployment API's OpenAPI spec by tools/gen_sdk.sh and is an implementation detail of the transport. APIDeploymentsClient and PlatformKeyClient are the supported surface — import from those, or from the response models re-exported alongside them, not from the generated tree, which is regenerated wholesale whenever the spec moves.

Cloning an organization

Installing unstract-client also provides a clone command. This package no longer installs an unstract console script, so invoke it as a module:

pip install unstract-client
python -m unstract.clone --help

python -m unstract.clone clone

Clones an organization's resources to another org, on the same or a different deployment (e.g. promote dev → QA → prod). Covers adapters, connectors, workflows, pipelines, API deployments, Prompt Studio projects and their files, user groups, and sharing state (users matched by email, groups by name).

Authenticates with each org admin's Platform API key; prefer the env vars so keys never land in shell history:

export UNSTRACT_SRC_PLATFORM_KEY="<source platform key>"
export UNSTRACT_TGT_PLATFORM_KEY="<target platform key>"

python -m unstract.clone clone \
  --source-url https://dev.example.com --source-org org_dev123 \
  --target-url https://qa.example.com --target-org org_qa456 \
  --dry-run

Drop --dry-run to perform the clone.

Option Description
--dry-run Plan only; nothing is written.
--include / --exclude Comma-separated phases to run / skip.
--on-name-conflict adopt (default) reuses like-named target resources; abort stops.
--clone-group-members Also add group members on target, matched by email.
--source-key / --target-key Platform API keys, if not set via env vars.
--api-prefix Backend URL prefix (default api/v1).

Re-runs are idempotent: existing target resources are adopted by name, so a failed run can be resumed by re-running the same command.

Exit code Meaning
0 Success.
1 Completed with failures — see the printed report.
2 Could not run (setup error or --on-name-conflict=abort collision).

Compatibility

Cloning is capability-probed: each phase checks for its endpoint on the source and target, and clones only what both orgs support. A capability missing on either side is reported and skipped — the run never fails because of a version difference. Cloning a newer source into an older target therefore drops the entity types the target lacks (listed in the end-of-run report).

  • Run the source and target on the same (or a newer-target) Unstract build.
  • Use unstract-client >= 1.4.0, the first release that ships the clone command.

Questions and Feedback

On Slack, join great conversations around LLMs, their ecosystem and leveraging them to automate the previously unautomatable!

Unstract Cloud: Signup and Try!

Unstract developer documentation: Learn more about Unstract and its API.

Metadata

Release files for unstract-client 1.7.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for unstract-client 1.7.1
File Size Uploaded
unstract_client-1.7.1.tar.gz 222.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for unstract-client 1.7.1
File Interpreter ABI Platform
unstract_client-1.7.1-py3-none-any.whl Python 3 none any Details

Total release size: 350.7 kB

Release files / unstract_client-1.7.1.tar.gz

Download URL unstract_client-1.7.1.tar.gz
Size 222.8 kB
Tags Source
SHA-256 checksum
How to use checksums
d192295a8eba9f25268915e60cb0435683a1eb000eaf51bc4f87db0e6e9f1288
BLAKE2b-256 checksum
How to use checksums
1dd0d0a6704436baca70e5b261058c0cd9a3a4853556bf6ade9fe201eb3f4b88
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.6.14

Release files / unstract_client-1.7.1-py3-none-any.whl

Download URL unstract_client-1.7.1-py3-none-any.whl
Size 127.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
82125d4fb5876fcd872595205d30ad6a1ba544a2d49ea1d3177910bc34877274
BLAKE2b-256 checksum
How to use checksums
d37b10584cb0c1cefd075990c2dac0f5e1cdbe05aebc9de41c4ef55c6f73f936
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.6.14

Release history Release notifications | RSS feed

This release

1.7.1 This release

2 release files

1.7.0

2 release files

1.6.0

2 release files

1.5.3

2 release files

1.5.2

2 release files

1.5.1

2 release files

1.5.0

2 release files

1.4.0

2 release files

1.3.0

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.0

2 release files

1.0.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page