# Python client

Every class and method of `supposing.cloud`, the Python client for the API. It ships in the open `supposing` package, has typed responses in sync and async versions, and needs nothing beyond `httpx`.

```python
from supposing.cloud import Client

sp = Client()  # SUPPOSING_API_KEY, or the key saved by `supposing login`
print(sp.me().org_name)
sp.close()
```

`Client(api_key=None, api_url=None, *, timeout=30.0, retries=2, source=None)`. `source` is recorded on the datasets and runs the client creates (`cli`, `mcp`; the API records `api` when it is left out). The key comes from the argument, then `SUPPOSING_API_KEY`, then the config file. The URL comes from the argument, then `SUPPOSING_API_URL`, then the config file, then `https://api.supposing.app`. GET and DELETE requests are retried on connection errors and 502, 503 and 504. POST requests are never retried.

## Datasets, runs, results

| Call | Returns |
|---|---|
| `sp.datasets.push(source, name=None, *, text_fields=None, id_field=None, title_field=None, metadata_fields=None, sheet=None, redact=False)` | `Dataset`. From a folder, every `.md`, `.txt`, `.html`, `.pdf` and `.docx` file is one item, titled by its first heading, with its file name as `source_id`. From a JSONL, JSON, CSV or XLSX file, every row is one item: `text_fields` name the text, `id_field` the row's id (kept as `source_id`), `title_field` the title, `metadata_fields` fields kept but never shown to the judge. CSV and XLSX go through the API's import, which guesses what you don't name. `skipped` lists what was left out, `duplicates` likely duplicates |
| `sp.datasets.create(name, items, ephemeral=False)` | `Dataset`, from `[{"title": ..., "text": ...}]`. `ephemeral=True` keeps a one-off out of lists; it is deleted after 30 days |
| `sp.datasets.list(limit=None, cursor=None)`, `sp.datasets.iter()` | `Page[Dataset]`, or every dataset |
| `sp.datasets.get(id)`, `add_items(id, items)`, `delete(id)` | |
| `sp.items.get(id)` | `Item` with its `text` |
| `sp.runs.estimate(dataset_id, rubric, **settings)` | `Estimate`: `min_calls`, `max_calls`, `est_cost_usd`, `est_seconds`. `describe()` gives one line |
| `sp.runs.create(dataset_id, rubric, *, provider, model, max_cost_usd, name, **settings)` | `Run` |
| `sp.runs.wait(run_id, on_progress=None, on_event=None, poll_interval=1.0, timeout=None)` | The finished `Run`. It follows the run's event stream and falls back to polling. `on_progress(run)` runs on each update, and `on_event(event)` also gets the current top 3 in `event.leaders` |
| `sp.runs.events(run_id)` | An iterator of `RunEvent`: `progress` whenever calls complete, then one `finished` |
| `sp.runs.get(id)`, `list(dataset_id=None)`, `cancel(id)`, `delete(id)` | |
| `sp.runs.results(run_id)` | `Results`: `summary`, then `leaderboard` of `LeaderboardEntry`, `diagnostics`, `interval`, `final` |
| `sp.runs.comparisons(run_id, item_id=None, status=None)` | `Page[Comparison]`: each call's winner and reasoning |

The settings are the ranking's own: `rounds`, `both_orders`, `pairing`, `goal` (`"full"` or `"top_n"`), `top_n`, `max_chars` and `seed`. Every response object keeps the API's JSON in `.raw`, and `.to_dict()` returns it.

```python
from supposing.cloud import Client

with Client() as sp:
    ds = sp.datasets.create("taglines", [
        {"title": "a", "text": "Rank anything by asking a judge to compare pairs."},
        {"title": "b", "text": "We have AI."},
        {"title": "c", "text": "Confidence intervals for taste."},
    ])
    est = sp.runs.estimate(ds.id, "Which tagline is clearest?", provider="mock", rounds=3)
    print(est.describe())
    if est.est_cost_usd is None or est.est_cost_usd < 1:
        run = sp.runs.wait(sp.runs.create(ds.id, "Which tagline is clearest?", provider="mock", rounds=3).id)
        res = sp.runs.results(run.id)
        print(res.summary)
        top = res.leaderboard[0]
        why = sp.runs.comparisons(run.id, item_id=top.item_id, status="done").data[0]
        print("Example verdict for", top.title, ":", why.reasoning)
```

## Credit and prices

```python
from supposing.cloud import Client

with Client() as sp:
    credit = sp.billing.get()
    print("balance $%.2f, held $%.2f" % (credit.balance_usd, credit.held_usd))
    for entry in sp.billing.ledger(limit=5).data:
        print(entry.kind, entry.amount_usd, entry.note)
    for tier in sp.pricing().tiers:
        print(tier.name, tier.price_per_call_usd)
```

`sp.billing.checkout(amount_usd)` returns a `Checkout` whose `url` is a payment page; nothing is charged until someone pays there. `sp.billing.portal().url` links to receipts. `sp.pricing()` needs no API key. A run's `Estimate` says whether it is `billed`, its `price_tier` and `price_per_call_usd`. A billed run that the balance can't cover raises `CloudError` with code `insufficient_credit`; its `hint` names where to add credit.

## Errors

Every failure raises `CloudError`, which has `code` (stable, safe to branch on), `message`, `hint` (what to do next), `status` and `details` (one entry per invalid field). [Errors](errors.md) lists every code.

```python
from supposing.cloud import Client, CloudError

with Client() as sp:
    try:
        sp.runs.get("00000000-0000-0000-0000-000000000000")
    except CloudError as e:
        assert e.code == "run_not_found"
        print(e.code, e.message, e.hint)
```

Client-side codes are `no_api_key`, `connection_error`, `bad_response`, `stream_error`, `wait_timeout` and `no_items`. All other codes come from the API.

## Async

`AsyncClient` has the same methods as coroutines, and `datasets.iter()` is an async iterator.

```python
import asyncio

from supposing.cloud import AsyncClient


async def main():
    async with AsyncClient() as sp:
        ds = await sp.datasets.push("./proposals")
        runs = [await sp.runs.create(ds.id, rubric, provider="mock", rounds=2)
                for rubric in ("Which is cheapest to deliver?", "Which helps the most people?")]
        for run in await asyncio.gather(*(sp.runs.wait(r.id, poll_interval=0.5) for r in runs)):
            print(run.config["rubric"], "->", (await sp.runs.results(run.id)).leaderboard[0].title)


asyncio.run(main())
```
