Download app.py from RDS777/bluster2: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/spaces/RDS777/bluster2/resolve/main/app.py
- Command line
-
hf download hf://spaces/RDS777/bluster2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/RDS777/bluster2/resolve/main/app.py
10.3 kB
| """Space n°2 — Copilote d'analyse pour agent_core (bluster2). | |
| Flux d'un appel POST /v1/chat/completions (format OpenAI, envoyé par relais.py) : | |
| 1. Phase A : 5 bots déterministes en parallèle sur le dernier message (code, logs, | |
| sorties d'outils) → briefing JSON compact. | |
| 2. Phase B : le briefing est AJOUTÉ au prompt système d'agent_core (jamais remplacé : | |
| c'est lui qui définit les outils valides), puis Qwen2.5-Coder-1.5B répond. | |
| 3. La réponse est normalisée (blocs ```json retirés) et renvoyée telle quelle ; | |
| agent_core valide le schéma et demande une correction si besoin. | |
| Si le modèle n'est pas prêt ou échoue → HTTP 503 : relais.py passe alors au Space suivant. | |
| Les 4 slots de llama-server servent jusqu'à 4 requêtes simultanées. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import json | |
| import logging | |
| import os | |
| import re | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor | |
| from typing import Any | |
| import httpx | |
| from fastapi import FastAPI | |
| from fastapi.responses import JSONResponse | |
| from pydantic import BaseModel, ConfigDict | |
| from bots import cartographe, chirurgien, dependances, diagnostic_erreurs, garde_fou | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") | |
| log = logging.getLogger("space2") | |
| logging.getLogger("httpx").setLevel(logging.WARNING) | |
| LLAMA_BASE = os.environ.get("LLAMA_BASE", "http://127.0.0.1:8181") | |
| LLAMA_TIMEOUT = float(os.environ.get("LLAMA_TIMEOUT", "200")) | |
| MAX_TOKENS_PLAFOND = int(os.environ.get("MAX_TOKENS_PLAFOND", "768")) | |
| TAILLE_ANALYSE_MAX = 60_000 # caractères analysés par les bots | |
| app = FastAPI(title="Space n°2 — Copilote agent_core", version="1.1.0") | |
| _POOL = ThreadPoolExecutor(max_workers=5, thread_name_prefix="bot") | |
| class Message(BaseModel): | |
| model_config = ConfigDict(extra="ignore") | |
| role: str | |
| content: str = "" | |
| class ChatRequest(BaseModel): | |
| # extra="ignore" : relais.py envoie aussi turn_idx, raison_relais… | |
| model_config = ConfigDict(extra="ignore") | |
| model: str = "copilote" | |
| messages: list[Message] | |
| temperature: float = 0.1 | |
| max_tokens: int | None = None | |
| def _erreur(code: int, message: str) -> JSONResponse: | |
| return JSONResponse(status_code=code, content={"error": {"message": message, "code": code}}) | |
| # ── Phase A ───────────────────────────────────────────────────────────────── | |
| _RE_CHEMIN = re.compile(r"[\w./\\-]+\.(?:py|rs|toml|json|md|txt|js|ts)\b") | |
| def _construire_payload(messages: list[Message]) -> dict[str, Any]: | |
| """Payload pour les bots. Accepte un JSON structuré ou le texte brut d'agent_core.""" | |
| dernier = next((m.content for m in reversed(messages) if m.role != "system"), "") | |
| try: | |
| obj = json.loads(dernier) | |
| if isinstance(obj, dict) and ({"code", "log", "objectif"} & obj.keys()): | |
| return {k: obj.get(k, "") for k in ("objectif", "code", "fichier", "log", "action_json")} | |
| except (json.JSONDecodeError, TypeError): | |
| pass | |
| texte = dernier[-TAILLE_ANALYSE_MAX:] | |
| objectif = next((m.content for m in messages if m.role == "user"), "")[:500] | |
| fichiers = _RE_CHEMIN.findall(texte) | |
| return {"objectif": objectif, "code": texte, "fichier": fichiers[0] if fichiers else "", | |
| "log": texte, "action_json": ""} | |
| def _phase_a(payload: dict[str, Any]) -> dict[str, Any]: | |
| taches = { | |
| "cartographe": (cartographe.run, payload), | |
| "dependances": (dependances.run, payload), | |
| "chirurgien": (chirurgien.run, payload), | |
| "diagnostic_erreurs": (diagnostic_erreurs.run, {"log": payload.get("log", "")}), | |
| "garde_fou": (garde_fou.run, {"action_json": payload.get("action_json", ""), | |
| "code_propose": "", "fichier": payload.get("fichier", "")}), | |
| } | |
| futurs = {nom: _POOL.submit(fn, arg) for nom, (fn, arg) in taches.items()} | |
| res: dict[str, Any] = {} | |
| for nom, fut in futurs.items(): | |
| try: | |
| res[nom] = fut.result(timeout=10) | |
| except Exception as exc: # un bot en panne ne bloque pas les autres | |
| log.warning("bot %s KO : %s", nom, exc) | |
| res[nom] = {"erreur": str(exc)[:200]} | |
| return res | |
| def _briefing(payload: dict[str, Any], a: dict[str, Any]) -> str: | |
| """Briefing compact : seulement les champs non vides.""" | |
| b: dict[str, Any] = {} | |
| if payload.get("fichier"): | |
| b["fichier"] = payload["fichier"] | |
| sym = a.get("cartographe", {}).get("symboles", []) | |
| if sym: | |
| b["symboles"] = [f"{s['nom']}@L{s['ligne']}" for s in sym[:12]] | |
| imp = a.get("dependances", {}).get("imports", []) | |
| if imp: | |
| b["imports"] = imp[:10] | |
| zones = a.get("chirurgien", {}).get("zones", []) | |
| if zones: | |
| b["zones_risquees"] = [f"L{z['ligne_debut']}-{z['ligne_fin']}: {z['raison']}" for z in zones[:4]] | |
| diag = a.get("diagnostic_erreurs", {}) | |
| if diag.get("erreurs"): | |
| b["cause_racine"] = diag.get("cause_racine", "")[:300] | |
| gf = a.get("garde_fou", {}) | |
| if gf.get("erreurs"): | |
| b["alertes"] = gf["erreurs"][:3] | |
| return json.dumps(b, ensure_ascii=False) if b else "" | |
| def _historique_enrichi(messages: list[Message], briefing: str) -> list[dict[str, str]]: | |
| """Prompt système d'agent_core INCHANGÉ en tête (un seul message system) ; le briefing | |
| est ajouté à la FIN du dernier message. | |
| Pourquoi : llama.cpp réutilise le cache KV tant que le DÉBUT de la conversation est | |
| identique d'un tour à l'autre. Un briefing placé dans le system invalidait tout le | |
| cache (f_sim 0.23, ~1500 tokens relus, ~36 s par tour sur CPU). | |
| """ | |
| systemes = [m.content for m in messages if m.role == "system"] | |
| autres = [{"role": m.role, "content": m.content} for m in messages if m.role != "system"] | |
| if briefing and autres: | |
| autres[-1] = dict(autres[-1]) | |
| autres[-1]["content"] += ("\n\n[Analyse statique de ce message — informatif ; " | |
| "n'édite rien que l'objectif ne demande pas]\n" + briefing) | |
| systeme = "\n\n".join(systemes) | |
| return ([{"role": "system", "content": systeme}] if systeme else []) + autres | |
| # ── Phase B ───────────────────────────────────────────────────────────────── | |
| _RE_BLOC = re.compile(r"```(?:json)?\s*(\{.*\})\s*```", re.S) | |
| def _normaliser(texte: str) -> str: | |
| """Retire les balises ```json``` éventuelles ; laisse agent_core valider le schéma.""" | |
| m = _RE_BLOC.search(texte) | |
| return m.group(1).strip() if m else texte.strip() | |
| async def _llama_pret(client: httpx.AsyncClient) -> bool: | |
| try: | |
| r = await client.get(f"{LLAMA_BASE}/health", timeout=3) | |
| return r.status_code == 200 | |
| except Exception: | |
| return False | |
| async def chat_completions(req: ChatRequest) -> JSONResponse: | |
| t0 = time.perf_counter() | |
| if not req.messages: | |
| return _erreur(422, "messages vide") | |
| payload = _construire_payload(req.messages) | |
| analyse = await asyncio.get_running_loop().run_in_executor(None, _phase_a, payload) | |
| briefing = _briefing(payload, analyse) | |
| t_a = time.perf_counter() - t0 | |
| corps = { | |
| "messages": _historique_enrichi(req.messages, briefing), | |
| "temperature": req.temperature, | |
| "max_tokens": min(req.max_tokens or MAX_TOKENS_PLAFOND, MAX_TOKENS_PLAFOND), | |
| "stream": False, | |
| } | |
| async with httpx.AsyncClient() as client: | |
| if not await _llama_pret(client): | |
| return _erreur(503, "modèle en cours de chargement") | |
| try: | |
| r = await client.post(f"{LLAMA_BASE}/v1/chat/completions", json=corps, timeout=LLAMA_TIMEOUT) | |
| r.raise_for_status() | |
| contenu = r.json()["choices"][0]["message"]["content"] or "" | |
| except httpx.TimeoutException: | |
| return _erreur(504, f"modèle hors délai ({LLAMA_TIMEOUT:.0f} s)") | |
| except httpx.HTTPStatusError as exc: | |
| corps = exc.response.text[:300] | |
| if "context" in corps.lower() or "exceed" in corps.lower(): | |
| # 413 : l'historique ne tient pas dans le contexte du slot → agent_core | |
| # doit compacter (--limite-tokens) ; relais.py passe au Space suivant. | |
| return _erreur(413, f"contexte du modèle dépassé : {corps}") | |
| log.error("llama HTTP %d : %s", exc.response.status_code, corps) | |
| return _erreur(502, f"llama-server HTTP {exc.response.status_code} : {corps}") | |
| except Exception as exc: | |
| log.error("Phase B KO : %s", exc) | |
| return _erreur(503, f"modèle indisponible : {type(exc).__name__}") | |
| if not contenu.strip(): | |
| return _erreur(502, "réponse vide du modèle") | |
| contenu = _normaliser(contenu) | |
| duree = time.perf_counter() - t0 | |
| log.info("OK en %.1f s (phase A %.2f s, briefing %d car.)", duree, t_a, len(briefing)) | |
| return JSONResponse({ | |
| "id": f"space2-{int(t0 * 1000)}", | |
| "object": "chat.completion", | |
| "created": int(time.time()), | |
| "model": "space2-copilote", | |
| "choices": [{"index": 0, "message": {"role": "assistant", "content": contenu}, | |
| "finish_reason": "stop"}], | |
| "_meta": {"duree_sec": round(duree, 2), "phase_a_sec": round(t_a, 3), | |
| "briefing": briefing}, | |
| }) | |
| async def models() -> dict[str, Any]: | |
| return {"object": "list", "data": [{"id": "space2-copilote", "object": "model"}]} | |
| async def health() -> dict[str, Any]: | |
| async with httpx.AsyncClient() as client: | |
| pret = await _llama_pret(client) | |
| return {"status": "ok" if pret else "chargement", "service": "space2-copilote", "modele_pret": pret} | |
| async def root() -> dict[str, str]: | |
| return {"service": "Space n°2 — Copilote agent_core", | |
| "endpoint": "POST /v1/chat/completions", | |
| "bots": "cartographe, dependances, chirurgien, diagnostic_erreurs, garde_fou", | |
| "modele": "Qwen2.5-Coder-1.5B-Instruct Q4_K_M (4 slots)"} | |