API: support page with two Claude API clients, support and analyst (D-133)
Self-contained sub-project API/: a local support page where Marc pastes a client's mail; a support agent and an analyst agent stay alive for the session and produce a slide PDF that answers the client's question. Tools, detectors, knowledge and Typst brand are copied (API/PROVENANCE.md). First real case: Crissier (LENZSPITZE), workflow validated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
874f6bf7ea
commit
8ba75b92fa
130 files changed
+42094
No files matched your search
@@ -0,0 +1,123 @@
|
||||
"""Un agent de l'API Claude qui reste vivant : un historique seulement ajouté, une boucle d'outils, son coût.
|
||||
|
||||
L'historique n'est jamais réécrit (le modèle refuse un historique édité qui contient ses blocs de réflexion) ; un
|
||||
message assistant qui demande des outils n'y entre qu'avec ses tool_result, pour qu'une erreur au milieu d'un tour ne
|
||||
laisse pas de tool_use orphelin.
|
||||
"""
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from langsmith import traceable
|
||||
|
||||
PRIX = {"claude-opus-5-5": {"entree": 4.0, "sortie": 20.0, "cache_lu": 0.20, "cache_ecrit": 5.0}} # $ / Mtok
|
||||
MAX_TOKENS = 64000
|
||||
|
||||
|
||||
@traceable(run_type="llm", name="claude")
|
||||
def _llm(client, **kw):
|
||||
"""Un appel à l'API, tracé dans LangSmith (son enveloppe wrap_anthropic ne couvre pas beta.messages.stream)."""
|
||||
with client.beta.messages.stream(**kw) as flux:
|
||||
return flux.get_final_message()
|
||||
|
||||
|
||||
@traceable(run_type="tool")
|
||||
def _outil(executer, nom: str, entree: dict):
|
||||
return executer(nom, entree)
|
||||
|
||||
|
||||
def _resume(entree: dict) -> str:
|
||||
t = json.dumps(entree, ensure_ascii=False)
|
||||
return t if len(t) <= 200 else t[:200] + "…"
|
||||
|
||||
|
||||
# ponytail: l'historique grossit sans limite, images comprises (voir_image, voir_page) ; une longue analyse
|
||||
# approfondie finira par dépasser la taille de requête de l'API, et on ne peut pas tronquer l'historique.
|
||||
# Sortie prévue : la compaction côté serveur (beta compact-2026-01-12) ou le context editing des vieux tool_result.
|
||||
class Agent:
|
||||
def __init__(self, nom: str, systeme: str, outils: list[dict], executer: Callable[[str, dict], str | list[dict]],
|
||||
client, journal: Callable[[dict], None], effort: str, modele: str = "claude-opus-5-5"):
|
||||
self.nom, self.systeme, self.outils, self.executer = nom, systeme, outils, executer
|
||||
self.client, self.journal, self.effort, self.modele = client, journal, effort, modele
|
||||
self.messages: list[dict] = []
|
||||
self.cout = 0.0
|
||||
self.occupe = False
|
||||
self._verrou = threading.Lock()
|
||||
|
||||
def _dire(self, type_: str, texte: str, **plus):
|
||||
self.journal({"agent": self.nom, "type": type_, "texte": texte, **plus})
|
||||
|
||||
def _ajouter_user(self, blocs: list[dict]):
|
||||
# après un tour interrompu, l'historique finit sur un message user : on y ajoute plutôt que d'en mettre deux
|
||||
if self.messages and self.messages[-1]["role"] == "user":
|
||||
self.messages[-1]["content"] += blocs
|
||||
else:
|
||||
self.messages.append({"role": "user", "content": blocs})
|
||||
|
||||
def _compter(self, usage):
|
||||
p = PRIX[self.modele]
|
||||
self.cout += (usage.input_tokens * p["entree"] + usage.output_tokens * p["sortie"]
|
||||
+ (getattr(usage, "cache_read_input_tokens", 0) or 0) * p["cache_lu"]
|
||||
+ (getattr(usage, "cache_creation_input_tokens", 0) or 0) * p["cache_ecrit"]) / 1e6
|
||||
self._dire("cout", f"{self.cout:.2f}")
|
||||
|
||||
def _appel(self):
|
||||
return _llm(self.client, model=self.modele, max_tokens=MAX_TOKENS,
|
||||
system=[{"type": "text", "text": self.systeme, "cache_control": {"type": "ephemeral"}}],
|
||||
tools=self.outils, messages=self.messages, thinking={"type": "adaptive"},
|
||||
output_config={"effort": self.effort}, cache_control={"type": "ephemeral"})
|
||||
# pas de fallbacks="default" : un bloc de repli renvoyé tel quel casse l'historique (clé from_, blocs à
|
||||
# retirer) ; un refus finit le tour comme un max_tokens, sans rien ajouter à l'historique
|
||||
|
||||
def tour(self, contenu: str | list[dict], source: str) -> str:
|
||||
"""Ajoute le message de `source` (marc ou support), fait tourner la boucle jusqu'à la fin du tour, rend le
|
||||
texte final (vide si le tour s'arrête sur une erreur)."""
|
||||
blocs = [{"type": "text", "text": contenu}] if isinstance(contenu, str) else list(contenu)
|
||||
texte = next((b["text"] for b in blocs if b.get("type") == "text"), "")
|
||||
blocs = [{"type": "text", "text": f"<source>{source}</source>"}] + blocs
|
||||
with self._verrou:
|
||||
self.occupe = True
|
||||
try:
|
||||
self._ajouter_user(blocs)
|
||||
self._dire("entree", texte, source=source)
|
||||
return self._boucle()
|
||||
finally:
|
||||
self.occupe = False
|
||||
|
||||
def _boucle(self) -> str:
|
||||
while True:
|
||||
try:
|
||||
r = self._appel()
|
||||
except Exception as e: # noqa: BLE001 — surcharge, quota, réseau : le tour s'arrête, l'historique reste valide
|
||||
self._dire("erreur", f"{type(e).__name__}: {e}")
|
||||
return ""
|
||||
self._compter(r.usage)
|
||||
if r.stop_reason not in ("tool_use", "end_turn", "pause_turn"):
|
||||
# max_tokens, refusal… : la réponse peut porter un tool_use sans suite, qui rendrait l'historique
|
||||
# invalide pour toujours ; elle n'y entre pas, le tour s'arrête, le message suivant repart d'ici
|
||||
self._dire("erreur", f"tour arrêté : {r.stop_reason} (réponse non gardée)")
|
||||
return ""
|
||||
contenu = [b.model_dump(mode="json", exclude_none=True, by_alias=True) for b in r.content]
|
||||
for b in contenu:
|
||||
if b["type"] == "text" and b["text"].strip():
|
||||
self._dire("texte", b["text"])
|
||||
if r.stop_reason == "tool_use":
|
||||
resultats = []
|
||||
for b in (b for b in contenu if b["type"] == "tool_use"):
|
||||
self._dire("outil", f"{b['name']} {_resume(b['input'])}")
|
||||
try:
|
||||
res = {"type": "tool_result", "tool_use_id": b["id"], "content": _outil(self.executer, b["name"], b["input"])}
|
||||
except Exception as e: # noqa: BLE001 — l'erreur d'un outil est rendue au modèle
|
||||
res = {"type": "tool_result", "tool_use_id": b["id"], "content": f"{type(e).__name__}: {e}",
|
||||
"is_error": True}
|
||||
resultats.append(res)
|
||||
self.messages += [{"role": "assistant", "content": contenu}, {"role": "user", "content": resultats}]
|
||||
continue
|
||||
self.messages.append({"role": "assistant", "content": contenu})
|
||||
if r.stop_reason == "pause_turn": # seulement avec des outils serveur, que nous n'avons pas
|
||||
continue
|
||||
return "\n".join(b["text"] for b in contenu if b["type"] == "text")
|
||||
|
||||
def sauver(self, chemin: Path) -> None:
|
||||
Path(chemin).write_text(json.dumps(self.messages, ensure_ascii=False, indent=1))
|
||||
@@ -0,0 +1,245 @@
|
||||
"""Vérifications du support par l'API, sans appel à l'API (faux client) : API/.venv/bin/python API/support/check.py"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace as NS
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from agent import Agent # noqa: E402
|
||||
|
||||
API = Path(__file__).resolve().parents[1]
|
||||
DONNEES = API.parent / "data"
|
||||
|
||||
|
||||
class Bloc(NS):
|
||||
def model_dump(self, **_):
|
||||
return {k: v for k, v in vars(self).items() if v is not None}
|
||||
|
||||
|
||||
def reponse(contenu, stop, entree=10, sortie=10):
|
||||
return NS(content=contenu, stop_reason=stop, usage=NS(input_tokens=entree, output_tokens=sortie,
|
||||
cache_read_input_tokens=0, cache_creation_input_tokens=0))
|
||||
|
||||
|
||||
class FauxClient:
|
||||
"""beta.messages.stream(**kw) rend, dans l'ordre, les réponses scriptées ; une exception scriptée est levée."""
|
||||
def __init__(self, *reponses):
|
||||
self.reponses, self.appels = list(reponses), []
|
||||
self.beta = NS(messages=NS(stream=self._stream))
|
||||
|
||||
def _stream(self, **kw):
|
||||
self.appels.append(kw)
|
||||
r = self.reponses.pop(0)
|
||||
client = self
|
||||
|
||||
class Flux:
|
||||
def __enter__(self):
|
||||
if isinstance(r, Exception):
|
||||
raise r
|
||||
return NS(get_final_message=lambda: r)
|
||||
|
||||
def __exit__(self, *_):
|
||||
return False
|
||||
client.dernier = kw
|
||||
return Flux()
|
||||
|
||||
|
||||
def agent(client, executer=lambda n, e: "ok"):
|
||||
journal = []
|
||||
a = Agent("analyste", "système", [], executer, client, journal.append, effort="high")
|
||||
return a, journal
|
||||
|
||||
|
||||
def check_boucle():
|
||||
appels = []
|
||||
c = FauxClient(reponse([Bloc(type="tool_use", id="t1", name="detecteurs", input={"station": "X"})], "tool_use"),
|
||||
reponse([Bloc(type="text", text="fini")], "end_turn"))
|
||||
a, _ = agent(c, lambda n, e: appels.append((n, e)) or "3 événements")
|
||||
assert a.tour("question", "support") == "fini"
|
||||
roles = [m["role"] for m in a.messages]
|
||||
assert roles == ["user", "assistant", "user", "assistant"], roles
|
||||
res = a.messages[2]["content"][0]
|
||||
assert res["type"] == "tool_result" and res["tool_use_id"] == "t1" and res["content"] == "3 événements"
|
||||
assert appels == [("detecteurs", {"station": "X"})]
|
||||
assert not a.occupe
|
||||
|
||||
|
||||
def check_erreur():
|
||||
c = FauxClient(reponse([Bloc(type="tool_use", id="t1", name="detecteurs", input={})], "tool_use"),
|
||||
RuntimeError("surcharge"))
|
||||
a, journal = agent(c)
|
||||
a.tour("question", "marc")
|
||||
assert any(e["type"] == "erreur" for e in journal)
|
||||
dernier = a.messages[-1]
|
||||
assert not (dernier["role"] == "assistant" and any(b.get("type") == "tool_use" for b in dernier["content"]))
|
||||
assert not a.occupe
|
||||
# le tour suivant repart proprement : user après user est permis, pas de tool_use orphelin
|
||||
c.reponses.append(reponse([Bloc(type="text", text="repris")], "end_turn"))
|
||||
assert a.tour("encore", "marc") == "repris"
|
||||
|
||||
|
||||
def check_cout():
|
||||
r = reponse([Bloc(type="text", text="x")], "end_turn", entree=1_000_000, sortie=100_000)
|
||||
a, journal = agent(FauxClient(r))
|
||||
a.tour("q", "marc")
|
||||
assert abs(a.cout - 6.0) < 1e-9, a.cout
|
||||
assert any(e["type"] == "cout" for e in journal)
|
||||
|
||||
|
||||
def check_source():
|
||||
a, journal = agent(FauxClient(reponse([Bloc(type="text", text="x")], "end_turn")))
|
||||
a.tour("bonjour", "marc")
|
||||
premier = a.messages[0]["content"][0]
|
||||
assert premier["type"] == "text" and premier["text"].startswith("<source>marc</source>")
|
||||
assert journal[0]["type"] == "entree" and journal[0]["source"] == "marc"
|
||||
|
||||
|
||||
def check_outil_qui_leve():
|
||||
c = FauxClient(reponse([Bloc(type="tool_use", id="t1", name="x", input={})], "tool_use"),
|
||||
reponse([Bloc(type="text", text="vu")], "end_turn"))
|
||||
a, _ = agent(c, lambda n, e: 1 / 0)
|
||||
a.tour("q", "marc")
|
||||
res = a.messages[2]["content"][0]
|
||||
assert res["is_error"] is True and "division" in res["content"]
|
||||
|
||||
|
||||
def boite(dossier, station="NEBRASKA"):
|
||||
from outils import Boite
|
||||
return Boite(lambda: dossier, lambda: station, DONNEES, lambda m: "réponse", lambda st, su: dossier)
|
||||
|
||||
|
||||
def leve(f, *a):
|
||||
from outils import ErreurOutil
|
||||
try:
|
||||
f(*a)
|
||||
except ErreurOutil as e:
|
||||
return str(e)
|
||||
raise AssertionError(f"{f.__name__}{a} n'a pas levé ErreurOutil")
|
||||
|
||||
|
||||
def seance_temporaire():
|
||||
import tempfile
|
||||
return Path(tempfile.mkdtemp(prefix="seance-"))
|
||||
|
||||
|
||||
def check_lecture_refusee():
|
||||
b = boite(seance_temporaire())
|
||||
assert "rm" in leve(b.executer_analyste, "outil_de_lecture", {"nom": "rm", "arguments": []})
|
||||
|
||||
|
||||
def check_chemin():
|
||||
b = boite(seance_temporaire())
|
||||
for c in ("../../.env", "/etc/passwd"):
|
||||
leve(b.executer_analyste, "voir_image", {"chemin": c})
|
||||
|
||||
|
||||
def check_station_absente():
|
||||
b = boite(seance_temporaire())
|
||||
m = leve(b.executer_analyste, "detecteurs", {"station": "NULLEPART", "du": "2026-10-01", "au": "2026-10-02"})
|
||||
assert "NULLEPART" in m
|
||||
|
||||
|
||||
def check_detecteurs():
|
||||
b = boite(seance_temporaire())
|
||||
t = b.executer_analyste("detecteurs", {"station": "NEBRASKA", "du": "2026-10-20", "au": "2026-11-01"})
|
||||
assert "événement" in t and "capteurs :" in t, t
|
||||
|
||||
|
||||
def check_plafond():
|
||||
from outils import plafonner
|
||||
t = plafonner("x" * 50_000)
|
||||
assert len(t) <= 40_100 and t.endswith("tronqué : 50000 caractères]"), t[-60:]
|
||||
|
||||
|
||||
def check_image():
|
||||
import base64
|
||||
import io
|
||||
from PIL import Image
|
||||
from outils import bloc_image
|
||||
jpg = sorted((DONNEES / "NEBRASKA" / "images").glob("*.jpg"))[0]
|
||||
b = bloc_image(jpg)
|
||||
assert b["type"] == "image" and b["source"]["media_type"] == "image/jpeg"
|
||||
im = Image.open(io.BytesIO(base64.b64decode(b["source"]["data"])))
|
||||
assert max(im.size) <= 1568, im.size
|
||||
|
||||
|
||||
def check_compiler():
|
||||
import re
|
||||
import shutil
|
||||
d = seance_temporaire()
|
||||
modele = (API / "knowledge" / "support" / "modele.typ").read_text()
|
||||
(d / "nebraska.typ").write_text(modele)
|
||||
for f in set(re.findall(r'image\("([^"]+)"\)', modele)):
|
||||
shutil.copy(API.parent / "support" / "2026-11-02_BREITHORN_rapport-situation" / f, d)
|
||||
b = boite(d)
|
||||
assert b.executer_support("compiler", {}).startswith("v1.pdf : ") and (d / "v1.pdf").exists()
|
||||
assert b.executer_support("compiler", {}).startswith("v2.pdf : ")
|
||||
(d / "nebraska.typ").write_text("#oups(")
|
||||
leve(b.executer_support, "compiler", {})
|
||||
assert not (d / "v3.pdf").exists()
|
||||
page = b.executer_support("voir_page", {"n": 1})
|
||||
assert page[0]["type"] == "image"
|
||||
|
||||
|
||||
def check_max_tokens():
|
||||
# un tour coupé (max_tokens, refus) avec un tool_use : rien n'entre dans l'historique, la séance continue
|
||||
c = FauxClient(reponse([Bloc(type="tool_use", id="t1", name="ecrire_presentation", input={})], "max_tokens"),
|
||||
reponse([Bloc(type="text", text="repris")], "end_turn"))
|
||||
a, journal = agent(c)
|
||||
a.tour("q", "marc")
|
||||
assert any(e["type"] == "erreur" for e in journal)
|
||||
assert all(m["role"] == "user" for m in a.messages), [m["role"] for m in a.messages]
|
||||
assert a.tour("encore", "marc") == "repris"
|
||||
|
||||
|
||||
def check_sans_repli():
|
||||
# le repli de modèle casse l'historique renvoyé (clé from_) : il n'est pas demandé
|
||||
c = FauxClient(reponse([Bloc(type="text", text="x")], "end_turn"))
|
||||
a, _ = agent(c)
|
||||
a.tour("q", "marc")
|
||||
assert "fallbacks" not in c.dernier and "server-side-fallback-2026-07-01" not in c.dernier.get("betas", [])
|
||||
|
||||
|
||||
def check_capture_reduite():
|
||||
import io
|
||||
import shutil
|
||||
from PIL import Image
|
||||
from seance import Seance
|
||||
tampon = io.BytesIO()
|
||||
Image.new("RGB", (4000, 3000), "white").save(tampon, "PNG")
|
||||
s = Seance("mail", [("image/png", tampon.getvalue())], "", DONNEES, lambda e: None,
|
||||
client=FauxClient(reponse([Bloc(type="text", text="x")], "end_turn")))
|
||||
try:
|
||||
s.demarrer()
|
||||
bloc = next(b for b in s.support.messages[0]["content"] if b.get("type") == "image")
|
||||
import base64
|
||||
im = Image.open(io.BytesIO(base64.b64decode(bloc["source"]["data"])))
|
||||
assert max(im.size) <= 1568, im.size
|
||||
finally:
|
||||
shutil.rmtree(s.dossier)
|
||||
|
||||
|
||||
def check_image_proche():
|
||||
from datetime import datetime, timedelta
|
||||
b = boite(seance_temporaire())
|
||||
jpg = sorted((DONNEES / "NEBRASKA" / "images").glob("*.jpg"))[0]
|
||||
t = datetime.strptime(jpg.name[:14], "%Y%m%dT%H%MZ") + timedelta(minutes=2)
|
||||
bloc = b.executer_analyste("voir_image", {"chemin": "images/" + t.strftime("%Y%m%dT%H%MZ")})
|
||||
assert bloc[0]["type"] == "image"
|
||||
assert b._image_proche(t.strftime("%Y%m%dT%H%MZ")) == jpg
|
||||
leve(b._image_proche, "20200101T0000Z")
|
||||
|
||||
|
||||
def check_stations_dans_la_seance():
|
||||
from outils import AVEC_SORTIE
|
||||
assert "stations" in AVEC_SORTIE
|
||||
|
||||
|
||||
CHECKS = [check_image_proche, check_max_tokens, check_sans_repli, check_capture_reduite, check_stations_dans_la_seance, check_boucle, check_erreur, check_cout, check_source, check_outil_qui_leve, check_lecture_refusee,
|
||||
check_chemin, check_station_absente, check_detecteurs, check_plafond, check_image, check_compiler]
|
||||
|
||||
if __name__ == "__main__":
|
||||
nom = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
for f in CHECKS:
|
||||
if nom in (None, f.__name__):
|
||||
f()
|
||||
print("ok", f.__name__)
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Les outils des deux agents : leurs schémas pour l'API, et la Boite qui les exécute sur le poste.
|
||||
|
||||
Tout outil lance une copie de `API/tools/` par `subprocess`, n'écrit que dans le dossier de la séance (et dans la fabrique
|
||||
Typst `tools/typst/{documents,build}/`), et lève ErreurOutil sur une erreur : l'agent la rend au modèle en `is_error`.
|
||||
"""
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from PIL import Image
|
||||
|
||||
API = Path(__file__).resolve().parents[1]
|
||||
PY = str(API / ".venv" / "bin" / "python")
|
||||
TOOLS = API / "tools"
|
||||
TYPST = TOOLS / "typst"
|
||||
LECTURE = {"inventaire", "resume", "plages", "jours", "vignettes", "qualite", "ensemble", "graphique", "metriques",
|
||||
"stations"}
|
||||
AVEC_SORTIE = {"graphique", "ensemble", "jours", "metriques", "vignettes", "qualite", "stations"} # ceux qui écrivent des PNG
|
||||
DELAI = 600 # s
|
||||
VOIR = 1000 # px : les images regardées restent dans l'historique et repartent à chaque appel
|
||||
NOM = re.compile(r"^[A-Za-z0-9_-]+$")
|
||||
INSTANT = re.compile(r"^\d{8}T\d{4}Z$") # AAAAMMJJTHHMMZ, comme le début du nom des images
|
||||
PROCHE = 90 # min : au-delà, pas d'image « à cette heure »
|
||||
|
||||
|
||||
class ErreurOutil(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def plafonner(texte: str, n: int = 40_000) -> str:
|
||||
return texte if len(texte) <= n else texte[:n] + f"\n[… tronqué : {len(texte)} caractères]"
|
||||
|
||||
|
||||
def bloc_image(chemin: Path, cote: int = 1568) -> dict:
|
||||
"""Image -> bloc image de l'API, plus grand côté ≤ cote px (au-delà de 1568, l'API la réduirait de toute façon)."""
|
||||
im = Image.open(chemin)
|
||||
im.thumbnail((cote, cote))
|
||||
jpeg = Path(chemin).suffix.lower() in (".jpg", ".jpeg")
|
||||
if im.mode not in ("RGB", "L"):
|
||||
im = im.convert("RGB")
|
||||
tampon = io.BytesIO()
|
||||
im.save(tampon, "JPEG" if jpeg else "PNG")
|
||||
return {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg" if jpeg else "image/png",
|
||||
"data": base64.b64encode(tampon.getvalue()).decode()}}
|
||||
|
||||
|
||||
def _schema(nom: str, description: str, props: dict) -> dict:
|
||||
return {"name": nom, "description": description, "strict": True,
|
||||
"input_schema": {"type": "object", "properties": props, "required": list(props),
|
||||
"additionalProperties": False}}
|
||||
|
||||
|
||||
S, I = {"type": "string"}, {"type": "integer"}
|
||||
LISTE = {"type": "array", "items": {"type": "string"}}
|
||||
|
||||
OUTILS_ANALYSTE = [
|
||||
_schema("detecteurs", "Les événements des détecteurs du journal sur une plage : famille, sorte, capteurs, phrase. "
|
||||
"du et au : AAAA-MM-JJ, UTC, au exclu.", {"station": S, "du": S, "au": S}),
|
||||
_schema("outil_de_lecture", "Lance un outil de lecture (lire-les-donnees.md) : nom parmi " + ", ".join(sorted(LECTURE))
|
||||
+ ". arguments : la ligne de commande après le nom du script, data/<STATION> pour le dossier.",
|
||||
{"nom": S, "arguments": LISTE}),
|
||||
_schema("figure_courbes", "Figure corr_y à plage grisée (figure-y.py) dans le dossier de la séance, <nom>.png. "
|
||||
"debut, fin : AAAA-MM-JJTHH:MMZ. options : --cam tilt,pan, --temp, --zone D/F, --ligne T, --hauteur 5…",
|
||||
{"nom": S, "debut": S, "fin": S, "cibles": LISTE, "options": LISTE}),
|
||||
_schema("image_de_la_cause", "Recadrages éclaircis côte à côte autour d'une cible (x, y : pixel dans l'image entière), "
|
||||
"<nom>.png. instants : AAAAMMJJTHHMMZ=légende (l'image la plus proche de chaque heure), d'abord un instant "
|
||||
"sans la cause.",
|
||||
{"nom": S, "x": I, "y": I, "instants": LISTE}),
|
||||
_schema("voir_image", "Regarder une image : un fichier du dossier de la séance (ex. bosse.png), ou une image de la "
|
||||
"caméra, images/AAAAMMJJTHHMMZ (la plus proche de cette heure UTC) ou images/<fichier>.", {"chemin": S}),
|
||||
]
|
||||
|
||||
OUTILS_SUPPORT = [
|
||||
_schema("poser_station", "Fixe la station de la séance (un dossier de données) et le sujet en 2-3 mots "
|
||||
"(ex. courbes-bruitees) ; rend ce que la station a comme données.", {"station": S, "sujet": S}),
|
||||
_schema("demander_analyste", "Envoie un message à l'analyste (station, plage UTC, question ; ou un retour de fond) "
|
||||
"et rend sa réponse.", {"message": S}),
|
||||
_schema("ecrire_presentation", "Écrit le source Typst complet de la présentation dans le dossier de la séance.",
|
||||
{"source_typ": S}),
|
||||
_schema("compiler", "Compile la présentation : rend la version (v1.pdf, v2.pdf…), le nombre de diapositives qui "
|
||||
"débordent et les remarques du lint, ou l'erreur de Typst.", {}),
|
||||
_schema("voir_page", "Regarder la page n (à partir de 1) de la dernière version du PDF.", {"n": I}),
|
||||
]
|
||||
|
||||
|
||||
class Boite:
|
||||
def __init__(self, dossier_seance: Callable[[], Path], station: Callable[[], str | None], donnees: Path,
|
||||
demander_analyste: Callable[[str], str], poser: Callable[[str, str], Path]):
|
||||
self.dossier, self.station, self.donnees = dossier_seance, station, Path(donnees)
|
||||
self.demander_analyste, self.poser = demander_analyste, poser
|
||||
|
||||
# --- aides
|
||||
|
||||
def _lancer(self, args: list[str], env: dict | None = None) -> str:
|
||||
try:
|
||||
r = subprocess.run(args, cwd=self.dossier(), capture_output=True, text=True, timeout=DELAI,
|
||||
env={**os.environ, **(env or {})})
|
||||
except subprocess.TimeoutExpired:
|
||||
raise ErreurOutil(f"délai de {DELAI} s dépassé : {' '.join(args[1:3])}")
|
||||
sortie = (r.stdout + ("\n" + r.stderr if r.stderr.strip() else "")).strip()
|
||||
if r.returncode:
|
||||
raise ErreurOutil(plafonner(sortie or f"code de sortie {r.returncode}"))
|
||||
return plafonner(sortie or "(rien)")
|
||||
|
||||
def _station(self, station: str | None = None) -> Path:
|
||||
station = station or self.station()
|
||||
if not station:
|
||||
raise ErreurOutil("pas encore de station : le support doit d'abord appeler poser_station")
|
||||
if not NOM.match(station) or not (self.donnees / station).is_dir():
|
||||
raise ErreurOutil(f"station inconnue : {station} (pas de dossier dans les données)")
|
||||
return self.donnees / station
|
||||
|
||||
def _nom(self, nom: str) -> str:
|
||||
if not NOM.match(nom):
|
||||
raise ErreurOutil(f"nom de fichier refusé : {nom} (lettres, chiffres, - et _)")
|
||||
return nom
|
||||
|
||||
def _data(self, a: str) -> str:
|
||||
return str(self.donnees) + a[4:] if a == "data" or a.startswith("data/") else a
|
||||
|
||||
def _image_proche(self, instant: str) -> Path:
|
||||
"""L'image de la station la plus proche de l'instant (les images tombent à :00 ou :01, à un nom près)."""
|
||||
t = datetime.strptime(instant, "%Y%m%dT%H%MZ")
|
||||
ecart = lambda p: abs((datetime.strptime(p.name[:14], "%Y%m%dT%H%MZ") - t).total_seconds()) # noqa: E731
|
||||
images = [p for p in (self._station() / "images").glob("*.jpg") if INSTANT.match(p.name[:14])]
|
||||
proche = min(images, key=ecart, default=None)
|
||||
if not proche or ecart(proche) > PROCHE * 60:
|
||||
raise ErreurOutil(f"pas d'image à moins de {PROCHE} min de {instant}")
|
||||
return proche
|
||||
|
||||
def _image(self, chemin: str) -> Path:
|
||||
if chemin.startswith("images/") and INSTANT.match(chemin[7:21]) and not (self._station() / chemin).is_file():
|
||||
return self._image_proche(chemin[7:21])
|
||||
if chemin.startswith("images/"):
|
||||
base = self._station() / "images"
|
||||
p = (base / chemin[7:]).resolve()
|
||||
else:
|
||||
base = self.dossier()
|
||||
p = (base / chemin).resolve()
|
||||
if Path(chemin).is_absolute() or not p.is_relative_to(base.resolve()) or not p.is_file():
|
||||
raise ErreurOutil(f"image refusée ou absente : {chemin}")
|
||||
return p
|
||||
|
||||
def _versions(self) -> list[Path]:
|
||||
return sorted(self.dossier().glob("v*.pdf"), key=lambda p: int(p.stem[1:]))
|
||||
|
||||
# --- l'analyste
|
||||
|
||||
def executer_analyste(self, nom: str, e: dict):
|
||||
if nom == "detecteurs":
|
||||
return self._lancer([PY, str(TOOLS / "journal.py"), str(self._station(e["station"])), "--du", e["du"],
|
||||
"--au", e["au"]])
|
||||
if nom == "outil_de_lecture":
|
||||
if e["nom"] not in LECTURE:
|
||||
raise ErreurOutil(f"outil inconnu : {e['nom']} (permis : {', '.join(sorted(LECTURE))})")
|
||||
args = [self._data(a) for a in e["arguments"]]
|
||||
if e["nom"] in AVEC_SORTIE:
|
||||
args += ["--sortie", str(self.dossier())]
|
||||
return self._lancer([PY, str(TOOLS / "agent-tools" / f"{e['nom']}.py"), *args])
|
||||
if nom == "figure_courbes":
|
||||
sortie = self.dossier() / f"{self._nom(e['nom'])}.png"
|
||||
self._lancer([PY, str(TOOLS / "figures" / "figure-y.py"), str(self._station()), str(sortie), e["debut"],
|
||||
e["fin"], "--cibles", ",".join(e["cibles"]), *e["options"]])
|
||||
return f"{sortie.name} écrite ; la regarder avec voir_image avant de la garder"
|
||||
if nom == "image_de_la_cause":
|
||||
sortie = self.dossier() / f"{self._nom(e['nom'])}.png"
|
||||
instants = [] # chaque instant ramené à l'image la plus proche, sa légende gardée
|
||||
for i in e["instants"]:
|
||||
k, egal, legende = i.partition("=")
|
||||
instants.append(self._image_proche(k).name[:14] + egal + legende)
|
||||
self._lancer([PY, str(TOOLS / "figures" / "image-de-la-cause.py"), str(self._station()), str(e["x"]),
|
||||
str(e["y"]), str(sortie), *instants])
|
||||
return (f"{sortie.name} écrite, images : {', '.join(i.partition('=')[0] for i in instants)} ; "
|
||||
"la regarder avec voir_image avant de la garder")
|
||||
if nom == "voir_image":
|
||||
return [bloc_image(self._image(e["chemin"]), VOIR)]
|
||||
raise ErreurOutil(f"outil inconnu : {nom}")
|
||||
|
||||
# --- le support
|
||||
|
||||
def executer_support(self, nom: str, e: dict):
|
||||
if nom == "poser_station":
|
||||
dossier = self._station(e["station"])
|
||||
self.poser(e["station"], self._nom(e["sujet"]))
|
||||
sous = ", ".join(f"{d.name} ({sum(1 for _ in d.iterdir())} fichiers)" for d in sorted(dossier.iterdir())
|
||||
if d.is_dir())
|
||||
return f"station {e['station']} posée ; données : {sous}"
|
||||
if nom == "demander_analyste":
|
||||
return self.demander_analyste(e["message"])
|
||||
if nom == "ecrire_presentation":
|
||||
p = self.dossier() / f"{self._station().name.lower()}.typ"
|
||||
p.write_text(e["source_typ"])
|
||||
return f"{p.name} écrit ({len(e['source_typ'])} caractères)"
|
||||
if nom == "compiler":
|
||||
return self._compiler()
|
||||
if nom == "voir_page":
|
||||
return self._voir_page(int(e["n"]))
|
||||
raise ErreurOutil(f"outil inconnu : {nom}")
|
||||
|
||||
def _compiler(self) -> str:
|
||||
station = self._station().name.lower()
|
||||
source = self.dossier() / f"{station}.typ"
|
||||
if not source.exists():
|
||||
raise ErreurOutil("pas de source : appeler ecrire_presentation d'abord")
|
||||
slug = f"{station}-support"
|
||||
doc = TYPST / "documents" / slug
|
||||
shutil.rmtree(doc, ignore_errors=True)
|
||||
doc.mkdir(parents=True)
|
||||
shutil.copy(source, doc / "main.typ")
|
||||
for png in self.dossier().glob("*.png"):
|
||||
shutil.copy(png, doc)
|
||||
env = {"PATH": f"{Path.home() / '.local' / 'bin'}:{os.environ.get('PATH', '')}"}
|
||||
try:
|
||||
r = subprocess.run([PY, "brand/tools/build.py", slug], cwd=TYPST, capture_output=True, text=True,
|
||||
timeout=DELAI, env={**os.environ, **env})
|
||||
except subprocess.TimeoutExpired:
|
||||
raise ErreurOutil(f"compilation : délai de {DELAI} s dépassé")
|
||||
sortie = (r.stdout + "\n" + r.stderr).strip()
|
||||
pdf = TYPST / "build" / f"{slug}-draft.pdf"
|
||||
if r.returncode or not pdf.exists():
|
||||
raise ErreurOutil(plafonner(sortie))
|
||||
version = self.dossier() / f"v{len(self._versions()) + 1}.pdf"
|
||||
shutil.copy(pdf, version)
|
||||
pdf.unlink() # la prochaine compilation ratée ne doit pas trouver l'ancien PDF
|
||||
texte = subprocess.run(["pdftotext", str(version), "-"], capture_output=True, text=True).stdout
|
||||
remarques = "\n".join(l for l in sortie.splitlines() if "warning" in l and "bare-image" not in l)
|
||||
return f"{version.name} : {texte.count('Overflow')} diapositive(s) qui débordent" + (
|
||||
f"\nremarques du lint :\n{plafonner(remarques, 4000)}" if remarques else "")
|
||||
|
||||
def _voir_page(self, n: int) -> list[dict]:
|
||||
versions = self._versions()
|
||||
if not versions:
|
||||
raise ErreurOutil("pas encore de PDF : compiler d'abord")
|
||||
prefixe = self.dossier() / f".page-{n}"
|
||||
r = subprocess.run(["pdftoppm", "-f", str(n), "-l", str(n), "-png", "-r", "80", str(versions[-1]),
|
||||
str(prefixe)], capture_output=True, text=True)
|
||||
pages = sorted(self.dossier().glob(f".page-{n}-*.png"))
|
||||
if r.returncode or not pages:
|
||||
raise ErreurOutil(f"page {n} introuvable dans {versions[-1].name}")
|
||||
bloc = bloc_image(pages[0])
|
||||
for p in pages:
|
||||
p.unlink()
|
||||
return [bloc]
|
||||
@@ -0,0 +1,170 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Support AIMsight</title>
|
||||
<style>
|
||||
:root { --fond: #f6f7f9; --carte: #fff; --texte: #1d232b; --doux: #6b7480; --bord: #d9dde3;
|
||||
--support: #e8eefc; --analyste: #e7f5ec; --marc: #fdf0e3; --erreur: #b3261e; --accent: #2457c5; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; padding: 16px; font: 14px/1.45 system-ui, sans-serif; background: var(--fond); color: var(--texte); }
|
||||
h1 { font-size: 18px; margin: 0 0 12px; }
|
||||
.carte { background: var(--carte); border: 1px solid var(--bord); border-radius: 8px; padding: 12px; }
|
||||
.entree { display: grid; grid-template-columns: 2fr 1fr auto; gap: 12px; align-items: start; }
|
||||
label { font-size: 12px; color: var(--doux); display: block; margin-bottom: 4px; }
|
||||
textarea { width: 100%; border: 1px solid var(--bord); border-radius: 6px; padding: 8px; font: inherit; resize: vertical; }
|
||||
#mail { min-height: 140px; } #contexte { min-height: 140px; }
|
||||
button { font: inherit; padding: 8px 16px; border: 0; border-radius: 6px; background: var(--accent); color: #fff; cursor: pointer; }
|
||||
button:disabled { background: var(--bord); color: var(--doux); cursor: default; }
|
||||
.cote { display: flex; flex-direction: column; gap: 8px; min-width: 150px; }
|
||||
#cout { font-size: 12px; color: var(--doux); white-space: pre; }
|
||||
#vignettes img { height: 48px; margin: 4px 4px 0 0; border: 1px solid var(--bord); border-radius: 4px; }
|
||||
.fils { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin: 12px 0; }
|
||||
.fil { display: flex; flex-direction: column; height: 60vh; }
|
||||
.fil h2 { font-size: 14px; margin: 0 0 8px; display: flex; justify-content: space-between; }
|
||||
.etat { font-weight: normal; color: var(--doux); font-size: 12px; }
|
||||
.messages { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; padding-right: 4px; }
|
||||
.m { padding: 8px 10px; border-radius: 6px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.m.support { background: var(--support); } .m.analyste { background: var(--analyste); }
|
||||
.m.marc { background: var(--marc); align-self: flex-end; max-width: 85%; }
|
||||
.m.relai { background: var(--support); border-left: 3px solid var(--accent); }
|
||||
.m .qui { font-size: 11px; color: var(--doux); display: block; margin-bottom: 2px; }
|
||||
.outil { font-size: 12px; color: var(--doux); font-family: ui-monospace, monospace; overflow-wrap: anywhere; }
|
||||
.erreur { color: var(--erreur); font-size: 12px; }
|
||||
.saisie { display: flex; gap: 8px; margin-top: 8px; }
|
||||
.saisie textarea { min-height: 44px; height: 44px; }
|
||||
.rapport { display: flex; flex-direction: column; gap: 8px; }
|
||||
.rapport .barre { display: flex; justify-content: space-between; align-items: center; }
|
||||
iframe { width: 100%; height: 75vh; border: 1px solid var(--bord); border-radius: 6px; background: #fff; }
|
||||
.vide { color: var(--doux); padding: 24px; text-align: center; }
|
||||
@media (max-width: 900px) { .entree, .fils { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Support AIMsight</h1>
|
||||
|
||||
<div class="carte entree">
|
||||
<div>
|
||||
<label for="mail">Mail du client (texte ; colle les captures ici, elles s'ajoutent en vignettes)</label>
|
||||
<textarea id="mail" placeholder="Bonjour, …"></textarea>
|
||||
<div id="vignettes"></div>
|
||||
</div>
|
||||
<div>
|
||||
<label for="contexte">Ton contexte (station, plage, ce que tu sais du cas)</label>
|
||||
<textarea id="contexte"></textarea>
|
||||
</div>
|
||||
<div class="cote">
|
||||
<button id="analyser">Analyser</button>
|
||||
<div id="cout"></div>
|
||||
<div id="dossier" class="outil"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="fils">
|
||||
<div class="carte fil">
|
||||
<h2>Support <span class="etat" id="etat-support"></span></h2>
|
||||
<div class="messages" id="fil-support"></div>
|
||||
<div class="saisie"><textarea id="saisie-support" placeholder="Au support…"></textarea><button data-agent="support">Envoyer</button></div>
|
||||
</div>
|
||||
<div class="carte fil">
|
||||
<h2>Analyste <span class="etat" id="etat-analyste"></span></h2>
|
||||
<div class="messages" id="fil-analyste"></div>
|
||||
<div class="saisie"><textarea id="saisie-analyste" placeholder="À l'analyste…"></textarea><button data-agent="analyste">Envoyer</button></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="carte rapport">
|
||||
<div class="barre"><strong>Rapport <span id="version"></span></strong><a id="telecharger" hidden><button>Télécharger le PDF</button></a></div>
|
||||
<div id="pdf" class="vide">Pas encore de PDF.</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const images = [];
|
||||
let n = 0, version = null, id = null;
|
||||
|
||||
document.getElementById("mail").addEventListener("paste", ev => {
|
||||
for (const item of ev.clipboardData.items) {
|
||||
if (!item.type.startsWith("image/")) continue;
|
||||
const lecteur = new FileReader();
|
||||
lecteur.onload = () => {
|
||||
images.push({ nom: `capture-${images.length + 1}`, type: item.type, base64: lecteur.result.split(",")[1] });
|
||||
const img = document.createElement("img"); img.src = lecteur.result;
|
||||
document.getElementById("vignettes").append(img);
|
||||
};
|
||||
lecteur.readAsDataURL(item.getAsFile());
|
||||
}
|
||||
});
|
||||
|
||||
async function poster(chemin, corps) {
|
||||
const r = await fetch(chemin, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(corps) });
|
||||
if (!r.ok) alert((await r.json()).erreur);
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
document.getElementById("analyser").onclick = async () => {
|
||||
const mail = document.getElementById("mail").value, contexte = document.getElementById("contexte").value;
|
||||
if (!mail.trim()) return alert("Colle d'abord le mail du client.");
|
||||
if (await poster("/analyser", { mail, contexte, images })) {
|
||||
images.length = 0; document.getElementById("vignettes").innerHTML = ""; // pas de captures d'un client à l'autre
|
||||
}
|
||||
};
|
||||
|
||||
for (const b of document.querySelectorAll(".saisie button")) {
|
||||
b.onclick = async () => {
|
||||
const agent = b.dataset.agent, zone = document.getElementById(`saisie-${agent}`);
|
||||
if (zone.value.trim() && await poster("/message", { agent, texte: zone.value })) zone.value = "";
|
||||
};
|
||||
}
|
||||
|
||||
function ajouter(fil, classe, texte, qui) {
|
||||
const d = document.createElement("div"); d.className = classe;
|
||||
if (qui) { const q = document.createElement("span"); q.className = "qui"; q.textContent = qui; d.append(q); }
|
||||
d.append(document.createTextNode(texte));
|
||||
const f = document.getElementById(`fil-${fil}`); f.append(d); f.scrollTop = f.scrollHeight;
|
||||
}
|
||||
|
||||
function montrer(e) {
|
||||
if (e.type === "cout") return;
|
||||
if (e.type === "outil") return ajouter(e.agent, "outil", "→ " + e.texte);
|
||||
if (e.type === "erreur") return ajouter(e.agent, "erreur", "Erreur : " + e.texte);
|
||||
if (e.type === "entree") {
|
||||
if (e.source === "marc") return ajouter(e.agent, "m marc", e.texte.replace(/^<mail>\n?|\n?<\/mail>[\s\S]*$/g, ""), "Toi");
|
||||
return ajouter(e.agent, "m relai", e.texte, "Demande du support");
|
||||
}
|
||||
ajouter(e.agent, `m ${e.agent}`, e.texte, e.agent === "support" ? "Support" : "Analyste");
|
||||
}
|
||||
|
||||
async function interroger() {
|
||||
try {
|
||||
let r = await (await fetch(`/evenements?depuis=${n}`)).json();
|
||||
if (r.id && r.id !== id) { // une nouvelle séance : tout repartir de zéro (l'id ne change pas quand le dossier est renommé)
|
||||
id = r.id; version = null;
|
||||
for (const id of ["fil-support", "fil-analyste"]) document.getElementById(id).innerHTML = "";
|
||||
document.getElementById("pdf").outerHTML = `<div id="pdf" class="vide">Pas encore de PDF.</div>`;
|
||||
document.getElementById("version").textContent = ""; document.getElementById("telecharger").hidden = true;
|
||||
r = await (await fetch(`/evenements?depuis=0`)).json();
|
||||
}
|
||||
r.evenements.forEach(montrer); n = r.n;
|
||||
if (r.cout) document.getElementById("cout").textContent =
|
||||
`Support ${r.cout.support.toFixed(2)} $\nAnalyste ${r.cout.analyste.toFixed(2)} $\nTotal ${r.cout.total.toFixed(2)} $`;
|
||||
document.getElementById("dossier").textContent = r.dossier || "";
|
||||
for (const a of ["support", "analyste"]) {
|
||||
document.getElementById(`etat-${a}`).textContent = r.occupe[a] ? "occupé…" : "";
|
||||
document.getElementById(`saisie-${a}`).disabled = r.occupe[a];
|
||||
document.querySelector(`button[data-agent=${a}]`).disabled = r.occupe[a] || !r.dossier;
|
||||
}
|
||||
document.getElementById("analyser").disabled = r.occupe.support || r.occupe.analyste;
|
||||
if (r.version && r.version !== version) {
|
||||
version = r.version;
|
||||
document.getElementById("version").textContent = `(${version.replace(".pdf", "")})`;
|
||||
document.getElementById("pdf").outerHTML = `<iframe id="pdf" src="/pdf?v=${version}"></iframe>`;
|
||||
const a = document.getElementById("telecharger"); a.href = `/pdf?v=${version}`; a.download = `${r.dossier}_${version}`; a.hidden = false;
|
||||
}
|
||||
} catch (e) { /* serveur arrêté : on réessaie */ }
|
||||
setTimeout(interroger, 1000);
|
||||
}
|
||||
interroger();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,133 @@
|
||||
"""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/<nom>/ 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<savoir fichier="{f.name}">\n{f.read_text()}\n</savoir>'
|
||||
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"")
|
||||
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"<mail>\n{self.mail}\n</mail>\n<contexte>\n{self.contexte or '(aucun)'}\n</contexte>"
|
||||
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"<marc>{q}</marc>\n<analyste>{r}</analyste>" for q, r in self._echanges)
|
||||
blocs = [{"type": "text", "text": f"<echange_marc_analyste>\n{rapport}\n</echange_marc_analyste>"}, *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
|
||||
@@ -0,0 +1,134 @@
|
||||
"""La page support : API/.venv/bin/python API/support/serveur.py → http://127.0.0.1:8770
|
||||
|
||||
Une séance à la fois, en mémoire ; la page interroge /evenements chaque seconde.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import webbrowser
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from seance import Seance, donnees_par_defaut # noqa: E402
|
||||
|
||||
PORT = 8770
|
||||
HOTES = {f"127.0.0.1:{PORT}", f"localhost:{PORT}"} # contre le DNS rebinding : un autre site ne lit ni mails ni PDF
|
||||
PAGE = Path(__file__).resolve().parent / "page.html"
|
||||
verrou = threading.Lock()
|
||||
etat = {"seance": None, "evenements": []}
|
||||
|
||||
|
||||
def journal(e: dict) -> None:
|
||||
with verrou:
|
||||
etat["evenements"].append(e)
|
||||
|
||||
|
||||
def en_fond(f, *args):
|
||||
def lancer():
|
||||
try:
|
||||
f(*args)
|
||||
except Exception as e: # noqa: BLE001 — une erreur de la séance s'affiche dans la page, le serveur continue
|
||||
journal({"agent": "support", "type": "erreur", "texte": f"{type(e).__name__}: {e}"})
|
||||
threading.Thread(target=lancer, daemon=True).start()
|
||||
|
||||
|
||||
class Serveur(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def _envoyer(self, code: int, corps: bytes, type_: str = "application/json", plus: dict | None = None):
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", type_)
|
||||
self.send_header("Content-Length", str(len(corps)))
|
||||
for k, v in (plus or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
self.wfile.write(corps)
|
||||
|
||||
def _json(self, code: int, obj) -> None:
|
||||
self._envoyer(code, json.dumps(obj, ensure_ascii=False).encode())
|
||||
|
||||
def _refuse(self, post: bool = False) -> bool:
|
||||
"""Seule la page elle-même parle au serveur : bon Host ; en POST, un JSON déclaré (une page d'un autre site ne
|
||||
peut l'envoyer sans requête préalable, à laquelle le serveur ne répond pas)."""
|
||||
if self.headers.get("Host") not in HOTES or (
|
||||
post and not self.headers.get("Content-Type", "").startswith("application/json")):
|
||||
self._json(403, {"erreur": "requête refusée"})
|
||||
return True
|
||||
return False
|
||||
|
||||
def do_GET(self):
|
||||
if self._refuse():
|
||||
return
|
||||
url = urlparse(self.path)
|
||||
s = etat["seance"]
|
||||
if url.path == "/":
|
||||
return self._envoyer(200, PAGE.read_bytes(), "text/html; charset=utf-8")
|
||||
if url.path == "/evenements":
|
||||
depuis = int(parse_qs(url.query).get("depuis", ["0"])[0])
|
||||
with verrou:
|
||||
evs = etat["evenements"][depuis:]
|
||||
n = len(etat["evenements"])
|
||||
v = s.derniere_version() if s else None
|
||||
return self._json(200, {"evenements": evs, "n": n, "cout": s.cout() if s else None,
|
||||
"version": v.name if v else None, "dossier": s.dossier.name if s else None,
|
||||
"id": s.id if s else None,
|
||||
"occupe": {a: bool(s and s.occupe(a)) for a in ("support", "analyste")}})
|
||||
if url.path == "/pdf":
|
||||
v = s.derniere_version() if s else None
|
||||
if not v:
|
||||
return self._json(404, {"erreur": "pas encore de PDF"})
|
||||
nom = f"{s.dossier.name}_{v.name}"
|
||||
return self._envoyer(200, v.read_bytes(), "application/pdf",
|
||||
{"Content-Disposition": f'inline; filename="{nom}"'})
|
||||
self._json(404, {"erreur": url.path})
|
||||
|
||||
def do_POST(self):
|
||||
if self._refuse(post=True):
|
||||
return
|
||||
corps = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
||||
s = etat["seance"]
|
||||
if self.path == "/analyser":
|
||||
if s and (s.occupe("support") or s.occupe("analyste")):
|
||||
return self._json(409, {"erreur": "une séance travaille encore"})
|
||||
if not corps.get("mail", "").strip():
|
||||
return self._json(400, {"erreur": "le mail est vide"})
|
||||
images = [(i["type"], base64.b64decode(i["base64"])) for i in corps.get("images", [])]
|
||||
with verrou:
|
||||
etat["evenements"] = []
|
||||
etat["seance"] = s = Seance(corps["mail"], images, corps.get("contexte", ""), donnees_par_defaut(),
|
||||
journal)
|
||||
en_fond(s.demarrer)
|
||||
return self._json(200, {"dossier": s.dossier.name})
|
||||
if self.path == "/message":
|
||||
agent, texte = corps.get("agent"), corps.get("texte", "").strip()
|
||||
if not s:
|
||||
return self._json(400, {"erreur": "pas de séance : coller un mail et Analyser"})
|
||||
if agent not in ("support", "analyste") or not texte:
|
||||
return self._json(400, {"erreur": "agent ou texte manquant"})
|
||||
if s.occupe(agent):
|
||||
return self._json(409, {"erreur": f"{agent} occupé"})
|
||||
en_fond(s.parler, agent, texte)
|
||||
return self._json(200, {})
|
||||
self._json(404, {"erreur": self.path})
|
||||
|
||||
|
||||
def ouvrir(url: str) -> None:
|
||||
if "microsoft" in platform.uname().release.lower(): # WSL : le navigateur Windows
|
||||
subprocess.Popen(["explorer.exe", url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
else:
|
||||
webbrowser.open(url)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
url = f"http://127.0.0.1:{PORT}"
|
||||
serveur = ThreadingHTTPServer(("127.0.0.1", PORT), Serveur)
|
||||
print(f"Page support : {url}")
|
||||
if "--sans-navigateur" not in sys.argv:
|
||||
ouvrir(url)
|
||||
serveur.serve_forever()
|
||||
Reference in new issue
Block a user