# The Python SDK.

`ConceiverClient` takes the API URL and the account key. Read both from `TOOLVING_API_URL` and `TOOLVING_API_KEY`. To install the SDK on Linux, macOS, Windows or WSL and check the setup, follow the [quickstart](https://toolving.com/docs/quickstart.md). To learn how to teach each kind of task, read the [teaching guide](https://toolving.com/docs/teaching.md). For complete programs, start from the [example apps](https://toolving.com/docs/examples.md).

```python
from toolving import ConceiverClient

with ConceiverClient(api_url, api_key) as client:
    print(client.models())
    print(client.storage())
    instance = client.create(model="language", key="create-context")
    instance.teach("support queue", "Customer care", key="teach-queue")
    prediction = instance.query("support queue", key="ask-queue")
    print(prediction.status, prediction.text, prediction.output, prediction.confidence)
    print(prediction.evidence.markdown)
    remembered = instance.query("support queue", with_memory=True, key="ask-memory")
    print(remembered.evidence.episodes)
    instance.resolve(prediction.prediction_id, "Customer care", key="actual-outcome")
    current_text = instance.training_sequence()["text"]  # no server-side storage
    sequence = instance.save(key="save-account-learning")  # requires storage
    training_text = client.training_sequence_text(sequence)
    print(training_text)
    retirement = instance.reap(key="release-context")
    print(retirement.persisted, retirement.artifact)
    restored = client.create(sequence_id=sequence, key="restore-context")
    another = client.create(key="create-import-target")
    another.ingest_training_sequence(training_text)
```

`client.models()` lists two models: `language`, which starts empty and learns what you teach it, and `numbers`, a ready-made calculator (see [The numbers model](#the-numbers-model)). `create()` without `model` makes a `language` instance. Teach JSON answers to a `language` instance as one line and read the decoded value from `output`; there is no separate JSON model. `model="json"` with `client_host` and a 64-character lowercase hexadecimal `compatibility_scope` remains for agent-harness clients and is not listed: it is a language instance whose learning is shared by that client's sessions. `client.storage()` reports whether durable sequence and model storage is enabled, and what a spin-down keeps (see [Saving at spin-down](#saving-at-spin-down)).

## The numbers model

`client.create(model="numbers")` starts an instance that already answers arithmetic, so you do not have to teach it:

```python
calc = client.create(model="numbers")
calc.query("1234 plus 4321").text        # '5555'
calc.query("-5 + 3").text                # '-2'
calc.query("2.5 * 4").text               # '10'
calc.query("10 / 4").text                # '2.5'
calc.query("17 % 5").text                # '2'
calc.query("1,000 - 2,500").text         # '-1500'
calc.query("300 compared to 299").text   # 'greater'
calc.query("12 xor 10").text             # '6'
calc.query("65536 * 65536").text         # '4294967296'
calc.query("5 / 0").status               # 'UNRESOLVED'
calc.query("1 + 2 * 3").status           # 'UNRESOLVED'
```

| Operation | Write it as |
|---|---|
| add, subtract | `plus` or `+`, `minus` or `-` |
| multiply | `times`, `*` or `x` |
| divide, remainder | `divided by` or `/`, `mod` or `%` |
| compare | `compared to`; answers `greater`, `less` or `same` |
| bitwise | `and`, `or`, `xor` |

It reads negatives (`-5`), digit groups (`1,000`) and up to six decimals, and answers exactly to six decimal places (`1 / 3` is `0.333333`). Whole numbers can be up to 1,099,511,627,775; results can be far larger: `1000000000000 * 1000000000000` is `1000000000000000000000000`.

It declines rather than guesses. These come back `UNRESOLVED`, with no answer:

- a division or remainder by zero: `5 / 0`, `5 % 0`;
- more than one operation: `1 + 2 * 3`;
- a number past the limits: `10000000000000 + 1`, `1.0000001 + 1`;
- number words: `two plus two`, `two plus 2`;
- other words or symbols around the expression: `what is 2 + 2`, `2 + 2 =`, `2 + 2?`, `(2) + 2`;
- malformed numbers or a missing operand: `1.5.5 + 1`, `1,00 + 1`, `3 plus`;
- `and`, `or`, `xor` on negatives or decimals: `-12 or 10`, `2.5 xor 1`;
- any other way of writing a number or an operation (`3 × 4`, `1e3 + 1`, `12 Plus 10`).

Every answer comes back `hypothesis`, and confirming one with `resolve()` does not raise it. Check `status`, not `confidence`, to see whether it answered.

You can teach a numbers instance like any other: `support queue -> Customer care` and `create account <name>` patterns answer as they do in a `language` instance. Teaching it a new operation from a few examples did not work in our test: after `double 4 -> 8` and `double 7 -> 14`, `double 21` is `UNRESOLVED`. A stored artifact of a numbers instance loads into a new numbers instance with `create(model="numbers", artifact_id=...)`.

## Set delimiters for a language instance

Conceiver works on words. By default a language instance splits at the space and keeps each of `. , ; : ! ? ( ) [ ] { } " /` as a word of its own, so in `createAccount(alice)` the value `alice` is a word that can be a slot. Pass `delimiters` at creation time to choose others:

```python
instance = client.create(model="language", delimiters={"split": " ", "keep": ".(),"})
```

`split` characters separate words and are dropped; `keep` characters separate words and are words themselves. Use ASCII characters, at least one `split` character, and each character once across both. See the [teaching guide](https://toolving.com/docs/teaching.md#words-and-delimiters).

## The agent skill

The SDK ships `toolving-conceiver`, a skill for coding agents: how to teach Conceiver each kind of task, read its confidence and evidence, correct it, and what it does not do. Install it for every agent host on the machine:

```sh
python -m toolving.skill install            # Claude Code, Codex, Pi and ~/.agents/skills
python -m toolving.skill install --project  # this project's folders instead
python -m toolving.skill install --dir PATH # any other harness's skills folder
python -m toolving.skill print              # print it
```

`toolving-skill` is the same command. The SDK installer runs `install` for you unless `TOOLVING_SKILL=0`. Restart the agent host to load it.

## Results

`status` is `ANSWER` or `UNRESOLVED`. An `ANSWER` is Conceiver's best guess plus a flag, `confidence`, saying how much evidence it rests on. `text` carries the answer string. When that string contains valid JSON, `output` carries the SDK-decoded value; otherwise it carries the string. Raw JSON syntax support within Conceiver's taught language is in active development. When nothing taught fits, `status` is `UNRESOLVED`: there is no answer, only `evidence.markdown` explaining why. Conceiver does not invent an answer to fill a gap; pass the question to an LLM or a person, then teach the right answer. Check `confidence` and the evidence before acting on a `hypothesis`. `prediction_id` identifies the query for a later outcome.

SDK 0.16.x exposes `confidence`: `hypothesis`, `confident`, `highly confident`, `ambiguous` (`high` from Conceiver 1.x), or `None` when the result has no confidence field (an `UNRESOLVED` result has none). The level is counted from the answer's evidence: how many times it was given or confirmed (for), minus how many times it was corrected away (against).

| `confidence` | Evidence | Use it for |
|---|---|---|
| `hypothesis` | One more for than against, or the input fits a pattern in a way no example has shown (see below) | A best guess. Use it where a wrong answer is cheap, or have it checked. |
| `confident` | Two more for than against | Usually safe to act on. |
| `highly confident` | Three or more | Act on it. |
| `ambiguous` | For and against are level | Do not act on it. Ask, then resolve. |

These are counts of evidence, not calibrated probabilities. Your program decides which level is enough for each action. One example already gives a best guess, flagged `hypothesis`; a second example of the same pattern (for example `create account bob` after `create account alice`) raises the level for the inputs that fit it. A correction made with `resolve()` counts against the answer it replaces and for the new one, so the new answer leads at once. Check `status` before using an answer. Toolving preserves Conceiver's confidence and acceptance policy.

An answer stays at `hypothesis`, however much evidence its pattern has, when the input fits the pattern in a way no example has shown:

- **A new word in a slot that has only ever held one word.** Taught `turn on kitchen lights -> lights.on(kitchen)` and `turn on hall lights -> lights.on(hall)`, the word `on` is a slot that has only held `on`, so `turn off kitchen lights` answers `lights.off(kitchen)` as a `hypothesis`. A slot that has held two or more different words takes a new one at the pattern's level: `create account carol` is `confident` after `alice` and `bob`.
- **A value of several words where only single words were taught.** After `reset password for alice` and `reset password for bob`, `reset password for mary ann` answers `resetPassword(mary ann)` as a `hypothesis`. Confirm one such answer with `resolve()` and later values of that shape count as the pattern's own: `reset password for jo beth` then comes back `highly confident`.
- **A word repeated across slots**, where the examples had different words.

Answers from the [numbers model](#the-numbers-model) are always `hypothesis`.

`instance.training_sequence()` assembles current plain UTF-8 teaching text without storing it, including on Free accounts. `save()` stores that text as an account file and requires storage. Saved training sequences are plain UTF-8 text. A teaching is `question`, newline, `answer`; one empty line separates teachings. `ingest_training_sequence()` sends every pair through normal teaching. `evidence.markdown` explains answered and unresolved decisions. Pass `with_memory=True` to return `evidence.episodes`, which contains complete relevant input/output examples. Standard queries cost 1 credit; memory-enabled queries cost 2. `reap()` returns retirement details. On an account with storage it includes verified artifact metadata (`artifact`); a later instance loads that artifact only when created with `create(artifact_id=...)`. Final retirement without storage returns `persisted=False` and discards live memory. When nothing was kept, `skipped` says why: `NOTHING_TAUGHT` (the instance was never taught; queries do not count), `SAVE_OFF` (saving at spin-down is off), or `NO_STORAGE_ROOM` / `NO_UNPINNED_SLOT` (see below).

## Saving at spin-down

A spin-down is an instance retiring: a `reap()`, or the service retiring an idle instance. On an account with storage, a taught instance's spin-down saves the model as a stored artifact. This is a setting, on by default. It is the same setting as **Save model at spin-down** in the playground, beside **Save model** and **Unload model**.

```python
client.spin_down()             # {'save': True, 'stores': 'artifact', 'reason': None}
client.set_spin_down(False)    # {'save': False, 'stores': 'nothing', 'reason': 'SAVE_OFF'}
retirement = instance.reap()   # retirement.persisted is False, retirement.skipped is 'SAVE_OFF'
client.set_spin_down(True)     # {'save': True, 'stores': 'artifact', 'reason': None}
```

Both return what a spin-down would keep now: `stores` is `artifact`, `recovery-sequence` (the account has no storage, so a recovery copy of the training sequence is kept instead), or `nothing`, with `reason`. The same object is `spin_down` in `client.storage()`.

When storage is full, a spin-down overwrites the oldest unpinned artifact to make room. Pinned artifacts are never overwritten (`pin_artifact()`). If there is still no room, it stores nothing and overwrites nothing, and `skipped` and `storage.reason` say why:

- `NO_STORAGE_ROOM`: the storage quota is full and every artifact that could be overwritten is pinned.
- `NO_UNPINNED_SLOT`: on unlimited storage (10 artifact slots), every slot holds a pinned artifact.

Unpin an artifact (`unpin_artifact()`) or expand storage to save again. The retired instance's live learning is gone in that case; copy it first with `instance.training_sequence()` if you need it.

Retries retain the original confidence after later learning. Older receipts and instances using older application bundles may lack the field. A new instance uses the updated bundle with your account's existing private learning.

## Handle errors

An API error raises `ConceiverAPIError`. It has `status` (the HTTP status), `code`, `operation_id` and `retryable`.

| Code or status | What it means | What you do |
|---|---|---|
| `UNAUTHORIZED` (401) | The key is missing, wrong or revoked. | Ask the user for a new key from their account page. |
| 409 with a reused key | The same `key` was sent with different content. | Use a new key for the new request. |
| `INSTANCE_INACTIVE` (409) | The instance has retired. | Create a new instance. Do not retry on the old one. |
| `RUNTIME_OPERATION_REJECTED` (422) | Conceiver could not carry out this operation; the message says why. It has failed for good and nothing was charged. | Do not retry: the same key returns the same error. Change the input or skip it; the instance stays usable. |
| `MODEL_SIZE_LIMIT_REACHED` (409) | This model has reached its maximum size. The operation was not applied and nothing was charged. Upgrading account storage does not change this limit. | Continue with a new model. Sending the same call again with the same `key` tries it again. |
| `STORAGE_UPGRADE_REQUIRED` (402) | The account's storage is full or not enabled. The operation was not applied and nothing was charged. | Expand storage from the account page, then send the same call again with the same `key`. |
| `INVALID_REQUEST` (422) | The input is invalid. | Fix the input. Questions and answers are single lines. |
| 503 with an `operation_id` | The request was accepted but the response was lost. | Repeat the same call with the same `key`, or read the operation. |

When `retryable` is true, repeat the call with the same `key`. Do not change the key on a retry, or you start a new operation.

## Resuming a request

SDK calls generate an operation key when you omit one. Supply and retain `key` yourself when you need to recover an uncertain request. Reusing it with different content returns a conflict. Another deliberate observation needs another key.

The API retains accepted work if execution succeeds but the response is lost. Read its operation or repeat the original request with its original key. [HTTP operations](https://toolving.com/docs/http.md) describes this contract.

## Versions

Install SDK 0.16.x with the installer in the [quickstart](https://toolving.com/docs/quickstart.md) (`install.sh` on Linux, macOS and WSL, `install.ps1` on Windows), or from the [public Toolving release](https://github.com/hydra-dynamix/toolving/releases/tag/v0.16.2). `create(model="numbers")`, `spin_down()` and `set_spin_down()` need 0.16.0 or later. Earlier `LearnerClient` examples belong to the earlier API. [Deployment downloads](https://toolving.com/releases) show which wheels a particular service also provides.
