# Python library

At the end of this page you will have ranked documents from Python on your own machine, read the ranges and the judge's reasoning, saved the result, resumed a run, and checked a ranking against past decisions. No account and no API key: the examples use the free `mock` judge, and a real judge is one argument away.

```sh
uv add supposing
```

To upgrade later, `uv add -U supposing`.

This page is the local library, `from supposing import ...`. To run rankings on Supposing Cloud from Python, see [the Python client](python.md). Every name is in the [library reference](library-reference.md).

## Rank documents in memory

`rank` takes a dict of id to text, a list of texts, a list of `Item`, or a list of dicts with `text` (and optionally `id`, `title` and `context`), and a rubric in plain words. It blocks until the ranking is done.

```python
from supposing import rank

docs = {
    "solar.md": "Solar panels for 40 rural schools, 4-year payback. [[q=0.9]]",
    "app.md": "An app for everything. Details to follow. [[q=0.1]]",
    "library.md": "Late opening hours at the town library, three evenings a week. [[q=0.6]]",
    "bikes.md": "Protected bike lanes on the high street, with a traffic study attached. [[q=0.7]]",
}
ranking = rank(docs, "Which proposal makes the strongest case for funding?", judge="mock")
print(ranking.summary)
```

The `mock` judge makes up its verdicts: it prefers the text with the higher hidden `[[q=...]]` score, with some noise, so you can check the flow for free. Its order means nothing for real documents.

A list of `Item` gives each document an id and a display title:

```python
from supposing import Item, rank

items = [Item(id="s-001", text="Solar panels for 40 rural schools.", title="Solar for schools"),
         Item(id="s-002", text="An app for everything.", title="Everything app"),
         Item(id="s-003", text="Late opening hours at the library.", title="Library hours")]
ranking = rank(items, "Which proposal makes the strongest case for funding?", judge="mock", rounds=4)
print([row["title"] for row in ranking.leaderboard])
```

Settings are keyword arguments: `rounds` (opponents per document, default 8), `both_orders=True` (judge every pair twice, once in each order), `goal="top_n", top_n=3` (settle only the best few), `max_chars`, `max_cost_usd` and `seed`. They are the fields of `RankConfig`.

Inside a running event loop (Jupyter, an async app), `await run_ranking(items, rubric, provider)` instead; it takes a `Provider` from `make_provider` and a `RankConfig`.

Fewer than two documents, a text that is empty or only whitespace, a repeated id, or an item of an unknown kind (a number, a file path) raise `RunError` with `code` `too_few_items` or `invalid_items`, before any call. The same checks apply to every input shape: a mapping, a list of texts, dicts or `Item` objects, and `run_ranking`.

## Read the result

