From 73b52cde2caa89e3f104667b218f63a5e6d271ca Mon Sep 17 00:00:00 2001 From: ALI YESILKAYA Date: Mon, 22 Jun 2026 22:10:59 +0200 Subject: [PATCH] feat(stt): recherche web (SearXNG in-cluster) + fix cluster_status (#49) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 2 d'Asa agentique : nouvel outil web_search adossé à un SearXNG self-host in-cluster, + correction du faux positif de cluster_status. - SearXNG (k8s/apps/searxng/) : Deployment + Service + ConfigMap settings.yml + IngressRoute searxng.lab.local, Application ArgoCD. Namespace ai, interne (l'outil tape http://searxng:8080). use_default_settings + search.formats inclut json (sinon API JSON 403) ; limiter/image_proxy off ; image pinnée ; conf copiée dans un emptyDir via initContainer (contourne le mount RO) ; PodSecurity restricted. - Outil web_search (tools._web_search) ajouté au contexte asa + STT_SEARXNG_URL. - fix(cluster_status) : les pods de CronJob TERMINÉS (Succeeded/Failed, ex. sacrifice-assign-renfort) comptaient comme « non prêts » → fausse alarme. Join kube_pod_status_phase{phase=~"Running |Pending"} (3 faux positifs → 0, validé in-cluster). - Serveur 0.8.0 ; doc stt.md + journal mis à jour. Co-authored-by: Claude Opus 4.8 --- admin/ia/stt.md | 24 ++++++--- k8s/apps-of-apps/apps/searxng.yaml | 24 +++++++++ k8s/apps/searxng/configmap.yaml | 29 +++++++++++ k8s/apps/searxng/deployment.yaml | 82 ++++++++++++++++++++++++++++++ k8s/apps/searxng/ingress.yaml | 16 ++++++ k8s/apps/searxng/service.yaml | 11 ++++ k8s/apps/stt/deployment.yaml | 3 ++ progress/2026-06-22.md | 17 ++++++- stt/server/pyproject.toml | 2 +- stt/server/stt_server/__init__.py | 2 +- stt/server/stt_server/config.py | 4 ++ stt/server/stt_server/contexts.py | 13 ++--- stt/server/stt_server/sources.py | 7 ++- stt/server/stt_server/tools.py | 52 +++++++++++++++++++ 14 files changed, 270 insertions(+), 16 deletions(-) create mode 100644 k8s/apps-of-apps/apps/searxng.yaml create mode 100644 k8s/apps/searxng/configmap.yaml create mode 100644 k8s/apps/searxng/deployment.yaml create mode 100644 k8s/apps/searxng/ingress.yaml create mode 100644 k8s/apps/searxng/service.yaml diff --git a/admin/ia/stt.md b/admin/ia/stt.md index 22dd28c..1824d4e 100644 --- a/admin/ia/stt.md +++ b/admin/ia/stt.md @@ -103,13 +103,25 @@ sur un contexte figé, Asa **décide elle-même** quels outils appeler (`tools.p partir de leurs résultats (`brain.ask_with_tools`, boucle bornée par `STT_TOOL_MAX_ITERS=4` ; au-delà, réponse forcée sans outils). C'est ce qui débloque les questions à **état live** sans présélection — ex. « gpu-01 tourne bien ? » → l'outil `host_health` est appelé → réponse réelle -(avant : le RAG seul disait « la doc ne le précise pas »). Outils Phase 1, **LECTURE SEULE** : +(avant : le RAG seul disait « la doc ne le précise pas »). Outils **LECTURE SEULE** (`tools.py`) : `search_docs` (RAG `funk-docs`), `host_health(gpu-01|storage-01)` (up/charge/RAM + llama-server, -Prometheus), `cluster_status` (nœuds/pods), `prometheus_query(expr)` (PromQL arbitraire). Modèle -**local** Qwen3-8B (le tool-calling natif de llama.cpp fonctionne, **même avec `/no_think`** — -vérifié). Le `trace` des outils appelés est renvoyé dans `context` → visualiseur HUD (un bloc par -appel). L'écriture (agir) reste au contexte `agent` ci-dessous (Phase 3 : la brancher comme outil). -> Web search (SearXNG in-cluster) = Phase 2 ; actions admin pilotées par le LLM = Phase 3. +Prometheus), `cluster_status` (nœuds/pods), `prometheus_query(expr)` (PromQL arbitraire), et +**`web_search(query)`** (recherche INTERNET via SearXNG, **Phase 2**). Modèle **local** Qwen3-8B +(le tool-calling natif de llama.cpp fonctionne, **même avec `/no_think`** — vérifié). Le `trace` +des outils appelés est renvoyé dans `context` → visualiseur HUD (un bloc par appel). L'écriture +(agir) reste au contexte `agent` ci-dessous (Phase 3 : la brancher comme outil). + +> **`cluster_status`** filtre les pods **terminés** (CronJob Succeeded/Failed) via un join +> `kube_pod_status_phase` → ne signale comme « non prêts » que les pods réellement actifs (sinon +> les pods cron finis, ex. `sacrifice-assign-renfort`, déclenchaient une fausse alarme). + +**SearXNG (recherche web in-cluster, Phase 2)** : méta-moteur self-host, manifests +`k8s/apps/searxng/` (Deployment + Service + ConfigMap `settings.yml` + IngressRoute +`searxng.lab.local`), Application ArgoCD `searxng`. Namespace `ai`, **interne** (l'outil tape +`http://searxng:8080`). Points clés : `use_default_settings: true` (hérite des moteurs), +**`search.formats` inclut `json`** (sinon l'API JSON renvoie 403), `limiter:false`/`image_proxy:false` +(usage interne), image **pinnée**, conf copiée dans un emptyDir via initContainer (évite le mount RO). +Outil = `STT_SEARXNG_URL` (`tools._web_search`). Actions admin pilotées par le LLM = **Phase 3**. La réponse `/v1/ask` renvoie le **contexte assemblé** (`context`: system prompt + blocs live + extraits RAG + mémoire) → alimente le **visualiseur** du HUD (« voir ce qu'on envoie à Asa »). diff --git a/k8s/apps-of-apps/apps/searxng.yaml b/k8s/apps-of-apps/apps/searxng.yaml new file mode 100644 index 0000000..d17844b --- /dev/null +++ b/k8s/apps-of-apps/apps/searxng.yaml @@ -0,0 +1,24 @@ +apiVersion: argoproj.io/v1alpha1 +kind: Application +metadata: + name: searxng + namespace: argocd + finalizers: + - resources-finalizer.argocd.argoproj.io +spec: + project: default + source: + repoURL: git@github.com:Alkatrazz24/Funk-lab.git + targetRevision: main + path: k8s/apps/searxng + directory: + recurse: true + destination: + server: https://kubernetes.default.svc + namespace: ai + syncPolicy: + automated: + prune: true + selfHeal: true + syncOptions: + - CreateNamespace=true diff --git a/k8s/apps/searxng/configmap.yaml b/k8s/apps/searxng/configmap.yaml new file mode 100644 index 0000000..c2a57a7 --- /dev/null +++ b/k8s/apps/searxng/configmap.yaml @@ -0,0 +1,29 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: searxng-settings + namespace: ai +data: + # SearXNG hérite de ses défauts (tous les moteurs) via use_default_settings, puis on + # surcharge le strict nécessaire. CRITIQUE : `search.formats` doit inclure `json` — sinon + # l'API JSON (utilisée par l'outil web_search d'Asa) renvoie 403. Instance INTERNE au + # cluster (pas d'Ingress WAN) : limiter/botdetection off, image_proxy off. + settings.yml: | + use_default_settings: true + general: + instance_name: "Funk SearXNG" + debug: false + server: + # secret_key d'une instance INTERNE (HMAC image-proxy, ici désactivé) — sensibilité + # faible. Déplaçable vers un Secret + SEARXNG_SECRET plus tard si besoin. + secret_key: "3c7090f1caa8fb060ad99e432fd9523aa8dacbfb134438ff02afbddf6cf350ad" + limiter: false + image_proxy: false + search: + formats: + - html + - json + safe_search: 0 + autocomplete: "" + ui: + static_use_hash: true diff --git a/k8s/apps/searxng/deployment.yaml b/k8s/apps/searxng/deployment.yaml new file mode 100644 index 0000000..43d0e50 --- /dev/null +++ b/k8s/apps/searxng/deployment.yaml @@ -0,0 +1,82 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: searxng + namespace: ai +spec: + replicas: 1 + selector: + matchLabels: + app: searxng + template: + metadata: + labels: + app: searxng + annotations: + # Redéploie le pod quand settings.yml change (le hash bouge → nouveau rollout). + checksum/config: "searxng-settings-v1" + spec: + # Conformité PodSecurity "restricted" (namespace ai). L'image tourne en uid 977 (searxng). + # fsGroup 977 → l'emptyDir /etc/searxng est accessible en écriture par l'init + le main. + securityContext: + runAsNonRoot: true + runAsUser: 977 + runAsGroup: 977 + fsGroup: 977 + seccompProfile: + type: RuntimeDefault + # Copie settings.yml (ConfigMap RO) dans un emptyDir inscriptible → évite les soucis + # de mount RO de l'entrypoint searxng (chown/sed éventuels sur le fichier de conf). + initContainers: + - name: copy-config + image: docker.io/searxng/searxng:2026.6.22-952896d29 + command: ["sh", "-c", "cp /config-src/settings.yml /etc/searxng/settings.yml"] + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + volumeMounts: + - name: config-src + mountPath: /config-src + readOnly: true + - name: config + mountPath: /etc/searxng + containers: + - name: searxng + image: docker.io/searxng/searxng:2026.6.22-952896d29 + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + ports: + - containerPort: 8080 + env: + # Base URL interne (pas d'exposition WAN). Requis par SearXNG pour générer ses liens. + - name: SEARXNG_BASE_URL + value: "http://searxng.lab.local/" + volumeMounts: + - name: config + mountPath: /etc/searxng + readinessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: 8080 + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: 100m + memory: 192Mi + limits: + cpu: "1" + memory: 512Mi + volumes: + - name: config-src + configMap: + name: searxng-settings + - name: config + emptyDir: {} diff --git a/k8s/apps/searxng/ingress.yaml b/k8s/apps/searxng/ingress.yaml new file mode 100644 index 0000000..e5b5981 --- /dev/null +++ b/k8s/apps/searxng/ingress.yaml @@ -0,0 +1,16 @@ +# Exposition LAN facultative (debug / usage manuel du méta-moteur). L'outil web_search +# d'Asa, lui, tape le Service in-cluster directement (http://searxng:8080). +apiVersion: traefik.io/v1alpha1 +kind: IngressRoute +metadata: + name: searxng + namespace: ai +spec: + entryPoints: + - web + routes: + - match: Host(`searxng.lab.local`) + kind: Rule + services: + - name: searxng + port: 8080 diff --git a/k8s/apps/searxng/service.yaml b/k8s/apps/searxng/service.yaml new file mode 100644 index 0000000..1dd53fb --- /dev/null +++ b/k8s/apps/searxng/service.yaml @@ -0,0 +1,11 @@ +apiVersion: v1 +kind: Service +metadata: + name: searxng + namespace: ai +spec: + selector: + app: searxng + ports: + - port: 8080 + targetPort: 8080 diff --git a/k8s/apps/stt/deployment.yaml b/k8s/apps/stt/deployment.yaml index d45b1b3..f9393dd 100644 --- a/k8s/apps/stt/deployment.yaml +++ b/k8s/apps/stt/deployment.yaml @@ -56,6 +56,9 @@ spec: # live du homelab et la doc d'elle-même. « funk » (RAG strict) reste sélectionnable. - name: STT_DEFAULT_CONTEXT value: "asa" + # Recherche web (outil web_search du contexte asa) → SearXNG in-cluster (ns ai). + - name: STT_SEARXNG_URL + value: "http://searxng:8080" - name: STT_PROMETHEUS_URL value: "http://kube-prometheus-stack-prometheus.monitoring:9090" - name: STT_ALERTMANAGER_URL diff --git a/progress/2026-06-22.md b/progress/2026-06-22.md index 9b18c34..97bde87 100644 --- a/progress/2026-06-22.md +++ b/progress/2026-06-22.md @@ -83,9 +83,24 @@ appeler, puis répond à partir des résultats. la boucle (hors-ligne). (PR `feat/asa-tool-loop`.) - **Choix** : web search = **SearXNG in-cluster** (Phase 2) ; modèle = **local uniquement**. +### Validation prod (#48 mergé) + Phase 2 + +- ✅ **Déployé et testé en prod** : « gpu-01 tourne bien ? » → outil `host_health` → *« en ligne, + charge 0.08, 48 % RAM, llama-server actif »*. « le cluster va bien ? » → `cluster_status`. + (Rollout : ArgoCD s'était calé sur le commit de merge ; un `refresh=hard` l'a fait rouler vers + l'image CI `sha-7cafc06`.) +- 🐛 **Fix `cluster_status`** : les pods de CronJob **terminés** (`sacrifice-assign-renfort`, + Succeeded) comptaient comme « non prêts » → fausse alarme. Join `kube_pod_status_phase{phase=~ + "Running|Pending"}` → 3 faux positifs → 0 (validé in-cluster). +- ✅ **Phase 2 — recherche web** : SearXNG self-host (`k8s/apps/searxng/`, Application ArgoCD, + ns `ai`, interne) + outil `web_search` (`STT_SEARXNG_URL`). Gotcha clé : `search.formats` doit + inclure `json`. Image pinnée, conf via initContainer→emptyDir (mount RO contourné), PodSecurity + restricted. (PR `feat/asa-web-search`, serveur 0.8.0.) + ## Prochaines étapes -- **Phase 2** — outil `web_search` (SearXNG self-host in-cluster, namespace `ai`, ArgoCD). +- **Vérifier SearXNG au déploiement** : pod Ready + `web_search` renvoie des résultats réels + (test end-to-end comme pour #48). Ajuster les moteurs SearXNG si bruyant. - **Phase 3** — outil `admin_action` (écriture) : brancher `hermes-exec` comme outil piloté par le LLM, avec le handshake de confirmation vocale existant. - Enrichir `host_health`/`cluster_status` (GPU via `rocm_scraper`, fs, températures) si utile. diff --git a/stt/server/pyproject.toml b/stt/server/pyproject.toml index c6e333b..9c1fbb2 100644 --- a/stt/server/pyproject.toml +++ b/stt/server/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "stt-server" -version = "0.7.0" +version = "0.8.0" description = "STT-server — orchestrateur AI du homelab Funk (API pour les clients STT)" requires-python = ">=3.11" diff --git a/stt/server/stt_server/__init__.py b/stt/server/stt_server/__init__.py index 05a3dee..b1d2771 100644 --- a/stt/server/stt_server/__init__.py +++ b/stt/server/stt_server/__init__.py @@ -1,3 +1,3 @@ """STT-server — orchestrateur AI in-cluster pour les clients STT.""" -__version__ = "0.7.0" +__version__ = "0.8.0" diff --git a/stt/server/stt_server/config.py b/stt/server/stt_server/config.py index c063af1..522263d 100644 --- a/stt/server/stt_server/config.py +++ b/stt/server/stt_server/config.py @@ -85,6 +85,10 @@ class Settings: tool_max_tokens: int = int(os.getenv("STT_TOOL_MAX_TOKENS", "512")) # Température basse pour le tool-use (sélection d'outil + arguments déterministes). tool_temperature: float = float(os.getenv("STT_TOOL_TEMPERATURE", "0.2")) + # Recherche web (outil web_search) — SearXNG self-host in-cluster (namespace ai), API JSON. + searxng_url: str = os.getenv("STT_SEARXNG_URL", "http://searxng:8080") + web_search_results: int = int(os.getenv("STT_WEB_SEARCH_RESULTS", "5")) + web_search_timeout: float = float(os.getenv("STT_WEB_SEARCH_TIMEOUT", "8")) # Actions via Hermes (contexte « agent ») — OPT-IN, désactivé par défaut. # Le contexte « agent » n'est exposé que si actions_enabled ET un jeton est présent. diff --git a/stt/server/stt_server/contexts.py b/stt/server/stt_server/contexts.py index 614f6da..5556568 100644 --- a/stt/server/stt_server/contexts.py +++ b/stt/server/stt_server/contexts.py @@ -42,12 +42,13 @@ CONTEXTS: dict[str, Context] = { id="asa", label="Asa · agent", icon="✨", description="Asa répond en s'appuyant sur des outils (doc + état live du homelab).", system_prompt=_BASE + " Tu disposes d'outils pour obtenir l'état RÉEL et LIVE du " - "homelab (santé des machines, état du cluster, métriques Prometheus) et pour chercher " - "dans la documentation Funk. Dès qu'une question porte sur l'état courant, un fait " - "précis ou la config du homelab, APPELLE l'outil adéquat puis réponds à partir de son " - "résultat — n'invente jamais. Si les outils ne donnent pas l'information, dis-le " - "simplement. Pour le bavardage général, réponds directement sans outil.", - tools=("search_docs", "host_health", "cluster_status", "prometheus_query"), + "homelab (santé des machines, état du cluster, métriques Prometheus), chercher dans la " + "documentation Funk, et faire une recherche sur INTERNET (web_search). Dès qu'une " + "question porte sur l'état courant, un fait précis du homelab, ou une info externe / " + "récente, APPELLE l'outil adéquat puis réponds à partir de son résultat — n'invente " + "jamais. Si les outils ne donnent pas l'information, dis-le simplement. Pour le " + "bavardage général, réponds directement sans outil.", + tools=("search_docs", "host_health", "cluster_status", "prometheus_query", "web_search"), ), "funk": Context( id="funk", label="Funk · cluster", icon="🛠️", diff --git a/stt/server/stt_server/sources.py b/stt/server/stt_server/sources.py index f6e1ec2..fee616e 100644 --- a/stt/server/stt_server/sources.py +++ b/stt/server/stt_server/sources.py @@ -137,8 +137,13 @@ async def alerts_block(client: httpx.AsyncClient) -> str: async def cluster_block(client: httpx.AsyncClient) -> str: try: nodes = await _prom_query(client, 'up{job=~"storage-01|gpu-01-node"}') + # « Non prêt » = ready false ET pod ENCORE actif (Running/Pending). Sans le filtre de + # phase, les pods de CronJob terminés (Succeeded/Failed — ex. sacrifice-assign-renfort) + # comptent comme « non prêts » → fausse alarme. Le join exclut les pods terminés. not_ready = await _prom_query( - client, 'kube_pod_status_ready{condition="false"} == 1' + client, + 'kube_pod_status_ready{condition="false"} == 1' + ' and on(namespace,pod) kube_pod_status_phase{phase=~"Running|Pending"} == 1', ) ready = await _prom_query(client, 'count(kube_pod_status_ready{condition="true"} == 1)') except httpx.HTTPError: diff --git a/stt/server/stt_server/tools.py b/stt/server/stt_server/tools.py index c313742..c404279 100644 --- a/stt/server/stt_server/tools.py +++ b/stt/server/stt_server/tools.py @@ -114,6 +114,38 @@ async def _prometheus_query(args: dict, deps: ToolDeps) -> str: return _fmt_series(rows) +async def _web_search(args: dict, deps: ToolDeps) -> str: + query = (args.get("query") or "").strip() + if not query: + return "Aucune requête de recherche fournie." + url = settings.searxng_url.rstrip("/") + "/search" + try: + r = await deps.client.get( + url, + params={"q": query, "format": "json", "safesearch": 0, "language": "fr"}, + timeout=settings.web_search_timeout, + ) + r.raise_for_status() + data = r.json() + except httpx.HTTPError: + return "Recherche web indisponible : SearXNG injoignable." + except ValueError: + return "Recherche web indisponible : réponse SearXNG inattendue (API JSON activée ?)." + results = data.get("results") or [] + if not results: + answers = data.get("answers") or [] + if answers: + return " ".join(str(a) for a in answers[:2]) + return "Aucun résultat web pour cette recherche." + lines = [] + for res in results[: settings.web_search_results]: + title = (res.get("title") or "").strip() + content = (res.get("content") or "").strip() + src = res.get("url") or "" + lines.append(f"- {title} : {content} ({src})" if content else f"- {title} ({src})") + return "\n".join(lines) + + # --- Registre : nom → (schéma OpenAI, exécuteur) -------------------------------- _TOOLS: dict[str, tuple[dict, object]] = { @@ -191,6 +223,26 @@ _TOOLS: dict[str, tuple[dict, object]] = { }, _prometheus_query, ), + "web_search": ( + { + "type": "function", + "function": { + "name": "web_search", + "description": "Recherche sur INTERNET (méta-moteur SearXNG) : actualité, faits " + "généraux, documentation externe, sujets hors du homelab Funk. À utiliser quand " + "l'information n'est ni dans le homelab ni dans ta connaissance, ou pour vérifier " + "un fait récent.", + "parameters": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Termes de recherche"} + }, + "required": ["query"], + }, + }, + }, + _web_search, + ), }