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

> ## Agent Instructions
> getclean's own MCP server is at https://mcp.getclean.ai/mcp. The /mcp path of this docs site is Mintlify's search over these pages, not getclean.
> Every answer of the API opens with outcome. A page that could not be read is a record whose outcome says why, never an HTTP error; read outcome before anything else.
> The API's contract is the OpenAPI 3.1 file at https://docs.getclean.ai/openapi.yaml; the SDKs are generated from it.
> The product's name is written getclean, in lower case.

# getclean for Python

> The getclean package for Python, for a research agent and for the person who builds one: create the client, make the first fetch and read the record, run the research loop, read a record again for free, upload documents, handle errors, retry safely, and keep every request inside a budget.

The `getclean` package calls the getclean API from Python. It's generated from the API's OpenAPI contract, so each of the 22 operations is a method of the client with the operation's own name, its fields are keyword arguments with the API's own names, and its answer is a typed object you read with dots. Every method's docstring is the operation's description from the contract, so help in your editor says the same thing as the [API reference](https://docs.getclean.ai/api-reference/overview.md). On top of the generated code, a small hand-written layer does the things a research agent would otherwise write itself: it follows an upload's job to the record, pages a long section, drops repeated items from a list, and retries a request whose first attempt is still running.

```bash theme={"theme":"css-variables"}
pip install getclean
```

## Create the client

```python theme={"theme":"css-variables"}
from getclean import GetClean

client = GetClean()  # reads GETCLEAN_API_KEY
```

With no argument, the client reads your API key from `GETCLEAN_API_KEY`. If there's no key there and you pass none, the constructor raises `ConfigurationError` before any request leaves, with the message "api\_key is required: pass it to the client or set the environment variable GETCLEAN\_API\_KEY." A missing key never looks like a network problem.

You can also pass the key, or a function that returns an access token:

```python theme={"theme":"css-variables"}
client = GetClean(api_key="your-api-key")

def read_access_token() -> str:
    ...  # return a token that is still valid

client = GetClean(api_key=read_access_token)
```

The SDK calls your function when it needs a credential and never refreshes a token itself, so the function returns a token that's still valid. [Authenticate a request](https://docs.getclean.ai/start/authentication.md) covers both kinds of credential.

The client talks to `https://api.getclean.ai`. To point it elsewhere, pass `base_url` or set `GETCLEAN_BASE_URL`. The client holds a connection pool, so close it when you're done, or use it as a context manager:

```python theme={"theme":"css-variables"}
with GetClean() as client:
    ...
```

There's an async twin, `AsyncGetClean`, with the same 22 methods as coroutines and the same hand-written helpers:

```python theme={"theme":"css-variables"}
from getclean import AsyncGetClean

async with AsyncGetClean() as client:
    record = await client.fetch_contents(url="https://example.com/q3")
```

## The first fetch, and how to read it

```python theme={"theme":"css-variables"}
record = client.fetch_contents(
    url="https://example.com/q3",
    highlights=["Revenue rose 12%", "what drove the margin"],
    summary=True,
)

record.outcome.kind             # "delivered"
record.outcome.reason           # "whole"
record.highlights[1].basis      # "judged"
record.highlights[1].block_id   # "b9"
record.cost.actual.amount       # "0.0090"
record.id                       # "cnt_3Fk9abaUhNX7t2eKkgfd3e"
```

Read `outcome` first, every time. A page that couldn't be read is still a record, returned normally, and its outcome says why. Nothing is raised for a failed page:

```python theme={"theme":"css-variables"}
record = client.fetch_contents(url="https://shop.example/offer")

if record.outcome.kind in ("failed", "refused", "needs_person"):
    print(record.outcome.reason)   # "challenge_served"
    print(record.outcome.message)  # what may work next
```

A record that failed, was refused or needs a person has no content, and `record.cost.actual.amount` is `"0.0000"`. Notices come right after the outcome and are worth a look before you use the result:

```python theme={"theme":"css-variables"}
for notice in record.notices:
    print(notice.code, notice.message)
```

[Records](https://docs.getclean.ai/understand/records.md) says what a record has, and [Outcomes and notices](https://docs.getclean.ai/understand/outcomes-and-notices.md) lists every reason and code.

## Requests and types

Every field of a request is a keyword argument. The ids from the path come first, positionally: `client.get_contents(record.id, max_characters=0)`, `client.get_section(record.id, "s2")`. A field whose value is an object takes the SDK's model of it, such as `Money` for a spending limit:

```python theme={"theme":"css-variables"}
from getclean import Money, SearchContentsOptions

result = client.search(
    query="EU AI Act article 50 marking obligations",
    published_within_days=365,
    max_candidates=3,
    contents=SearchContentsOptions(top=1, max_characters=8000),
    max_cost=Money(amount="0.1000", currency="USD"),
)

result.candidates[0].contents.id  # "cnt_8Lq5XFriyaJ0jEc2oPNx6E"
```

A plain dict in place of a model also works at runtime, but a type checker will flag it. Amounts are strings, as the API sends them, so there's no floating point in your money. A closed set such as `scope` is a `Literal` type, and an open set such as `outcome.reason` is a plain string, so a value added in a later version arrives without breaking anything. A member that doesn't apply to a record is `None`, and so is a member the API sends as `null`; the member's description in the reference tells you which it can be.

## The research loop

This is the loop a research agent runs, in Python: search, fetch the best result, find where it says the thing, read the rest for free, and keep a pointer that survives.

```python theme={"theme":"css-variables"}
from getclean import GetClean, Money

client = GetClean()

# 1. Search, with a spending limit, and let the search fetch the top result in the same call.
found = client.search(
    query="EU AI Act article 50 marking obligations",
    published_within_days=365,
    max_candidates=5,
    contents={"top": 1, "max_characters": 8000},
    max_cost=Money(amount="0.1000", currency="USD"),
)

lead = found.candidates[0]
record_id = lead.contents.id  # the fetched record, already yours

# 2. Find where the record says what you need. Strings found word for word are free.
places = client.highlight_contents(
    record_id,
    highlights=["machine-readable format", "which obligations apply to deployers"],
    max_characters=0,
)
for h in places.highlights:
    print(h.query_index, h.basis, h.section_id, h.block_id)

# 3. Read the section that holds the answer, for free.
section = client.get_section(record_id, places.highlights[0].section_id)
print(section.markdown)

# 4. Keep a pointer for the citation pass: the record, its fingerprint, and the place.
citation = (record_id, section.fingerprint, places.highlights[0].section_id, places.highlights[0].block_id)
```

Every read of a record you already have is free and keeps the record alive for another 48 hours. The pointer in step 4 is what makes a claim checkable later: the same fingerprint means the same text. [Records](https://docs.getclean.ai/understand/records.md) explains how long a record is kept, and the guides under Contents and Search show each call with its full response.

## Reading a record again

`get_contents` returns the same record in any format, at any size, under either view, with the highlights, summary and schema values the fetch produced. It's free, so the record it returns has no `cost`:

```python theme={"theme":"css-variables"}
whole = client.get_contents(record_id, max_characters=200000)
outline = client.get_contents(record_id, max_characters=0)      # sections, no text
tables = client.get_contents(record_id, formats=["json"], block_kinds=["table"])
```

A long section comes in pieces. `iter_section` walks them for you, one page of the section at a time, until there's no more:

```python theme={"theme":"css-variables"}
for page in client.iter_section(record_id, "s4", max_characters=8000):
    print(page.markdown)
```

Each page is a `SectionContents`, the same object `get_section` returns, so you can stop whenever you have enough.

## Pagers

The seven list operations return a pager. Loop over it and it reads the next page when it needs to:

```python theme={"theme":"css-variables"}
for item in client.list_contents(url="https://example.com/*"):
    print(item.id, item.source.title, item.expires_at)

for block in client.list_blocks(record_id, block_kinds=["table"]):
    print(block.page_number, block.table.rows)
```

The page's own members live on the pager's `response`. A page of blocks, for example, repeats the record's fingerprint and version:

```python theme={"theme":"css-variables"}
pager = client.list_blocks(record_id, block_ids=["b7"])
pager.response.fingerprint
pager.response.version
```

`list_links`, `list_datasources`, `get_search` and `compare_contents` page the same way. On `list_contents` and `list_jobs`, a record or a job created while you page can make an item appear twice, and the SDK drops the repeat for you, by `id`.

## Uploading a document

Pass the document as a path, as bytes, or as an open stream. A long document runs as a job, and with `wait=True` the SDK follows the job to the record:

```python theme={"theme":"css-variables"}
from getclean import Money, JobCanceled

answer = client.upload_contents(
    document="records.pdf",
    max_cost=Money(amount="1.0000", currency="USD"),
    wait=True,
)

record = answer.contents       # the record, whether the parse finished at once or ran as a job
job = answer.job               # the final job, when there was one
```

When the parse finishes within `wait_seconds`, the API answers `201` and `answer.contents` is the record straight away. When it runs on as a job, the API answers `202`, and with `wait=True` the SDK reads the job with `get_job`, which waits on the server for up to a minute per request, until the job is final, then reads the record under the upload's own `max_characters`, `formats` and `block_kinds`. A job that fails before any record exists raises the error class of its problem's status, the same class the API would have raised had it refused the upload directly. A job canceled before any page was done raises `JobCanceled`, which carries the job. A job still running after the API's own limit of 30 minutes comes back as it stands, so you're never stuck.

Without `wait`, you get the `202` as it is, with `answer.job` set, and you follow it yourself:

```python theme={"theme":"css-variables"}
answer = client.upload_contents(document="records.pdf")

job = answer.job
while job is not None and not job.finished:
    job = client.get_job(job.id, wait_seconds=60)
record = client.get_contents(job.contents_id) if job and job.contents_id else answer.contents
```

Set `max_cost` on every upload: a long scan is the most expensive request there is. An upload requires an idempotency key, and the SDK generates one when you give none. [Turn PDFs, Office files, and scans into evidence you can cite by page](https://docs.getclean.ai/read/pdfs-scans-and-documents.md) covers what a document gives you.

## Errors

A problem, the API's own refusal, raises an error. Each HTTP status has its own class, named after the status, and the error carries the problem as `body`:

```python theme={"theme":"css-variables"}
from getclean import NotFoundError, UnprocessableEntityError

try:
    client.delete_contents("cnt_3Fk9abaUhNX7t2eKkgfd3e")
except NotFoundError as error:
    print(error.body.type)          # "https://api.getclean.ai/problems/not-found"
    print(error.body.who_must_act)  # "caller"

try:
    client.fetch_contents(url="https://example.com/q3", formats=["pdf"])
except UnprocessableEntityError as error:
    for v in error.body.violations:
        print(v.kind, v.pointer, v.message)
```

Several problem types share one status, so compare on `body.type` and not on the class alone: the eleven `422` types all raise `UnprocessableEntityError`. The error's message starts with the problem's title and detail, so a log line says what happened without unpacking anything. `body.retryable` says whether asking again can help, and `body.change` carries the fix when it's data. Every class derives from `ApiError`, which also carries the status code and the headers. `ApiError`, `ConfigurationError` and `JobCanceled` are all importable from `getclean`. [Errors](https://docs.getclean.ai/understand/errors.md) lists every type.

## Retries and the idempotency key

The SDK retries on its own when the API answers `429`, `502`, `503` or `504`: up to five attempts in all, with a backoff that starts at one second and doubles to a ceiling of 30 seconds, plus jitter. When the response has `Retry-After` within that ceiling, the SDK waits exactly that long. A `Retry-After` beyond it ends the retries, and the error reaches your code as it arrived, with `retry_after_seconds` in its body.

On the eight operations that take an idempotency key, the SDK generates one per request when you give none and sends the same key on every attempt, so a retry is never charged twice. That covers one more case: `409 idempotency-key-in-flight`, which means the first attempt with this key is still running on the server. The SDK waits the `retry_after_seconds` the API asks for and sends the same request with the same key again, up to five attempts under the same ceiling, and once the first attempt has answered, the same key returns its response. Any other `409` is raised at once.

Give your own key when your program may repeat a request after a crash or a restart, so the second run finds the first response:

```python theme={"theme":"css-variables"}
record = client.fetch_contents(
    url="https://example.com/q3",
    idempotency_key="fetch-q3-2026-11-04",
)
record.cost.replayed  # True when this is the original response again
```

[Errors](https://docs.getclean.ai/understand/errors.md) has every rule of the key.

## Budgets and time

Two arguments keep a research agent inside its budget. `max_cost` is the most one request may cost, and the API drops optional work from the end of a published order rather than refuse the request; `cost.ceiling` on the response shows the limit that applied. `wait_seconds` is how long one request may work on the server. [Set a spending limit that no call can pass](https://docs.getclean.ai/understand/costs-and-budgets.md) explains how the money is reserved and cut.

The client's own timeout is a separate thing: it bounds one attempt on your side. It starts at 120 seconds. Before the first request that can be charged, the client reads your limits once and sets the timeout for each family to the API's own `call_seconds` bound plus ten seconds, so a request gets the time the API itself allows and no more. A timeout you pass for one request in `request_options` stands.

## Per-request options

Every operation accepts a W3C `traceparent` header, which getclean logs with the request and never forwards to a site or a source. It goes through `request_options`, together with a per-request timeout when one request needs more than the client's default:

```python theme={"theme":"css-variables"}
record = client.fetch_contents(
    url="https://example.com/q3",
    request_options={"additional_headers": {"traceparent": traceparent}, "timeout_in_seconds": 200},
)
```


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