supposing 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
supposing/__init__.py ADDED
@@ -0,0 +1,54 @@
1
+ """Supposing: rank documents with LLM judges.
2
+
3
+ from supposing import rank
4
+ ranking = rank({"a.md": text_a, "b.md": text_b, ...}, "Which proposal is most fundable?", provider="mock")
5
+ ranking.leaderboard
6
+
7
+ Three layers, each usable on its own:
8
+
9
+ - ``rank`` and ``run_ranking`` run a whole ranking in this process and return a ``Ranking``.
10
+ - ``next_action``, ``plan_round`` and ``results`` are the run as a pure state machine over ``Comparison``
11
+ rows, for running it from a job queue or across workers. ``judge_pair``, ``apply_verdict`` and
12
+ ``apply_error`` make and record one judge call.
13
+ - ``supposing.samples`` holds sample datasets for a first ranking with no files of your own.
14
+ - ``supposing.present`` words runs, results, estimates and errors for agents and terminals.
15
+ - ``Provider`` (built with ``make_provider``) is the judge; ``RunStore`` (``MemoryStore``, ``SQLiteStore``)
16
+ is where a run's comparisons are kept.
17
+ """
18
+ from . import present, samples
19
+ from .judge import SYSTEM_PROMPT, apply_error, apply_verdict, judge_pair
20
+ from .providers import Completion, Provider, ProviderError, make_provider
21
+ from .ranking import (
22
+ Action,
23
+ Comparison,
24
+ ConfigError,
25
+ Item,
26
+ RankConfig,
27
+ affordable,
28
+ fewest_calls,
29
+ next_action,
30
+ plan_round,
31
+ planned_calls,
32
+ results,
33
+ timeline,
34
+ )
35
+ from .report import judge_checks, summarize, tiers
36
+ from .rubric import Criterion, Rubric
37
+ from .runner import Ranking, RunError, rank, run_ranking
38
+ from .store import MemoryStore, RunStore, SQLiteStore
39
+
40
+ __version__ = "0.1.0"
41
+
42
+ __all__ = [
43
+ # Run a ranking
44
+ "rank", "run_ranking", "Ranking", "RunError", "Item", "Rubric", "Criterion", "RankConfig", "ConfigError", "planned_calls",
45
+ "fewest_calls",
46
+ # The state machine
47
+ "Comparison", "Action", "next_action", "affordable", "plan_round", "results", "timeline",
48
+ # Results in words
49
+ "summarize", "tiers", "judge_checks", "present", "samples",
50
+ # One judge call
51
+ "judge_pair", "apply_verdict", "apply_error", "SYSTEM_PROMPT",
52
+ # Judges and stores
53
+ "Provider", "Completion", "ProviderError", "make_provider", "RunStore", "MemoryStore", "SQLiteStore",
54
+ ]
@@ -0,0 +1,232 @@
1
+ """The ``supposing`` command. ``supposing rank`` runs on this machine; ``supposing run`` runs in the cloud. Both
2
+ take the same flags and print the same result shape. Every command takes ``--json``."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from collections.abc import Callable
8
+ from pathlib import Path
9
+ from typing import NoReturn
10
+
11
+ from .. import __version__
12
+ from ..cloud import CloudError
13
+ from ..rubric import Rubric
14
+ from . import billing, cloud, local
15
+ from .output import (
16
+ AUTH,
17
+ EXIT_CODES_HELP,
18
+ INTERRUPTED,
19
+ NEEDS_CREDIT,
20
+ NOT_FOUND,
21
+ REFUSED,
22
+ UNAVAILABLE,
23
+ USAGE,
24
+ CliError,
25
+ error,
26
+ )
27
+
28
+ Handler = Callable[[argparse.Namespace], int]
29
+
30
+
31
+ class Parser(argparse.ArgumentParser):
32
+ """argparse, except that with --json anywhere on the line a usage error is the usual JSON error object."""
33
+
34
+ json_errors = False
35
+
36
+ def error(self, message: str) -> NoReturn:
37
+ if Parser.json_errors:
38
+ raise CliError(message[0].upper() + message[1:] + ".", code="usage", exit_code=USAGE,
39
+ hint="See `%s --help`." % self.prog)
40
+ super().error(message)
41
+
42
+
43
+ def _rubric(value: str) -> str | Rubric:
44
+ """A rubric in plain words, or @file: Markdown, text or JSON read by ``Rubric.load`` (criteria and weights)."""
45
+ if value.startswith("@"):
46
+ try:
47
+ return Rubric.load(value[1:])
48
+ except OSError as exc:
49
+ raise argparse.ArgumentTypeError(
50
+ "can't read the rubric file %s (%s). Create it, or pass the rubric in quotes: --rubric \"Which is "
51
+ "clearer?\"" % (value[1:], exc.strerror)) from exc
52
+ except ValueError as exc:
53
+ raise argparse.ArgumentTypeError("%s is not a valid rubric: %s" % (value[1:], exc)) from exc
54
+ return value
55
+
56
+
57
+ def _source_flags(p: argparse.ArgumentParser) -> None:
58
+ """For a JSONL, JSON or CSV file: which fields make each item. Names match the API's import."""
59
+ g = p.add_argument_group("reading a JSONL, JSON or CSV file (one item per row)")
60
+ g.add_argument("--text-field", dest="text_fields", action="append", metavar="FIELD",
61
+ help="the field with the text; repeat to join several, each under a heading (default: a field "
62
+ "named text, output, response, answer or content)")
63
+ g.add_argument("--id-field", metavar="FIELD", help="each row's id, kept in every output (default: a field named "
64
+ "id, else the row number)")
65
+ g.add_argument("--title-field", metavar="FIELD", help="the title to show (default: the id)")
66
+ g.add_argument("--metadata-field", dest="metadata_fields", action="append", metavar="FIELD",
67
+ help="keep this field on the item but never show it to the judge; repeatable")
68
+
69
+
70
+ def _run_flags(p: argparse.ArgumentParser) -> None:
71
+ """Flags shared by `rank` (local) and `run` (cloud)."""
72
+ p.add_argument("--rubric", type=_rubric, required=True,
73
+ help="what the judge should prefer, in plain words, or @file to read it from a file")
74
+ p.add_argument("--provider", help="judge provider: openrouter (default), mock (free, fake), claude_cli; "
75
+ "locally also anthropic and openai_compat")
76
+ p.add_argument("--model", help="judge model, e.g. anthropic/claude-haiku-5.5")
77
+ p.add_argument("--rounds", type=int, help="opponents per item (default 8); more rounds, tighter intervals")
78
+ p.add_argument("--top-n", type=int, help="only settle the top N, spending fewer calls on the rest")
79
+ p.add_argument("--one-order", action="store_true", help="judge each pair once instead of in both orders")
80
+ p.add_argument("--pairing", choices=["swiss", "random"])
81
+ p.add_argument("--max-chars", type=int, help="cut items longer than this before judging")
82
+ p.add_argument("--max-cost", type=float, metavar="USD", help="hard spend cap: no judge call starts that could take the cost past USD")
83
+ p.add_argument("--seed", type=int)
84
+ p.add_argument("-y", "--yes", action="store_true", help="start without asking, even if it costs money")
85
+ p.add_argument("--dry-run", action="store_true", help="show the estimate and stop")
86
+
87
+
88
+ def build_parser() -> argparse.ArgumentParser:
89
+ common = Parser(add_help=False)
90
+ common.add_argument("--json", action="store_true", help="print JSON on stdout (errors too)")
91
+ common.add_argument("--api-url", help="API base URL (default: SUPPOSING_API_URL, the saved login, or "
92
+ "https://api.supposing.app)")
93
+
94
+ parser = Parser(
95
+ prog="supposing", formatter_class=argparse.RawDescriptionHelpFormatter,
96
+ description="Rank documents with LLM judges: pairwise tournaments with confidence intervals.",
97
+ epilog="quick start:\n supposing rank ./docs --rubric \"Which is clearest?\" --provider mock\n"
98
+ " supposing login\n supposing run ./docs --rubric \"Which is clearest?\"\n\n" + EXIT_CODES_HELP)
99
+ parser.add_argument("--version", action="version", version="supposing %s" % __version__)
100
+ sub = parser.add_subparsers(dest="command", required=True, metavar="command")
101
+
102
+ def add(name: str, handler: Handler, help: str, parent=sub) -> argparse.ArgumentParser:
103
+ p = parent.add_parser(name, help=help, description=help, parents=[common])
104
+ p.set_defaults(handler=handler)
105
+ return p
106
+
107
+ r = add("rank", local.rank, "rank a folder of documents, or the rows of a JSONL or CSV file, on this machine")
108
+ r.add_argument("folder", type=Path, metavar="source",
109
+ help="a folder of .md, .txt and .html files (one document each), or a .jsonl, .json or .csv file "
110
+ "(one item per row)")
111
+ _run_flags(r)
112
+ _source_flags(r)
113
+ r.add_argument("--base-url", help="for openai_compat, e.g. http://localhost:11434/v1")
114
+ r.add_argument("--concurrency", type=int, default=8, help="judge calls at once (default 8)")
115
+ r.add_argument("--state", type=Path, help="SQLite file to save progress in; rerun with it to resume")
116
+
117
+ r = add("run", cloud.run, "rank a folder or an uploaded dataset in the cloud")
118
+ r.add_argument("source", help="a folder or a .jsonl, .json or .csv file to upload, or the id of a dataset "
119
+ "already uploaded")
120
+ _run_flags(r)
121
+ _source_flags(r)
122
+ r.add_argument("--name", help="name for the run")
123
+ r.add_argument("--detach", action="store_true", help="start the run and print it, without waiting")
124
+
125
+ r = add("login", cloud.login, "save an API key for this machine (create one in the web app under Developers)")
126
+ r.add_argument("--api-key", help="the key; if left out, it is read from stdin or asked for")
127
+ add("logout", cloud.logout, "forget the saved API key")
128
+ add("whoami", cloud.whoami, "show which workspace the API key belongs to")
129
+
130
+ ds = sub.add_parser("datasets", help="upload and manage datasets").add_subparsers(
131
+ dest="sub", required=True, metavar="command")
132
+ r = add("push", cloud.datasets_push, "upload a folder (one item per file) or a JSONL, JSON or CSV file (one item "
133
+ "per row) as a new dataset", ds)
134
+ r.add_argument("folder", type=Path, metavar="source")
135
+ r.add_argument("--name", help="dataset name (default: the folder's or file's name)")
136
+ _source_flags(r)
137
+ r = add("list", cloud.datasets_list, "list datasets, newest first", ds)
138
+ r.add_argument("--limit", type=int, default=50)
139
+ r = add("get", cloud.datasets_get, "show a dataset and its items", ds)
140
+ r.add_argument("dataset_id")
141
+ r = add("delete", cloud.datasets_delete, "delete a dataset and its runs", ds)
142
+ r.add_argument("dataset_id")
143
+
144
+ runs = sub.add_parser("runs", help="list, watch and cancel runs").add_subparsers(
145
+ dest="sub", required=True, metavar="command")
146
+ r = add("list", cloud.runs_list, "list runs, newest first", runs)
147
+ r.add_argument("--dataset", dest="dataset_id")
148
+ r.add_argument("--limit", type=int, default=20)
149
+ r = add("get", cloud.runs_get, "show a run's status and progress", runs)
150
+ r.add_argument("run_id")
151
+ r = add("watch", cloud.runs_watch, "follow a run until it finishes, then print its results", runs)
152
+ r.add_argument("run_id")
153
+ r = add("cancel", cloud.runs_cancel, "stop a run; calls already made are kept", runs)
154
+ r.add_argument("run_id")
155
+
156
+ r = add("results", cloud.results, "print a run's results: the verdict, then the leaderboard")
157
+ r.add_argument("run_id")
158
+ # `supposing billing` alone shows the balance; its subcommands do the rest.
159
+ bl = add("billing", billing.show, "credit balance, ledger and top-ups").add_subparsers(
160
+ dest="sub", required=False, metavar="command")
161
+ r = add("ledger", billing.ledger, "every credit movement, newest first", bl)
162
+ r.add_argument("--limit", type=int, default=30)
163
+ r = add("topup", billing.topup, "print a payment page for adding credit (nothing is charged until you pay)", bl)
164
+ r.add_argument("amount", type=billing.check_amount, help="whole US dollars, e.g. 10")
165
+ add("portal", billing.portal, "print a link to receipts and payment details", bl)
166
+ add("pricing", billing.pricing, "the price of a judge call by model tier (no login needed)")
167
+ add("usage", billing.usage, "this month's runs, judge calls and spend, and the credit balance")
168
+
169
+ r = add("comparisons", cloud.comparisons, "list a run's judge calls, with each verdict's reasoning")
170
+ r.add_argument("run_id")
171
+ r.add_argument("--item", dest="item_id", help="only calls involving this item")
172
+ r.add_argument("--status", choices=["pending", "claimed", "done", "failed"])
173
+ r.add_argument("--limit", type=int, default=50)
174
+
175
+ r = add("mcp", _mcp, "serve the MCP tools over stdio for a local coding agent (needs supposing[mcp])")
176
+ r.add_argument("--local", action="store_true", help="rank with the engine on this machine even if logged in")
177
+ r.add_argument("mcp_args", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)
178
+ return parser
179
+
180
+
181
+ def _mcp(args: argparse.Namespace) -> int:
182
+ """Start the stdio MCP server: cloud tools when an API key resolves, the local engine otherwise."""
183
+ try:
184
+ from ..mcp_server import main as mcp_main # type: ignore[import-not-found]
185
+ except ImportError as exc:
186
+ raise CliError("The MCP server needs the mcp package (%s)." % exc, code="mcp_not_installed",
187
+ exit_code=USAGE, hint="pip install 'supposing[mcp]'") from exc
188
+ rest = list(args.mcp_args)
189
+ if args.local:
190
+ rest.insert(0, "--local")
191
+ return int(mcp_main(rest) or 0)
192
+
193
+
194
+ _CLOUD_EXIT = {"insufficient_credit": NEEDS_CREDIT, "no_api_key": AUTH, "unauthorized": AUTH, "invalid_api_key": AUTH, "invalid_session": AUTH,
195
+ "connection_error": UNAVAILABLE, "server_error": UNAVAILABLE, "internal_error": UNAVAILABLE,
196
+ "bad_response": UNAVAILABLE, "no_items": USAGE}
197
+
198
+
199
+ def _from_cloud(exc: CloudError) -> CliError:
200
+ code = _CLOUD_EXIT.get(exc.code)
201
+ if code is None:
202
+ code = (NOT_FOUND if exc.status == 404 or exc.code.endswith("_not_found")
203
+ else UNAVAILABLE if (exc.status or 0) >= 500 or exc.status == 429 else REFUSED)
204
+ return CliError(exc.message, code=exc.code, exit_code=code, hint=exc.hint)
205
+
206
+
207
+ def main(argv: list[str] | None = None) -> int:
208
+ argv = sys.argv[1:] if argv is None else argv
209
+ Parser.json_errors = "--json" in argv
210
+ try:
211
+ args = build_parser().parse_args(argv)
212
+ except CliError as exc:
213
+ return error(exc, True)
214
+ try:
215
+ return args.handler(args)
216
+ except CliError as exc:
217
+ return error(exc, args.json)
218
+ except CloudError as exc:
219
+ err = _from_cloud(exc)
220
+ if exc.code == "insufficient_credit": # say where to top up, in words and in --json
221
+ from ..cloud import Client
222
+
223
+ with Client(api_url=getattr(args, "api_url", None), source="cli") as sp:
224
+ err.extra = billing.topup_hint(sp)
225
+ return error(err, args.json)
226
+ except KeyboardInterrupt:
227
+ hint = getattr(args, "interrupt_hint", None)
228
+ return error(CliError("Interrupted.", code="interrupted", exit_code=INTERRUPTED, hint=hint), args.json)
229
+
230
+
231
+ if __name__ == "__main__":
232
+ sys.exit(main())
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from . import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,148 @@
1
+ """Credit and prices: `supposing billing`, `supposing pricing`, `supposing usage`.
2
+
3
+ Runs on our model key are paid from the workspace's prepaid credit. Runs on your own OpenRouter key, the mock
4
+ judge and claude_cli are never billed. Every amount comes from the API; nothing here knows a price.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ from typing import Any
10
+
11
+ from ..cloud import Billing, Client, CloudError, Estimate
12
+ from .output import OK, emit_json, info, table
13
+
14
+
15
+ def _client(args: argparse.Namespace) -> Client:
16
+ return Client(api_url=args.api_url, source="cli")
17
+
18
+
19
+ def _usd(v: float) -> str:
20
+ return "$%.2f" % v if abs(v) >= 0.01 or v == 0 else "$%.4f" % v
21
+
22
+
23
+ def topup_hint(sp: Client) -> dict[str, Any]:
24
+ """Where to add credit, for an insufficient_credit error: the web page and the CLI command. Best effort."""
25
+ out: dict[str, Any] = {}
26
+ try:
27
+ b = sp.billing.get()
28
+ except CloudError:
29
+ return out
30
+ if b.topup_url:
31
+ out["topup_url"] = b.topup_url
32
+ if b.enabled and b.topup_options_usd:
33
+ out["topup_command"] = "supposing billing topup %d" % b.topup_options_usd[0]
34
+ out["balance_usd"] = b.balance_usd
35
+ return out
36
+
37
+
38
+ def balance_after(sp: Client, est: Estimate) -> str | None:
39
+ """For a billed run: 'balance $2.00, $1.74 after at most'. None for runs that are not billed."""
40
+ if not est.billed or est.est_cost_usd is None:
41
+ return None
42
+ try:
43
+ b = sp.billing.get()
44
+ except CloudError:
45
+ return None
46
+ after = b.balance_usd - est.est_cost_usd
47
+ if after < 0:
48
+ return "balance %s, short by %s" % (_usd(b.balance_usd), _usd(-after))
49
+ return "balance %s, %s after at most" % (_usd(b.balance_usd), _usd(after))
50
+
51
+
52
+ def show(args: argparse.Namespace) -> int:
53
+ with _client(args) as sp:
54
+ b = sp.billing.get()
55
+ if args.json:
56
+ emit_json(b.to_dict())
57
+ return OK
58
+ print("Balance %s%s" % (_usd(b.balance_usd), ", %s held by running runs" % _usd(b.held_usd) if b.held_usd else ""))
59
+ if not b.enabled:
60
+ print("Billing is off on this server: runs on your own OpenRouter key and the mock judge still work.")
61
+ return OK
62
+ print("Add credit: supposing billing topup <%s>%s" % (
63
+ "|".join(str(x) for x in b.topup_options_usd), " or %s" % b.topup_url if b.topup_url else ""))
64
+ print("Runs on your own OpenRouter key (Settings) are never billed. Prices: supposing pricing")
65
+ return OK
66
+
67
+
68
+ def ledger(args: argparse.Namespace) -> int:
69
+ with _client(args) as sp:
70
+ page = sp.billing.ledger(limit=args.limit)
71
+ if args.json:
72
+ emit_json({"data": [e.to_dict() for e in page.data], "next_cursor": page.next_cursor})
73
+ return OK
74
+ if not page.data:
75
+ print("No credit movements yet.")
76
+ return OK
77
+ print(table([[str(e.created_at or "")[:16], e.kind, ("+" if e.amount_usd > 0 else "") + _usd(e.amount_usd),
78
+ e.run_id or "", e.note or ""] for e in page.data],
79
+ ["when", "kind", "amount", "run", "note"], right={2}))
80
+ return OK
81
+
82
+
83
+ def topup(args: argparse.Namespace) -> int:
84
+ with _client(args) as sp:
85
+ session = sp.billing.checkout(args.amount)
86
+ if args.json:
87
+ emit_json({"amount_usd": args.amount, **session.to_dict()})
88
+ return OK
89
+ info("Open this page to pay %s. The credit arrives as soon as the payment is confirmed." % _usd(args.amount))
90
+ print(session.url)
91
+ return OK
92
+
93
+
94
+ def portal(args: argparse.Namespace) -> int:
95
+ with _client(args) as sp:
96
+ session = sp.billing.portal()
97
+ if args.json:
98
+ emit_json(session.to_dict())
99
+ else:
100
+ print(session.url)
101
+ return OK
102
+
103
+
104
+ def pricing(args: argparse.Namespace) -> int:
105
+ with _client(args) as sp:
106
+ p = sp.pricing()
107
+ if args.json:
108
+ emit_json(p.to_dict())
109
+ return OK
110
+ print("Price of one judge call on our model key%s:" % (" (provisional)" if p.provisional else ""))
111
+ print()
112
+ print(table([[t.name, "$%.4f" % t.price_per_call_usd if t.price_per_call_usd < 0.01 else "$%.3f" % t.price_per_call_usd,
113
+ ", ".join(t.examples)] for t in p.tiers], ["tier", "per call", "for example"], right={1}))
114
+ print()
115
+ print("One call reads up to %s characters of the two items together; a longer pair counts as more calls." %
116
+ f"{p.unit_chars:,}")
117
+ print("Runs on your own OpenRouter key, the mock judge and claude_cli are free. New workspaces get %s of credit."
118
+ % _usd(p.free_grant_usd))
119
+ return OK
120
+
121
+
122
+ def usage(args: argparse.Namespace) -> int:
123
+ with _client(args) as sp:
124
+ u = sp.usage()
125
+ try:
126
+ b: Billing | None = sp.billing.get()
127
+ except CloudError:
128
+ b = None
129
+ if args.json:
130
+ emit_json({**u, "billing": b.to_dict() if b else None})
131
+ return OK
132
+ print("%s so far: %d runs, %d judge calls, %s of model spend (%s on our key)." % (
133
+ str(u.get("month", ""))[:7], u.get("runs", 0), u.get("judge_calls", 0), _usd(u.get("cost_usd") or 0),
134
+ _usd(u.get("platform_cost_usd") or 0)))
135
+ if b:
136
+ print("Credit balance %s." % _usd(b.balance_usd))
137
+ return OK
138
+
139
+
140
+ def check_amount(value: str) -> int:
141
+ try:
142
+ amount = int(value)
143
+ except ValueError as exc:
144
+ raise argparse.ArgumentTypeError("the amount is whole US dollars, e.g. 10") from exc
145
+ if amount <= 0:
146
+ raise argparse.ArgumentTypeError("the amount must be positive")
147
+ return amount
148
+