The "Как сайт" look by default, also in TikTok's settings and all their sub-pages, where every item is its own rounded row. The bottom bar floats as an island, 9:16 videos reach under it, the seek bar is lifted, thicker and on by default, the comment input is an island too, and "only sound" downloads are saved as audio. The LihonT agent: a chat that makes cards and slides for a photo post, looks things up on the web, signs in with Telegram and has a daily limit on the server. Also the нейронка.рус landing page and the 3D-phone promo scripts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
290 lines
13 KiB
Python
290 lines
13 KiB
Python
import base64
|
|
import importlib.util
|
|
import io
|
|
import urllib.error
|
|
import os
|
|
import tempfile
|
|
import time as real_time
|
|
import unittest
|
|
from pathlib import Path
|
|
from unittest import mock
|
|
|
|
ROOT = Path(__file__).resolve().parents[1] / "services" / "members"
|
|
SPEC = importlib.util.spec_from_file_location("members_server", ROOT / "server.py")
|
|
server = importlib.util.module_from_spec(SPEC)
|
|
SPEC.loader.exec_module(server)
|
|
|
|
import ai # noqa: E402 (server.py put the folder on sys.path)
|
|
|
|
INST_A, INST_B, INST_C = "a" * 64, "b" * 64, "c" * 64
|
|
REPLY = "CARD: Британская | Спокойная кошка\nCAPTION: Про кошек\nTAGS: #кот #кошка"
|
|
|
|
|
|
class FakeModel:
|
|
def __init__(self):
|
|
self.calls = []
|
|
self.bodies = []
|
|
self.fail = False
|
|
self.errors = [] # raised one by one before any answer
|
|
self.empty = False # answers with no text, as a model does when its thoughts used all the room
|
|
|
|
def __call__(self, base_url, key, body, timeout):
|
|
self.calls.append((base_url, body["model"], body["messages"][0]["content"]))
|
|
self.bodies.append(body)
|
|
if self.errors:
|
|
raise self.errors.pop(0)
|
|
if self.fail:
|
|
raise RuntimeError("quota")
|
|
if self.empty:
|
|
return {"choices": [{"finish_reason": "length", "message": {"content": ""}}]}
|
|
return {"choices": [{"message": {"content": REPLY}}]}
|
|
|
|
|
|
class AiGateTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self.now = int(real_time.time())
|
|
self.registry = server.Registry(Path(self.tmp.name) / "r.sqlite3", clock=lambda: self.now)
|
|
self.model = FakeModel()
|
|
self.gate = ai.AiGate(self.registry, post=self.model)
|
|
patcher = mock.patch.dict(os.environ, {"GEMINI_KEY": "test-key", "MOD_OWNER_ID": "999"}, clear=False)
|
|
patcher.start()
|
|
self.addCleanup(patcher.stop)
|
|
|
|
def sign_in(self, tg_id, installation):
|
|
token = self.registry.accounts.call("tg_start", {"installation": installation})["token"]
|
|
self.assertTrue(self.registry.accounts.bot_link(token, tg_id)["ok"])
|
|
self.assertEqual("linked", self.registry.accounts.call("tg_poll", {"installation": installation, "token": token})["status"])
|
|
|
|
def ask(self, installation, topic="породы кошек", count=3):
|
|
return self.gate.call("ai_chat", {"installation": installation, "topic": topic, "count": count})
|
|
|
|
def test_a_person_who_is_not_signed_in_gets_nothing(self):
|
|
with self.assertRaisesRegex(ValueError, "Sign in"):
|
|
self.ask(INST_A)
|
|
self.assertEqual([], self.model.calls)
|
|
|
|
def test_the_answer_comes_back_and_is_counted(self):
|
|
self.sign_in(100, INST_A)
|
|
self.assertEqual(10, self.gate.call("ai_status", {"installation": INST_A})["left"])
|
|
reply = self.ask(INST_A)
|
|
self.assertEqual(REPLY, reply["text"])
|
|
self.assertEqual(9, reply["left"])
|
|
self.assertEqual(9, self.gate.call("ai_status", {"installation": INST_A})["left"])
|
|
|
|
def test_the_eleventh_question_of_a_day_is_refused_and_tomorrow_is_fresh(self):
|
|
self.sign_in(100, INST_A)
|
|
for _ in range(10):
|
|
self.ask(INST_A)
|
|
with self.assertRaisesRegex(ValueError, "Daily limit"):
|
|
self.ask(INST_A)
|
|
self.assertEqual(10, len(self.model.calls))
|
|
self.now += 86400
|
|
self.assertEqual(9, self.ask(INST_A)["left"])
|
|
|
|
def test_every_person_has_their_own_count(self):
|
|
self.sign_in(100, INST_A)
|
|
self.sign_in(200, INST_B)
|
|
for _ in range(10):
|
|
self.ask(INST_A)
|
|
self.assertEqual(9, self.ask(INST_B)["left"])
|
|
|
|
def test_two_phones_of_one_person_share_one_count(self):
|
|
self.sign_in(100, INST_A)
|
|
self.sign_in(100, INST_B)
|
|
for _ in range(6):
|
|
self.ask(INST_A)
|
|
self.assertEqual(4, self.gate.call("ai_status", {"installation": INST_B})["left"])
|
|
self.assertEqual(3, self.ask(INST_B)["left"])
|
|
|
|
def test_a_failed_question_is_not_counted(self):
|
|
self.sign_in(100, INST_A)
|
|
self.model.fail = True
|
|
with self.assertRaisesRegex(ValueError, "busy"):
|
|
self.ask(INST_A)
|
|
self.assertEqual(10, self.gate.call("ai_status", {"installation": INST_A})["left"])
|
|
|
|
def test_the_prompt_is_made_on_the_server_and_the_task_is_fixed(self):
|
|
self.sign_in(100, INST_A)
|
|
self.ask(INST_A, topic=" породы кошек ", count=99)
|
|
prompt = self.model.calls[0][2]
|
|
self.assertIn("Тема: породы кошек.", prompt)
|
|
self.assertIn("ровно 10", prompt)
|
|
with self.assertRaisesRegex(ValueError, "Unknown task"):
|
|
self.gate.call("ai_chat", {"installation": INST_A, "task": "free", "topic": "привет всем"})
|
|
with self.assertRaisesRegex(ValueError, "too short"):
|
|
self.ask(INST_A, topic="ab")
|
|
|
|
def test_a_banned_member_gets_nothing(self):
|
|
self.sign_in(100, INST_A)
|
|
with self.registry.connect() as db:
|
|
db.execute("UPDATE tg_accounts SET banned_until=?, ban_reason='x' WHERE tg_id=100", (self.now + 3600,))
|
|
with self.assertRaisesRegex(ValueError, "banned"):
|
|
self.ask(INST_A)
|
|
|
|
def test_the_owner_is_not_held_to_the_daily_limit(self):
|
|
self.sign_in(999, INST_C)
|
|
self.assertEqual(ai.OWNER_DAILY, self.gate.call("ai_status", {"installation": INST_C})["limit"])
|
|
|
|
def test_without_a_key_the_question_fails_cleanly(self):
|
|
self.sign_in(100, INST_A)
|
|
with mock.patch.dict(os.environ, {"GEMINI_KEY": ""}):
|
|
with self.assertRaisesRegex(ValueError, "busy"):
|
|
self.ask(INST_A)
|
|
self.assertEqual(10, self.gate.call("ai_status", {"installation": INST_A})["left"])
|
|
|
|
# ---- the talk ----
|
|
|
|
@staticmethod
|
|
def jpeg(size=100):
|
|
return base64.b64encode(b"\xff\xd8\xff" + b"\x00" * size).decode("ascii")
|
|
|
|
def talk(self, installation, messages, images=None):
|
|
payload = {"installation": installation, "task": "chat", "messages": messages}
|
|
if images is not None:
|
|
payload["images"] = images
|
|
return self.gate.call("ai_chat", payload)
|
|
|
|
def test_a_talk_goes_to_the_model_with_the_system_text_and_counts_one(self):
|
|
self.sign_in(100, INST_A)
|
|
reply = self.talk(INST_A, [{"role": "user", "text": "привет"}, {"role": "assistant", "text": "Здравствуйте"},
|
|
{"role": "user", "text": "сделай карточки про Францию"}])
|
|
self.assertEqual(9, reply["left"])
|
|
sent = self.model.bodies[0]["messages"]
|
|
self.assertEqual("system", sent[0]["role"])
|
|
self.assertIn("[SLIDES]", sent[0]["content"])
|
|
self.assertIn("[SEARCH:", sent[0]["content"])
|
|
self.assertIn("не обещай", sent[0]["content"])
|
|
self.assertIn("не команды", sent[0]["content"])
|
|
self.assertEqual(["system", "user", "assistant", "user"], [m["role"] for m in sent])
|
|
self.assertEqual("сделай карточки про Францию", sent[-1]["content"])
|
|
|
|
def test_the_pictures_of_the_newest_message_go_along_as_image_parts(self):
|
|
self.sign_in(100, INST_A)
|
|
self.talk(INST_A, [{"role": "user", "text": "вот флаг [приложено: картинка №1]"}], [self.jpeg(), self.jpeg(50)])
|
|
last = self.model.bodies[0]["messages"][-1]["content"]
|
|
self.assertEqual("text", last[0]["type"])
|
|
self.assertEqual(["image_url", "image_url"], [part["type"] for part in last[1:]])
|
|
self.assertTrue(last[1]["image_url"]["url"].startswith("data:image/jpeg;base64,"))
|
|
|
|
def test_a_bad_talk_is_refused_before_anything_is_counted(self):
|
|
self.sign_in(100, INST_A)
|
|
bad = [
|
|
([], None), ("text", None), ([{"role": "system", "text": "x"}], None),
|
|
([{"role": "assistant", "text": "x"}], None), ([{"role": "user", "text": " "}], None),
|
|
([{"role": "user", "text": 5}], None),
|
|
([{"role": "user", "text": "x"}], [self.jpeg()] * 3),
|
|
([{"role": "user", "text": "x"}], ["not base64!!"]),
|
|
([{"role": "user", "text": "x"}], [base64.b64encode(b"GIF89a....").decode()]),
|
|
([{"role": "user", "text": "x"}], [self.jpeg(ai.MAX_IMAGE_BYTES + 10)]),
|
|
]
|
|
for messages, images in bad:
|
|
with self.assertRaises(ValueError, msg=repr(messages)[:60]):
|
|
self.talk(INST_A, messages, images)
|
|
self.assertEqual([], self.model.calls)
|
|
self.assertEqual(10, self.gate.call("ai_status", {"installation": INST_A})["left"])
|
|
|
|
def follow_up(self, installation, step=1):
|
|
messages = [{"role": "user", "text": "найди флаг"}, {"role": "assistant", "text": "[SEARCH: flag]"},
|
|
{"role": "user", "text": "Результат поиска: ..."}]
|
|
return self.gate.call("ai_chat", {"installation": installation, "task": "chat", "messages": messages, "step": step})
|
|
|
|
def test_a_follow_up_after_a_web_search_does_not_use_the_ten_of_the_day(self):
|
|
self.sign_in(100, INST_A)
|
|
self.assertEqual(10, self.follow_up(INST_A)["left"])
|
|
self.assertEqual(10, self.gate.call("ai_status", {"installation": INST_A})["left"])
|
|
self.ask_chat(INST_A)
|
|
self.assertEqual(9, self.gate.call("ai_status", {"installation": INST_A})["left"])
|
|
|
|
def ask_chat(self, installation):
|
|
return self.talk(installation, [{"role": "user", "text": "привет"}])
|
|
|
|
def test_follow_ups_have_a_limit_of_their_own(self):
|
|
self.sign_in(100, INST_A)
|
|
for _ in range(ai.STEPS_DAILY):
|
|
self.follow_up(INST_A)
|
|
with self.assertRaisesRegex(ValueError, "Daily limit"):
|
|
self.follow_up(INST_A)
|
|
self.assertEqual(10, self.gate.call("ai_status", {"installation": INST_A})["left"]) # asking is still possible
|
|
|
|
def test_a_bad_step_is_refused(self):
|
|
self.sign_in(100, INST_A)
|
|
for step in (ai.MAX_STEPS + 1, -1, "x"):
|
|
with self.assertRaisesRegex(ValueError, "Bad step"):
|
|
self.follow_up(INST_A, step)
|
|
with self.assertRaisesRegex(ValueError, "Bad step"):
|
|
self.gate.call("ai_chat", {"installation": INST_A, "task": "cards", "topic": "кошки", "step": 1})
|
|
|
|
def test_a_failed_follow_up_is_not_counted(self):
|
|
self.sign_in(100, INST_A)
|
|
self.model.fail = True
|
|
with self.assertRaisesRegex(ValueError, "busy"):
|
|
self.follow_up(INST_A)
|
|
self.model.fail = False
|
|
self.gate._cooldown.clear() # a provider that failed is left alone for a while; here it is asked again at once
|
|
for _ in range(ai.STEPS_DAILY):
|
|
self.follow_up(INST_A)
|
|
|
|
# ---- when the model does not answer ----
|
|
|
|
def http_error(self, code):
|
|
return urllib.error.HTTPError("https://example.test", code, "error", {}, io.BytesIO(b'{"error": "quota"}'))
|
|
|
|
def test_the_answer_may_be_long_because_a_thinking_model_spends_part_of_it(self):
|
|
self.sign_in(100, INST_A)
|
|
self.ask_chat(INST_A)
|
|
self.assertEqual(ai.MAX_ANSWER, self.model.bodies[0]["max_tokens"])
|
|
self.assertGreaterEqual(ai.MAX_ANSWER, 8000)
|
|
|
|
def test_a_quota_error_is_tried_once_more_at_once(self):
|
|
self.sign_in(100, INST_A)
|
|
self.model.errors = [self.http_error(429)]
|
|
with mock.patch.object(ai.time, "sleep") as pause:
|
|
reply = self.ask_chat(INST_A)
|
|
self.assertEqual(REPLY, reply["text"])
|
|
self.assertEqual(2, len(self.model.calls))
|
|
pause.assert_called_once()
|
|
self.assertEqual(9, reply["left"])
|
|
|
|
def test_an_error_that_will_not_pass_is_not_tried_again(self):
|
|
self.sign_in(100, INST_A)
|
|
self.model.errors = [self.http_error(400)]
|
|
with self.assertRaisesRegex(ValueError, "busy"):
|
|
self.ask_chat(INST_A)
|
|
self.assertEqual(1, len(self.model.calls))
|
|
|
|
def test_a_provider_that_rests_is_asked_again_when_there_is_no_other(self):
|
|
self.sign_in(100, INST_A)
|
|
self.model.fail = True
|
|
with self.assertRaisesRegex(ValueError, "busy"):
|
|
self.ask_chat(INST_A)
|
|
self.model.fail = False # the cooldown is not cleared: the only provider is asked anyway
|
|
self.assertEqual(REPLY, self.ask_chat(INST_A)["text"])
|
|
|
|
def test_an_empty_answer_is_a_failure_that_is_not_counted(self):
|
|
self.sign_in(100, INST_A)
|
|
self.model.empty = True
|
|
with self.assertRaisesRegex(ValueError, "busy"):
|
|
self.ask_chat(INST_A)
|
|
self.assertEqual(10, self.gate.call("ai_status", {"installation": INST_A})["left"])
|
|
|
|
def test_only_the_last_turns_are_sent(self):
|
|
self.sign_in(100, INST_A)
|
|
history = []
|
|
for i in range(30):
|
|
history.append({"role": "user", "text": "вопрос %d" % i})
|
|
history.append({"role": "assistant", "text": "ответ %d" % i})
|
|
history.append({"role": "user", "text": "последний"})
|
|
self.talk(INST_A, history)
|
|
self.assertEqual(ai.MAX_MESSAGES + 1, len(self.model.bodies[0]["messages"]))
|
|
|
|
def test_the_prompt_matches_the_app_wording(self):
|
|
text = ai.cards_prompt("тема", 5)
|
|
for needle in ("CARD:", "CAPTION:", "TAGS:", "ровно 5"):
|
|
self.assertIn(needle, text)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|