Metadata-Version: 2.5
Name: sqwishai
Version: 0.5.0
Summary: Sqwish AI: OneHot API clients and local Kettei inference
Project-URL: Homepage, https://docs.sqwish.ai
Project-URL: Documentation, https://docs.sqwish.ai/guides/sdks
Project-URL: API reference, https://docs.sqwish.ai/api-reference/overview
Project-URL: Console, https://console.sqwish.ai
Author-email: Sqwish Labs <help@sqwish.ai>
Maintainer-email: Sqwish Labs <help@sqwish.ai>
License-Expression: Apache-2.0
License-File: LICENSE
License-File: LICENSE-MODEL.md
License-File: THIRD_PARTY_NOTICES.md
Keywords: ai,classification,decisions,kettei,llm,onehot,probabilities,sdk,sqwish,sqwish labs
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
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: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx<1,>=0.28
Provides-Extra: local
Requires-Dist: huggingface-hub<2,>=1.5; extra == 'local'
Requires-Dist: jinja2>=3.1; extra == 'local'
Requires-Dist: mlx<0.33,>=0.32.4; (sys_platform == 'darwin' and platform_machine == 'arm64') and extra == 'local'
Requires-Dist: numpy<3,>=2; (sys_platform == 'darwin' and platform_machine == 'arm64') and extra == 'local'
Requires-Dist: safetensors>=0.6; extra == 'local'
Requires-Dist: torch<3,>=2.6; (sys_platform != 'darwin') and extra == 'local'
Requires-Dist: transformers<5.18,>=5.17; extra == 'local'
Provides-Extra: test
Requires-Dist: build; extra == 'test'
Requires-Dist: pytest<10,>=8; extra == 'test'
Requires-Dist: wheel; extra == 'test'
Description-Content-Type: text/markdown

# OneHot Python SDK

Synchronous and asynchronous clients for the OneHot API. A decision is one question
with a fixed set of allowed outcomes, and OneHot answers it with a probability for
each outcome. The SDK needs Python 3.11 or newer and uses `httpx` with `anyio`.

## Install

```sh
pip install sqwishai
```

The package installs and imports as `sqwishai`: `from sqwishai import OneHot`.

## Your first decision

