# python3 -m unittest discover -s tests -v (depuis mon-space-hf/) # # Teste l'orchestration des modes avec un FAUX modèle « à script » : il ne calcule rien, il # suit une politique (question -> texte à produire). Cela vérifie la détection des balises, # l'annulation des appels inutiles (retour arrière du cache KV), l'injection des résultats, # le raisonnement forcé à se fermer et les limites de contexte, sans télécharger de poids. import os import sys import unittest from types import SimpleNamespace import torch sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import modes as M import tools as T V = 2048 EOS = 3 class CharTok: """Tokenizer à un token par caractère (mêmes méthodes que FrenchTokenizerWrapper).""" eot_token = EOS bos_token = None vocab_size = V def __init__(self): self.c2i, self.i2c = {}, {} def _id(self, ch): if ch not in self.c2i: i = 4 + len(self.c2i) assert i < V self.c2i[ch], self.i2c[i] = i, ch return self.c2i[ch] def encode(self, text): return [self._id(c) for c in text] def decode(self, ids): return "".join(self.i2c.get(i, "") for i in ids) class ScriptedModel: """policy(question, emitted) -> texte complet voulu après le dernier repère ; alt(question) -> texte à produire si le premier token voulu est interdit.""" def __init__(self, tok, policy, alt=None, max_seq_len=1024): self.tok, self.policy, self.alt = tok, policy, alt self.args = SimpleNamespace(n_layers=2, max_seq_len=max_seq_len, vocab_size=V) self.feeds = [] # historique des (start_pos, nb tokens) : vérifie la cohérence du cache def eval(self): return self def parameters(self): return iter([torch.zeros(1)]) def forward(self, tokens, kv_caches=None, start_pos=0): ids = tokens[0].tolist() past = kv_caches[0][0] s0 = 0 if past is None else past.shape[2] assert s0 == start_pos, f"cache incohérent : {s0} tokens en cache, start_pos={start_pos}" self.feeds.append((start_pos, len(ids))) col = torch.tensor(ids, dtype=torch.float).view(1, 1, -1, 1) new = [] for k, v in kv_caches: nk = col if k is None else torch.cat([k, col], dim=2) new.append((nk, nk)) ctx = [int(x) for x in new[0][0][0, 0, :, 0].tolist()] text = self.tok.decode(ctx) marks = [(text.rfind(m), m) for m in (T.ASSISTANT_TAG + "\n", T.TOOL_RES_CLOSE + "\n")] at, m = max(marks) question = text.rsplit(T.USER_TAG + "\n", 1)[-1].split("\n" + T.ASSISTANT_TAG)[0] emitted = text[at + len(m):] after_result = m.startswith(T.TOOL_RES_CLOSE) ctx_for_policy = text[text.rfind(T.ASSISTANT_TAG):] if after_result else "" want = self.policy(question, emitted, ctx_for_policy) logits = torch.zeros(1, ids and len(ids), V) logits = torch.full((1, len(ids), V), -5.0) i = len(emitted) nxt = want[i] if want.startswith(emitted) and i < len(want) else None top = EOS if nxt is None else self.tok._id(nxt) logits[0, -1, top] = 10.0 if i == 0 and self.alt: logits[0, -1, self.tok._id(self.alt(question)[0])] = 5.0 return logits, new def run(model, tok, question, mode="agent", toolbox=None, cfg=None, prompt=None): cfg = cfg or M.GenConfig(temperature=0.0, repetition_penalty=1.0, top_k=0, top_p=1.0, max_new=200) prompt = prompt or f"{T.USER_TAG}\n{question}\n{T.ASSISTANT_TAG}\n" events = list(M.generate(mode, model, tok, prompt, cfg, toolbox=toolbox, user_text=question)) text = "".join(v for k, v in events if k == "token" or k == "text") notes = [v for k, v in events if k == "note"] stats = [v for k, v in events if k == "stats"][0] return text, notes, stats def calc_call(expr): return T.TOOL_CALL_OPEN + T.tjson({"name": "calculator", "arguments": {"expression": expr}}) + T.TOOL_CALL_CLOSE class AgentTests(unittest.TestCase): def setUp(self): self.tok = CharTok() def toolbox(self, **kw): return T.ToolBox(enabled=kw.get("enabled", {"calculator", "web_search", "rag_search"}), docs=kw.get("docs", []), web_search_fn=kw.get("web", lambda q: {"results": [{"title": "Météo Lyon", "snippet": "21 °C, ensoleillé", "url": "https://meteo.example/lyon"}]})) def test_calculator_round_trip(self): def policy(q, emitted, ctx): if "<|/tool_result|>" in ctx: return "12 × 7 = 84." return calc_call("12*7") model = ScriptedModel(self.tok, policy) text, notes, stats = run(model, self.tok, "Combien font 12 × 7 ?", toolbox=self.toolbox()) self.assertEqual(text, calc_call("12*7") + '\n<|tool_result|>{"result":84}<|/tool_result|>\n12 × 7 = 84.') self.assertEqual(notes, []) self.assertEqual([t["name"] for t in stats["tools"]], ["calculator"]) self.assertTrue(stats["tools"][0]["ok"]) # le cache n'a jamais été désynchronisé et le résultat a été avalé en un seul bloc self.assertEqual(model.feeds[0][0], 0) def test_useless_call_is_cancelled_and_model_answers_directly(self): # « Raconte-moi une histoire » : le faux modèle (mal entraîné) appelle la calculatrice. def policy(q, emitted, ctx): return calc_call("2+2") model = ScriptedModel(self.tok, policy, alt=lambda q: "Il était une fois…") # Après le veto, le premier caractère « < » est interdit : le modèle prend son 2e choix. # On fait suivre ce 2e choix d'une vraie réponse en changeant de politique selon l'émis. def policy2(q, emitted, ctx): if emitted.startswith("I"): return "Il était une fois…" return calc_call("2+2") model.policy = policy2 text, notes, stats = run(model, self.tok, "Raconte-moi une histoire", toolbox=self.toolbox()) self.assertEqual(text, "Il était une fois…") self.assertNotIn("tool_call", text) self.assertEqual(stats["vetoes"], 1) self.assertEqual(stats["tools"], []) self.assertEqual(len(notes), 1) self.assertIn("calculatrice", notes[0]["text"].lower()) # le cache a été ramené en arrière : après le prompt, on repart de sa longueur prompt_len = len(f"{T.USER_TAG}\nRaconte-moi une histoire\n{T.ASSISTANT_TAG}\n") self.assertTrue(any(sp == prompt_len for sp, n in model.feeds[1:])) def test_tool_disabled_gives_error_result(self): def policy(q, emitted, ctx): if "<|/tool_result|>" in ctx: return "La calculatrice est indisponible." return calc_call("12*7") model = ScriptedModel(self.tok, policy) tb = self.toolbox(enabled={"web_search"}) text, notes, stats = run(model, self.tok, "Combien font 12 × 7 ?", toolbox=tb) self.assertIn('<|tool_result|>{"error":"outil indisponible"}<|/tool_result|>', text) self.assertEqual(stats["tools"][0]["ok"], False) def test_web_search_with_related_query(self): call = T.TOOL_CALL_OPEN + T.tjson({"name": "web_search", "arguments": {"query": "météo Lyon"}}) + T.TOOL_CALL_CLOSE def policy(q, emitted, ctx): if "<|/tool_result|>" in ctx: return "À Lyon : 21 °C, ensoleillé." return call model = ScriptedModel(self.tok, policy) text, notes, stats = run(model, self.tok, "Quel temps fait-il à Lyon ?", toolbox=self.toolbox()) self.assertIn("meteo.example/lyon", text) self.assertTrue(text.endswith("À Lyon : 21 °C, ensoleillé.")) self.assertEqual(stats["vetoes"], 0) def test_malformed_call_receives_error(self): def policy(q, emitted, ctx): if "<|/tool_result|>" in ctx: return "Désolé." return T.TOOL_CALL_OPEN + "{pas du json" + T.TOOL_CALL_CLOSE model = ScriptedModel(self.tok, policy) text, notes, stats = run(model, self.tok, "Combien font 1 + 1 ?", toolbox=self.toolbox()) self.assertIn('{"error":"appel invalide"}', text) def test_call_limit(self): # Le modèle boucle : il rappelle sans cesse. Il doit être arrêté à MAX_TOOL_CALLS. def policy(q, emitted, ctx): n = ctx.count("<|/tool_result|>") return calc_call(f"{n}+1") model = ScriptedModel(self.tok, policy, alt=lambda q: "Stop") def policy2(q, emitted, ctx): if emitted.startswith("S"): return "Stop" return policy(q, emitted, ctx) model.policy = policy2 text, notes, stats = run(model, self.tok, "Calcule 1 + 1 puis encore et encore", toolbox=self.toolbox()) self.assertEqual(len(stats["tools"]), T.MAX_TOOL_CALLS) self.assertTrue(text.endswith("Stop")) def test_result_is_shrunk_to_fit_the_context(self): big = {"results": [{"title": "t", "snippet": "x" * 280, "url": "https://a.fr"} for _ in range(8)]} call = T.TOOL_CALL_OPEN + T.tjson({"name": "web_search", "arguments": {"query": "météo Lyon"}}) + T.TOOL_CALL_CLOSE def policy(q, emitted, ctx): return "Voilà." if "<|/tool_result|>" in ctx else call model = ScriptedModel(self.tok, policy, max_seq_len=520) tb = self.toolbox(web=lambda q: {"results": [dict(r) for r in big["results"]]}) text, notes, stats = run(model, self.tok, "Quel temps fait-il à Lyon ?", toolbox=tb) self.assertTrue(text.endswith("Voilà.")) self.assertLessEqual(len(model.tok.encode(text)) + 40, 520) class ReasoningTests(unittest.TestCase): def setUp(self): self.tok = CharTok() def test_natural_reasoning(self): def policy(q, emitted, ctx): return "\n24 / 3 = 8, puis 8 + 5 = 13\n\nIl lui reste 13 billes." text, _, stats = run(ScriptedModel(self.tok, policy), self.tok, "Problème de billes", mode="reasoning") self.assertTrue(text.startswith("")) self.assertTrue(text.endswith("13 billes.")) self.assertFalse(stats["forced_close"]) def test_runaway_reasoning_is_closed_and_answered(self): def policy(q, emitted, ctx): if "" in emitted: return emitted[:emitted.index("") + len("\n")] + "Réponse : 42." return "\n" + "je réfléchis " * 400 cfg = M.GenConfig(temperature=0.0, repetition_penalty=1.0, top_k=0, top_p=1.0, max_new=60, reasoning_budget=80) text, _, stats = run(ScriptedModel(self.tok, policy), self.tok, "Question difficile", mode="reasoning", cfg=cfg) self.assertTrue(stats["forced_close"]) self.assertIn("\n\n", text) self.assertTrue(text.endswith("Réponse : 42.")) class ChatTests(unittest.TestCase): def test_chat_stops_at_next_turn_tags(self): tok = CharTok() def policy(q, emitted, ctx): return "Bonjour !" + T.USER_TAG + "\nautre chose" text, _, _ = run(ScriptedModel(tok, policy), tok, "Salut", mode="chat") self.assertEqual(text, "Bonjour !") def test_budget_is_respected(self): tok = CharTok() cfg = M.GenConfig(temperature=0.0, repetition_penalty=1.0, top_k=0, top_p=1.0, max_new=10) text, _, stats = run(ScriptedModel(tok, lambda q, e, c: "a" * 500), tok, "Salut", mode="chat", cfg=cfg) self.assertEqual(len(text), 10) self.assertTrue(stats["truncated"]) if __name__ == "__main__": unittest.main()