Metadata-Version: 2.5
Name: spavik
Version: 0.1.0
Summary: Python client for the Spavik API: training, prediction, forecasting, feedback loop.
Project-URL: Homepage, https://spavik.co
Project-URL: Documentation, https://docs.spavik.co/libraries/python
Project-URL: Repository, https://github.com/spavik-co/spavik-python-sdk
Project-URL: Issues, https://github.com/spavik-co/spavik-python-sdk/issues
Author-email: Spavik <admin@spavik.co>
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: forecasting,prediction,sdk,spavik
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx>=0.24
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: respx>=0.20; extra == 'dev'
Requires-Dist: twine>=5; extra == 'dev'
Provides-Extra: pandas
Requires-Dist: pandas>=1.3; extra == 'pandas'
Description-Content-Type: text/markdown

# Spavik Python SDK

[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
[![CI](https://github.com/spavik-co/spavik-python-sdk/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/spavik-co/spavik-python-sdk/actions/workflows/ci.yml)

Prediction infrastructure for developers.

Add predictive capabilities to your application without building an ML stack.

## Install

Requires Python 3.11 or later.

Early release: the API may change before 1.0.

```sh
python -m pip install spavik
```

## Get your API key

Create a free account at [spavik.co](https://spavik.co) and generate your API key from the dashboard.

The Free plan includes **100 predictions per calendar month**, reset on the
1st at 00:00 UTC. No credit card required.

```bash
export SPAVIK_API_KEY="sk-spv-api-..."
```

The client reads `SPAVIK_API_KEY`, and `SPAVIK_BASE_URL` when set, at the moment
it is created. Without a key, every call except the public engine catalogue
(`engines()`, `engine_families()`) raises `SpavikAuthError` locally, and nothing
is sent.

## Quickstart

Download [churn.csv](examples/data/churn.csv) and save it in your application's
working directory. It contains synthetic customer records with `plan`, `seats`,
`tickets_90d` and the known outcome `churn`. It demonstrates the API, not model quality.

Save this as `quickstart.py` beside the CSV:

```python
from spavik import Spavik

# Read your API key from SPAVIK_API_KEY.
with Spavik() as client:
    # Train on historical customers; "churn" is the value to predict. Training is free.
    model = client.train("churn.csv", target="churn")

    # Predict for a new customer using the same input columns. This consumes credits.
    result = model.predict({"plan": "pro", "seats": 12, "tickets_90d": 2})
    print(result.predictions)
```

```sh
python quickstart.py
```

`result.predictions` contains the predictions returned by the API. Reuse the trained
model for subsequent predictions; you do not need to train for every request.

Training needs at least 100 rows; with fewer, `train()` raises `SpavikDataError`
and nothing is sent. 100 rows give a much better chance of a useful result, not
a guarantee: call `client.evaluate("churn.csv", target="churn")` first, it is
free and says whether the data can predict that column.

`result.request_id`, `result.predictions_remaining` and `result.engine_version`
come from the response headers. `result.data` is the response body as the API
sent it.

## Timeouts and uncertain results

`Spavik(timeout=0.25)` and `AsyncSpavik(timeout=0.25)` apply that timeout to
every request, including retries. It overrides each operation's default.
Omit `timeout` or pass `None` to keep operation defaults, such as 15 seconds
for account usage, 120 for training and 60 for forecasting. The timeout applies
to each [HTTPX network phase](https://www.python-httpx.org/advanced/timeouts/)
of each attempt, not to the total duration of an operation
with retries and backoff.

When network retries are exhausted, `SpavikTransportError.idempotency_key`
preserves the key used for an idempotent request, and `__cause__` retains the
underlying HTTPX error. A read request has no idempotency key.
After a timeout, the server may already have executed the request. Do not
blindly call the mutation again: a new SDK call generates a new key and can
repeat the operation. To replay safely, pass the same key yourself:
`train`, `forecast`, `Model.predict`, `Model.submit_outcomes` and
`Model.refresh` accept `idempotency_key=...`, reused on every retry, so a
replayed call is not billed twice.

```python
model.predict(rows, idempotency_key="order-1234-score")
```

When the API asks to wait (`Retry-After`), the client waits up to 60 seconds
before retrying. A longer wait is not slept through: the error, such as
`SpavikRateLimited`, is raised at once.

## Input formats

The SDK accepts dictionaries, lists of dictionaries, DataFrames, raw CSV/JSON
text and file paths. JSON strings containing URLs or paths remain JSON content.
Use `pathlib.Path` to explicitly identify a file, including filenames that start
with `[` or `{`, or have no extension.

A plain string that looks like a path is read as a file: a single line ending
in `.csv`, `.tsv`, `.txt` or `.json`, or containing the path separator. Its
content is then sent to the API. If your application passes a string that comes
from its own users, do not hand it to the SDK as data: pass rows, or a
`pathlib.Path` you built yourself.

Dates and times (`datetime`, `date`, pandas `Timestamp`) are sent as ISO 8601
text, `Decimal` as a number, and missing values (`NaN`, `NaT`, `pd.NA`,
infinities) as null. This holds for DataFrames and for lists of dictionaries,
so `pd.read_csv(..., parse_dates=["date"])` works as is. A value that still
cannot be sent as JSON raises `SpavikDataError` naming the column.

CSV headers must be unique and non-empty, and lose their leading and trailing
spaces (`"plan "` becomes `"plan"`, as in the JavaScript SDK). Rows with more
fields than the header and invalid quoting raise `SpavikDataError` with the line
number before any API call. Missing values in shorter rows remain `None`; quoted
commas and newlines are preserved.

Two differences with the JavaScript SDK remain on CSV text. An integer too large
for a JavaScript number stays a Python `int` here, while the JavaScript SDK keeps
it as text. A quote inside an unquoted field (`5" screen`) is accepted here as a
literal character, while the JavaScript SDK refuses the file. Send lists of
dictionaries or a DataFrame when the two SDKs must read the same data
identically.

## Outcome feedback and data retention

Zero Data Retention only disables the archiving of the inputs and outputs of
`evaluate`, `backtest`, `forecast` and `predict`. API contracts and behavior are
identical for every data policy. Successful idempotent responses remain
replayable from a technical cache for 24 hours. There is no prediction-history endpoint on any plan,
and no `model.predictions()` method. Save prediction results and their
`request_id` values in your application if you need them later. The API request
log contains technical metadata, not prediction values.

Model creation, context, diagnostics, versions and outcome feedback are
functional model data. They require no additional retention opt-in, including
under Zero Data Retention:

```python
from spavik import Spavik

with Spavik() as client:
    model = client.train("churn.csv", target="churn")
    model.submit_outcomes([
        {"features": {"plan": "pro", "seats": 12, "tickets_90d": 2}, "actual": 1},
    ])
    model.refresh()
```

Every outcome requires a non-empty `features` object and `actual`, on every
plan. An optional `request_id` is correlation metadata; no inference archive
is queried to recover features. Pending outcomes remain available until integration or model deletion.
Examples integrated into the model become part of its persistent context.
To measure prediction quality, also provide the original `prediction`, `version`
and exact `engine`, plus `probabilities` when available. These client-reported
measurements populate `observed` and `quality_reports`, with source
`client_reported_predictions`; inference archives are never used for performance.
The same rules apply to `Spavik` and `AsyncSpavik`.

## What you can do

- Classification and regression
- Time-series forecasting
- Dataset validation and evaluation
- Model performance monitoring and outcome feedback

## Documentation

See [docs.spavik.co](https://docs.spavik.co) for guides and the API reference.
For development and contributions, see [CONTRIBUTING.md](CONTRIBUTING.md).

## License

[Apache-2.0](LICENSE)
