Metadata-Version: 2.4
Name: kos-cloud
Version: 1.0.0b1
Summary: Python client for KOS Cloud: solve LP and MIP models on the KOS solver service
Author-email: Katsenia SpA <support@katsenia.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://katsenia.com
Project-URL: Documentation, https://katsenia.com/cloud-api.html
Keywords: linear programming,mixed integer programming,LP,MIP,optimization,solver,KOS,cloud
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
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: Topic :: Scientific/Engineering :: Mathematics
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Provides-Extra: kos
Requires-Dist: kos-solver>=1.0.0b1; extra == "kos"
Dynamic: license-file

# kos-cloud

A small Python client for **KOS Cloud**, the hosted service of the KOS optimization solver: send an LP or MIP model,
wait for it and read the solution, from a script or a notebook, without curl.

- Pure Python, no dependencies, Python 3.9 or newer.
- Full API reference: <https://katsenia.com/cloud-api.html>

```
pip install --pre kos-cloud
```

`--pre` is needed while kos-cloud is a beta release (1.0.0b1).

## Quick start

Create an API key in your KOS Cloud account and put it in the environment:

```
export KOS_API_KEY=kos_...
```

```python
import kos_cloud

r = kos_cloud.solve("model.mps", tier="medium", time_limit=600)
print(r.status, r.objective)   # optimal 1234.5
print(r.values["x"])           # the value of column x
print(r.duals["demand"])       # the dual of row "demand" (LP)
```

`solve` uploads the model, waits for the job and downloads its solution. Pass `progress=True` to see the solver log
as it runs.

## What you can send

| `model`                                   | sent as                                                  |
|-------------------------------------------|----------------------------------------------------------|
| a path (`str` or `pathlib.Path`)          | the file as it is: `.mps`, `.lp`, or compressed `.gz`, `.bz2`, `.xz`, `.zip` |
| LP or MPS text (a `str` with line breaks) | text; add `format="lp"` or `format="mps"` if needed      |
| `bytes`                                   | the contents of a file                                   |
| a `kos.Model`                             | MPS, compressed with gzip                                |

The service detects the format and the compression. For a `kos.Model`, install the solver package too:
`pip install --pre "kos-cloud[kos]"` (it installs `kos-solver`, imported as `kos`). `kos_cloud` never imports `kos`
itself.

Options of `solve` and `submit`: `tier`, `time_limit` (seconds), `params` (a dict of KOS parameters), `profile`,
`keep_model`, `prove_objective` (for an LP, prove the objective in exact arithmetic; the service does by default),
`certificate` (ask for the certificate of an LP), `name`, `format`.

## Machine tiers and prices

Choose a tier with `tier=` (without it, the API's default tier). The catalog comes from the API, with each tier's
machine, limits and price per second:

```python
for c in kos_cloud.classes():
    print(c.id, c.vcpu, c.memory_gb, c.price_per_second_usd, c.limits["time_limit_max"])
```

The tiers and prices in force are the ones `classes()` returns and <https://katsenia.com/pricing.html> shows. A job is
charged for its seconds of compute at its tier's price, at least one second of its tier; `r.billing` says what was
charged (see "Results"). Before uploading, the client checks the model size and
`time_limit` against the tier's limits and raises the error at once (`check_limits=False` skips it; the service
checks again).

## Waiting, progress and Ctrl+C

```python
job = kos_cloud.submit("big.mps.gz", tier="large", time_limit=3600)   # returns at once
print(job.id, job.state)
job = kos_cloud.wait(job, progress=True)                               # the log goes to stderr
r = kos_cloud.result(job, log=True)
```

- `progress=True` writes the log to stderr as it arrives; a function (`progress=lines.append`) receives each
  piece of the log text instead.
- `wait_timeout=` limits the wait (then `WaitTimeoutError`; the job keeps running).
- **Ctrl+C while waiting cancels the job**: on `KeyboardInterrupt` the client sends the cancellation, waits up to
  about 10 seconds for the job to stop and raises `KeyboardInterrupt` again. It does not ask, so it behaves the same
  in scripts and notebooks. Pass `cancel_on_interrupt=False` to leave the job running. A job cancelled while it
  runs usually ends `finished` with the status `interrupted` and the best solution found so far, which
  `kos_cloud.result(job_id)` returns. Ctrl+C during the upload stops it; if the service had already received the
  whole model, the job may exist and keep running: look for it with `kos_cloud.jobs()`.

## Results

A `Result` has `status`, `objective`, `bound`, `gap`, `state`, `job_id`, `values` (column name to value), `duals`
(row name to dual, LP), `reduced_costs` (column name to reduced cost, LP), `log` (with `log=True`), `certificate`
(with `certificate=True`, when the job has one), `job` (the job as the API returns it) and `billing` (what was
charged). Money is always a `decimal.Decimal` in dollars:

```python
print(r.billing.charged_usd, r.billing.billed_seconds)
print(kos_cloud.balance().available_usd)
```

Other calls: `jobs(limit=25, state=None)`, `job(id)`, `cancel(id)`, `balance()`, `classes()`.

## Errors

Every error is a `kos_cloud.KosCloudError`, with `code`, `status`, `message` and `details`:

| error                       | when                                                                   |
|-----------------------------|------------------------------------------------------------------------|
| `AuthenticationError`       | no API key, or the key is invalid or revoked                           |
| `PreviewGateError`          | the site answered with its preview-stage gate; requests with an API key should pass it: if they do not, write to support@katsenia.com |
| `InsufficientBalanceError`  | the balance is not enough; `top_up_url` says where to top up          |
| `EmailNotVerifiedError`     | the account's email is not verified yet                               |
| `ModelTooLargeError`        | the model is too large for the upload, the tier or the storage quota  |
| `TimeLimitError`            | `time_limit` above the tier's maximum (`max_time_limit`)              |
| `MachineNotAvailableError`  | the tier cannot be used                                               |
| `RateLimitError`            | too many requests; `retry_after` in seconds                           |
| `NetworkError`              | no connection, a timeout, or the service unavailable after the retries |
| `JobFailedError`            | the job failed (`code`, `message`, `job_id`)                          |
| `JobCancelledError`         | the job was cancelled                                                 |

`ModelTooLargeError` and `TimeLimitError` are `LimitError`s.

## Retries and safety

Reads and cancellations are retried on network errors, 502/503/504 and 429 (following `Retry-After`). A submission is
retried only with its own `Idempotency-Key`, so a retry never creates a second job. Nothing else is retried.

The API key goes only in the `Authorization` header to the API's own host. Result downloads may be redirected to
short-lived signed storage URLs: those are followed without the key, only over https. The key is never printed: not
in `repr`, errors or logs.

## Your own client

```python
client = kos_cloud.Client(api_key="kos_...", base_url="https://katsenia.com/api/v1/", timeout=60)
r = client.solve("model.lp")
```

`base_url` defaults to `KOS_CLOUD_URL` or `https://katsenia.com/api/v1/`.

## License

Apache License 2.0 (see `LICENSE` and `NOTICE`). Copyright 2026 Katsenia SpA. The use of KOS Cloud is governed by its
terms: <https://katsenia.com/terms.html>.
