xia commited on
Commit ·
f3d2401
1
Parent(s): 80ee2b1
feat: agentic RAG multi-compétences + MLOps/LLMOps complet (38 tests)
Browse files- .dockerignore +12 -0
- .env.example +1 -1
- .github/workflows/azure.yml +50 -0
- .github/workflows/github-docker-cicd.yaml +70 -0
- CLAUDE.md +108 -0
- Dockerfile +14 -0
- app.py +79 -1
- requirements.txt +9 -4
- src/agents/agent.py +225 -1
- src/agents/tools.py +446 -1
- src/config.py +193 -0
- src/memory/memory.py +84 -1
- src/rag/hybrid_retriever.py +62 -0
- tests/__init__.py +0 -0
- tests/test_config.py +130 -0
- tests/test_memory.py +78 -0
- tests/test_structure.py +94 -0
- tests/test_tools.py +77 -0
.dockerignore
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.env
|
| 3 |
+
__pycache__
|
| 4 |
+
*.pyc
|
| 5 |
+
.ipynb_checkpoints
|
| 6 |
+
venv/
|
| 7 |
+
.venv/
|
| 8 |
+
data/raw/
|
| 9 |
+
notebooks/
|
| 10 |
+
docs/
|
| 11 |
+
*.md
|
| 12 |
+
!requirements.txt
|
.env.example
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
ANTHROPIC_API_KEY=your_anthropic_api_key_here
|
.github/workflows/azure.yml
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Deploy to Azure Container Apps
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [ "main" ]
|
| 6 |
+
|
| 7 |
+
env:
|
| 8 |
+
AZURE_RESOURCE_GROUP: catastrophes-climatiques-rg
|
| 9 |
+
ACR_NAME: ragcatastrophesacr
|
| 10 |
+
CONTAINER_APP_NAME: rag-catastrophes-app
|
| 11 |
+
CONTAINER_APP_ENV: rag-catastrophes-env
|
| 12 |
+
|
| 13 |
+
permissions:
|
| 14 |
+
contents: read
|
| 15 |
+
|
| 16 |
+
jobs:
|
| 17 |
+
deploy:
|
| 18 |
+
name: Deploy
|
| 19 |
+
runs-on: ubuntu-latest
|
| 20 |
+
environment: production
|
| 21 |
+
|
| 22 |
+
steps:
|
| 23 |
+
- name: Checkout
|
| 24 |
+
uses: actions/checkout@v4
|
| 25 |
+
|
| 26 |
+
- name: Login to Azure
|
| 27 |
+
uses: azure/login@v2
|
| 28 |
+
with:
|
| 29 |
+
creds: ${{ secrets.AZURE_CREDENTIALS }}
|
| 30 |
+
|
| 31 |
+
- name: Login to Azure Container Registry
|
| 32 |
+
run: |
|
| 33 |
+
az acr login --name ${{ env.ACR_NAME }}
|
| 34 |
+
|
| 35 |
+
- name: Build, tag, and push image to ACR
|
| 36 |
+
id: build-image
|
| 37 |
+
env:
|
| 38 |
+
IMAGE_TAG: ${{ github.sha }}
|
| 39 |
+
run: |
|
| 40 |
+
docker build --no-cache -t ${{ env.ACR_NAME }}.azurecr.io/rag-catastrophes:$IMAGE_TAG .
|
| 41 |
+
docker push ${{ env.ACR_NAME }}.azurecr.io/rag-catastrophes:$IMAGE_TAG
|
| 42 |
+
echo "image=${{ env.ACR_NAME }}.azurecr.io/rag-catastrophes:$IMAGE_TAG" >> $GITHUB_OUTPUT
|
| 43 |
+
|
| 44 |
+
- name: Deploy to Azure Container Apps
|
| 45 |
+
run: |
|
| 46 |
+
az containerapp update \
|
| 47 |
+
--name ${{ env.CONTAINER_APP_NAME }} \
|
| 48 |
+
--resource-group ${{ env.AZURE_RESOURCE_GROUP }} \
|
| 49 |
+
--image ${{ steps.build-image.outputs.image }} \
|
| 50 |
+
--set-env-vars "ANTHROPIC_API_KEY=secretref:anthropic-api-key"
|
.github/workflows/github-docker-cicd.yaml
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Github-Docker Hub MLOps pipeline - RAG Catastrophes Climatiques
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
env:
|
| 5 |
+
DOCKER_USER: ${{secrets.DOCKER_USER}}
|
| 6 |
+
DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}}
|
| 7 |
+
REPO_NAME: ${{secrets.REPO_NAME}}
|
| 8 |
+
|
| 9 |
+
on:
|
| 10 |
+
push:
|
| 11 |
+
branches:
|
| 12 |
+
- main
|
| 13 |
+
pull_request:
|
| 14 |
+
branches:
|
| 15 |
+
- main
|
| 16 |
+
|
| 17 |
+
jobs:
|
| 18 |
+
|
| 19 |
+
ci_pipeline:
|
| 20 |
+
runs-on: ubuntu-latest
|
| 21 |
+
|
| 22 |
+
steps:
|
| 23 |
+
- uses: actions/checkout@v4
|
| 24 |
+
with:
|
| 25 |
+
fetch-depth: 0
|
| 26 |
+
|
| 27 |
+
- name: Set up Python 3.11
|
| 28 |
+
uses: actions/setup-python@v5
|
| 29 |
+
with:
|
| 30 |
+
python-version: '3.11'
|
| 31 |
+
|
| 32 |
+
- name: Install dependencies
|
| 33 |
+
run: |
|
| 34 |
+
python -m pip install --upgrade pip
|
| 35 |
+
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
|
| 36 |
+
|
| 37 |
+
- name: Format
|
| 38 |
+
run: |
|
| 39 |
+
black --check src/ app.py tests/
|
| 40 |
+
|
| 41 |
+
- name: Lint
|
| 42 |
+
run: |
|
| 43 |
+
pylint --disable=R,C src/ app.py
|
| 44 |
+
|
| 45 |
+
- name: Test
|
| 46 |
+
run: |
|
| 47 |
+
python -m pytest -vv tests/
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
cd_pipeline:
|
| 51 |
+
|
| 52 |
+
runs-on: ubuntu-latest
|
| 53 |
+
needs: [ci_pipeline]
|
| 54 |
+
|
| 55 |
+
steps:
|
| 56 |
+
|
| 57 |
+
- uses: actions/checkout@v4
|
| 58 |
+
- name: docker login
|
| 59 |
+
run: |
|
| 60 |
+
docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
|
| 61 |
+
|
| 62 |
+
- name: Get current date
|
| 63 |
+
id: date
|
| 64 |
+
run: echo "date=$(date +'%Y-%m-%d--%H-%M-%S')" >> $GITHUB_OUTPUT
|
| 65 |
+
|
| 66 |
+
- name: Build the Docker image
|
| 67 |
+
run: docker build --no-cache . --file Dockerfile --tag $DOCKER_USER/$REPO_NAME:${{ steps.date.outputs.date }}
|
| 68 |
+
|
| 69 |
+
- name: Docker Push
|
| 70 |
+
run: docker push $DOCKER_USER/$REPO_NAME:${{ steps.date.outputs.date }}
|
CLAUDE.md
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CLAUDE.md — catastrophes-climatiques-rag
|
| 2 |
+
|
| 3 |
+
## Projet
|
| 4 |
+
|
| 5 |
+
Assistant intelligent Agentic RAG multi-compétences pour l'analyse des catastrophes climatiques.
|
| 6 |
+
Combine RAG sur corpus scientifique + agents météo/web/calcul + analyse de risque prédictive.
|
| 7 |
+
|
| 8 |
+
## Dataset / Corpus
|
| 9 |
+
|
| 10 |
+
- **Dossier** : `data/raw/` (ne jamais uploader dans le repo)
|
| 11 |
+
- **10 rapports PDF** : GIEC AR6, Copernicus 2023, EM-DAT 2023, NOAA, JRC, WMO, EU Floods Directive
|
| 12 |
+
- **Vector store** : `faiss_store/` (généré localement, ignoré par git)
|
| 13 |
+
|
| 14 |
+
## Stack technique
|
| 15 |
+
|
| 16 |
+
- **Langage** : Python 3.11
|
| 17 |
+
- **LLM** : Anthropic Claude (Haiku 4.5 / Sonnet 4.5 / Opus 4.6 selon l'agent)
|
| 18 |
+
- **Embeddings** : HuggingFace all-MiniLM-L6-v2 (local, gratuit)
|
| 19 |
+
- **Vector store** : FAISS
|
| 20 |
+
- **Framework** : LangChain + LangGraph
|
| 21 |
+
- **Recherche** : Hybride BM25 + Dense (EnsembleRetriever)
|
| 22 |
+
- **UI** : Chainlit
|
| 23 |
+
- **API météo** : OpenMeteo (gratuit, sans clé)
|
| 24 |
+
- **Recherche web** : DuckDuckGo
|
| 25 |
+
- **Conteneurisation** : Docker
|
| 26 |
+
- **CI/CD** : GitHub Actions (black + pylint + pytest + Docker Hub)
|
| 27 |
+
- **Déploiement** : Azure Container Apps (retex loan-default : rebuild from scratch, pas Render)
|
| 28 |
+
|
| 29 |
+
## Structure du projet
|
| 30 |
+
|
| 31 |
+
```
|
| 32 |
+
catastrophes-climatiques-rag/
|
| 33 |
+
├── data/
|
| 34 |
+
│ └── raw/ # PDFs du corpus (non versionnés)
|
| 35 |
+
├── src/
|
| 36 |
+
│ ├── config.py # Configuration centralisée et spécialisation LLM
|
| 37 |
+
│ ├── rag/
|
| 38 |
+
│ │ ├── loader.py # Chargement et découpage des PDFs
|
| 39 |
+
│ │ ├── embeddings.py # Création et persistance du vector store FAISS
|
| 40 |
+
│ │ └── retriever.py # Récupération MMR avec citations
|
| 41 |
+
│ ├── agents/
|
| 42 |
+
│ │ ├── tools.py # 6 outils : météo (3), web, calcul, RAG
|
| 43 |
+
│ │ └── agent.py # Agent agentic RAG multi-compétences (ReAct)
|
| 44 |
+
│ ├── memory/
|
| 45 |
+
│ │ └── memory.py # Mémoire conversationnelle (InMemoryChatMessageHistory)
|
| 46 |
+
│ └── router/
|
| 47 |
+
│ └── router.py # Routing conditionnel (mode linéaire)
|
| 48 |
+
├── tests/ # Tests pytest
|
| 49 |
+
├── notebooks/
|
| 50 |
+
│ ├── 01_test_rag.ipynb
|
| 51 |
+
│ ├── 02_test_agents.ipynb
|
| 52 |
+
│ ├── 03_demo_analyse_risque.ipynb
|
| 53 |
+
│ └── 04_comparatifs.ipynb
|
| 54 |
+
├── .github/workflows/ci.yml # Pipeline CI/CD
|
| 55 |
+
├── app.py # Point d'entrée Chainlit
|
| 56 |
+
├── Dockerfile
|
| 57 |
+
├── .env.example
|
| 58 |
+
├── requirements.txt
|
| 59 |
+
└── CLAUDE.md
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## Équipe et branches
|
| 63 |
+
|
| 64 |
+
| Branche | Membre | Responsabilité |
|
| 65 |
+
|---|---|---|
|
| 66 |
+
| `main` (P1) | Diego Merchán | Corpus & RAG (loader, embeddings, retriever) |
|
| 67 |
+
| `amorphya/agenttools` (P2) | Camille Koenig | Agents & Tools (tools.py, agent.py) |
|
| 68 |
+
| `feature/p3-router-ui` (P3) | Jayson Phan Nguyen | Router & UI Chainlit (router.py, app.py) |
|
| 69 |
+
| `feature/p4-memory-agent` (P4) | Xia Bizot | Mémoire, Agentic RAG, MLOps, Notebooks |
|
| 70 |
+
|
| 71 |
+
## Phases du projet
|
| 72 |
+
|
| 73 |
+
| Phase | Nom | Description |
|
| 74 |
+
|---|---|---|
|
| 75 |
+
| 0 | Setup | Initialisation du repo, structure, .env |
|
| 76 |
+
| 1 | RAG | Pipeline ingestion, embeddings FAISS, retriever MMR |
|
| 77 |
+
| 2 | Agents & Tools | 6 outils + agent LangGraph ReAct |
|
| 78 |
+
| 3 | Router & UI | Routing conditionnel + interface Chainlit streaming |
|
| 79 |
+
| 4 | Agentic RAG | Multi-agents, mémoire, analyse de risque, MLOps |
|
| 80 |
+
| 5 | Notebooks | Tests, métriques, démo analyse de risque |
|
| 81 |
+
| 6 | CI/CD | Docker, GitHub Actions, déploiement Azure |
|
| 82 |
+
| 7 | Soutenance | Présentation finale |
|
| 83 |
+
|
| 84 |
+
## Conventions de code
|
| 85 |
+
|
| 86 |
+
- **Variables, fonctions et commentaires** : en français
|
| 87 |
+
- **Commits** : Conventional Commits
|
| 88 |
+
- `feat:` nouvelle fonctionnalité
|
| 89 |
+
- `fix:` correction de bug
|
| 90 |
+
- `chore:` tâche technique (dépendances, config)
|
| 91 |
+
- `docs:` documentation
|
| 92 |
+
- **Ne jamais committer sur main directement**
|
| 93 |
+
- **Formatteur** : black
|
| 94 |
+
- **Linter** : pylint (--disable=R,C)
|
| 95 |
+
- **Tests** : pytest
|
| 96 |
+
|
| 97 |
+
## Règles de sécurité
|
| 98 |
+
|
| 99 |
+
- Ne **jamais** uploader les PDFs du corpus dans le repo
|
| 100 |
+
- Ne **jamais** hardcoder des credentials (clés API, tokens)
|
| 101 |
+
- Utiliser des variables d'environnement via `.env` (listé dans `.gitignore`)
|
| 102 |
+
- Le `.env.example` sert de modèle
|
| 103 |
+
|
| 104 |
+
## Retex projet loan-default-mlops
|
| 105 |
+
|
| 106 |
+
- Render ne rebuild pas l'image complète (incrémental) → solution non reproductible
|
| 107 |
+
- Sur ce projet : Docker build `--no-cache` systématique en CI/CD
|
| 108 |
+
- Déploiement Azure Container Apps au lieu de Render
|
Dockerfile
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
|
| 7 |
+
RUN pip install --no-cache-dir --upgrade pip && \
|
| 8 |
+
pip install --no-cache-dir -r requirements.txt
|
| 9 |
+
|
| 10 |
+
COPY . .
|
| 11 |
+
|
| 12 |
+
EXPOSE 8000
|
| 13 |
+
|
| 14 |
+
CMD ["chainlit", "run", "app.py", "--host", "0.0.0.0", "--port", "8000"]
|
app.py
CHANGED
|
@@ -1 +1,79 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Point d'entrée Chainlit — Interface conversationnelle.
|
| 3 |
+
Branche l'agent agentic RAG multi-compétences avec la mémoire conversationnelle.
|
| 4 |
+
LLMOps : monitoring tokens, estimation coût, logging.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
import chainlit as cl
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
|
| 12 |
+
from src.agents.agent import get_prompt_version, get_token_summary, run_agent
|
| 13 |
+
from src.memory.memory import add_exchange, get_session_history
|
| 14 |
+
|
| 15 |
+
load_dotenv()
|
| 16 |
+
logging.basicConfig(level=logging.INFO)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@cl.on_chat_start
|
| 21 |
+
async def on_chat_start():
|
| 22 |
+
"""Initialise une nouvelle session de chat."""
|
| 23 |
+
session_id = cl.user_session.get("id")
|
| 24 |
+
cl.user_session.set("session_id", session_id)
|
| 25 |
+
logger.info("Nouvelle session Chainlit : %s", session_id)
|
| 26 |
+
|
| 27 |
+
await cl.Message(
|
| 28 |
+
content=(
|
| 29 |
+
"**Assistant Catastrophes Climatiques**\n\n"
|
| 30 |
+
"Je peux :\n"
|
| 31 |
+
"- Répondre à vos questions sur le corpus scientifique "
|
| 32 |
+
"(GIEC, Copernicus, EM-DAT...)\n"
|
| 33 |
+
"- Consulter la météo actuelle, historique ou les prévisions\n"
|
| 34 |
+
"- Effectuer des calculs\n"
|
| 35 |
+
"- Rechercher des actualités sur le web\n"
|
| 36 |
+
"- Croiser toutes ces sources pour une analyse de risque\n\n"
|
| 37 |
+
"Comment puis-je vous aider ?"
|
| 38 |
+
)
|
| 39 |
+
).send()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@cl.on_message
|
| 43 |
+
async def on_message(message: cl.Message):
|
| 44 |
+
"""Traite un message utilisateur."""
|
| 45 |
+
session_id = cl.user_session.get("session_id")
|
| 46 |
+
question = message.content
|
| 47 |
+
|
| 48 |
+
# Récupérer l'historique de la session
|
| 49 |
+
history = get_session_history(session_id)
|
| 50 |
+
chat_history = history.messages
|
| 51 |
+
|
| 52 |
+
# Indicateur de chargement
|
| 53 |
+
msg = cl.Message(content="")
|
| 54 |
+
await msg.send()
|
| 55 |
+
|
| 56 |
+
# Exécuter l'agent avec l'historique
|
| 57 |
+
answer = run_agent(question, chat_history=chat_history)
|
| 58 |
+
|
| 59 |
+
# Mettre à jour la mémoire (avec fenêtre glissante)
|
| 60 |
+
add_exchange(session_id, question, answer)
|
| 61 |
+
|
| 62 |
+
# Afficher la réponse
|
| 63 |
+
msg.content = answer
|
| 64 |
+
await msg.update()
|
| 65 |
+
|
| 66 |
+
# Afficher le monitoring LLMOps
|
| 67 |
+
tokens = get_token_summary()
|
| 68 |
+
if tokens["total_tokens"] > 0:
|
| 69 |
+
cost = tokens.get("estimated_cost_usd", 0)
|
| 70 |
+
await cl.Message(
|
| 71 |
+
content=(
|
| 72 |
+
f"*Tokens : {tokens['total_tokens']} "
|
| 73 |
+
f"(in: {tokens['total_input_tokens']}, "
|
| 74 |
+
f"out: {tokens['total_output_tokens']}) — "
|
| 75 |
+
f"Coût estimé : ${cost:.4f} — "
|
| 76 |
+
f"Prompt {get_prompt_version()}*"
|
| 77 |
+
),
|
| 78 |
+
author="system",
|
| 79 |
+
).send()
|
requirements.txt
CHANGED
|
@@ -1,6 +1,10 @@
|
|
| 1 |
langchain
|
|
|
|
| 2 |
langchain-community
|
| 3 |
-
langchain-
|
|
|
|
|
|
|
|
|
|
| 4 |
faiss-cpu
|
| 5 |
sentence-transformers
|
| 6 |
chainlit
|
|
@@ -9,6 +13,7 @@ tiktoken
|
|
| 9 |
duckduckgo-search
|
| 10 |
requests
|
| 11 |
python-dotenv
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
| 1 |
langchain
|
| 2 |
+
langchain-anthropic
|
| 3 |
langchain-community
|
| 4 |
+
langchain-core
|
| 5 |
+
langchain-huggingface
|
| 6 |
+
langchain-text-splitters
|
| 7 |
+
langgraph
|
| 8 |
faiss-cpu
|
| 9 |
sentence-transformers
|
| 10 |
chainlit
|
|
|
|
| 13 |
duckduckgo-search
|
| 14 |
requests
|
| 15 |
python-dotenv
|
| 16 |
+
rank-bm25
|
| 17 |
+
black
|
| 18 |
+
pylint
|
| 19 |
+
pytest
|
src/agents/agent.py
CHANGED
|
@@ -1 +1,225 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Agent Agentic RAG multi-compétences avec orchestration LangGraph.
|
| 3 |
+
L'agent décide seul quels outils appeler et dans quel ordre,
|
| 4 |
+
y compris le RAG comme outil pour croiser données corpus + météo + web.
|
| 5 |
+
|
| 6 |
+
Architecture ReAct : Reason → Act → Observe → Repeat → Answer
|
| 7 |
+
LLMOps : logging, monitoring tokens, versioning prompt, fallback.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import logging
|
| 11 |
+
from typing import Annotated
|
| 12 |
+
|
| 13 |
+
from dotenv import load_dotenv
|
| 14 |
+
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage
|
| 15 |
+
from langgraph.graph import END, StateGraph
|
| 16 |
+
from langgraph.graph.message import add_messages
|
| 17 |
+
from langgraph.prebuilt import ToolNode
|
| 18 |
+
from typing_extensions import TypedDict
|
| 19 |
+
|
| 20 |
+
from src.agents.tools import ALL_TOOLS
|
| 21 |
+
from src.config import TOKEN_TRACKING, TokenCounter, get_fallback_llm, get_llm
|
| 22 |
+
|
| 23 |
+
load_dotenv()
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
# ── Prompt système de l'agent (versionné) ──────────────────────────────────
|
| 27 |
+
|
| 28 |
+
PROMPT_VERSION = "v1.0"
|
| 29 |
+
|
| 30 |
+
AGENT_SYSTEM_PROMPT = """Tu es un assistant expert en catastrophes climatiques et environnement.
|
| 31 |
+
Tu disposes de 6 outils que tu peux appeler librement et enchaîner dans l'ordre que tu veux :
|
| 32 |
+
|
| 33 |
+
1. **search_corpus** : chercher dans le corpus de rapports scientifiques (GIEC, Copernicus,
|
| 34 |
+
EM-DAT, NOAA, JRC, WMO). Utilise-le pour toute question sur les catastrophes climatiques,
|
| 35 |
+
les seuils de risque, les données historiques documentées.
|
| 36 |
+
|
| 37 |
+
2. **get_weather** : météo actuelle d'une ville (OpenMeteo, temps réel).
|
| 38 |
+
|
| 39 |
+
3. **get_historical_weather** : météo d'une date passée pour une ville donnée.
|
| 40 |
+
|
| 41 |
+
4. **get_forecast** : prévisions météo des 7 prochains jours pour une ville.
|
| 42 |
+
|
| 43 |
+
5. **web_search** : recherche web DuckDuckGo pour des informations récentes ou actualités.
|
| 44 |
+
|
| 45 |
+
6. **calculator** : calculs mathématiques (statistiques, conversions, projections).
|
| 46 |
+
|
| 47 |
+
Règles :
|
| 48 |
+
- Quand on te pose une question sur les catastrophes climatiques, cherche d'abord dans le
|
| 49 |
+
corpus (search_corpus), puis vérifie les conditions météo historiques ou actuelles des lieux
|
| 50 |
+
et dates concernés, et croise les deux pour donner une analyse complète.
|
| 51 |
+
- Pour une analyse de risque, consulte les prévisions météo (get_forecast), compare avec les
|
| 52 |
+
seuils critiques du corpus (search_corpus), et réfère-toi aux événements passés similaires.
|
| 53 |
+
- Cite toujours tes sources avec [Source: nom_fichier, Page: X] quand tu utilises le corpus.
|
| 54 |
+
- Réponds toujours en français, de façon claire et structurée.
|
| 55 |
+
- Si la question est une simple conversation (bonjour, merci, etc.), réponds directement
|
| 56 |
+
sans appeler d'outil.
|
| 57 |
+
- Retiens les informations données par l'utilisateur (prénom, contexte) pour les réutiliser
|
| 58 |
+
plus tard dans la conversation.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
# ── Compteur de tokens global ──────────────────────────────────────────────
|
| 62 |
+
|
| 63 |
+
token_counter = TokenCounter()
|
| 64 |
+
|
| 65 |
+
# ── État du graphe ─────────────────────────────────────────────────────────
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class AgentState(TypedDict):
|
| 69 |
+
messages: Annotated[list[BaseMessage], add_messages]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ── Construction du LLM (une seule fois) ──────────────────────────────────
|
| 73 |
+
|
| 74 |
+
_llm_with_tools = None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _get_llm_with_tools():
|
| 78 |
+
"""Retourne le LLM orchestrateur avec les outils bindés (singleton)."""
|
| 79 |
+
global _llm_with_tools
|
| 80 |
+
if _llm_with_tools is None:
|
| 81 |
+
try:
|
| 82 |
+
llm = get_llm("orchestrator")
|
| 83 |
+
logger.info("LLM orchestrateur initialisé (prompt %s)", PROMPT_VERSION)
|
| 84 |
+
except Exception as exc:
|
| 85 |
+
logger.warning("Fallback LLM activé : %s", exc)
|
| 86 |
+
llm = get_fallback_llm()
|
| 87 |
+
_llm_with_tools = llm.bind_tools(ALL_TOOLS)
|
| 88 |
+
return _llm_with_tools
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ── Nœuds du graphe ────────────────────────────────────────────────────────
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def call_model(state: AgentState) -> AgentState:
|
| 95 |
+
"""Appelle le LLM avec l'historique complet des messages."""
|
| 96 |
+
llm_with_tools = _get_llm_with_tools()
|
| 97 |
+
|
| 98 |
+
messages = state["messages"]
|
| 99 |
+
if not any(isinstance(m, SystemMessage) for m in messages):
|
| 100 |
+
messages = [SystemMessage(content=AGENT_SYSTEM_PROMPT)] + messages
|
| 101 |
+
|
| 102 |
+
response = llm_with_tools.invoke(messages)
|
| 103 |
+
|
| 104 |
+
# Monitoring des tokens (si activé)
|
| 105 |
+
if TOKEN_TRACKING and hasattr(response, "usage_metadata") and response.usage_metadata:
|
| 106 |
+
token_counter.log("orchestrator", response)
|
| 107 |
+
logger.debug(
|
| 108 |
+
"Tokens : in=%d, out=%d",
|
| 109 |
+
response.usage_metadata.get("input_tokens", 0),
|
| 110 |
+
response.usage_metadata.get("output_tokens", 0),
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
return {"messages": [response]}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def should_continue(state: AgentState) -> str:
|
| 117 |
+
"""Décide si on doit appeler un outil ou terminer."""
|
| 118 |
+
last_message = state["messages"][-1]
|
| 119 |
+
if isinstance(last_message, AIMessage) and last_message.tool_calls:
|
| 120 |
+
tool_names = [tc["name"] for tc in last_message.tool_calls]
|
| 121 |
+
logger.info("Outils appelés : %s", tool_names)
|
| 122 |
+
return "tools"
|
| 123 |
+
logger.info("Fin de la boucle ReAct — réponse finale")
|
| 124 |
+
return END
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# ── Construction du graphe LangGraph ──────────────────────────────────────
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def build_agent_graph() -> StateGraph:
|
| 131 |
+
"""Construit le graphe ReAct : call_model ↔ tools → END."""
|
| 132 |
+
tool_node = ToolNode(ALL_TOOLS)
|
| 133 |
+
|
| 134 |
+
graph = StateGraph(AgentState)
|
| 135 |
+
graph.add_node("call_model", call_model)
|
| 136 |
+
graph.add_node("tools", tool_node)
|
| 137 |
+
|
| 138 |
+
graph.set_entry_point("call_model")
|
| 139 |
+
graph.add_conditional_edges(
|
| 140 |
+
"call_model",
|
| 141 |
+
should_continue,
|
| 142 |
+
{"tools": "tools", END: END},
|
| 143 |
+
)
|
| 144 |
+
graph.add_edge("tools", "call_model")
|
| 145 |
+
|
| 146 |
+
return graph.compile()
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ── Interface publique ─────────────────────────────────────────────────────
|
| 150 |
+
|
| 151 |
+
_agent_graph = None
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def get_agent():
|
| 155 |
+
"""Retourne l'agent compilé (singleton)."""
|
| 156 |
+
global _agent_graph
|
| 157 |
+
if _agent_graph is None:
|
| 158 |
+
_agent_graph = build_agent_graph()
|
| 159 |
+
logger.info("Agent RAG compilé (prompt %s, %d outils)", PROMPT_VERSION, len(ALL_TOOLS))
|
| 160 |
+
return _agent_graph
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def run_agent(question: str, chat_history: list[BaseMessage] | None = None) -> str:
|
| 164 |
+
"""
|
| 165 |
+
Exécute l'agent sur une question et retourne la réponse finale.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
question: La question de l'utilisateur.
|
| 169 |
+
chat_history: Historique des messages précédents (optionnel).
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
Réponse textuelle finale de l'agent.
|
| 173 |
+
"""
|
| 174 |
+
logger.info("Question reçue : %s", question[:100])
|
| 175 |
+
agent = get_agent()
|
| 176 |
+
messages = (chat_history or []) + [HumanMessage(content=question)]
|
| 177 |
+
|
| 178 |
+
result = agent.invoke({"messages": messages})
|
| 179 |
+
|
| 180 |
+
for msg in reversed(result["messages"]):
|
| 181 |
+
if isinstance(msg, AIMessage) and not msg.tool_calls:
|
| 182 |
+
logger.info("Réponse générée (%d caractères)", len(msg.content))
|
| 183 |
+
return msg.content
|
| 184 |
+
|
| 185 |
+
logger.warning("L'agent n'a pas produit de réponse finale")
|
| 186 |
+
return "L'agent n'a pas pu produire de réponse."
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def get_token_summary() -> dict:
|
| 190 |
+
"""Retourne le résumé de consommation de tokens."""
|
| 191 |
+
return token_counter.summary()
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def get_prompt_version() -> str:
|
| 195 |
+
"""Retourne la version du prompt système."""
|
| 196 |
+
return PROMPT_VERSION
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def reset_token_counter():
|
| 200 |
+
"""Remet à zéro le compteur de tokens."""
|
| 201 |
+
token_counter.reset()
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# ── Test rapide ───────────────────────────────────────────────────────────
|
| 205 |
+
|
| 206 |
+
if __name__ == "__main__":
|
| 207 |
+
import sys
|
| 208 |
+
|
| 209 |
+
logging.basicConfig(level=logging.INFO)
|
| 210 |
+
|
| 211 |
+
questions = [
|
| 212 |
+
"Quelles catastrophes climatiques ont touché la Méditerranée en 2023 ?",
|
| 213 |
+
"Quel est le risque d'inondation à Marseille cette semaine ?",
|
| 214 |
+
"Quel temps faisait-il à Paris le 1er janvier 2023 ?",
|
| 215 |
+
"Combien font 3+7*2 ?",
|
| 216 |
+
"Bonjour, je suis Kamila",
|
| 217 |
+
]
|
| 218 |
+
|
| 219 |
+
question = sys.argv[1] if len(sys.argv) > 1 else questions[0]
|
| 220 |
+
print(f"\nQuestion : {question}")
|
| 221 |
+
print("-" * 60)
|
| 222 |
+
answer = run_agent(question)
|
| 223 |
+
print(f"Réponse :\n{answer}")
|
| 224 |
+
print(f"\nTokens : {get_token_summary()}")
|
| 225 |
+
print(f"Prompt version : {get_prompt_version()}")
|
src/agents/tools.py
CHANGED
|
@@ -1 +1,446 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Outils pour l'agent LangGraph Agentic RAG.
|
| 3 |
+
6 outils :
|
| 4 |
+
1. get_weather → météo actuelle (OpenMeteo)
|
| 5 |
+
2. get_historical_weather → météo historique (OpenMeteo Archive)
|
| 6 |
+
3. get_forecast → prévisions météo 7 jours (OpenMeteo)
|
| 7 |
+
4. web_search → recherche web (DuckDuckGo)
|
| 8 |
+
5. calculator → calculs mathématiques
|
| 9 |
+
6. search_corpus → recherche hybride dans le corpus RAG (BM25 + Dense)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import logging
|
| 13 |
+
import math
|
| 14 |
+
import re
|
| 15 |
+
|
| 16 |
+
import requests
|
| 17 |
+
from duckduckgo_search import DDGS
|
| 18 |
+
from langchain_core.tools import tool
|
| 19 |
+
|
| 20 |
+
from src.config import (
|
| 21 |
+
METEO_FORECAST_DAYS,
|
| 22 |
+
OPENMETEO_BASE_URL,
|
| 23 |
+
OPENMETEO_GEOCODING_URL,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
# ══════════════════════════════════════════════════════════════════
|
| 29 |
+
# UTILITAIRE — Géocodage (partagé entre les 3 outils météo)
|
| 30 |
+
# ══════════════════════════════════════════════════════════════════
|
| 31 |
+
|
| 32 |
+
_WMO_CODES: dict[int, str] = {
|
| 33 |
+
0: "Ciel dégagé",
|
| 34 |
+
1: "Principalement dégagé",
|
| 35 |
+
2: "Partiellement nuageux",
|
| 36 |
+
3: "Couvert",
|
| 37 |
+
45: "Brouillard",
|
| 38 |
+
48: "Brouillard givrant",
|
| 39 |
+
51: "Bruine légère",
|
| 40 |
+
53: "Bruine modérée",
|
| 41 |
+
55: "Bruine dense",
|
| 42 |
+
61: "Pluie légère",
|
| 43 |
+
63: "Pluie modérée",
|
| 44 |
+
65: "Pluie forte",
|
| 45 |
+
71: "Neige légère",
|
| 46 |
+
73: "Neige modérée",
|
| 47 |
+
75: "Neige forte",
|
| 48 |
+
77: "Grains de neige",
|
| 49 |
+
80: "Averses légères",
|
| 50 |
+
81: "Averses modérées",
|
| 51 |
+
82: "Averses violentes",
|
| 52 |
+
85: "Averses de neige",
|
| 53 |
+
86: "Averses de neige fortes",
|
| 54 |
+
95: "Orage",
|
| 55 |
+
96: "Orage avec grêle",
|
| 56 |
+
99: "Orage violent avec grêle",
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _geocode(city: str) -> tuple[float, float, str] | None:
|
| 61 |
+
"""Géocode une ville via l'API gratuite Open-Meteo geocoding."""
|
| 62 |
+
try:
|
| 63 |
+
resp = requests.get(
|
| 64 |
+
OPENMETEO_GEOCODING_URL,
|
| 65 |
+
params={"name": city, "count": 1, "language": "fr"},
|
| 66 |
+
timeout=10,
|
| 67 |
+
)
|
| 68 |
+
resp.raise_for_status()
|
| 69 |
+
results = resp.json().get("results", [])
|
| 70 |
+
if not results:
|
| 71 |
+
return None
|
| 72 |
+
r = results[0]
|
| 73 |
+
return r["latitude"], r["longitude"], r.get("name", city)
|
| 74 |
+
except Exception:
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# ══════════════════════════════════════════════════════════════════
|
| 79 |
+
# OUTIL 1 — Météo actuelle (OpenMeteo)
|
| 80 |
+
# ══════════════════════════════════════════════════════════════════
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@tool
|
| 84 |
+
def get_weather(city: str) -> str:
|
| 85 |
+
"""
|
| 86 |
+
Récupère la météo actuelle d'une ville via l'API OpenMeteo (gratuit, sans clé).
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
city: Nom de la ville (ex: "Paris", "Lyon", "Bogota")
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
Résumé météo : conditions, température, humidité, vent, précipitations.
|
| 93 |
+
"""
|
| 94 |
+
logger.info("Appel get_weather pour %s", city)
|
| 95 |
+
geo = _geocode(city)
|
| 96 |
+
if geo is None:
|
| 97 |
+
return f"Impossible de trouver la ville « {city} »."
|
| 98 |
+
|
| 99 |
+
lat, lon, city_name = geo
|
| 100 |
+
|
| 101 |
+
try:
|
| 102 |
+
params = {
|
| 103 |
+
"latitude": lat,
|
| 104 |
+
"longitude": lon,
|
| 105 |
+
"current": (
|
| 106 |
+
"temperature_2m,apparent_temperature,relative_humidity_2m,"
|
| 107 |
+
"weather_code,wind_speed_10m,precipitation,surface_pressure"
|
| 108 |
+
),
|
| 109 |
+
"timezone": "auto",
|
| 110 |
+
"forecast_days": 1,
|
| 111 |
+
}
|
| 112 |
+
resp = requests.get(
|
| 113 |
+
f"{OPENMETEO_BASE_URL}/forecast", params=params, timeout=10
|
| 114 |
+
)
|
| 115 |
+
resp.raise_for_status()
|
| 116 |
+
cur = resp.json()["current"]
|
| 117 |
+
except requests.RequestException as exc:
|
| 118 |
+
return f"Erreur API météo pour « {city_name} » : {exc}"
|
| 119 |
+
|
| 120 |
+
wmo = cur.get("weather_code", 0)
|
| 121 |
+
conditions = _WMO_CODES.get(wmo, f"Code WMO {wmo}")
|
| 122 |
+
|
| 123 |
+
return (
|
| 124 |
+
f"Météo actuelle à {city_name}\n"
|
| 125 |
+
f"- Conditions : {conditions}\n"
|
| 126 |
+
f"- Température : {cur.get('temperature_2m', 'N/A')} °C "
|
| 127 |
+
f"(ressenti {cur.get('apparent_temperature', 'N/A')} °C)\n"
|
| 128 |
+
f"- Humidité : {cur.get('relative_humidity_2m', 'N/A')} %\n"
|
| 129 |
+
f"- Vent : {cur.get('wind_speed_10m', 'N/A')} km/h\n"
|
| 130 |
+
f"- Précipitations: {cur.get('precipitation', 0)} mm\n"
|
| 131 |
+
f"- Pression : {cur.get('surface_pressure', 'N/A')} hPa"
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# ══════════════════════════════════════════════════════════════════
|
| 136 |
+
# OUTIL 2 — Météo historique (OpenMeteo Archive)
|
| 137 |
+
# ══════════════════════════════════════════════════════════════════
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@tool
|
| 141 |
+
def get_historical_weather(city: str, date: str) -> str:
|
| 142 |
+
"""
|
| 143 |
+
Récupère la météo historique d'une ville à une date passée via OpenMeteo Archive.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
city: Nom de la ville (ex: "Marseille", "Paris")
|
| 147 |
+
date: Date au format YYYY-MM-DD (ex: "2023-01-15")
|
| 148 |
+
|
| 149 |
+
Returns:
|
| 150 |
+
Résumé météo du jour : température min/max, précipitations, vent max.
|
| 151 |
+
"""
|
| 152 |
+
logger.info("Appel get_historical_weather pour %s le %s", city, date)
|
| 153 |
+
geo = _geocode(city)
|
| 154 |
+
if geo is None:
|
| 155 |
+
return f"Impossible de trouver la ville « {city} »."
|
| 156 |
+
|
| 157 |
+
lat, lon, city_name = geo
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
params = {
|
| 161 |
+
"latitude": lat,
|
| 162 |
+
"longitude": lon,
|
| 163 |
+
"start_date": date,
|
| 164 |
+
"end_date": date,
|
| 165 |
+
"daily": (
|
| 166 |
+
"temperature_2m_max,temperature_2m_min,"
|
| 167 |
+
"precipitation_sum,wind_speed_10m_max,weather_code"
|
| 168 |
+
),
|
| 169 |
+
"timezone": "auto",
|
| 170 |
+
}
|
| 171 |
+
resp = requests.get(
|
| 172 |
+
f"{OPENMETEO_BASE_URL}/archive", params=params, timeout=10
|
| 173 |
+
)
|
| 174 |
+
resp.raise_for_status()
|
| 175 |
+
daily = resp.json()["daily"]
|
| 176 |
+
except requests.RequestException as exc:
|
| 177 |
+
return f"Erreur API météo historique pour « {city_name} » le {date} : {exc}"
|
| 178 |
+
|
| 179 |
+
if not daily.get("time"):
|
| 180 |
+
return f"Aucune donnée disponible pour « {city_name} » le {date}."
|
| 181 |
+
|
| 182 |
+
wmo = daily.get("weather_code", [0])[0]
|
| 183 |
+
conditions = _WMO_CODES.get(wmo, f"Code WMO {wmo}")
|
| 184 |
+
|
| 185 |
+
return (
|
| 186 |
+
f"Météo historique à {city_name} le {date}\n"
|
| 187 |
+
f"- Conditions : {conditions}\n"
|
| 188 |
+
f"- Température max : {daily.get('temperature_2m_max', ['N/A'])[0]} °C\n"
|
| 189 |
+
f"- Température min : {daily.get('temperature_2m_min', ['N/A'])[0]} °C\n"
|
| 190 |
+
f"- Précipitations : {daily.get('precipitation_sum', [0])[0]} mm\n"
|
| 191 |
+
f"- Vent max : {daily.get('wind_speed_10m_max', ['N/A'])[0]} km/h"
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# ══════════════════════════════════════════════════════════════════
|
| 196 |
+
# OUTIL 3 — Prévisions météo 7 jours (OpenMeteo Forecast)
|
| 197 |
+
# ══════════════════════════════════════════════════════════════════
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@tool
|
| 201 |
+
def get_forecast(city: str) -> str:
|
| 202 |
+
"""
|
| 203 |
+
Récupère les prévisions météo des 7 prochains jours via OpenMeteo.
|
| 204 |
+
|
| 205 |
+
Args:
|
| 206 |
+
city: Nom de la ville (ex: "Lyon", "Marseille")
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
Prévisions jour par jour : température min/max, précipitations, vent.
|
| 210 |
+
"""
|
| 211 |
+
logger.info("Appel get_forecast pour %s", city)
|
| 212 |
+
geo = _geocode(city)
|
| 213 |
+
if geo is None:
|
| 214 |
+
return f"Impossible de trouver la ville « {city} »."
|
| 215 |
+
|
| 216 |
+
lat, lon, city_name = geo
|
| 217 |
+
|
| 218 |
+
try:
|
| 219 |
+
params = {
|
| 220 |
+
"latitude": lat,
|
| 221 |
+
"longitude": lon,
|
| 222 |
+
"daily": (
|
| 223 |
+
"temperature_2m_max,temperature_2m_min,"
|
| 224 |
+
"precipitation_sum,wind_speed_10m_max,weather_code"
|
| 225 |
+
),
|
| 226 |
+
"timezone": "auto",
|
| 227 |
+
"forecast_days": METEO_FORECAST_DAYS,
|
| 228 |
+
}
|
| 229 |
+
resp = requests.get(
|
| 230 |
+
f"{OPENMETEO_BASE_URL}/forecast", params=params, timeout=10
|
| 231 |
+
)
|
| 232 |
+
resp.raise_for_status()
|
| 233 |
+
daily = resp.json()["daily"]
|
| 234 |
+
except requests.RequestException as exc:
|
| 235 |
+
return f"Erreur API prévisions pour « {city_name} » : {exc}"
|
| 236 |
+
|
| 237 |
+
lines = [f"Prévisions météo à {city_name} ({METEO_FORECAST_DAYS} jours)\n"]
|
| 238 |
+
for i, day in enumerate(daily.get("time", [])):
|
| 239 |
+
wmo = daily.get("weather_code", [0])[i]
|
| 240 |
+
conditions = _WMO_CODES.get(wmo, f"Code WMO {wmo}")
|
| 241 |
+
t_max = daily.get("temperature_2m_max", ["N/A"])[i]
|
| 242 |
+
t_min = daily.get("temperature_2m_min", ["N/A"])[i]
|
| 243 |
+
precip = daily.get("precipitation_sum", [0])[i]
|
| 244 |
+
wind = daily.get("wind_speed_10m_max", ["N/A"])[i]
|
| 245 |
+
lines.append(
|
| 246 |
+
f" {day} : {conditions}, {t_min}-{t_max}°C, "
|
| 247 |
+
f"pluie {precip}mm, vent {wind}km/h"
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
return "\n".join(lines)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# ══════════════════════════════════════════════════════════════════
|
| 254 |
+
# OUTIL 4 — Recherche web (DuckDuckGo)
|
| 255 |
+
# ══════════════════════════════════════════════════════════════════
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@tool
|
| 259 |
+
def web_search(query: str, max_results: int = 5) -> str:
|
| 260 |
+
"""
|
| 261 |
+
Recherche web via DuckDuckGo pour des informations récentes.
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
query: Requête de recherche en langage naturel.
|
| 265 |
+
max_results: Nombre maximum de résultats (défaut : 5).
|
| 266 |
+
|
| 267 |
+
Returns:
|
| 268 |
+
Liste des résultats avec titre, URL et extrait.
|
| 269 |
+
"""
|
| 270 |
+
logger.info("Appel web_search pour : %s", query)
|
| 271 |
+
try:
|
| 272 |
+
with DDGS() as ddgs:
|
| 273 |
+
results = list(ddgs.text(query, max_results=max_results))
|
| 274 |
+
except Exception as exc:
|
| 275 |
+
return f"Erreur lors de la recherche web : {exc}"
|
| 276 |
+
|
| 277 |
+
if not results:
|
| 278 |
+
return f"Aucun résultat trouvé pour : « {query} »"
|
| 279 |
+
|
| 280 |
+
lines = [f"Résultats de recherche pour : « {query} »\n"]
|
| 281 |
+
for i, r in enumerate(results, 1):
|
| 282 |
+
title = r.get("title", "Sans titre")
|
| 283 |
+
href = r.get("href", "")
|
| 284 |
+
body = r.get("body", "")
|
| 285 |
+
snippet = body[:300].strip() + ("..." if len(body) > 300 else "")
|
| 286 |
+
lines.append(f"{i}. {title}\n {href}\n {snippet}\n")
|
| 287 |
+
|
| 288 |
+
return "\n".join(lines)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
# ══════════════════════════════════════════════════════════════════
|
| 292 |
+
# OUTIL 5 — Calculatrice (avec garde-fou regex)
|
| 293 |
+
# ══════════════════════════════════════════════════════════════════
|
| 294 |
+
|
| 295 |
+
_SAFE_GLOBALS = {
|
| 296 |
+
"__builtins__": {},
|
| 297 |
+
"abs": abs,
|
| 298 |
+
"round": round,
|
| 299 |
+
"min": min,
|
| 300 |
+
"max": max,
|
| 301 |
+
"sum": sum,
|
| 302 |
+
"pow": pow,
|
| 303 |
+
"int": int,
|
| 304 |
+
"float": float,
|
| 305 |
+
"sqrt": math.sqrt,
|
| 306 |
+
"log": math.log,
|
| 307 |
+
"log10": math.log10,
|
| 308 |
+
"log2": math.log2,
|
| 309 |
+
"exp": math.exp,
|
| 310 |
+
"sin": math.sin,
|
| 311 |
+
"cos": math.cos,
|
| 312 |
+
"tan": math.tan,
|
| 313 |
+
"asin": math.asin,
|
| 314 |
+
"acos": math.acos,
|
| 315 |
+
"atan": math.atan,
|
| 316 |
+
"ceil": math.ceil,
|
| 317 |
+
"floor": math.floor,
|
| 318 |
+
"pi": math.pi,
|
| 319 |
+
"e": math.e,
|
| 320 |
+
"inf": math.inf,
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
_SAFE_FUNC_NAMES = (
|
| 324 |
+
"sqrt|log|log10|log2|sin|cos|tan|asin|acos|atan|"
|
| 325 |
+
"exp|ceil|floor|abs|round|min|max|sum|pow|int|float|pi|inf"
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@tool
|
| 330 |
+
def calculator(expression: str) -> str:
|
| 331 |
+
"""
|
| 332 |
+
Évalue une expression mathématique et retourne le résultat.
|
| 333 |
+
|
| 334 |
+
Args:
|
| 335 |
+
expression: Expression mathématique (ex: "3+7*2", "sqrt(144)", "log(1000)/log(10)")
|
| 336 |
+
|
| 337 |
+
Returns:
|
| 338 |
+
Le résultat numérique ou un message d'erreur.
|
| 339 |
+
"""
|
| 340 |
+
logger.info("Appel calculator pour : %s", expression)
|
| 341 |
+
expr = expression.strip()
|
| 342 |
+
|
| 343 |
+
# Garde-fou : rejeter les caractères non mathématiques
|
| 344 |
+
cleaned = re.sub(_SAFE_FUNC_NAMES, "", expr)
|
| 345 |
+
if re.search(r"[a-zA-Z]{2,}", cleaned):
|
| 346 |
+
return (
|
| 347 |
+
f"Expression non reconnue : « {expression} ». "
|
| 348 |
+
"Utilisez uniquement des opérateurs mathématiques."
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
try:
|
| 352 |
+
result = eval(expr, _SAFE_GLOBALS, {}) # noqa: S307
|
| 353 |
+
if isinstance(result, float) and result.is_integer():
|
| 354 |
+
formatted = str(int(result))
|
| 355 |
+
elif isinstance(result, float):
|
| 356 |
+
formatted = f"{result:.6g}"
|
| 357 |
+
else:
|
| 358 |
+
formatted = str(result)
|
| 359 |
+
return f"{expression} = {formatted}"
|
| 360 |
+
except ZeroDivisionError:
|
| 361 |
+
return "Erreur : division par zéro."
|
| 362 |
+
except (ValueError, TypeError, OverflowError) as exc:
|
| 363 |
+
return f"Erreur de calcul : {exc}"
|
| 364 |
+
except Exception as exc:
|
| 365 |
+
return f"Expression invalide : {exc}"
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
# ══════════════════════════════════════════════════════════════════
|
| 369 |
+
# OUTIL 6 — Recherche hybride dans le corpus RAG (BM25 + Dense)
|
| 370 |
+
# ══════════════════════════════════════════════════════════════════
|
| 371 |
+
|
| 372 |
+
# Singleton pour ne pas recharger le vector store à chaque appel
|
| 373 |
+
_cached_vector_store = None
|
| 374 |
+
_cached_chunks = None
|
| 375 |
+
_cached_hybrid_retriever = None
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _get_hybrid_retriever():
|
| 379 |
+
"""Charge le retriever hybride une seule fois (singleton)."""
|
| 380 |
+
global _cached_vector_store, _cached_chunks, _cached_hybrid_retriever
|
| 381 |
+
|
| 382 |
+
if _cached_hybrid_retriever is not None:
|
| 383 |
+
return _cached_hybrid_retriever
|
| 384 |
+
|
| 385 |
+
from src.rag.embeddings import charger_vector_store
|
| 386 |
+
from src.rag.hybrid_retriever import creer_hybrid_retriever
|
| 387 |
+
from src.rag.loader import charger_et_decouper
|
| 388 |
+
|
| 389 |
+
_cached_vector_store = charger_vector_store()
|
| 390 |
+
if _cached_vector_store is None:
|
| 391 |
+
return None
|
| 392 |
+
|
| 393 |
+
_cached_chunks = charger_et_decouper("data/raw")
|
| 394 |
+
_cached_hybrid_retriever = creer_hybrid_retriever(
|
| 395 |
+
_cached_vector_store, _cached_chunks
|
| 396 |
+
)
|
| 397 |
+
logger.info("Retriever hybride BM25+Dense chargé (singleton)")
|
| 398 |
+
return _cached_hybrid_retriever
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
@tool
|
| 402 |
+
def search_corpus(question: str) -> str:
|
| 403 |
+
"""
|
| 404 |
+
Recherche hybride (BM25 + Dense) dans le corpus de documents climatiques
|
| 405 |
+
(PDFs GIEC, Copernicus, EM-DAT, etc.). Combine recherche sémantique et
|
| 406 |
+
recherche par mots-clés pour une meilleure couverture.
|
| 407 |
+
|
| 408 |
+
Args:
|
| 409 |
+
question: Question en langage naturel sur les catastrophes climatiques.
|
| 410 |
+
|
| 411 |
+
Returns:
|
| 412 |
+
Passages pertinents avec citations [Source: fichier, Page: X].
|
| 413 |
+
"""
|
| 414 |
+
logger.info("Appel search_corpus pour : %s", question)
|
| 415 |
+
|
| 416 |
+
retriever = _get_hybrid_retriever()
|
| 417 |
+
if retriever is None:
|
| 418 |
+
# Fallback sur le retriever dense seul
|
| 419 |
+
from src.rag.embeddings import charger_vector_store
|
| 420 |
+
from src.rag.retriever import creer_retriever, interroger_rag
|
| 421 |
+
|
| 422 |
+
vector_store = charger_vector_store()
|
| 423 |
+
if vector_store is None:
|
| 424 |
+
return "Le vector store n'est pas disponible. Lancez d'abord embeddings.py."
|
| 425 |
+
retriever_dense = creer_retriever(vector_store)
|
| 426 |
+
resultat = interroger_rag(retriever_dense, question)
|
| 427 |
+
return resultat["contexte"]
|
| 428 |
+
|
| 429 |
+
from src.rag.retriever import formater_contexte_avec_citations
|
| 430 |
+
|
| 431 |
+
docs = retriever.invoke(question)
|
| 432 |
+
return formater_contexte_avec_citations(docs)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
# ══════════════════════════════════════════════════════════════════
|
| 436 |
+
# Export : liste des outils pour l'agent LangGraph
|
| 437 |
+
# ══════════════════════════════════════════════════════════════════
|
| 438 |
+
|
| 439 |
+
ALL_TOOLS = [
|
| 440 |
+
get_weather,
|
| 441 |
+
get_historical_weather,
|
| 442 |
+
get_forecast,
|
| 443 |
+
web_search,
|
| 444 |
+
calculator,
|
| 445 |
+
search_corpus,
|
| 446 |
+
]
|
src/config.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Configuration centralisée du projet RAG Catastrophes Climatiques.
|
| 3 |
+
Hyperparamètres, spécialisation des LLM par agent, monitoring LLMOps.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
from langchain_anthropic import ChatAnthropic
|
| 8 |
+
|
| 9 |
+
# ── Modèles Anthropic disponibles ─────────────────────────────────────────
|
| 10 |
+
|
| 11 |
+
MODEL_HAIKU = "claude-haiku-4-5-20251001"
|
| 12 |
+
MODEL_SONNET = "claude-sonnet-4-20250514"
|
| 13 |
+
MODEL_OPUS = "claude-opus-4-20250514"
|
| 14 |
+
|
| 15 |
+
# ── Tarifs Anthropic ($ / 1M tokens) pour estimation de coût ──────────────
|
| 16 |
+
|
| 17 |
+
MODEL_PRICING = {
|
| 18 |
+
MODEL_HAIKU: {"input": 0.25, "output": 1.25},
|
| 19 |
+
MODEL_SONNET: {"input": 3.00, "output": 15.00},
|
| 20 |
+
MODEL_OPUS: {"input": 15.00, "output": 75.00},
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
# ── Configuration par type d'agent ────────────────────────────────────────
|
| 24 |
+
|
| 25 |
+
AGENT_CONFIGS = {
|
| 26 |
+
"orchestrator": {
|
| 27 |
+
"model": MODEL_HAIKU,
|
| 28 |
+
"temperature": 0,
|
| 29 |
+
"max_tokens": 512,
|
| 30 |
+
"description": "Décide quel sous-agent appeler selon la question",
|
| 31 |
+
},
|
| 32 |
+
"rag": {
|
| 33 |
+
"model": MODEL_SONNET,
|
| 34 |
+
"temperature": 0.2,
|
| 35 |
+
"max_tokens": 2048,
|
| 36 |
+
"description": "Répond en citant les sources du corpus climatique",
|
| 37 |
+
},
|
| 38 |
+
"meteo": {
|
| 39 |
+
"model": MODEL_HAIKU,
|
| 40 |
+
"temperature": 0,
|
| 41 |
+
"max_tokens": 1024,
|
| 42 |
+
"description": "Interprète les données météo (actuel/historique/prévisions)",
|
| 43 |
+
},
|
| 44 |
+
"web": {
|
| 45 |
+
"model": MODEL_HAIKU,
|
| 46 |
+
"temperature": 0.2,
|
| 47 |
+
"max_tokens": 1024,
|
| 48 |
+
"description": "Synthétise les actualités issues de la recherche web",
|
| 49 |
+
},
|
| 50 |
+
"analyst": {
|
| 51 |
+
"model": MODEL_OPUS,
|
| 52 |
+
"temperature": 0.5,
|
| 53 |
+
"max_tokens": 4096,
|
| 54 |
+
"description": "Croise les données pour produire l'analyse de risque",
|
| 55 |
+
},
|
| 56 |
+
"chat": {
|
| 57 |
+
"model": MODEL_HAIKU,
|
| 58 |
+
"temperature": 0.7,
|
| 59 |
+
"max_tokens": 1024,
|
| 60 |
+
"description": "Conversation simple, salutations, hors-sujet",
|
| 61 |
+
},
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
# ── Modèle de fallback ────────────────────────────────────────────────────
|
| 65 |
+
|
| 66 |
+
FALLBACK_MODEL = MODEL_HAIKU
|
| 67 |
+
|
| 68 |
+
# ── Paramètres du chunking ────────────────────────────────────────────────
|
| 69 |
+
|
| 70 |
+
CHUNK_SIZE = 1500
|
| 71 |
+
CHUNK_OVERLAP = 150
|
| 72 |
+
|
| 73 |
+
# ── Paramètres des embeddings ─────────────────────────────────────────────
|
| 74 |
+
|
| 75 |
+
EMBEDDING_MODEL = "all-MiniLM-L6-v2"
|
| 76 |
+
FAISS_STORE_PATH = "faiss_store"
|
| 77 |
+
|
| 78 |
+
# ── Paramètres du retriever ───────────────────────────────────────────────
|
| 79 |
+
|
| 80 |
+
RETRIEVER_K = 4
|
| 81 |
+
RETRIEVER_FETCH_K = 10
|
| 82 |
+
RETRIEVER_SEARCH_TYPE = "mmr"
|
| 83 |
+
|
| 84 |
+
# ── Recherche hybride BM25 + Dense ────────────────────────────────────────
|
| 85 |
+
|
| 86 |
+
BM25_WEIGHT = 0.5
|
| 87 |
+
DENSE_WEIGHT = 0.5
|
| 88 |
+
|
| 89 |
+
# ── Mémoire conversationnelle ─────────────────────────────────────────────
|
| 90 |
+
|
| 91 |
+
MEMORY_WINDOW_SIZE = 20
|
| 92 |
+
|
| 93 |
+
# ── Monitoring LLMOps ─────────────────────────────────────────────────────
|
| 94 |
+
|
| 95 |
+
TOKEN_TRACKING = True
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class TokenCounter:
|
| 99 |
+
"""Compteur de tokens par agent, par session, avec estimation de coût."""
|
| 100 |
+
|
| 101 |
+
def __init__(self):
|
| 102 |
+
self.total_input = 0
|
| 103 |
+
self.total_output = 0
|
| 104 |
+
self.calls_by_agent = {}
|
| 105 |
+
self.tokens_by_agent = {}
|
| 106 |
+
|
| 107 |
+
def log(self, agent_type: str, response):
|
| 108 |
+
usage = response.usage_metadata
|
| 109 |
+
input_tokens = usage["input_tokens"]
|
| 110 |
+
output_tokens = usage["output_tokens"]
|
| 111 |
+
|
| 112 |
+
self.total_input += input_tokens
|
| 113 |
+
self.total_output += output_tokens
|
| 114 |
+
self.calls_by_agent[agent_type] = (
|
| 115 |
+
self.calls_by_agent.get(agent_type, 0) + 1
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if agent_type not in self.tokens_by_agent:
|
| 119 |
+
self.tokens_by_agent[agent_type] = {"input": 0, "output": 0}
|
| 120 |
+
self.tokens_by_agent[agent_type]["input"] += input_tokens
|
| 121 |
+
self.tokens_by_agent[agent_type]["output"] += output_tokens
|
| 122 |
+
|
| 123 |
+
def estimate_cost(self) -> float:
|
| 124 |
+
"""Estime le coût total en $ basé sur les tarifs Anthropic."""
|
| 125 |
+
total_cost = 0.0
|
| 126 |
+
for agent_type, tokens in self.tokens_by_agent.items():
|
| 127 |
+
model = AGENT_CONFIGS.get(agent_type, {}).get("model", MODEL_HAIKU)
|
| 128 |
+
pricing = MODEL_PRICING.get(model, MODEL_PRICING[MODEL_HAIKU])
|
| 129 |
+
cost_input = (tokens["input"] / 1_000_000) * pricing["input"]
|
| 130 |
+
cost_output = (tokens["output"] / 1_000_000) * pricing["output"]
|
| 131 |
+
total_cost += cost_input + cost_output
|
| 132 |
+
return total_cost
|
| 133 |
+
|
| 134 |
+
def summary(self) -> dict:
|
| 135 |
+
return {
|
| 136 |
+
"total_input_tokens": self.total_input,
|
| 137 |
+
"total_output_tokens": self.total_output,
|
| 138 |
+
"total_tokens": self.total_input + self.total_output,
|
| 139 |
+
"calls_by_agent": self.calls_by_agent,
|
| 140 |
+
"tokens_by_agent": self.tokens_by_agent,
|
| 141 |
+
"estimated_cost_usd": self.estimate_cost(),
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
def reset(self):
|
| 145 |
+
self.total_input = 0
|
| 146 |
+
self.total_output = 0
|
| 147 |
+
self.calls_by_agent = {}
|
| 148 |
+
self.tokens_by_agent = {}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# ── API météo OpenMeteo ───────────────────────────────────────────────────
|
| 152 |
+
|
| 153 |
+
OPENMETEO_BASE_URL = "https://api.open-meteo.com/v1"
|
| 154 |
+
OPENMETEO_GEOCODING_URL = "https://geocoding-api.open-meteo.com/v1/search"
|
| 155 |
+
METEO_FORECAST_DAYS = 7
|
| 156 |
+
|
| 157 |
+
# ── Chainlit ──────────────────────────────────────────────────────────────
|
| 158 |
+
|
| 159 |
+
CHAINLIT_HOST = "0.0.0.0"
|
| 160 |
+
CHAINLIT_PORT = 8000
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ── Construction du LLM ───────────────────────────────────────────────────
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def get_llm(agent_type: str) -> ChatAnthropic:
|
| 167 |
+
"""Retourne un LLM configuré pour un type d'agent donné."""
|
| 168 |
+
if agent_type not in AGENT_CONFIGS:
|
| 169 |
+
raise ValueError(
|
| 170 |
+
f"Type d'agent inconnu : '{agent_type}'. "
|
| 171 |
+
f"Disponibles : {list(AGENT_CONFIGS.keys())}"
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
if not os.getenv("ANTHROPIC_API_KEY"):
|
| 175 |
+
raise EnvironmentError(
|
| 176 |
+
"ANTHROPIC_API_KEY manquante. Ajoutez-la dans votre fichier .env"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
config = AGENT_CONFIGS[agent_type]
|
| 180 |
+
return ChatAnthropic(
|
| 181 |
+
model=config["model"],
|
| 182 |
+
temperature=config["temperature"],
|
| 183 |
+
max_tokens=config["max_tokens"],
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def get_fallback_llm() -> ChatAnthropic:
|
| 188 |
+
"""LLM de secours en cas d'échec du modèle principal."""
|
| 189 |
+
return ChatAnthropic(
|
| 190 |
+
model=FALLBACK_MODEL,
|
| 191 |
+
temperature=0.2,
|
| 192 |
+
max_tokens=1024,
|
| 193 |
+
)
|
src/memory/memory.py
CHANGED
|
@@ -1 +1,84 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Mémoire conversationnelle pour le suivi du contexte.
|
| 3 |
+
Pattern aligné sur le TP du prof (langchain.ipynb) :
|
| 4 |
+
InMemoryChatMessageHistory + RunnableWithMessageHistory.
|
| 5 |
+
Fenêtre glissante : tronque les messages anciens au-delà de MEMORY_WINDOW_SIZE.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
from langchain_core.chat_history import InMemoryChatMessageHistory
|
| 11 |
+
from langchain_core.runnables.history import RunnableWithMessageHistory
|
| 12 |
+
|
| 13 |
+
from src.config import MEMORY_WINDOW_SIZE
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
# ── Stockage des sessions en mémoire ──────────────────────────────────────
|
| 18 |
+
|
| 19 |
+
_store = {}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_session_history(session_id: str) -> InMemoryChatMessageHistory:
|
| 23 |
+
"""
|
| 24 |
+
Retourne l'historique d'une session.
|
| 25 |
+
Crée une nouvelle session si elle n'existe pas.
|
| 26 |
+
"""
|
| 27 |
+
if session_id not in _store:
|
| 28 |
+
_store[session_id] = InMemoryChatMessageHistory()
|
| 29 |
+
logger.info("Nouvelle session créée : %s", session_id)
|
| 30 |
+
return _store[session_id]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def add_exchange(session_id: str, question: str, reponse: str):
|
| 34 |
+
"""
|
| 35 |
+
Ajoute un échange utilisateur/assistant et applique la fenêtre glissante.
|
| 36 |
+
Si l'historique dépasse MEMORY_WINDOW_SIZE paires, supprime les plus anciens.
|
| 37 |
+
"""
|
| 38 |
+
history = get_session_history(session_id)
|
| 39 |
+
history.add_user_message(question)
|
| 40 |
+
history.add_ai_message(reponse)
|
| 41 |
+
|
| 42 |
+
# Fenêtre glissante : garder les N dernières paires (2 messages par paire)
|
| 43 |
+
max_messages = MEMORY_WINDOW_SIZE * 2
|
| 44 |
+
if len(history.messages) > max_messages:
|
| 45 |
+
overflow = len(history.messages) - max_messages
|
| 46 |
+
history.messages = history.messages[overflow:]
|
| 47 |
+
logger.debug(
|
| 48 |
+
"Session %s : troncature de %d messages (fenêtre %d)",
|
| 49 |
+
session_id,
|
| 50 |
+
overflow,
|
| 51 |
+
MEMORY_WINDOW_SIZE,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def wrap_chain_with_memory(chain):
|
| 56 |
+
"""
|
| 57 |
+
Enveloppe une chaîne LangChain avec la mémoire conversationnelle.
|
| 58 |
+
Permet au LLM de voir l'historique des échanges précédents.
|
| 59 |
+
"""
|
| 60 |
+
return RunnableWithMessageHistory(
|
| 61 |
+
chain,
|
| 62 |
+
get_session_history,
|
| 63 |
+
input_messages_key="input",
|
| 64 |
+
history_messages_key="history",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def clear_session(session_id: str):
|
| 69 |
+
"""Efface l'historique d'une session."""
|
| 70 |
+
if session_id in _store:
|
| 71 |
+
_store[session_id].clear()
|
| 72 |
+
logger.info("Session %s effacée", session_id)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def list_sessions() -> list[str]:
|
| 76 |
+
"""Liste toutes les sessions actives."""
|
| 77 |
+
return list(_store.keys())
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_session_message_count(session_id: str) -> int:
|
| 81 |
+
"""Retourne le nombre de messages dans une session."""
|
| 82 |
+
if session_id not in _store:
|
| 83 |
+
return 0
|
| 84 |
+
return len(_store[session_id].messages)
|
src/rag/hybrid_retriever.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Retriever hybride BM25 + Dense (EnsembleRetriever).
|
| 3 |
+
Combine la recherche sémantique (FAISS/MMR) avec la recherche par mots-clés (BM25/TF-IDF).
|
| 4 |
+
Référence : slide 11 du cours — "Hybrid: BM25 + Dense + Filters".
|
| 5 |
+
|
| 6 |
+
Ne modifie pas le retriever.py de Diego, l'enveloppe par-dessus.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from langchain.retrievers import EnsembleRetriever
|
| 10 |
+
from langchain_community.retrievers import BM25Retriever
|
| 11 |
+
|
| 12 |
+
from src.config import BM25_WEIGHT, DENSE_WEIGHT, RETRIEVER_K
|
| 13 |
+
from src.rag.retriever import creer_retriever
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def creer_hybrid_retriever(vector_store, chunks: list) -> EnsembleRetriever:
|
| 17 |
+
"""
|
| 18 |
+
Crée un retriever hybride combinant :
|
| 19 |
+
- Dense (FAISS/MMR) : comprend le sens sémantique des questions
|
| 20 |
+
- BM25 (TF-IDF) : trouve les correspondances exactes de mots-clés
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
vector_store: Le vector store FAISS chargé.
|
| 24 |
+
chunks: La liste des documents LangChain (nécessaire pour BM25).
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
EnsembleRetriever pondéré BM25 + Dense.
|
| 28 |
+
"""
|
| 29 |
+
# Retriever dense (celui de Diego, inchangé)
|
| 30 |
+
dense_retriever = creer_retriever(vector_store)
|
| 31 |
+
|
| 32 |
+
# Retriever BM25 (recherche par mots-clés)
|
| 33 |
+
bm25_retriever = BM25Retriever.from_documents(chunks, k=RETRIEVER_K)
|
| 34 |
+
|
| 35 |
+
# Combinaison pondérée
|
| 36 |
+
hybrid_retriever = EnsembleRetriever(
|
| 37 |
+
retrievers=[bm25_retriever, dense_retriever],
|
| 38 |
+
weights=[BM25_WEIGHT, DENSE_WEIGHT],
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
return hybrid_retriever
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
from src.rag.embeddings import charger_vector_store
|
| 46 |
+
from src.rag.loader import charger_et_decouper
|
| 47 |
+
from src.rag.retriever import formater_contexte_avec_citations
|
| 48 |
+
|
| 49 |
+
vector_store = charger_vector_store()
|
| 50 |
+
if vector_store is None:
|
| 51 |
+
print("Vector store introuvable. Lancez d'abord embeddings.py.")
|
| 52 |
+
else:
|
| 53 |
+
chunks = charger_et_decouper("data/raw")
|
| 54 |
+
hybrid = creer_hybrid_retriever(vector_store, chunks)
|
| 55 |
+
|
| 56 |
+
question = "Quelles sont les recommandations du rapport CELEX sur les inondations ?"
|
| 57 |
+
print(f"\nQuestion : {question}\n")
|
| 58 |
+
|
| 59 |
+
docs = hybrid.invoke(question)
|
| 60 |
+
contexte = formater_contexte_avec_citations(docs)
|
| 61 |
+
print("--- Contexte hybride BM25 + Dense ---\n")
|
| 62 |
+
print(contexte)
|
tests/__init__.py
ADDED
|
File without changes
|
tests/test_config.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests pour la configuration centralisée."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def test_agent_configs_complete():
|
| 8 |
+
"""Vérifie que tous les types d'agents sont configurés."""
|
| 9 |
+
from src.config import AGENT_CONFIGS
|
| 10 |
+
|
| 11 |
+
types_attendus = ["orchestrator", "rag", "meteo", "web", "analyst", "chat"]
|
| 12 |
+
for agent_type in types_attendus:
|
| 13 |
+
assert agent_type in AGENT_CONFIGS, f"Agent '{agent_type}' manquant"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_agent_configs_have_required_keys():
|
| 17 |
+
"""Vérifie que chaque config d'agent contient les clés requises."""
|
| 18 |
+
from src.config import AGENT_CONFIGS
|
| 19 |
+
|
| 20 |
+
cles_requises = ["model", "temperature", "max_tokens", "description"]
|
| 21 |
+
for agent_type, config in AGENT_CONFIGS.items():
|
| 22 |
+
for cle in cles_requises:
|
| 23 |
+
assert cle in config, f"Clé '{cle}' manquante pour l'agent '{agent_type}'"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_temperature_ranges():
|
| 27 |
+
"""Vérifie que les températures sont dans les bornes valides."""
|
| 28 |
+
from src.config import AGENT_CONFIGS
|
| 29 |
+
|
| 30 |
+
for agent_type, config in AGENT_CONFIGS.items():
|
| 31 |
+
temp = config["temperature"]
|
| 32 |
+
assert 0 <= temp <= 1, (
|
| 33 |
+
f"Température {temp} hors bornes pour '{agent_type}'"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_max_tokens_positive():
|
| 38 |
+
"""Vérifie que les max_tokens sont positifs."""
|
| 39 |
+
from src.config import AGENT_CONFIGS
|
| 40 |
+
|
| 41 |
+
for agent_type, config in AGENT_CONFIGS.items():
|
| 42 |
+
assert config["max_tokens"] > 0, (
|
| 43 |
+
f"max_tokens négatif pour '{agent_type}'"
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_get_llm_invalid_type():
|
| 48 |
+
"""Vérifie que get_llm lève une erreur pour un type inconnu."""
|
| 49 |
+
from src.config import get_llm
|
| 50 |
+
|
| 51 |
+
with pytest.raises(ValueError):
|
| 52 |
+
get_llm("type_inexistant")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_get_llm_missing_api_key():
|
| 56 |
+
"""Vérifie que get_llm lève une erreur sans clé API."""
|
| 57 |
+
from src.config import get_llm
|
| 58 |
+
|
| 59 |
+
old_key = os.environ.pop("ANTHROPIC_API_KEY", None)
|
| 60 |
+
try:
|
| 61 |
+
with pytest.raises(EnvironmentError):
|
| 62 |
+
get_llm("chat")
|
| 63 |
+
finally:
|
| 64 |
+
if old_key:
|
| 65 |
+
os.environ["ANTHROPIC_API_KEY"] = old_key
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_token_counter():
|
| 69 |
+
"""Vérifie le fonctionnement du compteur de tokens."""
|
| 70 |
+
from src.config import TokenCounter
|
| 71 |
+
|
| 72 |
+
counter = TokenCounter()
|
| 73 |
+
assert counter.total_input == 0
|
| 74 |
+
assert counter.total_output == 0
|
| 75 |
+
|
| 76 |
+
class FakeResponse:
|
| 77 |
+
usage_metadata = {"input_tokens": 100, "output_tokens": 50}
|
| 78 |
+
|
| 79 |
+
counter.log("rag", FakeResponse())
|
| 80 |
+
summary = counter.summary()
|
| 81 |
+
assert summary["total_input_tokens"] == 100
|
| 82 |
+
assert summary["total_output_tokens"] == 50
|
| 83 |
+
assert summary["total_tokens"] == 150
|
| 84 |
+
assert summary["calls_by_agent"]["rag"] == 1
|
| 85 |
+
assert summary["tokens_by_agent"]["rag"]["input"] == 100
|
| 86 |
+
assert summary["tokens_by_agent"]["rag"]["output"] == 50
|
| 87 |
+
|
| 88 |
+
counter.reset()
|
| 89 |
+
assert counter.total_input == 0
|
| 90 |
+
assert counter.tokens_by_agent == {}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_token_counter_cost_estimation():
|
| 94 |
+
"""Vérifie l'estimation de coût."""
|
| 95 |
+
from src.config import TokenCounter
|
| 96 |
+
|
| 97 |
+
counter = TokenCounter()
|
| 98 |
+
|
| 99 |
+
class FakeResponse:
|
| 100 |
+
usage_metadata = {"input_tokens": 1_000_000, "output_tokens": 1_000_000}
|
| 101 |
+
|
| 102 |
+
counter.log("orchestrator", FakeResponse())
|
| 103 |
+
summary = counter.summary()
|
| 104 |
+
# Haiku : input $0.25/M + output $1.25/M = $1.50
|
| 105 |
+
assert summary["estimated_cost_usd"] == pytest.approx(1.50, rel=0.01)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_model_pricing_complete():
|
| 109 |
+
"""Vérifie que tous les modèles ont un tarif."""
|
| 110 |
+
from src.config import MODEL_HAIKU, MODEL_OPUS, MODEL_PRICING, MODEL_SONNET
|
| 111 |
+
|
| 112 |
+
assert MODEL_HAIKU in MODEL_PRICING
|
| 113 |
+
assert MODEL_SONNET in MODEL_PRICING
|
| 114 |
+
assert MODEL_OPUS in MODEL_PRICING
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_retriever_params():
|
| 118 |
+
"""Vérifie les paramètres du retriever."""
|
| 119 |
+
from src.config import RETRIEVER_FETCH_K, RETRIEVER_K
|
| 120 |
+
|
| 121 |
+
assert RETRIEVER_K > 0
|
| 122 |
+
assert RETRIEVER_FETCH_K >= RETRIEVER_K
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_memory_window_size():
|
| 126 |
+
"""Vérifie la taille de la fenêtre mémoire."""
|
| 127 |
+
from src.config import MEMORY_WINDOW_SIZE
|
| 128 |
+
|
| 129 |
+
assert MEMORY_WINDOW_SIZE > 0
|
| 130 |
+
assert MEMORY_WINDOW_SIZE == 20
|
tests/test_memory.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests pour la mémoire conversationnelle."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def test_get_session_history_creates_new():
|
| 5 |
+
"""Vérifie qu'une nouvelle session est créée automatiquement."""
|
| 6 |
+
from src.memory.memory import get_session_history
|
| 7 |
+
|
| 8 |
+
history = get_session_history("test_session_new")
|
| 9 |
+
assert history is not None
|
| 10 |
+
assert len(history.messages) == 0
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_get_session_history_returns_same():
|
| 14 |
+
"""Vérifie qu'on récupère la même session."""
|
| 15 |
+
from src.memory.memory import get_session_history
|
| 16 |
+
|
| 17 |
+
h1 = get_session_history("test_session_same")
|
| 18 |
+
h2 = get_session_history("test_session_same")
|
| 19 |
+
assert h1 is h2
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_add_exchange():
|
| 23 |
+
"""Vérifie l'ajout d'échanges via add_exchange."""
|
| 24 |
+
from src.memory.memory import add_exchange, get_session_history
|
| 25 |
+
|
| 26 |
+
add_exchange("test_exchange", "Je suis Kamila", "Bonjour Kamila !")
|
| 27 |
+
history = get_session_history("test_exchange")
|
| 28 |
+
assert len(history.messages) == 2
|
| 29 |
+
assert history.messages[0].content == "Je suis Kamila"
|
| 30 |
+
assert history.messages[1].content == "Bonjour Kamila !"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_memory_window_truncation():
|
| 34 |
+
"""Vérifie que la fenêtre glissante tronque les vieux messages."""
|
| 35 |
+
from src.config import MEMORY_WINDOW_SIZE
|
| 36 |
+
from src.memory.memory import add_exchange, get_session_history
|
| 37 |
+
|
| 38 |
+
session_id = "test_truncation"
|
| 39 |
+
# Ajouter plus que MEMORY_WINDOW_SIZE échanges
|
| 40 |
+
for i in range(MEMORY_WINDOW_SIZE + 5):
|
| 41 |
+
add_exchange(session_id, f"question_{i}", f"reponse_{i}")
|
| 42 |
+
|
| 43 |
+
history = get_session_history(session_id)
|
| 44 |
+
# Doit contenir exactement MEMORY_WINDOW_SIZE * 2 messages
|
| 45 |
+
assert len(history.messages) == MEMORY_WINDOW_SIZE * 2
|
| 46 |
+
|
| 47 |
+
# Le premier message doit être question_5 (les 5 premiers supprimés)
|
| 48 |
+
assert history.messages[0].content == "question_5"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_clear_session():
|
| 52 |
+
"""Vérifie la suppression d'une session."""
|
| 53 |
+
from src.memory.memory import add_exchange, clear_session, get_session_history
|
| 54 |
+
|
| 55 |
+
add_exchange("test_clear", "test", "réponse")
|
| 56 |
+
clear_session("test_clear")
|
| 57 |
+
assert len(get_session_history("test_clear").messages) == 0
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_list_sessions():
|
| 61 |
+
"""Vérifie le listing des sessions."""
|
| 62 |
+
from src.memory.memory import get_session_history, list_sessions
|
| 63 |
+
|
| 64 |
+
get_session_history("test_list_a")
|
| 65 |
+
get_session_history("test_list_b")
|
| 66 |
+
sessions = list_sessions()
|
| 67 |
+
assert "test_list_a" in sessions
|
| 68 |
+
assert "test_list_b" in sessions
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_get_session_message_count():
|
| 72 |
+
"""Vérifie le comptage des messages."""
|
| 73 |
+
from src.memory.memory import add_exchange, get_session_message_count
|
| 74 |
+
|
| 75 |
+
add_exchange("test_count_v2", "un", "deux")
|
| 76 |
+
add_exchange("test_count_v2", "trois", "quatre")
|
| 77 |
+
assert get_session_message_count("test_count_v2") == 4
|
| 78 |
+
assert get_session_message_count("inexistant") == 0
|
tests/test_structure.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests de structure du projet (inspiré de loan-default-mlops)."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
ROOT = Path(__file__).parent.parent
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_dockerfile_exists():
|
| 10 |
+
"""Vérifie que le Dockerfile existe."""
|
| 11 |
+
assert (ROOT / "Dockerfile").exists()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_dockerfile_contenu():
|
| 15 |
+
"""Vérifie que le Dockerfile contient les éléments essentiels."""
|
| 16 |
+
content = (ROOT / "Dockerfile").read_text()
|
| 17 |
+
assert "FROM python" in content
|
| 18 |
+
assert "requirements.txt" in content
|
| 19 |
+
assert "--no-cache-dir" in content
|
| 20 |
+
assert "chainlit" in content
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_requirements_exists():
|
| 24 |
+
"""Vérifie que requirements.txt existe."""
|
| 25 |
+
assert (ROOT / "requirements.txt").exists()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_requirements_contenu():
|
| 29 |
+
"""Vérifie les dépendances essentielles."""
|
| 30 |
+
content = (ROOT / "requirements.txt").read_text()
|
| 31 |
+
assert "langchain-anthropic" in content
|
| 32 |
+
assert "langgraph" in content
|
| 33 |
+
assert "chainlit" in content
|
| 34 |
+
assert "faiss-cpu" in content
|
| 35 |
+
assert "rank-bm25" in content
|
| 36 |
+
assert "langchain-groq" not in content # on a migré vers Anthropic
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_app_py_exists():
|
| 40 |
+
"""Vérifie que app.py existe."""
|
| 41 |
+
assert (ROOT / "app.py").exists()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_claude_md_exists():
|
| 45 |
+
"""Vérifie que CLAUDE.md existe."""
|
| 46 |
+
assert (ROOT / "CLAUDE.md").exists()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_env_example_exists():
|
| 50 |
+
"""Vérifie que .env.example existe."""
|
| 51 |
+
assert (ROOT / ".env.example").exists()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_env_example_anthropic():
|
| 55 |
+
"""Vérifie que .env.example utilise Anthropic, pas Groq."""
|
| 56 |
+
content = (ROOT / ".env.example").read_text()
|
| 57 |
+
assert "ANTHROPIC_API_KEY" in content
|
| 58 |
+
assert "GROQ_API_KEY" not in content
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_gitignore_env():
|
| 62 |
+
"""Vérifie que .env est dans le .gitignore."""
|
| 63 |
+
content = (ROOT / ".gitignore").read_text()
|
| 64 |
+
assert ".env" in content
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_src_structure():
|
| 68 |
+
"""Vérifie la structure src/."""
|
| 69 |
+
assert (ROOT / "src" / "__init__.py").exists()
|
| 70 |
+
assert (ROOT / "src" / "config.py").exists()
|
| 71 |
+
assert (ROOT / "src" / "rag" / "loader.py").exists()
|
| 72 |
+
assert (ROOT / "src" / "rag" / "embeddings.py").exists()
|
| 73 |
+
assert (ROOT / "src" / "rag" / "retriever.py").exists()
|
| 74 |
+
assert (ROOT / "src" / "rag" / "hybrid_retriever.py").exists()
|
| 75 |
+
assert (ROOT / "src" / "agents" / "tools.py").exists()
|
| 76 |
+
assert (ROOT / "src" / "agents" / "agent.py").exists()
|
| 77 |
+
assert (ROOT / "src" / "memory" / "memory.py").exists()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_github_workflows():
|
| 81 |
+
"""Vérifie que les workflows CI/CD existent."""
|
| 82 |
+
workflows = ROOT / ".github" / "workflows"
|
| 83 |
+
assert workflows.exists()
|
| 84 |
+
files = [f.name for f in workflows.iterdir()]
|
| 85 |
+
assert "github-docker-cicd.yaml" in files
|
| 86 |
+
assert "azure.yml" in files
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_tests_directory():
|
| 90 |
+
"""Vérifie que le dossier tests/ contient des tests."""
|
| 91 |
+
tests_dir = ROOT / "tests"
|
| 92 |
+
assert tests_dir.exists()
|
| 93 |
+
test_files = [f.name for f in tests_dir.glob("test_*.py")]
|
| 94 |
+
assert len(test_files) >= 3
|
tests/test_tools.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests pour les outils de l'agent."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def test_all_tools_list():
|
| 5 |
+
"""Vérifie que ALL_TOOLS contient les 6 outils."""
|
| 6 |
+
from src.agents.tools import ALL_TOOLS
|
| 7 |
+
|
| 8 |
+
assert len(ALL_TOOLS) == 6
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_tool_names():
|
| 12 |
+
"""Vérifie les noms des outils."""
|
| 13 |
+
from src.agents.tools import ALL_TOOLS
|
| 14 |
+
|
| 15 |
+
noms = [t.name for t in ALL_TOOLS]
|
| 16 |
+
attendus = [
|
| 17 |
+
"get_weather",
|
| 18 |
+
"get_historical_weather",
|
| 19 |
+
"get_forecast",
|
| 20 |
+
"web_search",
|
| 21 |
+
"calculator",
|
| 22 |
+
"search_corpus",
|
| 23 |
+
]
|
| 24 |
+
for nom in attendus:
|
| 25 |
+
assert nom in noms, f"Outil '{nom}' manquant dans ALL_TOOLS"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_calculator_basic():
|
| 29 |
+
"""Vérifie que la calculatrice fonctionne."""
|
| 30 |
+
from src.agents.tools import calculator
|
| 31 |
+
|
| 32 |
+
result = calculator.invoke({"expression": "3+7*2"})
|
| 33 |
+
assert "17" in result
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_calculator_sqrt():
|
| 37 |
+
"""Vérifie les fonctions mathématiques."""
|
| 38 |
+
from src.agents.tools import calculator
|
| 39 |
+
|
| 40 |
+
result = calculator.invoke({"expression": "sqrt(144)"})
|
| 41 |
+
assert "12" in result
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_calculator_division_zero():
|
| 45 |
+
"""Vérifie la gestion de la division par zéro."""
|
| 46 |
+
from src.agents.tools import calculator
|
| 47 |
+
|
| 48 |
+
result = calculator.invoke({"expression": "1/0"})
|
| 49 |
+
assert "zéro" in result.lower() or "zero" in result.lower()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_geocode():
|
| 53 |
+
"""Vérifie le géocodage d'une ville."""
|
| 54 |
+
from src.agents.tools import _geocode
|
| 55 |
+
|
| 56 |
+
result = _geocode("Paris")
|
| 57 |
+
assert result is not None
|
| 58 |
+
lat, lon, name = result
|
| 59 |
+
assert 48 < lat < 49
|
| 60 |
+
assert 2 < lon < 3
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_geocode_unknown_city():
|
| 64 |
+
"""Vérifie le géocodage d'une ville inexistante."""
|
| 65 |
+
from src.agents.tools import _geocode
|
| 66 |
+
|
| 67 |
+
result = _geocode("VilleQuiNExistePas12345")
|
| 68 |
+
assert result is None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_wmo_codes():
|
| 72 |
+
"""Vérifie que les codes WMO sont définis."""
|
| 73 |
+
from src.agents.tools import _WMO_CODES
|
| 74 |
+
|
| 75 |
+
assert 0 in _WMO_CODES
|
| 76 |
+
assert 95 in _WMO_CODES
|
| 77 |
+
assert "dégagé" in _WMO_CODES[0].lower() or "Ciel" in _WMO_CODES[0]
|