facet-models 2026.9.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.
facet/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """facet-models: a thin fact client for the Facet model registry.
2
+
3
+ Facts only — load the table, resolve names, filter and rank. Decisions stay
4
+ with the caller. Zero runtime dependencies (stdlib only).
5
+ """
6
+
7
+ from ._find import check, find, rank
8
+ from ._identity import build_lookup, identity, resolve
9
+ from ._table import BUNDLED_TABLE, DEFAULT_TABLE_URL, load
10
+
11
+ try: # written by tools/build_package.py; absent in a raw source tree
12
+ from ._version import __version__
13
+ except ImportError: # pragma: no cover
14
+ __version__ = "0.0.0.dev0"
15
+
16
+ __all__ = [
17
+ "BUNDLED_TABLE",
18
+ "DEFAULT_TABLE_URL",
19
+ "__version__",
20
+ "build_lookup",
21
+ "check",
22
+ "find",
23
+ "identity",
24
+ "load",
25
+ "rank",
26
+ "resolve",
27
+ ]
facet/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """``python -m facet`` -> the CLI."""
2
+
3
+ import sys
4
+
5
+ from .cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
facet/_find.py ADDED
@@ -0,0 +1,89 @@
1
+ """Filter + rank: hard requirements AND together; absence counts as unknown.
2
+
3
+ Same semantics as examples/pick_model.py check + rank. A fact that is ABSENT
4
+ can never *satisfy* a requirement, and an unknown price sorts last (price 0 is
5
+ treated as unknown — free-plan mirrors don't expose real pricing).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ def check(
12
+ rec: dict,
13
+ *,
14
+ min_context: int | None = None,
15
+ max_input_price: float | None = None,
16
+ max_output_price: float | None = None,
17
+ tool_call: bool = False,
18
+ reasoning: bool = False,
19
+ json_output: bool = False,
20
+ image_input: bool = False,
21
+ provider: str | None = None,
22
+ ) -> list[str]:
23
+ """Return the list of failed requirements (empty = the record qualifies)."""
24
+ failed: list[str] = []
25
+ if min_context is not None and (rec.get("context_window") or 0) < min_context:
26
+ failed.append(f"context>={min_context}")
27
+ for want, field in ((tool_call, "tool_call"), (reasoning, "reasoning"), (json_output, "structured_output")):
28
+ if want and rec.get(field) is not True:
29
+ failed.append(field)
30
+ if image_input and "image" not in (rec.get("modalities") or {}).get("input", []):
31
+ failed.append("image-input")
32
+ if provider is not None and rec.get("provider") != provider:
33
+ failed.append(f"provider={provider}")
34
+ cost = rec.get("cost") or {}
35
+ if max_input_price is not None:
36
+ p = cost.get("input_per_mtok")
37
+ if p is None or p > max_input_price:
38
+ failed.append(f"input-price<={max_input_price}")
39
+ if max_output_price is not None:
40
+ p = cost.get("output_per_mtok")
41
+ if p is None or p > max_output_price:
42
+ failed.append(f"output-price<={max_output_price}")
43
+ return failed
44
+
45
+
46
+ def rank(entries: list[tuple[str, dict]]) -> list[tuple[str, dict]]:
47
+ """Cheapest output first; unknown price last (0 == unknown); bigger context wins ties."""
48
+ def key(item: tuple[str, dict]):
49
+ _, rec = item
50
+ out = (rec.get("cost") or {}).get("output_per_mtok")
51
+ if not out:
52
+ out = None
53
+ return (out is None, out or 0.0, -(rec.get("context_window") or 0))
54
+
55
+ return sorted(entries, key=key)
56
+
57
+
58
+ def find(
59
+ table: dict,
60
+ *,
61
+ min_context: int | None = None,
62
+ max_input_price: float | None = None,
63
+ max_output_price: float | None = None,
64
+ tool_call: bool = False,
65
+ reasoning: bool = False,
66
+ json_output: bool = False,
67
+ image_input: bool = False,
68
+ provider: str | None = None,
69
+ limit: int | None = 10,
70
+ ) -> list[tuple[str, dict]]:
71
+ """Filter the table by hard requirements and rank what survives.
72
+
73
+ Returns [(key, rec), ...] — cheapest output price first, unknown prices
74
+ last, ties broken by larger context window. Every filter ANDs; an absent
75
+ fact never qualifies.
76
+ """
77
+ kwargs = dict(
78
+ min_context=min_context,
79
+ max_input_price=max_input_price,
80
+ max_output_price=max_output_price,
81
+ tool_call=tool_call,
82
+ reasoning=reasoning,
83
+ json_output=json_output,
84
+ image_input=image_input,
85
+ provider=provider,
86
+ )
87
+ entries = [(k, r) for k, r in table["models"].items() if not check(r, **kwargs)]
88
+ entries = rank(entries)
89
+ return entries if limit is None else entries[:limit]
facet/_identity.py ADDED
@@ -0,0 +1,35 @@
1
+ """Name identity: normalization, lookup build, resolve.
2
+
3
+ Same logic as examples/pick_model.py (copied, not imported — tools/ scripts
4
+ stay independently runnable).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ # Same normalization as tools/sync_models_dev.py: case, dots and hyphens are
12
+ # presentation, they never distinguish capabilities ('glm-5.3' == 'glm5.3').
13
+ _PREFIX_RE = re.compile(r"^[a-z0-9_~-]+/")
14
+ _NON_ALNUM_RE = re.compile(r"[^a-z0-9]+")
15
+
16
+
17
+ def identity(name: str) -> str:
18
+ """'OpenRouter/Anthropic/Claude-Sonnet-4.5' -> 'claudesonnet45'."""
19
+ return _NON_ALNUM_RE.sub("", _PREFIX_RE.sub("", name.strip().lower()))
20
+
21
+
22
+ def build_lookup(table: dict) -> dict[str, str]:
23
+ """normalized name -> table key. Canonical keys first, then aliases."""
24
+ lookup: dict[str, str] = {}
25
+ for key, rec in table["models"].items():
26
+ bare = key.split("/", 1)[1]
27
+ lookup.setdefault(identity(bare), key)
28
+ for alias in rec.get("aliases", []):
29
+ lookup.setdefault(identity(alias), key)
30
+ return lookup
31
+
32
+
33
+ def resolve(table: dict, name: str) -> str | None:
34
+ """Resolve a user-supplied name or alias to its table key (None if unknown)."""
35
+ return build_lookup(table).get(identity(name))
facet/_table.py ADDED
@@ -0,0 +1,73 @@
1
+ """Table loading: bundled snapshot, explicit local path, or refresh over HTTP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import urllib.error
8
+ import urllib.request
9
+ from pathlib import Path
10
+
11
+ #: Snapshot shipped inside the wheel (copied at build time by tools/build_package.py).
12
+ BUNDLED_TABLE = Path(__file__).resolve().parent / "data" / "model-registry.json"
13
+
14
+ #: Default refresh source: this repo's raw table on main.
15
+ DEFAULT_TABLE_URL: str | None = (
16
+ "https://raw.githubusercontent.com/hsliuping/Facet/main/registry/model-registry.json"
17
+ )
18
+
19
+ #: Environment variable consulted by load(refresh=True), between url= and the default.
20
+ TABLE_URL_ENV = "FACET_TABLE_URL"
21
+
22
+
23
+ def _validate(table: object) -> dict:
24
+ """Minimal contract check for anything facet loads (facts must be v1 shape)."""
25
+ if not isinstance(table, dict):
26
+ raise ValueError("table must be a JSON object")
27
+ if table.get("schema_version") != 1:
28
+ raise ValueError(f"unsupported schema_version: {table.get('schema_version')!r} (expected 1)")
29
+ if not isinstance(table.get("models"), dict):
30
+ raise ValueError("table is missing a 'models' object")
31
+ return table
32
+
33
+
34
+ def load(source: str | Path | None = None, *, refresh: bool = False, url: str | None = None) -> dict:
35
+ """Load the registry table.
36
+
37
+ source explicit local JSON path; defaults to the bundled snapshot
38
+ refresh fetch the latest table over HTTP(S) instead of reading a file
39
+ url override the refresh URL; else the FACET_TABLE_URL env var;
40
+ else DEFAULT_TABLE_URL
41
+
42
+ Failures raise — a facts table must never silently fall back to stale
43
+ data. Refresh without any URL raises RuntimeError with a fix-it hint.
44
+ """
45
+ if refresh:
46
+ target = url or os.environ.get(TABLE_URL_ENV) or DEFAULT_TABLE_URL
47
+ if not target:
48
+ raise RuntimeError(
49
+ f"refresh requested but no table URL: pass url=... or set the "
50
+ f"{TABLE_URL_ENV} environment variable"
51
+ )
52
+ try:
53
+ with urllib.request.urlopen(target, timeout=30) as resp:
54
+ raw = resp.read()
55
+ except (urllib.error.URLError, OSError) as e:
56
+ raise RuntimeError(f"failed to fetch table from {target}: {e}") from e
57
+ try:
58
+ table = json.loads(raw.decode("utf-8"))
59
+ except (UnicodeDecodeError, json.JSONDecodeError) as e:
60
+ raise RuntimeError(f"table fetched from {target} is not valid JSON: {e}") from e
61
+ return _validate(table)
62
+
63
+ path = BUNDLED_TABLE if source is None else Path(source)
64
+ try:
65
+ table = json.loads(path.read_text(encoding="utf-8"))
66
+ except FileNotFoundError as e:
67
+ if source is None:
68
+ raise RuntimeError(
69
+ "bundled snapshot missing; run 'python tools/build_package.py' "
70
+ "or pass an explicit path: facet.load('registry/model-registry.json')"
71
+ ) from e
72
+ raise
73
+ return _validate(table)
facet/_version.py ADDED
@@ -0,0 +1,2 @@
1
+ """Generated by tools/build_package.py — do not edit."""
2
+ __version__ = "2026.9.0"
facet/cli.py ADDED
@@ -0,0 +1,100 @@
1
+ """CLI: ``facet "glm-5.3"`` resolves one name; ``facet --tools ...`` filters + ranks.
2
+
3
+ Output format matches examples/pick_model.py.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ from . import _find, _identity, _table
14
+
15
+
16
+ def explain(rec: dict) -> str:
17
+ """One human-readable line of facts (absent = ?)."""
18
+ ctx = rec.get("context_window")
19
+ cost = rec.get("cost") or {}
20
+ parts = [
21
+ f"ctx={ctx/1000:.0f}k" if ctx else "ctx=?",
22
+ f"out<={rec['max_output']/1000:.0f}k" if rec.get("max_output") else "out=?",
23
+ "tools" if rec.get("tool_call") else "-tools",
24
+ "reason" if rec.get("reasoning") else "-reason",
25
+ "json" if rec.get("structured_output") else "-json",
26
+ "img-in" if "image" in (rec.get("modalities") or {}).get("input", []) else "-img-in",
27
+ ]
28
+ if cost.get("input_per_mtok") is not None or cost.get("output_per_mtok") is not None:
29
+ i = cost.get("input_per_mtok")
30
+ o = cost.get("output_per_mtok")
31
+ parts.append(f"${'?' if i is None else f'{i:g}'}/${'?' if o is None else f'{o:g}'} per MTok")
32
+ if rec.get("release_date"):
33
+ parts.append(f"released {rec['release_date']}")
34
+ return " ".join(parts)
35
+
36
+
37
+ def main(argv=None) -> int:
38
+ ap = argparse.ArgumentParser(
39
+ prog="facet", description="Pick models from the Facet registry table."
40
+ )
41
+ ap.add_argument("name", nargs="?", help="resolve one model by name or alias and print its facts")
42
+ ap.add_argument("--table", type=Path, default=None, help="registry table path (default: bundled snapshot)")
43
+ ap.add_argument("--min-context", type=int, default=None, help="minimum context window (tokens)")
44
+ ap.add_argument("--max-input-price", type=float, default=None, help="max USD per MTok input")
45
+ ap.add_argument("--max-output-price", type=float, default=None, help="max USD per MTok output")
46
+ ap.add_argument("--tools", action="store_true", help="require tool calling")
47
+ ap.add_argument("--reasoning", action="store_true", help="require reasoning")
48
+ ap.add_argument("--json", action="store_true", help="require structured output")
49
+ ap.add_argument("--image-input", action="store_true", help="require image input")
50
+ ap.add_argument("--provider", default=None, help="only models served by this provider")
51
+ ap.add_argument("--limit", type=int, default=10, help="how many rows to print")
52
+ ap.add_argument("--emit-json", action="store_true", help="output JSON instead of text")
53
+ args = ap.parse_args(argv)
54
+
55
+ filters = dict(
56
+ min_context=args.min_context,
57
+ max_input_price=args.max_input_price,
58
+ max_output_price=args.max_output_price,
59
+ tool_call=args.tools,
60
+ reasoning=args.reasoning,
61
+ json_output=args.json,
62
+ image_input=args.image_input,
63
+ provider=args.provider,
64
+ )
65
+
66
+ try:
67
+ table = _table.load(args.table)
68
+ except (RuntimeError, ValueError) as e:
69
+ print(f"ERROR: {e}", file=sys.stderr)
70
+ return 1
71
+
72
+ if args.name:
73
+ key = _identity.resolve(table, args.name)
74
+ if key is None:
75
+ print(f"not found: {args.name!r} (name not in table keys or aliases)", file=sys.stderr)
76
+ return 1
77
+ entries = [(key, table["models"][key])]
78
+ else:
79
+ entries = _find.find(table, limit=None, **filters)
80
+
81
+ rows = entries[: args.limit]
82
+ if args.emit_json:
83
+ print(json.dumps({k: r for k, r in rows}, ensure_ascii=False, indent=2))
84
+ return 0
85
+
86
+ label = args.table.name if args.table else "bundled snapshot"
87
+ print(
88
+ f"{len(entries)} match(es), showing {len(rows)} (table {label}, "
89
+ f"updated {table['updated_at']})\n"
90
+ )
91
+ for key, rec in rows:
92
+ print(key)
93
+ print(f" {explain(rec)}")
94
+ if args.name:
95
+ failed = _find.check(rec, **filters)
96
+ if failed:
97
+ print(f" (matches requested name; fails: {', '.join(failed)})")
98
+ if not entries:
99
+ print("Nothing matched. Loosen a constraint — every flag ANDs together.")
100
+ return 0