"""L'essai des brouillons sur l'instance de test (après preparer.py et preparer_ia.py) : une conversation par mail de instance-de-test/mails/, « Générer une réponse » sur chacune, un rapport dans cases/ (hors de git) à faire juger. Vérifie que Mailpit ne reçoit rien pendant la génération : un brouillon ne doit jamais partir. python -I instance-de-test/essayer_brouillons.py [mot de passe System] """ import datetime import html import http.cookiejar import json import re import sys import time import urllib.error import urllib.request from pathlib import Path B = "http://127.0.0.1:9100" MAILPIT = "http://127.0.0.1:9125/api/v1/messages" ICI = Path(__file__).resolve().parent MAILS = ICI / "mails" ESSAIS = ["4g", "cible-perdue", "fuseau", "hors-base", "suite"] # « suite » : après l'échange « histoire » jar = http.cookiejar.CookieJar() op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar)) def req(m, p, body=None, timeout=60): r = urllib.request.Request(B + p, method=m, data=json.dumps(body).encode() if body is not None else None, headers={"Content-Type": "application/json", "X-CSRFTOKEN": "t0k3n"}) try: with op.open(r, timeout=timeout) as x: return json.loads(x.read() or b"{}").get("data") except urllib.error.HTTPError as e: with e: sys.exit(f"{m} {p} : {e.code} {e.read().decode(errors='replace')[:300]}") def connexion(mot_de_passe: str) -> None: req("POST", "/api/v1/auth/login", {"email": "System", "password": mot_de_passe}) for c in jar: c.secure = False jar.set_cookie(http.cookiejar.Cookie(0, "csrf_token", "t0k3n", None, False, "127.0.0.1", False, False, "/", True, False, None, False, None, None, {})) def total_mailpit() -> int: with urllib.request.urlopen(MAILPIT, timeout=10) as r: return json.loads(r.read())["total"] def en_html(texte: str) -> str: return "".join(f"

{html.escape(p).replace(chr(10), '
')}

" for p in texte.strip().split("\n\n")) def en_texte(contenu: str) -> str: t = re.sub(r"
  • ", "- ", re.sub(r"

    ||
  • |", "\n", contenu)) return re.sub(r"\n{3,}", "\n\n", html.unescape(re.sub(r"<[^>]+>", "", t))).strip() def mail(nom: str) -> tuple[str, str]: objet, corps = (MAILS / f"{nom}.txt").read_text().split("\n", 1) return objet.strip(), corps.strip() def conversation(boite: int, nom: str, contact: str) -> str: objet, corps = mail(nom) conv = req("POST", "/api/v1/conversations", {"inbox_id": boite, "contact_email": contact, "first_name": "Client", "last_name": nom, "initiator": "contact", "subject": objet, "content": en_html(corps)}) return conv["uuid"] def main(mot_de_passe: str = "TestAdmin-2026!") -> None: connexion(mot_de_passe) boite = next(b["id"] for b in req("GET", "/api/v1/inboxes") if b["name"] == "Test") avant = total_mailpit() # L'échange précédent du contact « suite » : sa question et la réponse de l'agent (elle part dans Mailpit). histoire = conversation(boite, "histoire", "client-suite@example.com") req("POST", f"/api/v1/conversations/{histoire}/messages", {"message": en_html((MAILS / "histoire-reponse.txt").read_text()), "private": False, "sender_type": "agent", "to": ["client-suite@example.com"]}) uuids = {n: conversation(boite, n, "client-suite@example.com" if n == "suite" else f"client-{n}@example.com") for n in ESSAIS} for _ in range(30): # attendre que la réponse de l'agent soit arrivée dans Mailpit if total_mailpit() > avant: break time.sleep(1) reference = total_mailpit() lignes = [f"# Essai des brouillons, {datetime.date.today()}", ""] for n in ESSAIS: objet, corps = mail(n) debut = time.monotonic() rep = req("POST", "/api/v1/ai/generate-reply", {"conversation_uuid": uuids[n], "instruction": ""}, timeout=300) duree = time.monotonic() - debut brouillon = en_texte(rep.get("content") or "") if rep.get("status") == "completed" else json.dumps(rep) print(f"{n} : {rep.get('status')} en {duree:.0f} s") lignes += [f"## {n} : {objet}", "", f"Durée : {duree:.0f} s ; statut : {rep.get('status')}", "", "**Le mail**", "", corps, "", "**Le brouillon**", "", brouillon, ""] time.sleep(5) if total_mailpit() != reference: sys.exit(f"un message est sorti pendant la génération : Mailpit {reference} → {total_mailpit()}") sortie = ICI.parent / "cases" / f"essai-brouillons-{datetime.date.today()}.md" sortie.parent.mkdir(exist_ok=True) sortie.write_text("\n".join(lignes)) print(f"Mailpit inchangé pendant la génération ({reference}) ; rapport : {sortie}") if __name__ == "__main__": main(*sys.argv[1:2])