"""Une séance de support : un mail, le support et l'analyste vivants, le dossier de la séance dans API/cases/. Une séance = un fil (thread) LangSmith : chaque tour de Marc y est une trace, avec les appels à l'API et aux outils. """ import os from datetime import datetime, timezone from pathlib import Path from typing import Callable API = Path(__file__).resolve().parents[1] CASES = API / "cases" TYPES_IMAGE = {"image/png", "image/jpeg", "image/gif", "image/webp"} def charger_env(chemin: Path = API / ".env") -> None: """Les lignes CLE=valeur de API/.env dans l'environnement (sans écraser ce qui y est déjà).""" if chemin.exists(): for ligne in chemin.read_text().splitlines(): ligne = ligne.strip().removeprefix("export ") # accepte aussi la forme du shell : export CLE=valeur cle, egal, valeur = ligne.partition("=") if egal and cle and not cle.startswith("#"): os.environ.setdefault(cle.strip(), valeur.strip().strip('"').strip("'")) charger_env() # avant d'importer langsmith, qui garde en cache les variables qu'il a lues (LANGSMITH_ENDPOINT…) import anthropic # noqa: E402 from langsmith import traceable # noqa: E402 from agent import Agent # noqa: E402 from outils import OUTILS_ANALYSTE, OUTILS_SUPPORT, Boite, bloc_image # noqa: E402 def systeme(nom: str) -> str: """Le prompt de l'agent, puis chaque fichier de knowledge// dans sa balise : stable, donc en cache.""" texte = (API / "prompts" / f"{nom}.md").read_text() for f in sorted((API / "knowledge" / nom).iterdir()): texte += f'\n\n\n{f.read_text()}\n' return texte def donnees_par_defaut() -> Path: return Path(os.environ.get("AIMSIGHT_DATA", API.parent / "data")).resolve() class Seance: def __init__(self, mail: str, images: list[tuple[str, bytes]], contexte: str, donnees: Path, journal: Callable[[dict], None], client=None): self.mail, self.images, self.contexte, self.journal = mail, images, contexte, journal self.id = datetime.now(timezone.utc).strftime("%Y-%m-%d_%H%M%S") self.dossier = CASES / self.id self.dossier.mkdir(parents=True) self.station: str | None = None self._echanges: list[tuple[str, str]] = [] # ce que Marc a dit à l'analyste, pour le prochain tour du support client = client or anthropic.Anthropic() boite = Boite(lambda: self.dossier, lambda: self.station, donnees, self._demander_analyste, self._poser) self.support = Agent("support", systeme("support"), OUTILS_SUPPORT, boite.executer_support, client, journal, effort="medium") self.analyste = Agent("analyste", systeme("analyste"), OUTILS_ANALYSTE, boite.executer_analyste, client, journal, effort="high") # --- rappels des outils def _poser(self, station: str, sujet: str) -> Path: jour = self.id[:10] nouveau, i = CASES / f"{jour}_{station}_{sujet}", 2 while nouveau.exists() and nouveau != self.dossier: nouveau, i = CASES / f"{jour}_{station}_{sujet}-{i}", i + 1 if nouveau != self.dossier: self.dossier.rename(nouveau) self.dossier = nouveau self.station = station return nouveau def _demander_analyste(self, message: str) -> str: r = self.analyste.tour(message, "support") self._sauver() return r or "(l'analyste s'est arrêté sur une erreur, voir son fil)" # --- ce que fait Marc def _trace(self, nom: str, f, *args): return traceable(name=nom, metadata={"thread_id": self.id})(f)(*args) def demarrer(self) -> None: blocs, lignes = [], [] for i, (type_, donnee) in enumerate(self.images, 1): if type_ not in TYPES_IMAGE: continue nom = f"capture-{i}.{type_.split('/')[1]}" (self.dossier / nom).write_bytes(donnee) lignes.append(f"![Capture {i}]({nom})") blocs.append(bloc_image(self.dossier / nom)) # réduite : une capture 4K serait refusée, et pour toujours (self.dossier / "demande.md").write_text( f"# Demande du {self.id[:10]}\n\n## Mail du client\n\n{self.mail}\n\n## Contexte de Marc\n\n" f"{self.contexte or '(aucun)'}\n\n" + "\n".join(lignes) + "\n") texte = f"\n{self.mail}\n\n\n{self.contexte or '(aucun)'}\n" self._trace("séance : le mail", self._tour_support, [{"type": "text", "text": texte}, *blocs]) def parler(self, agent: str, texte: str) -> None: if agent == "analyste": self._trace("séance : Marc à l'analyste", self._tour_analyste, texte) else: self._trace("séance : Marc au support", self._tour_support, [{"type": "text", "text": texte}]) def _tour_analyste(self, texte: str) -> None: self._echanges.append((texte, self.analyste.tour(texte, "marc"))) self._sauver() def _tour_support(self, blocs: list[dict]) -> None: if self._echanges: rapport = "\n".join(f"{q}\n{r}" for q, r in self._echanges) blocs = [{"type": "text", "text": f"\n{rapport}\n"}, *blocs] self._echanges = [] self.support.tour(blocs, "marc") self._sauver() def _sauver(self) -> None: self.support.sauver(self.dossier / "support.json") self.analyste.sauver(self.dossier / "analyste.json") # --- ce que lit la page def occupe(self, agent: str) -> bool: return (self.support if agent == "support" else self.analyste).occupe def cout(self) -> dict: return {"support": self.support.cout, "analyste": self.analyste.cout, "total": self.support.cout + self.analyste.cout} def derniere_version(self) -> Path | None: v = sorted(self.dossier.glob("v*.pdf"), key=lambda p: int(p.stem[1:])) return v[-1] if v else None