Make a key in the console at [console.sqwish.ai](https://console.sqwish.ai). Keys look like
`onehot_sk_...`.

```python
import os

from sqwishai import OneHot

with OneHot("https://api.sqwish.ai", api_key=os.environ["SQWISH_API_KEY"]) as client:
    result = client.decide(
        context="Please refund the duplicate charge on my invoice.",
        decisions=[{
            "id": "team", "question": "Which team should handle this?",
            "outcomes": ["billing", "technical", "sales"],
        }],
    )
    team = result["decisions"]["team"]
    print(team["top"], team["p_top"], team["probabilities"])
```

The address is the server's origin, without `/v1`. An argument you pass wins. If you leave
out the address or the key, the client reads `SQWISH_BASE_URL` or `SQWISH_API_KEY`, and with no
address there either it uses `https://api.sqwish.ai`. With no key anywhere, a call
raises before anything is sent; only `lint` and `systemone_translate` work without one.

Leaving `model` out uses the server's default base size. To pick a size, pass its id as
`model`, such as `"kettei-core"`: `client.models.list()` lists every size with its status.
A family you have trained is called by its name, such as `"router"`, and one of its
models by its number, such as `"router@3"`.

Each decision has an `id`, a `question` and its outcomes. `kind` is `"single"` (the
default), `"binary"` (yes or no) or `"ordinal"` (levels `"0"`, `"1"` and so on, with one
`rubric` line per level). `temperature`, from 0.2 to 5, reshapes every answer's
probabilities: below 1 sharper, above 1 softer, and the top answer never changes. Left out,
the model's own default applies, and `temperature=1` gives the probabilities as the model
scored them.

Replies are plain dicts, typed in `sqwishai.types`, and every type imports from the package as
well: `from sqwishai import Job`. `AsyncOneHot` has the same methods, used with `await` and
`async with`.

## What else it covers

| Call | What it does |
|---|---|
| `client.lint(context, decisions)` | Warns about how questions are asked. No model runs. |
| `client.datasets` | `create` (rows as a JSONL file, its bytes or a list, up to 16 MiB), `get`, `list`, `iter`, `rows` (of any version), `rename`, `delete` and `restore`; `add_rows` adds a version, `versions` lists them and `download` reads one side of one; `labels_to_check` lists the labels prompt tuning doubted, each with its row |
| `client.evaluations` | Score models on a dataset's evaluation rows: `create`, `get`, `list`, `iter`, `cancel`, `retry` |
| `client.fine_tuning` | the jobs `families.create` and `families.continue_` queue: `get`, `wait`, `events`, `records` (the held-out answers), `cancel`, `list`, `iter` |
| `client.prompt_tuning` | Better wording for one decision: `create`, `get`, `wait`, `cancel`, `list`, `iter`; `dismiss_label_issues` takes a job's doubted labels off its dataset's labels to check |
| `client.families` | `create` (a new family's first fine-tune) and `continue_` (its next), each with its exact fee first (`estimate`, `estimate_continue`); `list`, `get`, `switch`, `keep_warm`, `rollback` and `delete`; `wait` until a family serves its new model |
| `client.models` | `list`, `get`, `ready`, `switch`, `keep_warm` and `delete`, each model by its number, such as `"router@3"` |
| `client.labeling` | Teacher labels for your own queries: `teachers`, then `sources.upload` and `jobs.create`, `wait`, `results`, `finalize`; `sources.delete` removes a source and its teacher answers for good |
| `client.account` | `get`, and `keys.list`, a page at a time, active or revoked, each with its `scope` and, for an inference key, its monthly cap. Keys are made and revoked in the console. |
| `client.capabilities()` | Models, recipes, limits, training availability and capacity warnings |

Most `list` calls return one page with `has_more` and `next_cursor`, and `iter` walks every
page. `client.models.list()`, `client.families.list()` and `client.datasets.versions()`
return the whole list. The lists of jobs filter by `status`, one or a list, and those of
fine-tunes and prompt-tuning jobs by `dataset_id` too:
`client.fine_tuning.list(status=["queued", "running"], dataset_id=dataset_id)`.
`wait` polls a job until it ends. The [fine-tuning](https://docs.sqwish.ai/guides/fine-tuning)
and [labelling](https://docs.sqwish.ai/guides/labelling) guides describe both flows step by step.

`client.capabilities().get("warnings", [])` contains advisory messages. `engine_busy`
names the affected catalogue model in `model`; `queue_full` and `tenant_queue_full`
concern fine-tuning. Display `message` beside the relevant action. Read again to clear
warnings as capacity returns. These snapshots do not reserve capacity, and missing or
stale engine measurements produce no warning, not a promise of spare capacity.

## Families and models

A family, such as `router`, is a line of models, each trained from the one before:
`router@1`, `router@2` and on. A model joins only if it passes its gate. Calls to `"router"`
get the model the family serves while it is switched on, and calls to `"router@1"` get that
model while its own switch is on.

```python
quote = client.families.estimate("router", dataset_id)  # the exact fee, before anything starts
job = client.families.create("router", dataset_id, dataset_version=quote["dataset_version"],
                             max_price_usd=quote["price_usd"])  # from core; start_from="router@2" starts from a model
job = client.fine_tuning.wait(job["id"])  # router@1; outcome "joined" if it passed its gate
client.datasets.add_rows(dataset_id, "more.jsonl")  # the dataset's next version
quote = client.families.estimate_continue("router")
job = client.families.continue_("router", dataset_version=quote["dataset_version"],
                                max_price_usd=quote["price_usd"])  # its next model, on the rows quoted
job = client.fine_tuning.wait(job["id"])  # a family trains one model at a time
family = client.families.wait("router", job["output_model"])  # calls to "router" now get it
family = client.families.get("router")  # served, latest, move, jobs and continue
client.models.switch("router@1", True)  # answers calls to its number as well
client.families.rollback("router", "router@1", ["router@2"])  # discards router@2 for good
```

A model that joins doesn't answer calls to the family's name straight away: a family that is
switched on moves to it by itself once it has loaded and answered a probe. `client.families.wait`
returns the family once it serves the model you name, the job's `output_model` or its number.
It raises at once for a wait that can't end: a family switched off never moves, a model that
failed its gate never joined, and a family moves only to its latest model. Running out of time
raises `TimeoutError`, saying what the move waits for. Continue a family only once its last
fine-tune has finished: while one trains, `families.continue_` raises `family_training`. It
trains on the dataset's newest version, or the `dataset_version` you name. The example names
the version it was quoted for, so rows added meanwhile wait for the next model. The version
must be newer than the one the family's last finished job trained on, or the call raises
`no_new_data`.

A switch or keep warm past your tier's limit raises `live_limit` or `warm_limit`. Its
`details` list what answers or is kept warm, least recently used first, and `switch_off=`
frees a place in the same call. `served=` on a family and `adapter=` on a model are the id you
read: the call raises `served_changed` or `model_changed` if it changed since.
`sqwishai.types.RefusalCode` lists the codes these calls refuse with.

## Estimates and paid requests

`client.estimate(context, decisions, model=..., fallback=...)` returns billed input tokens,
the pinned billing tokenizer, each eligible model's `quote_usd`, and
`maximum_charge_usd`, the requested model's price, which a fallback never exceeds. `client.systemone_estimate(state, questions, model=...)` quotes a
Jev request. Estimates run no model and reserve no money; a later request uses the policy
in effect when it is accepted.

`client.families.estimate(...)` takes the arguments of `create`, and
`client.families.estimate_continue(family, ...)` those of `continue_`, without
`max_price_usd` or `idempotency_key`. Each returns
the exact `price_usd` the job would hold if it started now, with its `trained_tokens`, `steps`,
`seed`, `passes`, the `rows` it takes (new, earlier and evaluation) and whether
`minimum_applied`. Pass `price_usd` as `max_price_usd`: a job that costs more by then, because
a price, the dataset or the family changed, raises `price_changed` and holds nothing.

`decide` and `systemone` send one generated operation key per call and reuse it for
network and retryable API failures. To survive a restart or retry a timed-out call, persist
your own `idempotency_key="your-operation-id"` and pass the same payload and key again. A
different payload with the same key returns `idempotency_conflict`; a new key creates a new
billable operation.

When a call fails, its `APIError` names the key it sent as `idempotency_key`: yours, or the
one the SDK made. After an error that is `retryable`, or whose `idempotency_status` is
`"pending"`, call again with that key and the same payload. A pending error is a
`409 request_in_progress` with an `operation_id`: the server accepted the decision, and it is
still running or its end isn't known yet. Only its key asks about it. A call without the key
is a new operation, and you are charged for both if the first was answered after all.

```python
import time

from sqwishai import APIError

ticket = "Please refund the duplicate charge on my invoice."
refund = [{"id": "refund", "kind": "binary", "question": "Does the customer ask for money back?"}]
try:
    result = client.decide(ticket, refund)
except APIError as error:
    if not (error.retryable or error.idempotency_status == "pending"):
        raise
    time.sleep(error.retry_after or 2)
    # The same key asks about the same decision. Without it, this would be a second one.
    result = client.decide(ticket, refund, idempotency_key=error.idempotency_key)
```

The same holds for every call that takes `idempotency_key`, such as `families.create`: a
second call without the key starts a second job. A call that got no answer leaves its outcome
unknown too: it ends with `TimeoutError`, or with the `httpx.TransportError` of a lost
connection, and that error carries the same `idempotency_key` attribute. Call again with it.
`getattr(error, "idempotency_key", None)` reads the key from any of these errors, and is
`None` for a call that sent none, such as a read.

The SDK sends a key with every `decide` and `systemone`, so it never meets
`409 outcome_unknown`. A request sent over plain HTTP without an `Idempotency-Key` gets that
when the server can't say how an accepted decision ended. It is not retryable: nothing names
that decision, so a request sent again would be a second one and could be a second charge.

The answer's `charge` contains `amount_usd` (the served model's final cost), `reserved_usd`
(the maximum reserved), `currency`, and `operation_id`. USD values are exact decimal
strings; use `decimal.Decimal` for arithmetic. Unused reserved credit is released.
Replaying a completed operation returns its stored answer without running or charging
again. Once the answer expires, the key still prevents rerunning it and returns
`idempotency_response_expired`.

A final failure releases its hold. `APIError.idempotency_status == "terminal"` and
`operation_id` identify this outcome, and the SDK stops retrying it. The one exception is
`model_warming` with `wait_for_warm`: that failure charged nothing, so the SDK sends the
decide again under a new key after each `Retry-After`, until `wait_for_warm` runs out. The
call then has [at least that wait, a full execution window and an answer margin](#how-long-a-call-may-take), so the
attempt that finds the model loaded is answered. It does this only for a key it made; with
your own `idempotency_key` it raises, and you start a new call deliberately.

## Errors and retries

Every API error raises `APIError`. It carries `status`, a stable `code` such as
`model_answers`, the API's sentence as `message`, `request_id`, `details` (on a 422, each bad
field with its path) and `retryable`, which says whether the same request can succeed later.
`str(error)` is the sentence, then the code, the status and the request id, which is what to quote
when you ask us for help: `... (model_answers, HTTP 409, request req_...)`.
`idempotency_key` is the key the call sent, or `None` for a call that sent none, such as a
read: [send a paid request again](#estimates-and-paid-requests) with it.

```python
from sqwishai import APIError

try:
    client.models.delete("router@2")
except APIError as error:
    print(error.code, error)  # model_answers: its family serves it, or its own switch is on
```

Eligible calls retry connection failures and API errors up to `max_retries` times after
the first attempt (default 2). The server's `retryable` flag takes precedence; without
that flag, a 429, 502, 503, 504 or 529 can retry. A terminal operation never retries.
Without a usable `Retry-After`, waits grow exponentially with random jitter and a bounded
base delay.

The SDK waits for the server's `Retry-After` delay in seconds and up to a random tenth more,
so callers refused together do not all retry together. If that wait would leave
too little time for another attempt, it raises the API error immediately with `retry_after`.
It does not retry early. A create keeps one `Idempotency-Key` and the same body across
retries; pass `idempotency_key=` to keep the key across restarts as well.
Set `max_retries` on the client to change the retry limit, or to `0` to disable the retry loop.

### How long a call may take

A call's budget counts every attempt, the waits between them and the reading of the answer.
The default leaves a margin beyond the server's execution deadline. The
[budget definitions](../../docs/code-tour/inference.md#request-budgets) link to the client
constants, server policy and proxy limits.

A settlement still unresolved at the response deadline returns `request_in_progress` with
`Idempotency-Status: pending` when a key was sent. Retry with that same key to find its outcome.
Without a key it returns non-retryable `outcome_unknown`; inspect the operation in usage before
sending more work. Time before execution, stalled admission or a custom policy can still
outlast the proxy; a proxy timeout does not prove the request was uncharged.

Every automatic inference retry can start fresh work. Even a pending key can be freed by
settlement before the retry arrives. A decision is sent again only when the wait leaves the
default execution deadline plus settlement grace; later failures are raised with their key.
The [budget definitions](../../docs/code-tour/inference.md#request-budgets) name this window.
Early refusals can therefore retry within the default call budget. Connection recovery and
gateway failures follow the same rule.

A deployment whose execution policy exceeds the SDK's assumed default also exceeds its
default call-budget assumption. A longer timeout lets a resend start later, but the window a
resend reserves stays the default execution deadline plus settlement grace; under a longer
server policy a resend can still run past it and then ends at your timeout, with the key.
With a `timeout` below that window a decision is never sent again automatically.

File uploads, fine-tune starts and estimates have operation-specific minimum budgets. A
decision that waits for its model to load has at least that wait, a full execution window
and the margin for its answer.
The [budget definitions](../../docs/code-tour/inference.md#request-budgets) name each minimum.
Creating a dataset with JSON rows or adding JSON rows uses the ordinary call budget.
The longer upload budget applies to methods that send file contents.

A timeout you set on the client replaces the default for ordinary calls. It never cuts an
operation's minimum budget short. A timeout you pass to one call is a hard limit on that call,
whatever the operation.

A call out of time ends with a timeout error that names the `Idempotency-Key` it sent. Its
request may still be running. Call again with that key: the server answers for the same
operation, and charges it once.

In Python the timeout is `timeout`, in seconds: on `OneHot` or `AsyncOneHot` for the client,
and on any request method for one call. A decision's wait is `wait_for_warm`, and a call out
of time raises `TimeoutError`.

For example, `client.models.list(timeout=5)` bounds one read. `wait_for_warm=30` alone asks
again for 30 seconds and leaves a full execution window plus the answer margin. To bound
the whole call to 30 seconds, pass both. That short budget cannot fit a warm retry, so
`model_warming` is raised immediately:

```python
result = client.decide(
    context="Please refund my invoice.",
    decisions=[{"id": "refund", "question": "Is a refund requested?", "kind": "binary"}],
    model="router", fallback="none", timeout=30, wait_for_warm=30,
)
```

The same options work with `await client.decide(...)` on `AsyncOneHot`. A `wait()` helper's
`timeout` covers its whole polling loop. An `iter(timeout=...)` override covers each page
request, including that page's retries; it does not bound time your code spends processing
items. Cancelling an async task stops its active request or warm wait.

The synchronous client's own connection pool uses cancellable HTTP I/O on a dedicated
event loop. Its deadline cancels the active request, including while reading a response
body. Concurrent calls keep their own connections and deadlines. A client made before a
process forks works in the child: under gunicorn `--preload`, Celery or `multiprocessing`,
each worker creates connections and an event-loop thread on its first call, and the parent
keeps its own. On Python 3.12 and later, forking after a synchronous call can emit Python's
DeprecationWarning about forking a process with threads. Prefer forking before the first
call. Close the client, or use it as a context manager, to release its pool.
A supplied synchronous `http_client` retains ownership of its transport: the SDK bounds
how long it waits, but cannot interrupt arbitrary blocking code in that client. Configure
its I/O timeouts, or use `AsyncOneHot` with an asynchronous transport for cancellation.

Some calls are never repeated automatically, because a lost reply leaves their outcome
unknown: a prompt-tuning job's `cancel`, a family's `delete`, and a family's `switch` that
names `served`, since a second one would find the family gone or moved. Check `retryable`, or
read the job with `prompt_tuning.get` or the family with `families.get`, before you send one again.

A client keeps its connection open between calls for up to `keepalive_expiry` seconds (default
180), so a call made within that time skips the setup of a new connection, about 100 ms. Pass
`keepalive_expiry=None` to keep it until the server closes it; with an `http_client` of your own,
set it on that client instead. When the server has closed a kept connection just as a call goes
out, a call safe to send twice (a read, or one with an `Idempotency-Key`) goes again at once
on a new connection without using a retry. Inference replay also requires the execution and
settlement window above to remain in the call budget. Any other call raises as above.

`wait()` raises `JobFailed` for a failed or cancelled job, with the whole job in
`error.job`. Running out of time stops the waiting, not the job.

## Moving from Jev

`client.systemone(state, questions, model=...)` sends TypeSafe's Jev request shape to
`POST /v1/systemone` and returns Jev's answer shape. It needs a `model`: a size's id from the
console or `client.models.list()`. Jev's own model ids are accepted too and run on one of our
base sizes, and the answer's `model` says which. A field that OneHot doesn't model is
rejected with a 422 naming it, rather than ignored.

```python
# A base model that is serving, not one of your fine-tunes (which carry an adapter, `lora`). Or
# use the id shown in the console.
size = next(m["id"] for m in client.models.list() if m["status"] == "ready" and not m.get("lora"))
answer = client.systemone(
    "My parcel arrived broken.",
    {"refund": {"type": "noul", "instructions": "Is the customer asking for a refund?"}},
    model=size,
)
print(answer["answers"]["refund"]["noul"])
```

`client.systemone_translate(state, questions, model=...)` takes the same arguments and
returns the native request as `request`, ready for `client.decide(**translated["request"])`,
with `notes` on what changed. The notes include how a Jev confidence threshold becomes a
`p_top` threshold. It runs no model and needs no key.

## More

- [api.sqwish.ai/openapi.json](https://api.sqwish.ai/openapi.json) is the source of
  truth for every field.

`create` and `add_rows` take `examples`, whose sides the API picks, or `training` and
`evaluation`, whose rows take the side of their part; never both. With `examples`,
`evaluation_fraction` is the share held out, from `0.1` to `1`, `0.2` by default; `1`, or
`evaluation` alone, makes an evaluation-only dataset. On `add_rows` it is the share of the new
contexts held out, `0.2` when left out, whatever share the dataset was made with. A row names no side, and a context keeps
its side in every version. Teacher-label finalisation takes `row_indices` with
`evaluation_fraction`, or `training_indices` and `evaluation_indices`, in the same way.
`download` takes the side, `"training"` or `"evaluation"`. The saved split cannot be edited.

Dataset `list` and `iter` accept `archived` to read the datasets we archived, when credit
couldn't cover their storage or the account was suspended; `restore` brings one back for new
work. `rows` accepts `partition` (`all`, `training` or `evaluation`). `rename` changes only the
name. `delete` removes a dataset for good, with every version's upload and the copies its
fine-tunes kept; the fine-tunes and their models stay, and work still reading it refuses.

Every request names the client in `User-Agent` and `OneHot-Client`: the SDK and its version, then
httpx, Python and the operating system. When this machine's Hugging Face cache holds Kettei Dot's or
Core's weights, the value ends with `local-kettei`. The SDK looks for them once, when it is imported,
and sends nothing else about the machine or the models.


## Kettei on your machine

Kettei Dot and Core are open models. `Kettei` runs either one on your own machine and answers the
same `decide` call as OneHot, in the same shape, with no key and nothing of yours sent anywhere. It
takes `decide`'s arguments but `fallback`, `wait_for_warm`, `idempotency_key` and `timeout`, which
manage a call to OneHot.

```sh
pip install "sqwishai[local]"
```

```python
from sqwishai import Kettei

with Kettei("kettei-dot") as kettei:
    result = kettei.decide(
        context="Please refund the duplicate charge on my invoice.",
        decisions=[{
            "id": "team", "question": "Which team should handle this?",
            "outcomes": ["billing", "technical", "sales"],
        }],
    )
print(result["decisions"]["team"]["top"])
```

The first use downloads the model from Hugging Face
([Sqwish/Kettei-Dot](https://huggingface.co/Sqwish/Kettei-Dot)) at the revision this release was
tested with, so `HF_HOME` and `HF_HUB_OFFLINE` work as usual. `"kettei-core"` is the larger size,
and a folder holding either checkpoint loads too. The model's own licence applies to its weights. A
request with more than 65,536 bytes of text is counted as OneHot counts input tokens, with the
tokenizer each of its answers names in `usage.tokenizer`, fetched from Hugging Face the first time.

On Apple silicon Kettei runs on the GPU with MLX, and an M5's Neural Accelerators run a tuned
engine. On Linux and Windows it runs with PyTorch, on CUDA when the machine has a GPU and PyTorch's
CUDA build. On Linux pip installs that build, so on a machine without a GPU, install the CPU build
first with `pip install torch --index-url https://download.pytorch.org/whl/cpu`. On Windows pip
installs the CPU build, so for a GPU install the CUDA one first, as pytorch.org shows for your CUDA
version. Intel Macs can't run Kettei.
`device="mlx"`, `"cpu"`, `"cuda"` or `"cuda:1"` asks for one, and `repr(kettei)` names what runs.
One `Kettei` may be shared by threads; its calls run one at a time.

Swap `Kettei("kettei-dot")` for `OneHot(...)` and the same call runs on OneHot, on Core unless you
name a model; OneHot serves Core, Chub and Fat, and Dot runs only on your machine. Local answers can
differ slightly from hosted ones. With no bill, `usage.prompt_tokens` counts the tokens the model
read on this machine, where OneHot counts billed `input_tokens`. Kettei Fat and Chub, images and
your fine-tuned families run on OneHot: `Kettei`
refuses them with a `KetteiError` that says how to call it, and every refusal carries the code
OneHot gives for the same thing.
