File size: 4,410 Bytes
2e72013
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// llm.js — rédaction de la réponse par un LLM ouvert, à partir UNIQUEMENT des
// passages retrouvés localement (RAG verrouillé). Endpoint gratuit sans clé
// (pollinations, openai-compatible, CORS *) ; streaming SSE.
// En cas d'échec (limite, réseau), l'appelant retombe sur le mode preuve.

const ENDPOINT = "https://text.pollinations.ai/openai";
const MODEL = "openai-fast";

const systemPrompt = (voice) => `Tu es NoireBox Ask, l'assistant conformité de LOI.EXE / NoireBox (AI Act européen + RGPD).

RÈGLES ABSOLUES :
- Réponds UNIQUEMENT à partir des PASSAGES fournis. N'invente jamais d'article, de chiffre, de date ou d'obligation.
- Cite tes sources inline : [AI Act art. 12(2)], [RGPD art. 17], [exigence RIA-012-01], [source : titre]…
- Hiérarchie d'autorité si les passages se contredisent : droit officiel (EUR-Lex, CNIL, Conseil d'État) > code officiel (GPAI CoP) > doctrine (CNCDH) > communication Commission > communauté/recherche > produit NoireBox. Signale le conflit et suis le niveau le plus officiel.
- Si les passages ne suffisent pas, dis-le franchement et propose de reformuler.
- Réponds en français.

STYLE : ${voice === "tech"
  ? "auditeur / développeur : concis et technique. Donnes les exigences avec leur identifiant et la règle vérifiable (règle normexe). Markdown léger (gras, listes) autorisé."
  : "chef de projet / métier : langage clair, sans jargon juridique. Explique ce qu'on attend concrètement et pourquoi ça doit être prouvé par un test, pas promis."}`;

const userBlock = (g, question) => {
  const parts = [];
  if (g.articles.length) {
    parts.push("ARTICLES OFFICIELS (consolidations EUR-Lex) :");
    for (const a of g.articles) {
      parts.push(`[${a.acte} art. ${a.article}${a.heading ? " — " + a.heading : ""}]\n${a.text}`);
    }
  }
  if (g.requirements.length) {
    parts.push("EXIGENCES VÉRIFIABLES (moteur LOI.EXE — chaque exigence correspond à un test exécutable) :");
    for (const r of g.requirements) {
      parts.push(`[${r.req_id}, ${r.acte} art. ${r.ref}, contrôle ${r.check_type}${r.machine ? ", règle : " + r.rule : ""}] ${r.obligation}`);
    }
  }
  if (g.passages.length) {
    parts.push("PASSAGES DE CONTEXTE (du plus officiel au moins officiel) :");
    for (const p of g.passages) {
      parts.push(`[${p.tier_label} — ${p.title}]\n${p.text}`);
    }
  }
  parts.push(`QUESTION : ${question}`);
  return parts.join("\n\n");
};

// streamAnswer : appelle le LLM en streaming, appelle onDelta(fragment) au fil
// de l'eau, retourne le texte complet. Lève une erreur typée en cas d'échec.
export async function streamAnswer({ grounding, question, voice, history = [], onDelta, signal }) {
  const messages = [
    { role: "system", content: systemPrompt(voice) },
    ...history.slice(-4),
    { role: "user", content: userBlock(grounding, question) },
  ];
  const res = await fetch(ENDPOINT, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ model: MODEL, messages, stream: true, private: true }),
    signal,
  });
  if (!res.ok) {
    let msg = `HTTP ${res.status}`;
    try {
      const j = await res.json();
      if (j?.error?.code === "FREE_LIMIT") msg = "limite gratuite (1 réponse / 30 s) — réessaie dans un instant";
      else if (j?.error?.message) msg = j.error.message;
    } catch { /* corps non JSON */ }
    throw new Error(msg);
  }

  const ctype = res.headers.get("content-type") || "";
  if (!ctype.includes("text/event-stream")) {
    // réponse non streamée : JSON complet
    const j = await res.json();
    const text = j?.choices?.[0]?.message?.content || "";
    onDelta(text);
    return text;
  }

  const reader = res.body.getReader();
  const dec = new TextDecoder();
  let buf = "", full = "";
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buf += dec.decode(value, { stream: true });
    const lines = buf.split("\n");
    buf = lines.pop();
    for (const line of lines) {
      const t = line.trim();
      if (!t.startsWith("data:")) continue;
      const payload = t.slice(5).trim();
      if (payload === "[DONE]") continue;
      try {
        const delta = JSON.parse(payload)?.choices?.[0]?.delta?.content || "";
        if (delta) { full += delta; onDelta(delta); }
      } catch { /* fragment SSE tronqué */ }
    }
  }
  return full;
}