facet-models 1.0.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.
Files changed (56) hide show
  1. facet/__init__.py +24 -0
  2. facet/__main__.py +8 -0
  3. facet/_find.py +98 -0
  4. facet/_identity.py +37 -0
  5. facet/_table.py +73 -0
  6. facet/cli.py +110 -0
  7. facet/data/model-registry.json +1 -0
  8. facet/gateway/__init__.py +11 -0
  9. facet/gateway/_alias.py +20 -0
  10. facet/gateway/accounts.py +195 -0
  11. facet/gateway/ark_quota.py +360 -0
  12. facet/gateway/audit.py +110 -0
  13. facet/gateway/bailian_quota.py +226 -0
  14. facet/gateway/cli.py +168 -0
  15. facet/gateway/completions.py +145 -0
  16. facet/gateway/convert.py +689 -0
  17. facet/gateway/core.py +1737 -0
  18. facet/gateway/deepseek_quota.py +54 -0
  19. facet/gateway/dsh.py +365 -0
  20. facet/gateway/facts.py +100 -0
  21. facet/gateway/freealign.py +336 -0
  22. facet/gateway/hunyuan_quota.py +142 -0
  23. facet/gateway/keys.py +178 -0
  24. facet/gateway/maintenance.py +1727 -0
  25. facet/gateway/minimax_quota.py +197 -0
  26. facet/gateway/modelscope_quota.py +155 -0
  27. facet/gateway/moonshot_quota.py +75 -0
  28. facet/gateway/notifier.py +400 -0
  29. facet/gateway/opencode_quota.py +89 -0
  30. facet/gateway/openrouter_quota.py +84 -0
  31. facet/gateway/persistence.py +180 -0
  32. facet/gateway/probe.py +384 -0
  33. facet/gateway/providers.json +511 -0
  34. facet/gateway/providers.py +446 -0
  35. facet/gateway/quota.py +147 -0
  36. facet/gateway/report.py +236 -0
  37. facet/gateway/responses.py +411 -0
  38. facet/gateway/seed.py +108 -0
  39. facet/gateway/server.py +6160 -0
  40. facet/gateway/static/app.js +5530 -0
  41. facet/gateway/static/index.html +1086 -0
  42. facet/gateway/static/setup.js +713 -0
  43. facet/gateway/static/style.css +601 -0
  44. facet/gateway/subscriptions.py +333 -0
  45. facet/gateway/tokenhub_quota.py +255 -0
  46. facet/gateway/ui.py +946 -0
  47. facet/gateway/usage.py +337 -0
  48. facet/gateway/watch.py +627 -0
  49. facet/gateway/zhipu_quota.py +195 -0
  50. facet/py.typed +0 -0
  51. facet_models-1.0.0.dist-info/METADATA +411 -0
  52. facet_models-1.0.0.dist-info/RECORD +56 -0
  53. facet_models-1.0.0.dist-info/WHEEL +5 -0
  54. facet_models-1.0.0.dist-info/entry_points.txt +5 -0
  55. facet_models-1.0.0.dist-info/licenses/LICENSE +21 -0
  56. facet_models-1.0.0.dist-info/top_level.txt +1 -0
