"""Model identity rules: spelling aliases, never replacement models.""" import re _CLAUDE_VERSION_FIRST = re.compile(r"claude-(\d+(?:-\d+)*)-(sonnet|opus|fable)") _CLAUDE_SHORT_NAME = re.compile(r"(?:opus|sonnet|fable)-\d+(?:-\d+)*") _CREATOR_PREFIXES = { "openai": ("gpt-", "o1", "o3", "o4"), "anthropic": ("claude-", "opus-", "sonnet-"), "x-ai": ("grok-",), "xai": ("grok-",), "z-ai": ("glm-", "cogview-"), "zhipu": ("glm-", "cogview-"), "moonshotai": ("kimi-",), "moonshot": ("kimi-",), "qwen": ("qwen",), "alibaba": ("qwen",), "deepseek": ("deepseek-",), "deepseek-ai": ("deepseek-",), } _AGGREGATOR_PREFIXES = {"kr", "cx", "or", "openrouter", "pool", "modeloc", "auto", "kimi"} class ModelIdentityError(RuntimeError): """A response names a different model than the one requested.""" terminal = True status = 503 code = "model_identity_mismatch" def __init__(self): super().__init__("Выбранная модель сейчас недоступна. Повтори позже.") def canonical_model(name): if not isinstance(name, str) or not name.strip(): return "" name = name.strip().lower() if "/" in name: creator, bare = name.split("/", 1) if creator in _AGGREGATOR_PREFIXES or bare.startswith(_CREATOR_PREFIXES.get(creator, ("\0",))): name = bare name = name.replace("_", "-").replace(".", "-") # Two documented spellings of the same Claude version. match = _CLAUDE_VERSION_FIRST.fullmatch(name) if match: name = "claude-" + match[2] + "-" + match[1] if _CLAUDE_SHORT_NAME.fullmatch(name): name = "claude-" + name # [YETA-UNC 23.10] unfiltered provider variant reported under base model name if name.endswith("-uncensored"): name = name[: -len("-uncensored")] return name def same_original_model(requested, actual): requested = canonical_model(requested) return bool(requested) and requested == canonical_model(actual) def check_response_model(requested, response): """Check a declared response identity; absent optional model is not evidence.""" if isinstance(response, dict) and response.get("model") is not None: if not same_original_model(requested, response["model"]): raise ModelIdentityError()