Files
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

253 lines
8.3 KiB
Python

#!/usr/bin/env python3
from __future__ import annotations
import json
import os
import stat
import threading
MAX_BYTES = 1024 * 1024
SPECS_NAME = "model_specs.json"
SCOPE_VENDOR = "vendor_reference"
SCOPE_UNKNOWN = "unknown"
DEFAULT_SOURCE = "https://openrouter.ai/api/v1/models"
_MAX_LIMIT = 1000000000
_ENTRY_FIELDS = ("source_model", "context_window", "max_input_tokens",
"max_output_tokens", "top_provider_context_window")
_LOCK = threading.Lock()
_CACHE = {"key": None, "specs": {}, "source": None, "scope": SCOPE_VENDOR,
"field_sources": {}, "notes": (), "bot_output_budget": None}
def candidate_paths():
"""Resolution order: explicit env override, module dir, canonical parent/bot, prod.
An explicit ``IISHKO_MODEL_SPECS`` is authoritative: when it is set, no other
location is consulted, so a missing/invalid/oversized override degrades to an
honest "unknown" reference instead of silently loading different numbers.
"""
override = os.environ.get("IISHKO_MODEL_SPECS")
if override is not None:
return [override] if override else []
here = os.path.dirname(os.path.abspath(__file__))
return [os.path.join(here, SPECS_NAME),
os.path.join(os.path.dirname(here), "bot", SPECS_NAME),
os.path.join(os.sep, "opt", "grok-bot", SPECS_NAME)]
def _positive_int(value):
if isinstance(value, bool) or not isinstance(value, int):
return None
return value if 0 < value <= _MAX_LIMIT else None
def _clean_entry(raw):
if not isinstance(raw, dict):
return None
source_model = raw.get("source_model")
if not isinstance(source_model, str) or not source_model.strip() or len(source_model) > 128:
return None
entry = {"source_model": source_model.strip()}
for field in _ENTRY_FIELDS[1:]:
value = raw.get(field)
if field == "max_input_tokens":
entry[field] = None # reference only: never inferred from context_window
continue
entry[field] = _positive_int(value)
return entry
def _clean_specs(document):
"""Return (models, header) from a parsed document, or ({}, header) when unusable."""
header = {"source": None, "scope": SCOPE_VENDOR, "field_sources": {}, "notes": (),
"bot_output_budget": None}
if not isinstance(document, dict):
return {}, header
source = document.get("source")
if isinstance(source, str) and 0 < len(source) <= 512:
header["source"] = source
scope = document.get("scope")
if isinstance(scope, str) and 0 < len(scope) <= 64:
header["scope"] = scope
field_sources = document.get("field_sources")
if isinstance(field_sources, dict):
header["field_sources"] = {k: v for k, v in field_sources.items()
if isinstance(k, str) and isinstance(v, str)}
notes = document.get("notes")
if isinstance(notes, list):
header["notes"] = tuple(n for n in notes if isinstance(n, str))
budget = document.get("bot_output_budget")
if isinstance(budget, dict):
header["bot_output_budget"] = {
"scope": budget.get("scope") if isinstance(budget.get("scope"), str) else "bot_runtime_local",
"not_a_vendor_limit": True,
"normal": _positive_int(budget.get("normal")),
"max": _positive_int(budget.get("max")),
}
models_raw = document.get("models")
if not isinstance(models_raw, dict):
return {}, header
models = {}
for name, raw in models_raw.items():
if not isinstance(name, str) or not 0 < len(name) <= 128:
continue
entry = _clean_entry(raw)
if entry is not None:
models[name] = entry
return models, header
def _stat_key(path):
try:
info = os.stat(path)
except OSError:
return None
if not stat.S_ISREG(info.st_mode) or info.st_size <= 0 or info.st_size > MAX_BYTES:
return None
return (os.path.realpath(path), info.st_mtime_ns, info.st_size)
def _load():
"""Populate the cache if the backing file changed. Never raises."""
key = None
raw = None
for path in candidate_paths():
key = _stat_key(path)
if key is None:
continue
try:
with open(path, "rb") as handle:
raw = handle.read(MAX_BYTES + 1)
except OSError:
key, raw = None, None
continue
break
with _LOCK:
if key is None:
_CACHE.update({"key": None, "specs": {}, "source": None, "scope": SCOPE_VENDOR,
"field_sources": {}, "notes": (), "bot_output_budget": None})
return
if _CACHE["key"] == key:
return
models, header = {}, {"source": None, "scope": SCOPE_VENDOR, "field_sources": {},
"notes": (), "bot_output_budget": None}
if raw is not None and len(raw) <= MAX_BYTES:
try:
document = json.loads(raw.decode("utf-8-sig"))
except (ValueError, UnicodeDecodeError):
document = None
models, header = _clean_specs(document)
_CACHE.update({"key": key, "specs": models, **header})
def reload():
"""Force the next lookup to re-read the file (deploy/tests)."""
with _LOCK:
_CACHE["key"] = None
def available():
"""True when a usable vendor reference is loaded."""
try:
_load()
return bool(_CACHE["specs"])
except Exception:
return False
def describe():
"""Header of the loaded reference; honest empty shape when nothing is loaded."""
try:
_load()
except Exception:
pass
with _LOCK:
return {
"scope": _CACHE["scope"] if _CACHE["specs"] else SCOPE_UNKNOWN,
"source": _CACHE["source"],
"gateway_verified": False,
"known_models": len(_CACHE["specs"]),
"field_sources": dict(_CACHE["field_sources"]),
"notes": list(_CACHE["notes"]),
"bot_output_budget": dict(_CACHE["bot_output_budget"] or {}) or None,
}
def _unknown(model_id):
return {
"model": model_id,
"known": False,
"scope": SCOPE_UNKNOWN,
"source": None,
"source_model": None,
"context_window": None,
"max_input_tokens": None,
"max_output_tokens": None,
"gateway_verified": False,
}
def for_model(model_id):
"""Metadata for one served model id. Unknown ids: explicit nulls, no guesses."""
if not isinstance(model_id, str) or not model_id:
return _unknown(model_id if isinstance(model_id, str) else None)
try:
_load()
with _LOCK:
entry = _CACHE["specs"].get(model_id)
source = _CACHE["source"]
scope = _CACHE["scope"]
if entry is None:
return _unknown(model_id)
meta = {
"model": model_id,
"known": True,
"scope": scope,
"source": source,
"source_model": entry["source_model"],
"context_window": entry["context_window"],
"max_input_tokens": None,
"max_output_tokens": entry["max_output_tokens"],
"gateway_verified": False,
}
if entry.get("top_provider_context_window") is not None:
meta["top_provider_context_window"] = entry["top_provider_context_window"]
return meta
except Exception:
return _unknown(model_id)
def for_models(model_ids):
"""Mapping id -> metadata for the given ids, in input order."""
result = {}
if not isinstance(model_ids, (list, tuple, set, frozenset)):
return result
for model_id in model_ids:
if isinstance(model_id, str) and model_id:
result[model_id] = for_model(model_id)
return result
def attach_rows(rows):
if not isinstance(rows, (list, tuple)):
return rows
try:
if not available():
return list(rows)
except Exception:
return list(rows)
out = []
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get("id"), str):
out.append(row)
continue
copy = dict(row)
copy["model_metadata"] = for_model(row["id"])
out.append(copy)
return out
__all__ = ["attach_rows", "available", "candidate_paths", "describe", "for_model",
"for_models", "reload"]