# Python library

> Install yhatlabs, configure the client, handle errors, use async, and see what each call did.

`yhatlabs` is the official Python library. It takes pandas, polars (lazy too), Spark, Dask or Ray tables, handles batching,
retries, background jobs and data checks, and returns pandas results. A distributed table larger than the API takes raises
`DataError` before it is collected.

## Install

```sh
pip install yhatlabs
```

Python 3.9 or later; it depends on httpx, numpy and pandas. Extras add optional features:

| Extra | Adds |
|---|---|
| `[sklearn]` | the scikit-learn estimators |
| `[plot]` | `yhatlabs.plots` and the `.plot()` methods (matplotlib) |
| `[parquet]` | smaller uploads of large tables (pyarrow) |
| `[fast]` | faster encoding of large requests (orjson, pyarrow) |
| `[all]` | all of the above, plus polars and holidays |

## The client

`Client()` is the entry point; every call goes through it.

| Argument | Default |
|---|---|
| `api_key` | `YHAT_API_KEY` |
| `base_url` | `YHAT_BASE_URL`, else `https://api.yhatlabs.com` |
| `timeout` | 300 seconds per request |
| `max_retries` | 3 |
| `max_concurrency` | 4 parallel requests when an input is split |
| `mask_columns` | `False`: column names are sent as they are ([Data handling](https://yhatlabs.com/models/docs/resources/data-handling#masking-column-names)) |

- `yh.with_options(timeout=1800)` returns a copy with other settings for one call, sharing the connection.
- `with Client() as yh:` closes the connection when the block ends.

| Time series | Tables | Account |
|---|---|---|
| `forecast`, `evaluate`, `scenarios`, `explain_forecast`, `detect_anomalies`, `anomaly_stream`, `fill_gaps` | `fit`, `predict`, `compare`, `evaluate_table`, `estimate_table`, `impute`, `get_fit`, `fits` | `whoami`, `models`, `usage`, `server_limits` |

Module functions: `yhatlabs.check`, `yhatlabs.outliers` (rows unlike the training rows; local, no key) and `yhatlabs.load`. Helpers in `yhatlabs.features`: `add_calendar` and `make_future`.
Charts in `yhatlabs.plots` ([Plots](https://yhatlabs.com/models/docs/tools/plots)).

`yh.limits` holds the API's request caps, read from `GET /v1/limits` on first need, and the features the API has switched
on: `yh.limits.supports("gzip_requests")`. The library uses a feature only once the API lists it, so features added to the
API later reach this version too.

## Async

`AsyncClient` has the same calls as coroutines, for services and notebooks that already run an event loop:

```python
from yhatlabs import AsyncClient

async with AsyncClient() as yh:
fc = await yh.forecast(df, h=24)
model = await yh.fit(train, target="churn")
res = await model.predict(test)
```

## Background jobs

A table past the direct size runs as a background job, and `fit` or `predict` waits for it, so the result is the same.
`background=True` returns a `Job` at once instead: `job.status()`, `job.wait(timeout=)` (two hours by default),
`job.result()` and `job.cancel()` ([Async jobs](https://yhatlabs.com/models/docs/api/jobs#in-python)).

## Errors

| Raised | When |
|---|---|
| `DataError` | before anything is sent: the input can't be used; the message says how to fix it |
| `UnsupportedError` | the model can't do what was asked |
| `ConfigurationError` | no key, or a missing optional package (the message names the package) |
| `APIError` and its subclasses | the API returned an error; they carry `.status`, `.type` and `.request_id` |
| `JobFailedError` | a background job failed or was canceled; `.job_id` names it |

`APIError` subclasses: `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `RequestTooLargeError`
(413), `BadRequestError` (400, 422), `RateLimitError` (429), `InternalServerError` (5xx), `ServiceUnavailableError` (503).
Network problems raise `APIConnectionError` or `APITimeoutError`.

Timeouts, connection errors, and 408, 409, 429 and 5xx responses are retried with backoff, honouring `Retry-After`. A used-up
quota is not retried. Quote the `request_id` to us and we can trace the call.

Every POST carries an `Idempotency-Key` that stays the same across its retries. If a connection drops after a fit was made,
the retry gets the first reply back instead of fitting, and paying, twice ([API overview](https://yhatlabs.com/models/docs/api/overview#conventions)).
Request bodies over 1 MB are sent gzip-compressed once the API lists the `gzip_requests` capability.

## See what each call did

- `YHAT_LOG=info` logs every request: method, path, status, time, request id and retries. Data and keys are never logged.
- In a terminal, a one-line activity indicator appears once a call runs for more than two seconds. `YHAT_PROGRESS=0` turns it
  off; scripts and notebooks stay silent.
- Every result carries `.provenance` (model, settings, request ids, library version, a fingerprint of the input) and `.timing`.