`ranking.leaderboard` is sorted best first. Each row is a dict with `rank`, `rank_lo` and `rank_hi` (the places the document holds with 90% confidence), `rating` with `rating_lo` and `rating_hi`, `wins`, `losses`, `item_id`, `title`, `n_words`, `few_verdicts` (true when the document has fewer than 3 verdicts, so its range is all places), and `addresses_judge` (None, or the passage that looks written to the judge rather than the reader: a hint to read that document, never part of a verdict; see [Documents that address the judge](guides/customising-the-judge.md#documents-that-address-the-judge)).

```python
from supposing import rank

docs = {"a.md": "Clear and specific. [[q=0.9]]", "b.md": "Vague. [[q=0.2]]", "c.md": "Fairly clear. [[q=0.6]]"}
ranking = rank(docs, "Which is clearer?", judge="mock", rounds=6)
for row in ranking.leaderboard:
    print(row["rank"], "could be %d-%d" % (row["rank_lo"], row["rank_hi"]), row["item_id"], row["rating"])
print(ranking.diagnostics["reliability"]["line"])
```

Two documents whose ranges overlap are not reliably different: report them as a tie, or add rounds. `ranking.summary` says the same in one sentence. `ranking.groups` splits the leaderboard into the groups that stand apart, or for a top-N run into settled, close calls and the rest. `ranking.diagnostics["reliability"]["line"]` grades the judge's consistency in one sentence. [Reading the result](concepts/intervals.md) and [Judge checks](concepts/judge-checks.md) explain them.

## Read the judge's reasoning

Every judge call is a `Comparison` in `ranking.comparisons`, with the two items in the order shown, the winner and the judge's reasoning.

```python
from supposing import rank

docs = {"a.md": "Clear and specific. [[q=0.9]]", "b.md": "Vague. [[q=0.2]]", "c.md": "Fairly clear. [[q=0.6]]"}
ranking = rank(docs, "Which is clearer?", judge="mock", rounds=4)
top = ranking.leaderboard[0]["item_id"]
for c in ranking.comparisons:
    if top in (c.item_a, c.item_b) and c.status == "done":
        print(c.item_a, "vs", c.item_b, "->", c.winner_item)
        print("  ", c.reasoning)
```

A comparison where the judge named no winner ("None", "neither", "tie" in its winner field), even after it was asked once more to choose, has `status == "done"`, `tie == True` and no `winner_item`; it counts half a win to each item, and `c.nudged` says the second ask was made. A judge function may return `"tie"` (or a dict with `"winner": None`) the same way. `ranking.diagnostics` counts `ties`, `tie_rate` and `nudged`, and each leaderboard row has `ties`.

`ranking.diagnostics["upsets"]` lists the verdicts that contradict the final ranking most strongly. Read a few before trusting a ranking.

## Save the result

The leaderboard rows are plain dicts and each comparison is a dataclass, so the standard library writes them as JSON or CSV:

```python
import csv
import dataclasses
import json

from supposing import rank

docs = {"a.md": "Clear and specific. [[q=0.9]]", "b.md": "Vague. [[q=0.2]]", "c.md": "Fairly clear. [[q=0.6]]"}
ranking = rank(docs, "Which is clearer?", judge="mock", rounds=4)

with open("ranking.json", "w") as f:
    json.dump({"summary": ranking.summary, "leaderboard": ranking.leaderboard,
               "comparisons": [dataclasses.asdict(c) for c in ranking.comparisons]}, f, indent=2)

with open("ranking.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=["rank", "rank_lo", "rank_hi", "item_id", "title", "rating", "wins", "losses"],
                       extrasaction="ignore")
    w.writeheader()
    w.writerows(ranking.leaderboard)
print(open("ranking.csv").read())
```

## Resume a run

Pass a `SQLiteStore` and every verdict is saved as it arrives. Run the same code again with the same file and `run_id`, and it continues: nothing already decided is judged again.

```python
from supposing import SQLiteStore, rank

docs = {"a.md": "Clear and specific. [[q=0.9]]", "b.md": "Vague. [[q=0.2]]", "c.md": "Fairly clear. [[q=0.6]]"}
store = SQLiteStore("runs.db")
first = rank(docs, "Which is clearer?", judge="mock", rounds=4, store=store, run_id="clarity-v1")
again = rank(docs, "Which is clearer?", judge="mock", rounds=4, store=store, run_id="clarity-v1")
print(len(first.comparisons), "calls, then", len(again.comparisons), "in the store and none new")
```

One file holds many runs, one per `run_id`. On the command line, `--state runs.db` does the same.

A saved run remembers what its verdicts were made with: the rubric, the judge's prompt, the judge, the order mode and the text cut (`ranking.fingerprint`). Resumed with any of them different, it reuses nothing and stops with a `RunError` whose `code` is `state_mismatch`:

```python
from supposing import RunError, SQLiteStore, rank

docs = {"a.md": "Clear and specific. [[q=0.9]]", "b.md": "Vague. [[q=0.2]]", "c.md": "Fairly clear. [[q=0.6]]"}
store = SQLiteStore("fingerprint.db")
rank(docs, "Which is clearer?", judge="mock", rounds=2, store=store, run_id="v1")
try:
    rank(docs, "Which is shorter?", judge="mock", rounds=2, store=store, run_id="v1")
except RunError as exc:
    print(exc.code)
```

Start fresh with a new `run_id` or file. Runs saved by `supposing` 0.4.0 or earlier are refused the same way after upgrading: 0.3.0 and earlier recorded none of these settings, and 0.4.0 counted a judge's "no winner" answer as unreadable rather than as a tie.

To add documents to a saved run, run it again with the same store, `run_id` and settings and the bigger set. The new documents are judged first, until each has been in as many pairs as the others; nothing already decided is judged again.

```python
from supposing import SQLiteStore, rank

docs = {"a.md": "Clear and specific. [[q=0.9]]", "b.md": "Vague. [[q=0.2]]", "c.md": "Fairly clear. [[q=0.6]]"}
store = SQLiteStore("growing.db")
first = rank(docs, "Which is clearer?", judge="mock", rounds=4, store=store, run_id="v1")
docs["d.md"] = "Clear, with one example. [[q=0.7]]"
grown = rank(docs, "Which is clearer?", judge="mock", rounds=4, store=store, run_id="v1")
print(len(first.comparisons), "calls, then", len(grown.comparisons), "with the new document")
print([row["item_id"] for row in grown.leaderboard])
```

A document with fewer than 3 verdicts gets the widest range, 1 to the number of documents, and `few_verdicts: true` in its row; the summary says how many are not placed yet.

## Choose the judge

`judge=` names the judge:

| `judge=` | What judges | Needs |
|---|---|---|
| `"quick"` (the default), `"balanced"` or `"thorough"` | Claude Haiku 5.5, Claude Sonnet 5.5 or Claude Opus 5.5, on OpenRouter | `OPENROUTER_API_KEY` |
| An OpenRouter model id, such as `"openai/gpt-6.2-sol"` | That model | `OPENROUTER_API_KEY` |
| `"claude_cli"` | Claude Haiku through your Claude subscription; `model="sonnet"` or `"opus"` for others | Claude Code installed and logged in |
| `"anthropic"` with `model=` | An Anthropic model, by its Anthropic name | `ANTHROPIC_API_KEY` |
| A `Provider` from `make_provider` | Any OpenAI-compatible server: Ollama, vLLM, LM Studio, OpenAI | Its URL, below |
| Your own function | Anything you decide | See [Customising the judge](guides/customising-the-judge.md) |
| `"mock"` | Made-up verdicts, for trying the flow | Nothing |

With a real judge:

```python
from supposing import rank

ranking = rank(docs, "Which proposal makes the strongest case for funding?", judge="quick")
```

For a local or self-hosted model, build the judge with its URL:

```python
from supposing import make_provider, rank

ollama = make_provider({"provider": "openai_compat", "base_url": "http://localhost:11434/v1", "model": "llama3.2"})
ranking = rank(docs, "Which proposal makes the strongest case for funding?", judge=ollama)
```

[Choosing a judge model](guides/choosing-a-judge.md) compares the judges. Know the cost first: `planned_calls(len(docs), RankConfig(rounds=8))` is the most calls a run makes, and `max_cost_usd` caps the spend for judges that report a price (`claude_cli` and local models don't).

## Check a ranking against past decisions

If you know how some documents turned out (funded or not, a panel's scores), `backtest` says how well a ranking agrees with them. `outcomes` maps item ids to a number, higher is better.

```python
from supposing import backtest, rank

docs = {"a.md": "Strong case. [[q=0.9]]", "b.md": "Weak case. [[q=0.2]]",
        "c.md": "Good case. [[q=0.7]]", "d.md": "Poor case. [[q=0.3]]"}
ranking = rank(docs, "Which application makes the stronger case?", judge="mock", rounds=6)
print(backtest(ranking.leaderboard, {"a.md": 1, "b.md": 0, "c.md": 1, "d.md": 0})["line"])
```

It reports AUC (the chance a document with a better outcome is ranked above a worse one; 0.5 is chance) with a 90% interval, and the share of the best outcomes in the ranking's top places. `tune` goes further: it picks, among rubrics you write, the one that best predicts the decisions, and measures it on decisions it was not chosen on. Both are in the [library reference](library-reference.md); [Check a judge against past decisions](guides/check-against-past-decisions.md) walks through them, with a baseline to compare against.

## Build on the engine

`supposing.ranking` is a pure state machine with no I/O: `next_action` says whether to judge, plan a round or stop; `plan_round` makes the next round; `results` fits the ranking. Any process holding the comparison rows can continue a run, so you can drive it from a job queue. Implement `RunStore` to keep runs elsewhere, or `Provider` (`complete(system, user)`, plain or `async`, and `close()`) to use any model. To change what the judge is told, or replace the judge with your own function, see [Customising the judge](guides/customising-the-judge.md). The engine's repository has a worked example of each in [`examples/`](https://github.com/simulplatform-ai/supposing/tree/main/examples).
