modelcheck 1.0.1__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.
- modelcheck/__init__.py +4 -0
- modelcheck/__main__.py +3 -0
- modelcheck/checks/__init__.py +12 -0
- modelcheck/checks/capabilities/__init__.py +1 -0
- modelcheck/checks/capabilities/check.py +64 -0
- modelcheck/checks/forty_questions/__init__.py +0 -0
- modelcheck/checks/forty_questions/check.py +79 -0
- modelcheck/checks/hidden_prompt/__init__.py +0 -0
- modelcheck/checks/hidden_prompt/check.py +52 -0
- modelcheck/checks/identity/__init__.py +1 -0
- modelcheck/checks/identity/check.py +118 -0
- modelcheck/checks/late_turns/__init__.py +0 -0
- modelcheck/checks/late_turns/check.py +71 -0
- modelcheck/checks/model_field/__init__.py +1 -0
- modelcheck/checks/model_field/check.py +67 -0
- modelcheck/checks/random_number/__init__.py +1 -0
- modelcheck/checks/random_number/check.py +70 -0
- modelcheck/checks/reasoning/__init__.py +0 -0
- modelcheck/checks/reasoning/check.py +104 -0
- modelcheck/checks/response_shape/__init__.py +1 -0
- modelcheck/checks/response_shape/check.py +89 -0
- modelcheck/checks/thinking_signature/__init__.py +1 -0
- modelcheck/checks/thinking_signature/check.py +66 -0
- modelcheck/checks/tokenizer/__init__.py +1 -0
- modelcheck/checks/tokenizer/check.py +89 -0
- modelcheck/cli.py +207 -0
- modelcheck/core/__init__.py +1 -0
- modelcheck/core/baselines.py +60 -0
- modelcheck/core/check.py +30 -0
- modelcheck/core/client.py +170 -0
- modelcheck/core/engine.py +97 -0
- modelcheck/core/rand.py +52 -0
- modelcheck/core/types.py +79 -0
- modelcheck/makers/__init__.py +69 -0
- modelcheck/makers/alibaba/__init__.py +14 -0
- modelcheck/makers/amazon/__init__.py +9 -0
- modelcheck/makers/anthropic/__init__.py +15 -0
- modelcheck/makers/bytedance/__init__.py +12 -0
- modelcheck/makers/cohere/__init__.py +9 -0
- modelcheck/makers/deepseek/__init__.py +14 -0
- modelcheck/makers/google/__init__.py +14 -0
- modelcheck/makers/meta/__init__.py +12 -0
- modelcheck/makers/microsoft/__init__.py +11 -0
- modelcheck/makers/minimax/__init__.py +12 -0
- modelcheck/makers/mistral/__init__.py +12 -0
- modelcheck/makers/moonshot/__init__.py +14 -0
- modelcheck/makers/nvidia/__init__.py +10 -0
- modelcheck/makers/openai/__init__.py +14 -0
- modelcheck/makers/sber/__init__.py +10 -0
- modelcheck/makers/xai/__init__.py +13 -0
- modelcheck/makers/yandex/__init__.py +10 -0
- modelcheck/makers/zhipu/__init__.py +14 -0
- modelcheck/report/__init__.py +1 -0
- modelcheck/report/render.py +98 -0
- modelcheck-1.0.1.dist-info/METADATA +87 -0
- modelcheck-1.0.1.dist-info/RECORD +59 -0
- modelcheck-1.0.1.dist-info/WHEEL +4 -0
- modelcheck-1.0.1.dist-info/entry_points.txt +2 -0
- modelcheck-1.0.1.dist-info/licenses/LICENSE +9 -0
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Размышления у reasoning-моделей всех производителей (кроме подписи Claude — она отдельно).
|
|
2
|
+
|
|
3
|
+
Что проверяем, в зависимости от профиля производителя:
|
|
4
|
+
- OpenAI / xAI: Responses API с include=["reasoning.encrypted_content"] должен вернуть
|
|
5
|
+
зашифрованный блок размышлений, и сервер должен принять его обратно следующим ходом.
|
|
6
|
+
Подделать шифр нельзя → сильная улика (★★☆, у посредника Responses API может не быть).
|
|
7
|
+
- DeepSeek / Qwen / GLM / Kimi / Doubao / MiniMax: reasoning-версия должна отдавать поле
|
|
8
|
+
reasoning_content. Нет поля у «reasoner» → подсунули обычную chat-модель (кейс CISPA:
|
|
9
|
+
deepseek-chat вместо deepseek-reasoner).
|
|
10
|
+
- Все: usage.completion_tokens_details.reasoning_tokens. На задаче, где нужно подумать,
|
|
11
|
+
у reasoning-модели > 0. Ноль → вырезали размышления или отдали другую модель.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
|
|
17
|
+
from ...core import rand
|
|
18
|
+
from ...core.check import Check, register
|
|
19
|
+
from ...core.types import Finding, Status
|
|
20
|
+
from ...makers import profile
|
|
21
|
+
|
|
22
|
+
NAMES = ["Аня", "Маша", "Оля", "Катя", "Лена", "Вика"]
|
|
23
|
+
REASONING_NAME = re.compile(r"reason|think|(?<![a-z])r1(?![0-9])|(?<![a-z])o[1-9](?![a-z0-9])|-pro|qwq|magistral|k3|thinking")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def make_task() -> tuple[str, str]:
|
|
27
|
+
"""Задача с подвохом: у девочки N братьев, у каждого брата S сестёр → сестёр у неё S-1."""
|
|
28
|
+
name, n, s = rand.pick(NAMES), rand.number(2, 4), rand.number(2, 4)
|
|
29
|
+
q = (f"У {name[:-1]}и {n} брата, у каждого брата {s} сестры. "
|
|
30
|
+
f"Сколько сестёр у {name[:-1]}и? Ответь только числом.")
|
|
31
|
+
return rand.cover(q), str(s - 1)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@register
|
|
35
|
+
class Reasoning(Check):
|
|
36
|
+
name = "reasoning"
|
|
37
|
+
title = "Размышления reasoning-моделей"
|
|
38
|
+
protocols = ("openai",)
|
|
39
|
+
level = 2
|
|
40
|
+
|
|
41
|
+
def applies(self, target, maker):
|
|
42
|
+
p = profile(maker)
|
|
43
|
+
return target.protocol == "openai" and (p.signature in ("openai_encrypted", "xai_encrypted") or p.reasoning_field)
|
|
44
|
+
|
|
45
|
+
def run(self, client, target, maker):
|
|
46
|
+
p = profile(maker)
|
|
47
|
+
out = []
|
|
48
|
+
is_reasoning = bool(REASONING_NAME.search(target.model.lower()))
|
|
49
|
+
task, answer = make_task()
|
|
50
|
+
|
|
51
|
+
# 1. зашифрованные размышления OpenAI / xAI
|
|
52
|
+
if p.signature in ("openai_encrypted", "xai_encrypted"):
|
|
53
|
+
r = client.responses(target.model, task, include_encrypted=True)
|
|
54
|
+
if r.status == 404 or (not r.ok and "responses" in r.error.lower()):
|
|
55
|
+
out.append(Finding(self.name, Status.INFO, "Зашифрованные размышления",
|
|
56
|
+
"Responses API недоступен у посредника — проверить шифр размышлений нельзя."))
|
|
57
|
+
elif not r.ok:
|
|
58
|
+
out.append(Finding(self.name, Status.INFO, "Зашифрованные размышления", f"Запрос не прошёл: {r.error[:120]}"))
|
|
59
|
+
else:
|
|
60
|
+
enc = r.extra.get("encrypted_reasoning")
|
|
61
|
+
if not enc:
|
|
62
|
+
out.append(Finding(self.name, Status.WARN if is_reasoning else Status.INFO, "Зашифрованные размышления",
|
|
63
|
+
"Responses API ответил, но без encrypted_content."))
|
|
64
|
+
else:
|
|
65
|
+
back = client.responses(target.model, "А если братьев на одного больше?", include_encrypted=True,
|
|
66
|
+
previous_items=r.extra["output_items"])
|
|
67
|
+
if back.ok:
|
|
68
|
+
out.append(Finding(self.name, Status.PASS, "Зашифрованные размышления",
|
|
69
|
+
f"Шифр размышлений есть ({len(enc)} симв.) и принят сервером обратно."))
|
|
70
|
+
elif "encrypt" in back.error.lower() or "reasoning" in back.error.lower():
|
|
71
|
+
out.append(Finding(self.name, Status.FAIL, "Зашифрованные размышления",
|
|
72
|
+
f"Сервер отклонил собственный шифр: {back.error[:140]}", critical=True))
|
|
73
|
+
else:
|
|
74
|
+
out.append(Finding(self.name, Status.WARN, "Зашифрованные размышления",
|
|
75
|
+
f"Шифр есть, но повторная отправка упала: {back.error[:120]}"))
|
|
76
|
+
|
|
77
|
+
# 2. reasoning_content у китайских reasoning-моделей + reasoning_tokens у всех
|
|
78
|
+
r = client.chat(target.model, [{"role": "user", "content": task}], max_tokens=2000)
|
|
79
|
+
if not r.ok:
|
|
80
|
+
out.append(Finding(self.name, Status.SKIP, "Счётчик размышлений", f"Нет ответа: {r.error[:120]}"))
|
|
81
|
+
return out
|
|
82
|
+
rt = ((r.usage.get("completion_tokens_details") or {}).get("reasoning_tokens"))
|
|
83
|
+
has_field = bool(r.extra.get("reasoning_content") or r.extra.get("reasoning"))
|
|
84
|
+
if p.reasoning_field and is_reasoning:
|
|
85
|
+
if has_field or (rt or 0) > 0:
|
|
86
|
+
out.append(Finding(self.name, Status.PASS, "Поле размышлений",
|
|
87
|
+
f"Reasoning-модель отдала размышления ({'reasoning_content' if has_field else f'{rt} токенов'})."))
|
|
88
|
+
else:
|
|
89
|
+
out.append(Finding(self.name, Status.FAIL, "Поле размышлений",
|
|
90
|
+
f"Заявлена reasoning-модель, но нет ни {p.reasoning_field}, ни reasoning_tokens: "
|
|
91
|
+
"похоже, отдают обычную chat-версию (так подменяли deepseek-reasoner на deepseek-chat).",
|
|
92
|
+
critical=True))
|
|
93
|
+
elif rt is not None:
|
|
94
|
+
if is_reasoning and rt == 0:
|
|
95
|
+
out.append(Finding(self.name, Status.WARN, "Счётчик размышлений",
|
|
96
|
+
"reasoning_tokens = 0 на задаче с подвохом: размышления вырезаны или модель не reasoning."))
|
|
97
|
+
else:
|
|
98
|
+
out.append(Finding(self.name, Status.INFO, "Счётчик размышлений", f"reasoning_tokens = {rt}."))
|
|
99
|
+
# правильный ответ — S-1 (сама девочка тоже сестра); невнимательные модели отвечают S
|
|
100
|
+
m = re.search(r"\d+", r.text)
|
|
101
|
+
if m and m.group() != answer and is_reasoning:
|
|
102
|
+
out.append(Finding(self.name, Status.WARN, "Задача на внимательность",
|
|
103
|
+
f"Ответ {m.group()} вместо {answer}: reasoning-модель уровня заявленной решает такое без ошибок."))
|
|
104
|
+
return out
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Форма ответа: id, usage, чужие поля.
|
|
2
|
+
|
|
3
|
+
У каждого производителя свой «почерк» ответа:
|
|
4
|
+
- Anthropic: id начинается с msg_, usage с input_tokens/output_tokens;
|
|
5
|
+
- OpenAI: id chatcmpl-…, system_fingerprint fp_…;
|
|
6
|
+
- DeepSeek выдаёт себя полем reasoning_content (у Claude/GPT его нет).
|
|
7
|
+
Чужие поля в ответе — след того, что внутри другая модель или переходник.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from ...core.check import Check, register
|
|
12
|
+
from ...core.types import Finding, Status
|
|
13
|
+
from ...makers import PROFILES, profile
|
|
14
|
+
|
|
15
|
+
ID_PREFIX = {"anthropic": ("msg_",), "openai": ("chatcmpl-", "resp_")}
|
|
16
|
+
# у кого родное поле reasoning_content (DeepSeek и китайские открытые модели)
|
|
17
|
+
REASONING_FIELD_MAKERS = {n for n, p in PROFILES.items() if p.reasoning_field == "reasoning_content"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@register
|
|
21
|
+
class ResponseShape(Check):
|
|
22
|
+
name = "response_shape"
|
|
23
|
+
title = "Форма ответа (id, usage, чужие поля)"
|
|
24
|
+
level = 1
|
|
25
|
+
|
|
26
|
+
def run(self, client, target, maker):
|
|
27
|
+
r = client.chat(target.model, [{"role": "user", "content": "Привет! Ответь одним словом."}], max_tokens=30)
|
|
28
|
+
if not r.ok:
|
|
29
|
+
return [Finding(self.name, Status.SKIP, self.title, f"Нет ответа: {r.error}")]
|
|
30
|
+
out = []
|
|
31
|
+
|
|
32
|
+
# 1. reasoning_content у тех, у кого его быть не должно
|
|
33
|
+
if r.extra.get("reasoning_content") and maker not in REASONING_FIELD_MAKERS:
|
|
34
|
+
out.append(Finding(self.name, Status.FAIL, "Поле reasoning_content",
|
|
35
|
+
"В ответе есть reasoning_content — фирменное поле DeepSeek и китайских моделей "
|
|
36
|
+
f"({', '.join(sorted(REASONING_FIELD_MAKERS))}). У {maker} его быть не должно.", critical=True))
|
|
37
|
+
|
|
38
|
+
# 1б. размышления в тексте <think>…</think> — так отвечают открытые модели (DeepSeek-R1, Qwen, MiniMax)
|
|
39
|
+
if "<think>" in r.text and not profile(maker).open_weights:
|
|
40
|
+
out.append(Finding(self.name, Status.FAIL, "Теги <think>",
|
|
41
|
+
f"В тексте ответа теги <think> — почерк открытых reasoning-моделей, не {maker}.",
|
|
42
|
+
critical=True, evidence={"text": r.text[:80]}))
|
|
43
|
+
|
|
44
|
+
# 2. префикс id (только если протокол родной для производителя)
|
|
45
|
+
prefixes = profile(maker).id_prefixes
|
|
46
|
+
native = profile(maker).native_protocol == target.protocol and prefixes
|
|
47
|
+
if native and r.id:
|
|
48
|
+
if r.id.startswith(prefixes):
|
|
49
|
+
out.append(Finding(self.name, Status.PASS, "Префикс id", f"id «{r.id[:12]}…» в родном формате."))
|
|
50
|
+
else:
|
|
51
|
+
out.append(Finding(self.name, Status.WARN, "Префикс id",
|
|
52
|
+
f"id «{r.id[:16]}» не похож на родной ({' / '.join(prefixes)})."))
|
|
53
|
+
elif native and not r.id:
|
|
54
|
+
out.append(Finding(self.name, Status.WARN, "Префикс id", "В ответе нет id."))
|
|
55
|
+
|
|
56
|
+
# 3. usage: чужая схема полей
|
|
57
|
+
u = r.usage
|
|
58
|
+
if not u:
|
|
59
|
+
out.append(Finding(self.name, Status.WARN, "Учёт токенов", "Поле usage пустое — нельзя проверить, за что списывают."))
|
|
60
|
+
else:
|
|
61
|
+
anth_style = "input_tokens" in u or "cache_creation_input_tokens" in u
|
|
62
|
+
oai_style = "prompt_tokens" in u
|
|
63
|
+
if target.protocol == "openai" and maker != "anthropic" and any("cache_creation" in k for k in u):
|
|
64
|
+
out.append(Finding(self.name, Status.FAIL, "Учёт токенов",
|
|
65
|
+
"В usage следы Anthropic (cache_creation_*), хотя модель не Claude: внутри другой бэкенд.",
|
|
66
|
+
critical=True))
|
|
67
|
+
elif target.protocol == "anthropic" and oai_style and not anth_style:
|
|
68
|
+
out.append(Finding(self.name, Status.WARN, "Учёт токенов",
|
|
69
|
+
"usage в формате OpenAI на Anthropic-протоколе: стоит переходник."))
|
|
70
|
+
else:
|
|
71
|
+
out.append(Finding(self.name, Status.PASS, "Учёт токенов", "Схема usage соответствует протоколу."))
|
|
72
|
+
|
|
73
|
+
# 4. system_fingerprint у OpenAI
|
|
74
|
+
if target.protocol == "openai" and maker == "openai":
|
|
75
|
+
fp = r.extra.get("system_fingerprint")
|
|
76
|
+
if fp and str(fp).startswith("fp_"):
|
|
77
|
+
out.append(Finding(self.name, Status.PASS, "system_fingerprint", f"Есть, формат OpenAI ({fp})."))
|
|
78
|
+
else:
|
|
79
|
+
out.append(Finding(self.name, Status.INFO, "system_fingerprint",
|
|
80
|
+
"Нет поля fp_…: у новых моделей OpenAI бывает, но настораживает в сумме."))
|
|
81
|
+
|
|
82
|
+
# 5. посредник в заголовках — факт, не обвинение
|
|
83
|
+
h = {k.lower(): v for k, v in r.headers.items()}
|
|
84
|
+
hops = [k for k in ("via", "x-oneapi-request-id", "x-new-api-version") if k in h]
|
|
85
|
+
if hops:
|
|
86
|
+
out.append(Finding(self.name, Status.INFO, "Посредник",
|
|
87
|
+
f"Ответ прошёл через прокси/перепродавца (заголовки: {', '.join(hops)}). "
|
|
88
|
+
"Это не доказательство подмены.", evidence={"headers": hops}))
|
|
89
|
+
return out
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Подпись размышлений Claude — криптографическая, подделать нельзя.
|
|
2
|
+
|
|
3
|
+
Как работает: просим модель «подумать» (extended thinking). Настоящий Claude
|
|
4
|
+
возвращает блок thinking с полем signature (~500–2000 символов), подписанным
|
|
5
|
+
серверами Anthropic. Затем отдаём этот блок обратно во втором ходе: настоящий
|
|
6
|
+
API примет подпись, а подделанную отклонит с ошибкой 400.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from ...core import rand
|
|
11
|
+
from ...core.check import Check, register
|
|
12
|
+
from ...core.types import Finding, Status
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@register
|
|
16
|
+
class ThinkingSignature(Check):
|
|
17
|
+
name = "thinking_signature"
|
|
18
|
+
title = "Подпись размышлений Claude"
|
|
19
|
+
protocols = ("anthropic",)
|
|
20
|
+
makers = ("anthropic",)
|
|
21
|
+
level = 1
|
|
22
|
+
|
|
23
|
+
def run(self, client, target, maker):
|
|
24
|
+
a, b = rand.number(12, 49), rand.number(12, 49)
|
|
25
|
+
msgs = [{"role": "user", "content": rand.cover(f"Сколько будет {a} * {b}? Ответь одним числом.")}]
|
|
26
|
+
r = client.chat(target.model, msgs, max_tokens=2000, thinking=1024)
|
|
27
|
+
if not r.ok:
|
|
28
|
+
return [Finding(self.name, Status.SKIP, self.title, f"Запрос с thinking не прошёл: {r.error}")]
|
|
29
|
+
|
|
30
|
+
signed = [b for b in r.thinking if b.get("type") == "thinking" and b.get("signature")]
|
|
31
|
+
redacted = [b for b in r.thinking if b.get("type") == "redacted_thinking"]
|
|
32
|
+
think_tokens = (r.usage.get("output_tokens_details") or {}).get("thinking_tokens")
|
|
33
|
+
|
|
34
|
+
if not r.thinking:
|
|
35
|
+
return [Finding(
|
|
36
|
+
self.name, Status.WARN, self.title,
|
|
37
|
+
"Режим размышлений запрошен, но блок thinking не вернулся"
|
|
38
|
+
+ (f" (thinking_tokens = {think_tokens})" if think_tokens is not None else "")
|
|
39
|
+
+ ". Посредник вырезает этот режим или за ним не Claude. Главный способ проверки недоступен.",
|
|
40
|
+
evidence={"thinking_tokens": think_tokens})]
|
|
41
|
+
|
|
42
|
+
if redacted and not signed:
|
|
43
|
+
return [Finding(self.name, Status.PASS, self.title,
|
|
44
|
+
"Пришёл зашифрованный блок redacted_thinking: такое отдаёт только Anthropic.")]
|
|
45
|
+
|
|
46
|
+
sig = signed[0]["signature"]
|
|
47
|
+
if len(sig) < 200:
|
|
48
|
+
return [Finding(self.name, Status.FAIL, self.title,
|
|
49
|
+
f"Подпись подозрительно короткая ({len(sig)} симв.), у настоящей 500–2000+.",
|
|
50
|
+
critical=True, evidence={"len": len(sig)})]
|
|
51
|
+
|
|
52
|
+
# второй ход: возвращаем подписанный блок — подделку API отклонит
|
|
53
|
+
follow = msgs + [{"role": "assistant", "content": r.raw["content"]},
|
|
54
|
+
{"role": "user", "content": f"А {a} * {b + 1}?"}]
|
|
55
|
+
r2 = client.chat(target.model, follow, max_tokens=2000, thinking=1024)
|
|
56
|
+
if r2.ok:
|
|
57
|
+
return [Finding(self.name, Status.PASS, self.title,
|
|
58
|
+
f"Подпись есть ({len(sig)} симв.) и принята сервером при повторной отправке.",
|
|
59
|
+
evidence={"len": len(sig)})]
|
|
60
|
+
low = r2.error.lower()
|
|
61
|
+
if "signature" in low or "thinking" in low or "cannot be modified" in low:
|
|
62
|
+
return [Finding(self.name, Status.FAIL, self.title,
|
|
63
|
+
f"Сервер отклонил собственную подпись: {r2.error[:160]}. Подпись поддельная.",
|
|
64
|
+
critical=True)]
|
|
65
|
+
return [Finding(self.name, Status.WARN, self.title,
|
|
66
|
+
f"Подпись есть ({len(sig)} симв.), но повторная отправка упала: {r2.error[:120]}")]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Отпечаток токенизатора: сколько input-токенов насчитали за один и тот же текст.
|
|
2
|
+
|
|
3
|
+
Каждое семейство моделей режет текст на токены по-своему. Системный промпт
|
|
4
|
+
может заставить модель назвать себя кем угодно, но токенизатор не изменит.
|
|
5
|
+
Шлём тексты разных алфавитов и сравниваем число токенов с эталонами, снятыми
|
|
6
|
+
с заведомо настоящих ключей (команда baseline).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from ...core import baselines
|
|
11
|
+
from ...core.check import Check, register
|
|
12
|
+
from ...core.types import Finding, Status
|
|
13
|
+
|
|
14
|
+
SAMPLES = {
|
|
15
|
+
"en": "The quick brown fox jumps over the lazy dog while the server logs every request.",
|
|
16
|
+
"ru": "Съешь же ещё этих мягких французских булок да выпей чаю, пока сервер пишет логи.",
|
|
17
|
+
"zh": "敏捷的棕色狐狸跳过了懒狗,服务器记录了每一个请求。",
|
|
18
|
+
"code": "def f(x: int) -> list[str]:\n return [str(i ** 2) for i in range(x) if i % 3 == 0]",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def measure(client, model, tries: int = 2) -> dict[str, int] | None:
|
|
23
|
+
"""Токены каждого текста = input_tokens(«x» + текст) − input_tokens(«x»).
|
|
24
|
+
|
|
25
|
+
Замер дважды: если разница «плавает» (кэш, скрытый промпт меняется) — данным
|
|
26
|
+
не доверяем. Проверка здравого смысла: токенов не больше, чем символов.
|
|
27
|
+
"""
|
|
28
|
+
def inp(text: str) -> int | None:
|
|
29
|
+
r = client.chat(model, [{"role": "user", "content": text}], max_tokens=1)
|
|
30
|
+
if not r.ok:
|
|
31
|
+
return None
|
|
32
|
+
u = r.usage
|
|
33
|
+
return u.get("input_tokens", u.get("prompt_tokens"))
|
|
34
|
+
|
|
35
|
+
out = {}
|
|
36
|
+
for k, t in SAMPLES.items():
|
|
37
|
+
vals = []
|
|
38
|
+
for _ in range(tries):
|
|
39
|
+
a, b = inp("x"), inp("x " + t)
|
|
40
|
+
if a is None or b is None:
|
|
41
|
+
return None
|
|
42
|
+
vals.append(b - a)
|
|
43
|
+
if max(vals) - min(vals) > 1 or not 0 < vals[0] <= len(t):
|
|
44
|
+
return None
|
|
45
|
+
out[k] = vals[0]
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def distance(a: dict, b: dict) -> float:
|
|
50
|
+
"""Средняя относительная разница по всем текстам (0 = совпадение)."""
|
|
51
|
+
keys = [k for k in SAMPLES if k in a and k in b and b[k]]
|
|
52
|
+
return sum(abs(a[k] - b[k]) / b[k] for k in keys) / max(len(keys), 1)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@register
|
|
56
|
+
class Tokenizer(Check):
|
|
57
|
+
name = "tokenizer"
|
|
58
|
+
title = "Отпечаток токенизатора"
|
|
59
|
+
level = 2
|
|
60
|
+
|
|
61
|
+
def run(self, client, target, maker):
|
|
62
|
+
got = measure(client, target.model)
|
|
63
|
+
if not got:
|
|
64
|
+
return [Finding(self.name, Status.SKIP, self.title,
|
|
65
|
+
"Счётчик входных токенов отсутствует или «плавает» между одинаковыми запросами — замер ненадёжен.")]
|
|
66
|
+
bases = baselines.load("tokens")
|
|
67
|
+
if not bases:
|
|
68
|
+
return [Finding(self.name, Status.INFO, self.title,
|
|
69
|
+
f"Замер: {got}. Эталонов нет — сними их командой «modelcheck baseline».",
|
|
70
|
+
evidence={"tokens": got})]
|
|
71
|
+
ranked = sorted(((distance(got, v["tokens"]), name, v) for name, v in bases.items()), key=lambda x: x[0])
|
|
72
|
+
best_d, best_name, best = ranked[0]
|
|
73
|
+
own_list = [(d, n, v) for d, n, v in ranked if v.get("maker") == maker]
|
|
74
|
+
ev = {"tokens": got, "closest": best_name, "distance": round(best_d, 3)}
|
|
75
|
+
if own_list and own_list[0][0] <= 0.05:
|
|
76
|
+
d, n, v = own_list[0]
|
|
77
|
+
return [Finding(self.name, Status.PASS, self.title,
|
|
78
|
+
f"Токенизатор совпадает с эталоном {n} (расхождение {d:.0%}){baselines.stale_note(v)}.", evidence=ev)]
|
|
79
|
+
own = own_list[0][0] if own_list else None
|
|
80
|
+
if best.get("maker") != maker and best_d <= 0.05 and (own is None or own > 0.15):
|
|
81
|
+
return [Finding(self.name, Status.FAIL, self.title,
|
|
82
|
+
f"Текст режется как у {best['maker']} ({best_name}), а не как у {maker}. "
|
|
83
|
+
f"Подменить токенизатор промптом нельзя{baselines.stale_note(best)}.", critical=True, evidence=ev)]
|
|
84
|
+
if not own_list:
|
|
85
|
+
return [Finding(self.name, Status.INFO, self.title,
|
|
86
|
+
f"Нет эталона для {maker}. Ближе всего: {best_name} ({best_d:.0%}).", evidence=ev)]
|
|
87
|
+
return [Finding(self.name, Status.WARN, self.title,
|
|
88
|
+
f"Ни один эталон не совпал точно (до своего {own:.0%}). Возможна другая версия модели"
|
|
89
|
+
f"{baselines.stale_note(own_list[0][2])}.", evidence=ev)]
|
modelcheck/cli.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Командная строка modelcheck.
|
|
2
|
+
|
|
3
|
+
run проверить ключ и модель
|
|
4
|
+
watch проверять по расписанию и писать историю (ловит подмену в часы пик)
|
|
5
|
+
baseline снять эталон с ЗАВЕДОМО настоящего ключа
|
|
6
|
+
list какие есть проверки
|
|
7
|
+
makers какие производители поддерживаются
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Optional
|
|
17
|
+
|
|
18
|
+
import typer
|
|
19
|
+
from rich.console import Console
|
|
20
|
+
from rich.table import Table
|
|
21
|
+
|
|
22
|
+
from . import __version__, checks # noqa: F401 (регистрирует все проверки)
|
|
23
|
+
from .core import baselines
|
|
24
|
+
from .core.check import REGISTRY
|
|
25
|
+
from .core.engine import detect_protocol, run as run_checks, run_many
|
|
26
|
+
from .core.types import Target, Verdict
|
|
27
|
+
from .makers import PROFILES, maker_of
|
|
28
|
+
from .report import render
|
|
29
|
+
|
|
30
|
+
app = typer.Typer(add_completion=False, no_args_is_help=True,
|
|
31
|
+
help="modelcheck — настоящая ли нейросеть за API-ключом.")
|
|
32
|
+
con = Console()
|
|
33
|
+
LEVELS = {"quick": 1, "standard": 2, "full": 3}
|
|
34
|
+
EXIT = {Verdict.GENUINE: 0, Verdict.SUSPICIOUS: 1, Verdict.FAKE: 2, Verdict.UNKNOWN: 3}
|
|
35
|
+
|
|
36
|
+
URL = typer.Argument(..., help="Адрес API, например https://api.example.com/v1")
|
|
37
|
+
MODEL = typer.Option(..., "--model", "-m", help="Заявленная модель, как у провайдера (anthropic/claude-opus-4.8)")
|
|
38
|
+
KEY = typer.Option(None, "--key", "-k", help="API-ключ. Лучше через переменную MODELCHECK_KEY")
|
|
39
|
+
PROTO = typer.Option(None, "--protocol", "-p", help="anthropic | openai. По умолчанию openai, кроме api.anthropic.com")
|
|
40
|
+
TIMEOUT = typer.Option(45.0, "--timeout", help="Таймаут одного запроса, сек")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _target(url, key, model, protocol) -> Target:
|
|
44
|
+
key = key or os.environ.get("MODELCHECK_KEY", "")
|
|
45
|
+
if not key:
|
|
46
|
+
raise typer.BadParameter("Нужен ключ: --key или переменная окружения MODELCHECK_KEY")
|
|
47
|
+
if protocol and protocol not in ("anthropic", "openai"):
|
|
48
|
+
raise typer.BadParameter("--protocol: anthropic или openai")
|
|
49
|
+
return Target(url, key, model, protocol or detect_protocol(model, url))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _version(v: bool):
|
|
53
|
+
if v:
|
|
54
|
+
con.print(f"modelcheck {__version__}")
|
|
55
|
+
raise typer.Exit()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@app.callback()
|
|
59
|
+
def main_cb(version: bool = typer.Option(False, "--version", "-V", callback=_version, is_eager=True,
|
|
60
|
+
help="Показать версию")):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@app.command()
|
|
65
|
+
def run(
|
|
66
|
+
url: str = URL, model: str = MODEL, key: Optional[str] = KEY, protocol: Optional[str] = PROTO,
|
|
67
|
+
level: str = typer.Option("standard", "--level", "-l", help="quick | standard | full"),
|
|
68
|
+
times: int = typer.Option(1, "--times", "-n", min=1, max=10, help="Сколько прогонов подряд (для пулов аккаунтов)"),
|
|
69
|
+
only: Optional[str] = typer.Option(None, "--only", help="Только эти проверки, через запятую (см. modelcheck list)"),
|
|
70
|
+
seed: Optional[int] = typer.Option(None, "--seed", help="Сид случайных формулировок (повторить прогон один в один)"),
|
|
71
|
+
timeout: float = TIMEOUT,
|
|
72
|
+
json_out: Optional[Path] = typer.Option(None, "--json", help="Сохранить отчёт в JSON"),
|
|
73
|
+
md_out: Optional[Path] = typer.Option(None, "--md", help="Сохранить отчёт в Markdown"),
|
|
74
|
+
quiet: bool = typer.Option(False, "--quiet", "-q", help="Без таблицы, только вердикт"),
|
|
75
|
+
):
|
|
76
|
+
"""Проверить ключ и модель. Код выхода: 0 настоящая, 1 подозрительно, 2 подмена, 3 нет данных."""
|
|
77
|
+
if level not in LEVELS:
|
|
78
|
+
raise typer.BadParameter("--level: quick, standard или full")
|
|
79
|
+
t = _target(url, key, model, protocol)
|
|
80
|
+
kw = dict(level=LEVELS[level], only=only.split(",") if only else None, timeout=timeout)
|
|
81
|
+
with con.status("Проверяю…") as st:
|
|
82
|
+
kw["on_step"] = lambda s: st.update(f"Проверяю: {s}")
|
|
83
|
+
rep = run_many(t, times, **kw) if times > 1 else run_checks(t, seed=seed, **kw)
|
|
84
|
+
render.to_console(rep, con, short=quiet)
|
|
85
|
+
if json_out:
|
|
86
|
+
json_out.write_text(render.to_json(rep), encoding="utf-8")
|
|
87
|
+
if md_out:
|
|
88
|
+
md_out.write_text(render.to_markdown(rep), encoding="utf-8")
|
|
89
|
+
raise typer.Exit(EXIT[rep.verdict])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@app.command()
|
|
93
|
+
def watch(
|
|
94
|
+
url: str = URL, model: str = MODEL, key: Optional[str] = KEY, protocol: Optional[str] = PROTO,
|
|
95
|
+
every: int = typer.Option(60, "--every", help="Интервал между проверками, минут"),
|
|
96
|
+
count: int = typer.Option(0, "--count", help="Сколько проверок сделать (0 — пока не остановишь Ctrl+C)"),
|
|
97
|
+
level: str = typer.Option("quick", "--level", "-l"),
|
|
98
|
+
log: Path = typer.Option(Path("modelcheck-history.jsonl"), "--log", help="Файл истории (по строке на проверку)"),
|
|
99
|
+
timeout: float = TIMEOUT,
|
|
100
|
+
):
|
|
101
|
+
"""Проверять по расписанию: подмену иногда включают только в часы пик."""
|
|
102
|
+
t = _target(url, key, model, protocol)
|
|
103
|
+
n = 0
|
|
104
|
+
con.print(f"Слежу за [cyan]{t.model}[/] каждые {every} мин → {log} (Ctrl+C — стоп)")
|
|
105
|
+
try:
|
|
106
|
+
while True:
|
|
107
|
+
rep = run_checks(t, LEVELS[level], timeout=timeout)
|
|
108
|
+
row = {"time": datetime.now().isoformat(timespec="seconds"), "model": t.model,
|
|
109
|
+
"verdict": rep.verdict.value, "service": rep.service.value, "score": rep.score,
|
|
110
|
+
"fails": [f.title for f in rep.findings if f.status.value == "fail"]}
|
|
111
|
+
with log.open("a", encoding="utf-8") as fh:
|
|
112
|
+
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
|
|
113
|
+
render.to_console(rep, con, short=True)
|
|
114
|
+
n += 1
|
|
115
|
+
if count and n >= count:
|
|
116
|
+
break
|
|
117
|
+
time.sleep(every * 60)
|
|
118
|
+
except KeyboardInterrupt:
|
|
119
|
+
pass
|
|
120
|
+
con.print(render.history_table(log))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@app.command()
|
|
124
|
+
def baseline(
|
|
125
|
+
url: str = URL, model: str = MODEL, key: Optional[str] = KEY, protocol: Optional[str] = PROTO,
|
|
126
|
+
full: bool = typer.Option(False, "--full", help="Ещё «случайное число» и «сорок вопросов» (~70 запросов)"),
|
|
127
|
+
name: Optional[str] = typer.Option(None, "--name", help="Имя эталона (по умолчанию — имя модели)"),
|
|
128
|
+
timeout: float = TIMEOUT,
|
|
129
|
+
):
|
|
130
|
+
"""Снять эталон с ЗАВЕДОМО НАСТОЯЩЕГО ключа (официальный API производителя)."""
|
|
131
|
+
from .checks.forty_questions.check import ask_all
|
|
132
|
+
from .checks.random_number.check import sample
|
|
133
|
+
from .checks.tokenizer.check import measure
|
|
134
|
+
from .core.client import make_client
|
|
135
|
+
t = _target(url, key, model, protocol)
|
|
136
|
+
cl = make_client(t.protocol, t.base_url, t.api_key, timeout=timeout)
|
|
137
|
+
entry: dict = {"maker": maker_of(t.model), "protocol": t.protocol, "source": t.base_url}
|
|
138
|
+
with con.status("Снимаю токенизатор…") as st:
|
|
139
|
+
tok = measure(cl, t.model)
|
|
140
|
+
if tok:
|
|
141
|
+
entry["tokens"] = tok
|
|
142
|
+
else:
|
|
143
|
+
con.print("[yellow]Счётчик токенов нестабилен — токенизатор пропущен.[/]")
|
|
144
|
+
if full:
|
|
145
|
+
st.update("Снимаю «случайное число»…")
|
|
146
|
+
entry["numbers"] = dict(sample(cl, t.model))
|
|
147
|
+
st.update("Снимаю «сорок вопросов»…")
|
|
148
|
+
entry["forty"] = {q: dict(c) for q, c in ask_all(cl, t.model).items()}
|
|
149
|
+
parts = [k for k in ("tokens", "numbers", "forty") if k in entry]
|
|
150
|
+
if not parts:
|
|
151
|
+
con.print("[red]Ничего снять не удалось.[/]")
|
|
152
|
+
raise typer.Exit(1)
|
|
153
|
+
f = baselines.save(name or t.model, entry)
|
|
154
|
+
con.print(f"[green]Эталон сохранён:[/] {f} ({', '.join(parts)})")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@app.command("baselines")
|
|
158
|
+
def list_baselines():
|
|
159
|
+
"""Какие эталоны сохранены и не устарели ли они."""
|
|
160
|
+
data = baselines.load()
|
|
161
|
+
if not data:
|
|
162
|
+
con.print(f"Эталонов нет. Папка: {baselines.base_dir()}")
|
|
163
|
+
return
|
|
164
|
+
tab = Table(box=None)
|
|
165
|
+
for c in ("Эталон", "Производитель", "Что есть", "Дата", "Состояние"):
|
|
166
|
+
tab.add_column(c)
|
|
167
|
+
for n, v in sorted(data.items()):
|
|
168
|
+
age = baselines.age_days(v)
|
|
169
|
+
state = "—" if age is None else ("[red]устарел[/]" if age > baselines.MAX_AGE_DAYS else f"{age} дн.")
|
|
170
|
+
tab.add_row(n, v.get("maker", "?"), ", ".join(k for k in ("tokens", "numbers", "forty") if k in v),
|
|
171
|
+
v.get("date", "?"), state)
|
|
172
|
+
con.print(tab)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@app.command("list")
|
|
176
|
+
def list_checks():
|
|
177
|
+
"""Какие есть проверки."""
|
|
178
|
+
names = {1: "quick", 2: "standard", 3: "full"}
|
|
179
|
+
tab = Table(box=None)
|
|
180
|
+
for c in ("Проверка", "Уровень", "Описание", "Для кого"):
|
|
181
|
+
tab.add_column(c)
|
|
182
|
+
for cls in REGISTRY:
|
|
183
|
+
tab.add_row(f"[cyan]{cls.name}[/]", names[cls.level], cls.title,
|
|
184
|
+
"/".join(cls.protocols) + (" · " + ",".join(cls.makers) if cls.makers else " · все"))
|
|
185
|
+
con.print(tab)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@app.command("makers")
|
|
189
|
+
def list_makers():
|
|
190
|
+
"""Какие производители поддерживаются и что у кого можно проверить."""
|
|
191
|
+
tab = Table(box=None)
|
|
192
|
+
for c in ("Производитель", "Подпись размышлений", "Поле размышлений", "Стоп-токен", "Открытые веса"):
|
|
193
|
+
tab.add_column(c)
|
|
194
|
+
sig = {"anthropic_thinking": "★★★ thinking", "openai_encrypted": "★★ encrypted", "xai_encrypted": "★★ encrypted",
|
|
195
|
+
"gemini_thought": "★★ thoughtSignature"}
|
|
196
|
+
for p in sorted(PROFILES.values(), key=lambda p: (p.signature is None, p.name)):
|
|
197
|
+
tab.add_row(p.title, sig.get(p.signature, "—"), p.reasoning_field or "—",
|
|
198
|
+
p.special_tokens[0] if p.special_tokens else "—", "да" if p.open_weights else "")
|
|
199
|
+
con.print(tab)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def main():
|
|
203
|
+
app()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
if __name__ == "__main__":
|
|
207
|
+
main()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Эталоны: снятые с ЗАВЕДОМО настоящего ключа отпечатки модели.
|
|
2
|
+
|
|
3
|
+
Хранятся в ~/.modelcheck/baselines/<имя>.json (папку можно сменить переменной
|
|
4
|
+
MODELCHECK_HOME). У каждого эталона есть дата: модели обновляются, токенизатор и
|
|
5
|
+
привычки меняются, поэтому эталон старше MAX_AGE_DAYS помечается как устаревший.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from datetime import date, datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
MAX_AGE_DAYS = 90
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def home() -> Path:
|
|
18
|
+
return Path(os.environ.get("MODELCHECK_HOME", Path.home() / ".modelcheck"))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def base_dir() -> Path:
|
|
22
|
+
return home() / "baselines"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def load(kind: str | None = None) -> dict[str, dict]:
|
|
26
|
+
"""Все эталоны; kind — оставить только те, где есть этот раздел (tokens / numbers / forty)."""
|
|
27
|
+
out: dict[str, dict] = {}
|
|
28
|
+
d = base_dir()
|
|
29
|
+
if d.exists():
|
|
30
|
+
for p in sorted(d.glob("*.json")):
|
|
31
|
+
try:
|
|
32
|
+
out.update(json.loads(p.read_text(encoding="utf-8")))
|
|
33
|
+
except (ValueError, OSError):
|
|
34
|
+
continue
|
|
35
|
+
return {k: v for k, v in out.items() if not kind or v.get(kind)}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def save(name: str, entry: dict) -> Path:
|
|
39
|
+
d = base_dir()
|
|
40
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
entry = {**entry, "date": date.today().isoformat()}
|
|
42
|
+
f = d / f"{name.replace('/', '_')}.json"
|
|
43
|
+
f.write_text(json.dumps({name: entry}, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
44
|
+
return f
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def age_days(entry: dict) -> int | None:
|
|
48
|
+
try:
|
|
49
|
+
return (date.today() - datetime.fromisoformat(entry["date"]).date()).days
|
|
50
|
+
except (KeyError, ValueError):
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def stale_note(entry: dict) -> str:
|
|
55
|
+
a = age_days(entry)
|
|
56
|
+
if a is None:
|
|
57
|
+
return " (дата эталона неизвестна)"
|
|
58
|
+
if a > MAX_AGE_DAYS:
|
|
59
|
+
return f" (эталон устарел: {a} дн., модель могла обновиться — сними заново)"
|
|
60
|
+
return ""
|