facet/__init__.py ADDED
@@ -0,0 +1,24 @@
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
+ __version__ = "1.0.0"
12
+
13
+ __all__ = [
14
+ "BUNDLED_TABLE",
15
+ "DEFAULT_TABLE_URL",
16
+ "__version__",
17
+ "build_lookup",
18
+ "check",
19
+ "find",
20
+ "identity",
21
+ "load",
22
+ "rank",
23
+ "resolve",
24
+ ]
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,98 @@
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
+ # Standing free tiers a record may carry; anything else (absent included)
11
+ # counts as unknown and can never satisfy the free-tier requirement.
12
+ FREE_TIERS = ("free_forever", "free_daily")
13
+
14
+
15
+ def check(
16
+ rec: dict,
17
+ *,
18
+ min_context: int | None = None,
19
+ max_input_price: float | None = None,
20
+ max_output_price: float | None = None,
21
+ tool_call: bool = False,
22
+ reasoning: bool = False,
23
+ json_output: bool = False,
24
+ image_input: bool = False,
25
+ provider: str | None = None,
26
+ free: bool = False,
27
+ ) -> list[str]:
28
+ """Return the list of failed requirements (empty = the record qualifies)."""
29
+ failed: list[str] = []
30
+ if min_context is not None and (rec.get("context_window") or 0) < min_context:
31
+ failed.append(f"context>={min_context}")
32
+ if free and rec.get("quota_tier") not in FREE_TIERS:
33
+ failed.append("free-tier")
34
+ for want, field in ((tool_call, "tool_call"), (reasoning, "reasoning"), (json_output, "structured_output")):
35
+ if want and rec.get(field) is not True:
36
+ failed.append(field)
37
+ if image_input and "image" not in (rec.get("modalities") or {}).get("input", []):
38
+ failed.append("image-input")
39
+ if provider is not None and rec.get("provider") != provider:
40
+ failed.append(f"provider={provider}")
41
+ cost = rec.get("cost") or {}
42
+ if max_input_price is not None:
43
+ p = cost.get("input_per_mtok")
44
+ if p is None or p > max_input_price:
45
+ failed.append(f"input-price<={max_input_price}")
46
+ if max_output_price is not None:
47
+ p = cost.get("output_per_mtok")
48
+ if p is None or p > max_output_price:
49
+ failed.append(f"output-price<={max_output_price}")
50
+ return failed
51
+
52
+
53
+ def rank(entries: list[tuple[str, dict]]) -> list[tuple[str, dict]]:
54
+ """Cheapest output first; unknown price last (0 == unknown); bigger context wins ties."""
55
+ def key(item: tuple[str, dict]):
56
+ _, rec = item
57
+ out = (rec.get("cost") or {}).get("output_per_mtok")
58
+ if not out:
59
+ out = None
60
+ return (out is None, out or 0.0, -(rec.get("context_window") or 0))
61
+
62
+ return sorted(entries, key=key)
63
+
64
+
65
+ def find(
66
+ table: dict,
67
+ *,
68
+ min_context: int | None = None,
69
+ max_input_price: float | None = None,
70
+ max_output_price: float | None = None,
71
+ tool_call: bool = False,
72
+ reasoning: bool = False,
73
+ json_output: bool = False,
74
+ image_input: bool = False,
75
+ provider: str | None = None,
76
+ free: bool = False,
77
+ limit: int | None = 10,
78
+ ) -> list[tuple[str, dict]]:
79
+ """Filter the table by hard requirements and rank what survives.
80
+
81
+ Returns [(key, rec), ...] — cheapest output price first, unknown prices
82
+ last, ties broken by larger context window. Every filter ANDs; an absent
83
+ fact never qualifies.
84
+ """
85
+ kwargs = dict(
86
+ min_context=min_context,
87
+ max_input_price=max_input_price,
88
+ max_output_price=max_output_price,
89
+ tool_call=tool_call,
90
+ reasoning=reasoning,
91
+ json_output=json_output,
92
+ image_input=image_input,
93
+ provider=provider,
94
+ free=free,
95
+ )
96
+ entries = [(k, r) for k, r in table["models"].items() if not check(r, **kwargs)]
97
+ entries = rank(entries)
98
+ return entries if limit is None else entries[:limit]
facet/_identity.py ADDED
@@ -0,0 +1,37 @@
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
+ # Some keys (e.g. embedding models) carry no "provider/" prefix;
27
+ # [-1] keeps those resolving instead of raising IndexError.
28
+ bare = key.split("/", 1)[-1]
29
+ lookup.setdefault(identity(bare), key)
30
+ for alias in rec.get("aliases", []):
31
+ lookup.setdefault(identity(alias), key)
32
+ return lookup
33
+
34
+
35
+ def resolve(table: dict, name: str) -> str | None:
36
+ """Resolve a user-supplied name or alias to its table key (None if unknown)."""
37
+ 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/cli.py ADDED
@@ -0,0 +1,110 @@
1
+ """CLI: ``facet "glm-5.3"`` resolves one name; ``facet --tools ...`` filters + ranks;
2
+ ``facet serve`` starts the self-maintaining gateway (its own argv follows).
3
+
4
+ Output format matches examples/pick_model.py.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ from . import _find, _identity, _table
15
+
16
+
17
+ def explain(rec: dict) -> str:
18
+ """One human-readable line of facts (absent = ?)."""
19
+ ctx = rec.get("context_window")
20
+ cost = rec.get("cost") or {}
21
+ parts = [
22
+ f"ctx={ctx/1000:.0f}k" if ctx else "ctx=?",
23
+ f"out<={rec['max_output']/1000:.0f}k" if rec.get("max_output") else "out=?",
24
+ "tools" if rec.get("tool_call") else "-tools",
25
+ "reason" if rec.get("reasoning") else "-reason",
26
+ "json" if rec.get("structured_output") else "-json",
27
+ "img-in" if "image" in (rec.get("modalities") or {}).get("input", []) else "-img-in",
28
+ ]
29
+ if cost.get("input_per_mtok") is not None or cost.get("output_per_mtok") is not None:
30
+ i = cost.get("input_per_mtok")
31
+ o = cost.get("output_per_mtok")
32
+ parts.append(f"${'?' if i is None else f'{i:g}'}/${'?' if o is None else f'{o:g}'} per MTok")
33
+ if rec.get("release_date"):
34
+ parts.append(f"released {rec['release_date']}")
35
+ return " ".join(parts)
36
+
37
+
38
+ def main(argv=None) -> int:
39
+ argv = list(sys.argv[1:] if argv is None else argv)
40
+ if argv and argv[0] == "serve":
41
+ # The gateway ships in this wheel; `facet serve` is its product form.
42
+ from .gateway.cli import main as serve_main
43
+ return serve_main(argv[1:])
44
+ ap = argparse.ArgumentParser(
45
+ prog="facet", description="Pick models from the Facet registry table."
46
+ )
47
+ ap.add_argument("name", nargs="?", help="resolve one model by name or alias and print its facts")
48
+ ap.add_argument("--table", type=Path, default=None, help="registry table path (default: bundled snapshot)")
49
+ ap.add_argument("--min-context", type=int, default=None, help="minimum context window (tokens)")
50
+ ap.add_argument("--max-input-price", type=float, default=None, help="max USD per MTok input")
51
+ ap.add_argument("--max-output-price", type=float, default=None, help="max USD per MTok output")
52
+ ap.add_argument("--tools", action="store_true", help="require tool calling")
53
+ ap.add_argument("--free", action="store_true",
54
+ help="require a free quota tier (free_forever / free_daily; "
55
+ "absent quota_tier counts as unknown and is excluded)")
56
+ ap.add_argument("--reasoning", action="store_true", help="require reasoning")
57
+ ap.add_argument("--json", action="store_true", help="require structured output")
58
+ ap.add_argument("--image-input", action="store_true", help="require image input")
59
+ ap.add_argument("--provider", default=None, help="only models served by this provider")
60
+ ap.add_argument("--limit", type=int, default=10, help="how many rows to print")
61
+ ap.add_argument("--emit-json", action="store_true", help="output JSON instead of text")
62
+ args = ap.parse_args(argv)
63
+
64
+ filters = dict(
65
+ min_context=args.min_context,
66
+ max_input_price=args.max_input_price,
67
+ max_output_price=args.max_output_price,
68
+ tool_call=args.tools,
69
+ reasoning=args.reasoning,
70
+ json_output=args.json,
71
+ image_input=args.image_input,
72
+ provider=args.provider,
73
+ free=args.free,
74
+ )
75
+
76
+ try:
77
+ table = _table.load(args.table)
78
+ except (RuntimeError, ValueError) as e:
79
+ print(f"ERROR: {e}", file=sys.stderr)
80
+ return 1
81
+
82
+ if args.name:
83
+ key = _identity.resolve(table, args.name)
84
+ if key is None:
85
+ print(f"not found: {args.name!r} (name not in table keys or aliases)", file=sys.stderr)
86
+ return 1
87
+ entries = [(key, table["models"][key])]
88
+ else:
89
+ entries = _find.find(table, limit=None, **filters)
90
+
91
+ rows = entries[: args.limit]
92
+ if args.emit_json:
93
+ print(json.dumps({k: r for k, r in rows}, ensure_ascii=False, indent=2))
94
+ return 0
95
+
96
+ label = args.table.name if args.table else "bundled snapshot"
97
+ print(
98
+ f"{len(entries)} match(es), showing {len(rows)} (table {label}, "
99
+ f"updated {table['updated_at']})\n"
100
+ )
101
+ for key, rec in rows:
102
+ print(key)
103
+ print(f" {explain(rec)}")
104
+ if args.name:
105
+ failed = _find.check(rec, **filters)
106
+ if failed:
107
+ print(f" (matches requested name; fails: {', '.join(failed)})")
108
+ if not entries:
109
+ print("Nothing matched. Loosen a constraint — every flag ANDs together.")
110
+ return 0