<!-- https://predictabl.tech/docs/python-reference/ -->
# Python reference

`predictabl` 0.1.1. Generated from the library itself, so the signatures here always match the package. `pip install predictabl`; source on [GitHub](https://github.com/predictabl/predictabl-python).

## Module functions

These use one shared client, configured by `login()` or the `PREDICTABL_API_KEY` and `PREDICTABL_BASE_URL` environment variables.

### `pb.login()`

```python
pb.login(api_key: str | None = None, base_url: str | None = None, **kw)
```

Configure the shared client. Without arguments, reads
PREDICTABL_API_KEY (and PREDICTABL_BASE_URL) from the environment. Other keyword arguments are passed to `Client`.

### `pb.account()`

```python
pb.account()
```

Who you are, your plan, your credits and what is left of your allowances.

### `pb.connect()`

```python
pb.connect(
    source: str | Path | Iterable[str | Path] | Any,
    name: str | None = None,
    *,
    wait: bool = True,
    quiet: bool = False,
    on_progress: Callback | None = None,
    timeout: float | None = 1800,
)
```

Connect data to Predictabl: a database or files.

* A Postgres address (``"postgresql://user:password@host:5432/db"``):
  Predictabl reads the database where it is, read-only. Use a
  read-only user, and make sure the database accepts connections from
  Predictabl's server.
* CSV, Excel or Parquet files, a list of them, or a pandas DataFrame:
  the files are uploaded to Predictabl. Several files become several
  tables Predictabl can join.

With `wait` (default) returns once Predictabl has read the tables.

### `pb.datasets()`

```python
pb.datasets()
```

Every dataset on this account: uploads and connected databases.

### `pb.data()`

```python
pb.data(data_id: str)
```

One dataset by id (from `datasets()` or the web app).

### `pb.plan()`

```python
pb.plan(question_id: str)
```

The latest plan of a question (opportunity) planned earlier, e.g.
in the web app, to retrain it from code without planning again.

### `pb.model()`

```python
pb.model(model_id: str)
```

One model by id (from `models()` or the web app address).

### `pb.models()`

```python
pb.models(limit: int = 50)
```

Your models, newest first, trained or not (check `model.ready`).

## Client

A connection to Predictabl.

`api_key` defaults to the PREDICTABL_API_KEY environment variable and
`base_url` to PREDICTABL_BASE_URL, else the hosted app. For a local
instance use `base_url="http://localhost:8000/api/v1"`.

```python
pb.Client(
    api_key: str | None = None,
    base_url: str | None = None,
    *,
    timeout: float = 120.0,
    poll_interval: float = 2.0,
)
```

### `client.account()`

```python
client.account()
```

Who you are, your plan, your credits and what is left of your allowances.

### `client.connect()`

```python
client.connect(
    source: str | Path | Iterable[str | Path] | Any,
    name: str | None = None,
    *,
    wait: bool = True,
    quiet: bool = False,
    on_progress: Callback | None = None,
    timeout: float | None = 1800,
)
```

Connect data to Predictabl: a database or files.

* A Postgres address (``"postgresql://user:password@host:5432/db"``):
  Predictabl reads the database where it is, read-only. Use a
  read-only user, and make sure the database accepts connections from
  Predictabl's server.
* CSV, Excel or Parquet files, a list of them, or a pandas DataFrame:
  the files are uploaded to Predictabl. Several files become several
  tables Predictabl can join.

With `wait` (default) returns once Predictabl has read the tables.

### `client.datasets()`

```python
client.datasets()
```

Every dataset on this account: uploads and connected databases.

### `client.data()`

```python
client.data(data_id: str)
```

One dataset by id (from `datasets()` or the web app).

### `client.plan()`

```python
client.plan(question_id: str)
```

The latest plan of a question (opportunity) planned earlier, e.g.
in the web app, to retrain it from code without planning again.

### `client.model()`

```python
client.model(model_id: str)
```

One model by id (from `models()` or the web app address).

### `client.models()`

```python
client.models(limit: int = 50)
```

Your models, newest first, trained or not (check `model.ready`).

### `client.close()`

```python
client.close()
```

Close the HTTP connection. `with pb.Client() as c:` does it for you.

## Data

A dataset on Predictabl: uploaded files or a connected database.

| Attribute | |
|---|---|
| `id` | Dataset id |
| `name` | Its name |
| `status` | `ready` once read |
| `table_count` | How many tables |
| `error` | Why reading failed, if it did |

### `data.plan()`

```python
data.plan(
    question: str,
    *,
    quiet: bool = False,
    on_progress: Callback | None = None,
    timeout: float | None = 1800,
)
```

Turn a question into a reviewable plan: target, features and what
was excluded as leakage. Spends one build on Predictabl's AI key.

### `data.predict()`

```python
data.predict(
    question: str,
    *,
    preset: str = "full_quality",
    engine: str = "auto",
    quiet: bool = False,
    on_progress: Callback | None = None,
    timeout: float | None = None,
)
```

The whole path: question -> plan -> trained, tested model.

### `data.questions()`

```python
data.questions()
```

Questions (prediction opportunities) found or asked on this data.

### `data.wait_ready()`

```python
data.wait_ready(*, timeout: float | None = 1800)
```

Wait until Predictabl has read the tables (status "ready").

### `data.refresh()`

```python
data.refresh()
```

Reload status and table count from the server.

### `data.delete()`

```python
data.delete()
```

Delete this dataset and its uploaded files. Models trained on it can
no longer read it, so delete only data you no longer score from.

## Plan

What Predictabl will train: the target, the features, and what it
excluded as leakage. Review it, refine it in plain words, then train.

| Attribute | |
|---|---|
| `id` | Plan id (what `train` uses) |
| `version` | Plan version |
| `opportunity_id` | The question it belongs to |
| `target` | The outcome, in words |
| `task` | `binary_classification`, `multiclass` or `regression` |
| `features` | Features it will use |
| `excluded` | Columns left out, with reasons |
| `spec` | The full plan, including its SQL |

### `plan.summary()`

```python
plan.summary()
```

The plan in a few readable lines; also what `print(plan)` shows.

### `plan.refine()`

```python
plan.refine(
    message: str,
    *,
    quiet: bool = False,
    on_progress: Callback | None = None,
    timeout: float | None = 1800,
)
```

Change the plan in plain words ("don't use the courier column").
Returns the new version; this object stays the version it was.

### `plan.train()`

```python
plan.train(
    *,
    preset: str = "full_quality",
    engine: str = "auto",
    wait: bool = True,
    quiet: bool = False,
    on_progress: Callback | None = None,
    timeout: float | None = None,
)
```

Train and test this plan. `preset="fast_preview"` is a ~15-second
sanity check on a sample; the default is the real model.

## Model

A trained (or training) model. `predict()` scores with it.

| Attribute | |
|---|---|
| `id` | Model id |
| `state` | `SUCCEEDED` when ready; `FAILED`, `CANCELLED`, or a step name while training |
| `ready` | `True` once trained |
| `title` | What it predicts |
| `kind` | `flat`, `event` or `forecast` |
| `meaning` | What its prediction number is |
| `created_via` | The token that created it, if made from code |
| `url` | The model in the web app |
| `error_code` | Why it failed, if it did |
| `suggestions` | Server-suggested fixes |

### `model.predict()`

```python
model.predict(
    rows: Any = None,
    *,
    ids: Iterable[str] | str | None = None,
    since: str | date | datetime | None = None,
    until: str | date | datetime | None = None,
    since_days: int | None = None,
    as_of: str | date | datetime | None = None,
    limit: int | None = None,
    filters: list[dict] | None = None,
    include: list[str] | None = None,
    calibrated: bool = False,
)
```

Score with this model.

* `rows` (DataFrame, list of dicts or one dict): score these records.
  Predictabl builds the features from them with the model's own SQL.
* otherwise Predictabl scores from the data it was trained on:
  forecasts from the latest data (or `as_of`), event models for rows
  dated today (or `since`/`until`/`since_days`), optionally only
  `ids`, highest first, at most `limit` (server cap 2000).

### `model.report()`

```python
model.report()
```

The tested result: metric, rows, top features, what it predicts.

### `model.wait()`

```python
model.wait(
    *,
    quiet: bool = False,
    on_progress: Callback | None = None,
    timeout: float | None = None,
)
```

Block until training ends. Raises BuildFailed if it failed.

### `model.events()`

```python
model.events()
```

Everything the run reported, step by step.

### `model.refresh()`

```python
model.refresh()
```

Reload state, kind and errors from the server.

### `model.cancel()`

```python
model.cancel()
```

Stop training. The model ends CANCELLED.

## Predictions

A list of predictions (dicts with `entity_id`, `prediction`, ...),
plus what they mean: `meaning`, `kind`, `as_of`, and any `note` or
`warning` the server attached.

| Attribute | |
|---|---|
| `meaning` | What `prediction` is, in words |
| `kind` | `flat`, `event` or `forecast` |
| `as_of` | Forecasts: the date they are made from |
| `note` | Why nothing matched, when nothing did |
| `warning` | A caveat about how the scores were made |
| `where_used` | Which rows were scored, as the server applied it |
| `count` | How many matched (can exceed `len()` when limited) |
| `raw` | The server's full response, without the predictions |

### `predictions.to_pandas()`

```python
predictions.to_pandas()
```

The predictions as a DataFrame (needs pandas). Context columns
requested with `include` become their own columns.

## Progress updates

`on_progress` callbacks receive `pb.Update` objects:

| Field | |
|---|---|
| `step` | e.g. `Uploading`, `Planning`, `Training`, `Final model` |
| `status` | `running`, `done` or `failed` |
| `detail` | Short text, e.g. `30 features · 2 excluded` |

## Errors

Every error carries the server's machine `code` (when it sent one) and a
message meant for a person: the API phrases refusals as "what happened and
what to do", and these classes pass that through untouched.

| Exception | |
|---|---|
| `pb.PredictablError` | Base class for everything this package raises. |
| `pb.AuthenticationError` | The API key is missing, wrong or revoked (HTTP 401). |
| `pb.PermissionDenied` | The API key is valid but its scope does not allow this (HTTP 403). Predictions only keys cannot connect data, plan or train. |
| `pb.NotFound` | No such object for this account (HTTP 404). Someone else's objects look exactly like missing ones, by design. |
| `pb.LimitReached` | A free-plan allowance on Predictabl's AI key is used up (HTTP 402). The message says how to continue (your own AI key, or an upgrade). |
| `pb.InvalidRequest` | The request was understood but refused (HTTP 4xx), e.g. a model that needs rows was asked to score without them. |
| `pb.BuildFailed` | A step of building a model (reading the data, finding the question, planning, training) ended in failure. `suggestions` lists the server's recovery options when it gave any. |
| `pb.ApiError` | Anything else the server answered with an error. |
