Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
154 lines
7.8 KiB
Python
154 lines
7.8 KiB
Python
"""Public desired catalogue, deliberately separate from routable API discovery."""
|
|
import ast
|
|
from contextlib import closing
|
|
from html import escape
|
|
import logging
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
try:
|
|
from model_advisories import for_model as provider_moderation_for_model
|
|
except ImportError: # Keep the base catalogue available during a partial deployment.
|
|
def provider_moderation_for_model(_model_id):
|
|
return None
|
|
|
|
LOG = logging.getLogger("public_catalogue")
|
|
BOT_SOURCE = Path("/opt/grok-bot/iishko_bot.py")
|
|
GATEWAY_DB = Path("/opt/grok-gateway/new-api/one-api.db")
|
|
# [REMOVE-AGENTS-A1 20261027] owner request: model retired from the public catalogue.
|
|
EXCLUDED = frozenset(("SenseNova-6.8-Flash-Lite", "Atria-Dawn-Preview", "Agents-A1"))
|
|
# Exact IDs observed in the operator's gateway; no invented aliases or routes.
|
|
FALLBACK = {
|
|
"claude-sonnet-5-5": 2,
|
|
"claude-opus-5-5": 4,
|
|
"claude-fable-5-1": 4,
|
|
"claude-haiku-5-5": 4,
|
|
"gpt-6.1-sol": 4,
|
|
"gpt-6-luna": 2,
|
|
"gpt-6-astra": 4,
|
|
"kimi/kimi-k3.1-pro": 3,
|
|
"deepseek-v4.1-flash-1017": 1,
|
|
"glm-5.3": 1,
|
|
"qwen-plus": 1,
|
|
"qwen-max": 1,
|
|
"qwen3.8-max": 1,
|
|
"qwen3.7-max": 1,
|
|
"qwen3-vl-plus": 1,
|
|
"qwen3.8-flash": 1,
|
|
"glm-5.3-flash": 1,
|
|
"gpt-5.6-luna": 2,
|
|
"gpt-5.6-terra": 2,
|
|
"grok-4.6": 2,
|
|
"grok-4.7": 2,
|
|
"qwen3.8-max-0902": 2,
|
|
"qwen3.8-27b": 2,
|
|
"kimi-k2.7-code": 2,
|
|
"deepseek-v4-pro": 3,
|
|
"kimi-k3.1-pro-highspeed": 3,
|
|
"Qwen3.8-Flash-Next": 3,
|
|
}
|
|
_LOCK = threading.Lock()
|
|
_CACHE = {}
|
|
|
|
|
|
def desired_models(source):
|
|
"""Parse only literal catalogue assignments: never import or execute the bot."""
|
|
source = Path(source)
|
|
if source.stat().st_size > 2 * 1024 * 1024:
|
|
raise ValueError("Catalogue source too large")
|
|
tree = ast.parse(source.read_bytes(), filename=str(source))
|
|
values = {}
|
|
for node in tree.body:
|
|
if (isinstance(node, ast.Assign) and len(node.targets) == 1
|
|
and isinstance(node.targets[0], ast.Name)
|
|
and node.targets[0].id in ("TIER_MODELS", "MODEL_DESCS")):
|
|
values[node.targets[0].id] = ast.literal_eval(node.value)
|
|
tiers = values.get("TIER_MODELS")
|
|
if (not isinstance(tiers, dict) or set(tiers) != {1, 2, 3, 4}
|
|
or any(type(rank) is not int or not isinstance(names, (list, tuple))
|
|
for rank, names in tiers.items())):
|
|
raise ValueError("Invalid ranked catalogue")
|
|
ranks = {}
|
|
for rank, names in tiers.items():
|
|
for name in names:
|
|
if (not isinstance(name, str) or not 0 < len(name) <= 128
|
|
or any(ord(char) < 32 for char in name)):
|
|
raise ValueError("Invalid catalogue ID")
|
|
if name not in EXCLUDED and not name.lower().startswith("codai"):
|
|
ranks[name] = min(rank, ranks.get(name, 4))
|
|
descriptions = values.get("MODEL_DESCS")
|
|
descriptions = descriptions if isinstance(descriptions, dict) else {}
|
|
return ranks, {name: value for name, value in descriptions.items()
|
|
if name in ranks and isinstance(value, str) and len(value) <= 1000}
|
|
|
|
|
|
def catalogue_snapshot(source=BOT_SOURCE, database=GATEWAY_DB, *, now=None):
|
|
source, database = Path(source), Path(database)
|
|
stamp = time.monotonic() if now is None else now
|
|
key = (str(source), str(database))
|
|
with _LOCK:
|
|
cached = _CACHE.get(key)
|
|
if cached and 0 <= stamp - cached[0] < 20:
|
|
return cached[1]
|
|
origin = "bot"
|
|
try:
|
|
ranks, descriptions = desired_models(source)
|
|
except (OSError, ValueError, SyntaxError, RecursionError, UnicodeError):
|
|
LOG.warning("desired_catalogue_unavailable")
|
|
if cached:
|
|
ranks = {item["id"]: item["min_rank"] for item in cached[1]["models"]}
|
|
descriptions = {item["id"]: item["description"] for item in cached[1]["models"]}
|
|
origin = "last_known"
|
|
else:
|
|
ranks, descriptions, origin = dict(FALLBACK), {}, "fallback"
|
|
configured = None
|
|
try:
|
|
with closing(sqlite3.connect(database.resolve().as_uri() + "?mode=ro", uri=True,
|
|
timeout=0.5)) as db:
|
|
configured = {row[0] for row in db.execute(
|
|
"SELECT DISTINCT a.model FROM abilities a JOIN channels c ON c.id=a.channel_id "
|
|
"WHERE a.enabled=1 AND c.status=1")}
|
|
except sqlite3.Error:
|
|
LOG.warning("catalogue_route_status_unavailable")
|
|
rows = [{"id": name, "description": descriptions.get(name, ""),
|
|
"min_rank": rank, "configured": None if configured is None else name in configured,
|
|
"status": "unknown" if configured is None else (
|
|
"configured" if name in configured else "awaiting_provider")}
|
|
for name, rank in sorted(ranks.items(), key=lambda item: (item[1], item[0]))]
|
|
for row in rows:
|
|
row["provider_moderation"] = provider_moderation_for_model(row["id"])
|
|
result = {"models": rows, "source": origin,
|
|
"note": "Конфигурация маршрута не подтверждает успешную генерацию. Ранги и лимиты проверяются отдельно."}
|
|
_CACHE.clear() # One production source; bounded even with arbitrary test paths.
|
|
_CACHE[key] = (stamp, result)
|
|
return result
|
|
|
|
|
|
def render_catalogue(snapshot):
|
|
cards = []
|
|
for model in snapshot["models"]:
|
|
label = {"configured": "Маршрут настроен · проверь свежую пробу в Mini App",
|
|
"awaiting_provider": "Ожидает провайдера · модель сохранена в каталоге",
|
|
"unknown": "Наличие маршрута не проверено"}[model["status"]]
|
|
advisory = model.get("provider_moderation")
|
|
advisory_html = ('<p class="small"><strong>' + escape(advisory["label"])
|
|
+ '</strong><br>' + escape(advisory["notice"]) + '</p>'
|
|
if advisory else '')
|
|
cards.append('<article class="card"><h2><code>' + escape(model["id"])
|
|
+ '</code></h2><p>' + escape(model["description"])
|
|
+ '</p><p class="small">Ранг: ' + str(model["min_rank"])
|
|
+ ' и выше</p><p class="muted">' + escape(label) + '</p>'
|
|
+ advisory_html + '</article>')
|
|
degraded = ('<div class="note" role="status">Основной источник каталога временно недоступен. '
|
|
'Показан сохранённый список; наличие маршрута проверяется отдельно.</div>'
|
|
if snapshot.get("source") in ("fallback", "last_known") else "")
|
|
return ('<p class="eyebrow">Бот · Mini App · API</p><h1>Каталог моделей.</h1>'
|
|
'<p class="lead">Современные модели остаются здесь, даже если подходящий провайдер '
|
|
'временно отсутствует. Выбирается точный ID: другая модель не подставляется незаметно.</p>'
|
|
'<div class="note">«Маршрут настроен» — не обещание работоспособности. '
|
|
'Результат и время реальной пробы смотри в Mini App. Наличие в каталоге '
|
|
'не снимает ограничения ранга, бюджета или ключа.</div>' + degraded
|
|
+ '<section class="grid" aria-label="Модели и наличие маршрута">'
|
|
+ ''.join(cards) + '</section>')
|