🚀 Mode Liberté Total + Documentation technique complète
## ✨ Mode Liberté Total Révolutionnaire - Contrôle de précision : 30% (créatif) à 90% (précis) - Streaming temps réel avec Server-Sent Events - Interface progressive avec barre de progression - Temperature dynamique selon la précision - Enrichissement complet du document à chaque itération ## 📖 Documentation technique professionnelle - Architecture détaillée avec diagrammes Mermaid - Structure de projet complète et annotée - Flux de données documentés (streaming, journaux) - Stack technique avec versions et utilités - Guide d'utilisation mis à jour - 18 templates organisés par domaines ## 🎨 Interface améliorée - Sélecteurs d'itérations (1-10) et précision (30-90%) - Affichage temps réel des explications IA - Feedback visuel avec progression et statut - Mode streaming non-bloquant 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
b85e6d3a25
commit
2846d2feef
305
README.md
305
README.md
@ -26,12 +26,13 @@ Un assistant intelligent de conception technique avec fonctionnalités IA avanc
|
||||
- **Vérification de doublons** et redondances
|
||||
- **Conseils d'amélioration** personnalisés
|
||||
|
||||
#### 🧠 **Mode Liberté Intelligent** (Nouveau !)
|
||||
#### 🚀 **Mode Liberté Total** (Révolutionnaire !)
|
||||
|
||||
- **Jusqu'à 15 itérations** d'amélioration automatique
|
||||
- **Analyse itérative** : chaque amélioration enrichit le document
|
||||
- **Arrêt intelligent** quand plus rien d'évident à améliorer
|
||||
- **Confiance 90%+** : ne modifie que ce qui est certain
|
||||
- **Jusqu'à 10 itérations** d'enrichissement progressif
|
||||
- **Contrôle de précision** : 30% (très créatif) à 90% (très précis)
|
||||
- **Streaming temps réel** : voir chaque amélioration en direct
|
||||
- **Feedback instantané** : explications détaillées pour chaque itération
|
||||
- **Document complet** : enrichit TOUT le document à chaque passage
|
||||
|
||||
### 🎨 Interface & Expérience
|
||||
|
||||
@ -39,24 +40,30 @@ Un assistant intelligent de conception technique avec fonctionnalités IA avanc
|
||||
|
||||
- **Mode sombre/clair** avec persistance des préférences
|
||||
- **Variables CSS** cohérentes pour tous les composants
|
||||
- **Basculement instantané** sans rechargement
|
||||
|
||||
#### 👁️ **Mode Prévisualisation**
|
||||
|
||||
- **Toggle édition/visualisation** en un clic
|
||||
- **Rendu Markdown complet** : titres, listes, code, liens, citations
|
||||
- **Rendu GitHub Markdown** : titres, listes, code, liens, citations, tables
|
||||
- **Support Mermaid** : diagrammes intégrés
|
||||
- **Styling professionnel** pour présentation finale
|
||||
|
||||
#### 🧭 **Navigation Avancée**
|
||||
|
||||
- **Table des matières** générée automatiquement
|
||||
- **Scroll intelligent** vers les sections
|
||||
- **Raccourcis clavier** (Ctrl+S pour sauvegarde)
|
||||
- **Scroll intelligent** vers les sections avec surbrillance
|
||||
- **Historique complet** : Ctrl+Z/Y pour toutes les actions IA
|
||||
- **Raccourcis clavier** : Ctrl+S sauvegarde, Tab indentation
|
||||
|
||||
### 📤 Export & Import
|
||||
|
||||
- **Export Markdown** (.md) natif
|
||||
- **Import de fichiers** Markdown
|
||||
- **Templates prédéfinis** pour démarrage rapide
|
||||
- **Export Markdown** (.md) natif avec préservation formatage
|
||||
- **Export PDF/HTML** professionnel via Puppeteer
|
||||
- **Import de fichiers** Markdown avec détection automatique
|
||||
- **Templates prédéfinis** (6 domaines × 3 niveaux = 18 templates)
|
||||
- 💻 Informatique • 💼 Business • 🎨 Design
|
||||
- ⚙️ Ingénierie • 📊 Mathématiques • 🔬 Recherche
|
||||
|
||||
## ⚙️ Installation
|
||||
|
||||
@ -76,30 +83,34 @@ cd conception-assistant
|
||||
# Installer les dépendances
|
||||
npm install
|
||||
|
||||
# Copier et configurer les variables d'environnement
|
||||
cp config/.env.example config/.env
|
||||
# Créer le fichier de configuration (optionnel)
|
||||
echo "PORT=3000
|
||||
MISTRAL_API_KEY=your_key_here
|
||||
AI_ENABLED=true" > .env
|
||||
```
|
||||
|
||||
### Configuration
|
||||
### Configuration (Optionnelle)
|
||||
|
||||
Éditez `config/.env` avec vos paramètres :
|
||||
L'application fonctionne sans configuration. Pour activer l'IA, éditez `.env` :
|
||||
|
||||
```env
|
||||
# Server Configuration
|
||||
# 🌐 Serveur (optionnel)
|
||||
PORT=3000
|
||||
|
||||
# Mistral AI Configuration
|
||||
MISTRAL_API_KEY=votre_clé_api_mistral_ici
|
||||
# 🤖 Mistral AI (requis pour l'IA)
|
||||
MISTRAL_API_KEY=your_mistral_api_key_here
|
||||
MISTRAL_MODEL=mistral-large-latest
|
||||
MISTRAL_BASE_URL=https://api.mistral.ai/v1
|
||||
|
||||
# AI Features Configuration
|
||||
# ⚙️ Configuration IA avancée (optionnel)
|
||||
AI_ENABLED=true
|
||||
AI_MAX_TOKENS=35000
|
||||
AI_TEMPERATURE=0.3
|
||||
AI_TOP_P=0.85
|
||||
```
|
||||
|
||||
> **💡 Sans clé API** : L'application fonctionne parfaitement pour la gestion des journaux, seules les fonctions IA sont désactivées.
|
||||
|
||||
### Lancement
|
||||
|
||||
```bash
|
||||
@ -123,26 +134,47 @@ http://localhost:3000
|
||||
- **Reformulation** : 0.2 (très précise)
|
||||
- **Analyses** : 0.1 (factuelle)
|
||||
- **Conseils** : 0.4 (équilibrée)
|
||||
- **Mode Liberté** : 0.2 (itératif intelligent)
|
||||
- **Mode Liberté Total** : 0.1-0.9 (dynamique selon précision)
|
||||
|
||||
## 🧠 Mode Liberté - Fonctionnement Avancé
|
||||
## 🚀 Mode Liberté Total - Fonctionnement Révolutionnaire
|
||||
|
||||
Le **Mode Liberté Intelligent** analyse votre document de manière itérative :
|
||||
Le **Mode Liberté Total** transforme votre document avec un contrôle précis de la créativité :
|
||||
|
||||
1. **Analyse** du contenu actuel
|
||||
2. **Identification** du point le plus évident à améliorer
|
||||
3. **Application** de l'amélioration avec 90%+ de confiance
|
||||
4. **Mise à jour** du document avec le nouveau contenu
|
||||
5. **Répétition** du processus sur le document enrichi
|
||||
6. **Arrêt automatique** quand plus rien d'évident
|
||||
### 🎯 **Contrôle de Précision**
|
||||
|
||||
### Exemple de Session
|
||||
| Niveau | Précision | Comportement | Usage |
|
||||
|--------|-----------|--------------|--------|
|
||||
| **30%** | Très Créatif | Peut créer 70% de contenu nouveau logique | Brainstorming initial |
|
||||
| **50%** | Équilibré | Balance déduction/création 50/50 | Développement standard |
|
||||
| **70%** | Conservateur | Principalement basé sur l'existant | Raffinement document |
|
||||
| **90%** | Très Précis | Seulement déductions évidentes | Finalisation technique |
|
||||
|
||||
### 🔄 **Processus Itératif en Temps Réel**
|
||||
|
||||
1. **📊 Analyse** : L'IA évalue le document selon la précision choisie
|
||||
2. **🎯 Enrichissement** : Ajoute sections, détails, diagrammes conceptuels
|
||||
3. **📡 Streaming** : Vous voyez l'explication en temps réel
|
||||
4. **✏️ Application** : Le document est automatiquement mis à jour
|
||||
5. **🔄 Itération** : Répétition sur le document enrichi
|
||||
6. **✅ Finalisation** : Sauvegarde automatique avec historique
|
||||
|
||||
### 📈 **Exemple de Session (Précision 70%)**
|
||||
|
||||
```
|
||||
Itération 1 : Ajout section "Contraintes techniques"
|
||||
Itération 2 : Détail des "Risques identifiés"
|
||||
Itération 3 : Complétion "Plan de tests"
|
||||
Itération 4 : STOP - Aucune amélioration évidente
|
||||
🔄 Itération 1/3 : Analyse du document...
|
||||
✅ Ajout section "Architecture technique détaillée"
|
||||
✅ Développement des "Contraintes de performance"
|
||||
|
||||
🔄 Itération 2/3 : Enrichissement du contenu...
|
||||
✅ Diagrammes de séquence pour les flux principaux
|
||||
✅ Matrice de risques avec plans d'atténuation
|
||||
|
||||
🔄 Itération 3/3 : Finalisation...
|
||||
✅ Plan de tests complet avec critères d'acceptation
|
||||
✅ Métriques de performance et indicateurs clés
|
||||
|
||||
✅ Mode Liberté Total terminé !
|
||||
Document enrichi de 85% avec 3 itérations
|
||||
```
|
||||
|
||||
## 📖 Utilisation
|
||||
@ -155,9 +187,12 @@ Itération 4 : STOP - Aucune amélioration évidente
|
||||
|
||||
### Utiliser l'IA
|
||||
|
||||
1. **Reformulation** : Sélectionnez du texte → bouton "Reformuler"
|
||||
2. **Analyse** : Boutons "Incohérences", "Doublons", "Conseils"
|
||||
3. **Mode Liberté** : Choisir le nombre d'itérations → "Mode Liberté"
|
||||
1. **Reformulation** : Sélectionnez du texte → bouton "🔄 Reformuler"
|
||||
2. **Analyse** : Boutons "🔍 Incohérences", "📋 Doublons", "💡 Conseils"
|
||||
3. **Mode Liberté Total** :
|
||||
- Choisir **itérations** (1-10) et **précision** (30-90%)
|
||||
- Clic sur "🚀 Mode Liberté Total"
|
||||
- Suivre le **streaming en temps réel**
|
||||
|
||||
### Mode Prévisualisation
|
||||
|
||||
@ -167,36 +202,184 @@ Itération 4 : STOP - Aucune amélioration évidente
|
||||
|
||||
## 🏗️ Architecture Technique
|
||||
|
||||
### Backend
|
||||
|
||||
- **Express.js** : Serveur web
|
||||
- **Mistral AI** : Modèles de langage avancés
|
||||
- **Multer** : Upload de fichiers
|
||||
- **dotenv** : Gestion configuration
|
||||
|
||||
### Frontend
|
||||
|
||||
- **Vanilla JavaScript** : Interface réactive
|
||||
- **CSS Variables** : Thèmes dynamiques
|
||||
- **Markdown Parser** : Rendu intelligent
|
||||
- **LocalStorage** : Persistance locale
|
||||
|
||||
### Structure
|
||||
### 📁 Structure du Projet
|
||||
|
||||
```
|
||||
conception-assistant/
|
||||
app.js # Serveur principal
|
||||
routes/
|
||||
ai.js # Routes IA avec logique avancée
|
||||
upload.js # Upload de fichiers
|
||||
assets/
|
||||
js/app.js # Application frontend
|
||||
css/style.css # Styles et thèmes
|
||||
views/ # Composants d'interface
|
||||
uploads/ # Fichiers uploadés
|
||||
config/ # Configuration
|
||||
├── app.js # ⚡ Serveur principal Express
|
||||
├── package.json # 📦 Dépendances et scripts
|
||||
├── package-lock.json # 🔒 Verrouillage des versions
|
||||
├── README.md # 📖 Documentation du projet
|
||||
│
|
||||
├── 📂 routes/ # 🛣️ Routes API et logique métier
|
||||
│ ├── index.js # 🏠 Page d'accueil et routes de base
|
||||
│ ├── api.js # 📝 CRUD journaux (create, read, update, delete)
|
||||
│ ├── ai.js # 🤖 Intelligence Artificielle (Mistral AI)
|
||||
│ ├── templates.js # 📄 Gestion des templates prédéfinis
|
||||
│ └── export.js # 📤 Export PDF/HTML (Puppeteer)
|
||||
│
|
||||
├── 📂 views/ # 🎨 Composants d'interface modulaires
|
||||
│ ├── page.js # 📄 Structure HTML principale
|
||||
│ ├── header.js # 🔝 En-tête avec navigation
|
||||
│ ├── main.js # 🎯 Zone principale (éditeur + assistant IA)
|
||||
│ └── footer.js # 🔽 Pied de page minimal
|
||||
│
|
||||
├── 📂 assets/ # 🎨 Ressources statiques
|
||||
│ ├── css/
|
||||
│ │ ├── style.css # 🎨 Styles principaux et thèmes
|
||||
│ │ └── github-preview.css # 👁️ Style GitHub pour prévisualisation
|
||||
│ └── js/
|
||||
│ └── app.js # ⚙️ Application frontend (4000+ lignes)
|
||||
│
|
||||
├── 📂 templates/ # 📝 Templates de conception prédéfinis
|
||||
│ ├── informatique/ # 💻 Templates IT (simple, détaillé, complet)
|
||||
│ ├── business/ # 💼 Templates business
|
||||
│ ├── design/ # 🎨 Templates design
|
||||
│ ├── ingenierie/ # ⚙️ Templates ingénierie
|
||||
│ ├── math/ # 📊 Templates mathématiques
|
||||
│ └── recherche/ # 🔬 Templates recherche
|
||||
│
|
||||
└── 📂 data/ # 💾 Stockage des journaux utilisateur
|
||||
└── journals_*.json # 📔 Fichiers JSON des journaux
|
||||
```
|
||||
|
||||
### 🔧 Architecture Technique Détaillée
|
||||
|
||||
#### 🖥️ **Backend (Node.js + Express.js)**
|
||||
|
||||
| Composant | Fichier | Responsabilité | Technologies |
|
||||
|-----------|---------|----------------|--------------|
|
||||
| **Serveur Principal** | `app.js` | Configuration Express, middleware, routes | Express.js 4.18+ |
|
||||
| **API Journaux** | `routes/api.js` | CRUD journaux, stockage JSON | File System, UUID |
|
||||
| **Intelligence Artificielle** | `routes/ai.js` | Intégration Mistral AI, streaming | Mistral AI API, Server-Sent Events |
|
||||
| **Templates** | `routes/templates.js` | Gestion templates par domaine | File System |
|
||||
| **Export** | `routes/export.js` | Génération PDF/HTML | Puppeteer |
|
||||
|
||||
#### 🎨 **Frontend (Vanilla JavaScript)**
|
||||
|
||||
| Composant | Fichier | Responsabilité | Fonctionnalités |
|
||||
|-----------|---------|----------------|-----------------|
|
||||
| **Application Principale** | `assets/js/app.js` | Logique métier frontend | Éditeur, IA, historique, navigation |
|
||||
| **Interface Modulaire** | `views/*.js` | Composants HTML | Header, main, footer |
|
||||
| **Styles** | `assets/css/*.css` | Thèmes et présentation | CSS Variables, GitHub Preview |
|
||||
|
||||
#### 🤖 **Système IA Avancé**
|
||||
|
||||
| Fonctionnalité | Endpoint | Méthode | Streaming | Précision |
|
||||
|---------------|----------|---------|-----------|-----------|
|
||||
| **Reformulation** | `/api/ai/rephrase` | POST | ❌ | 90%+ |
|
||||
| **Incohérences** | `/api/ai/check-inconsistencies` | POST | ❌ | Factuelle |
|
||||
| **Doublons** | `/api/ai/check-duplications` | POST | ❌ | Factuelle |
|
||||
| **Conseils** | `/api/ai/give-advice` | POST | ❌ | Équilibrée |
|
||||
| **Mode Liberté Total** | `/api/ai/liberty-mode` | POST | ✅ SSE | Configurable 30-90% |
|
||||
|
||||
### ⚡ **Technologies & Stack**
|
||||
|
||||
#### **Core Dependencies**
|
||||
|
||||
```json
|
||||
{
|
||||
"express": "^4.18.2", // 🌐 Serveur web
|
||||
"dotenv": "^17.2.2", // ⚙️ Variables d'environnement
|
||||
"puppeteer": "^24.22.3", // 📄 Génération PDF
|
||||
"uuid": "^13.0.0" // 🆔 Identifiants uniques
|
||||
}
|
||||
```
|
||||
|
||||
#### **API Externes**
|
||||
|
||||
- **Mistral AI** : Modèles de langage avancés
|
||||
- `mistral-large-latest` : Analyse et génération
|
||||
- Temperature dynamique : 0.1-0.9 selon la tâche
|
||||
- Max tokens : 35000 pour longs documents
|
||||
|
||||
#### **Stockage & Persistance**
|
||||
|
||||
- **Journaux** : Fichiers JSON avec UUID
|
||||
- **Préférences** : LocalStorage navigateur
|
||||
- **Templates** : Fichiers Markdown statiques
|
||||
- **Exports** : Génération temporaire PDF/HTML
|
||||
|
||||
### 🔄 **Flux de Données**
|
||||
|
||||
#### **Mode Liberté Total (Streaming)**
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User as 👤 Utilisateur
|
||||
participant Frontend as 🌐 Frontend
|
||||
participant Backend as ⚙️ Backend
|
||||
participant AI as 🤖 Mistral AI
|
||||
|
||||
User->>Frontend: Clic "Mode Liberté Total"
|
||||
Frontend->>Backend: POST /api/ai/liberty-mode (SSE)
|
||||
|
||||
loop Pour chaque itération
|
||||
Backend->>AI: Envoi document + précision
|
||||
AI->>Backend: Explication + Markdown amélioré
|
||||
Backend->>Frontend: Stream données (SSE)
|
||||
Frontend->>User: Affichage temps réel + MAJ éditeur
|
||||
end
|
||||
|
||||
Backend->>Frontend: Signal fin (completed: true)
|
||||
Frontend->>User: Notification terminée
|
||||
```
|
||||
|
||||
#### **Gestion des Journaux**
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[👤 Utilisateur] --> B[✏️ Éditeur]
|
||||
B --> C[💾 Sauvegarde Auto]
|
||||
C --> D[📁 data/journals_UUID.json]
|
||||
|
||||
A --> E[📂 Charger Journal]
|
||||
E --> F[📋 Liste Journaux]
|
||||
F --> G[🔄 Chargement Contenu]
|
||||
G --> B
|
||||
|
||||
B --> H[👁️ Mode Prévisualisation]
|
||||
H --> I[🎨 Rendu GitHub Markdown]
|
||||
I --> B
|
||||
```
|
||||
|
||||
### 🛡️ **Sécurité & Configuration**
|
||||
|
||||
#### **Variables d'Environnement**
|
||||
|
||||
```env
|
||||
# Serveur
|
||||
PORT=3000
|
||||
|
||||
# Mistral AI
|
||||
MISTRAL_API_KEY=your_key_here
|
||||
MISTRAL_MODEL=mistral-large-latest
|
||||
MISTRAL_BASE_URL=https://api.mistral.ai/v1
|
||||
|
||||
# IA
|
||||
AI_ENABLED=true
|
||||
AI_MAX_TOKENS=35000
|
||||
AI_TEMPERATURE=0.3
|
||||
AI_TOP_P=0.85
|
||||
```
|
||||
|
||||
#### **Gestion d'Erreur Robuste**
|
||||
|
||||
- **Backend** : Try-catch sur toutes les routes
|
||||
- **Frontend** : Gestion d'erreur asynchrone
|
||||
- **IA** : Fallback et retry automatique
|
||||
- **Streaming** : Gestion déconnexion SSE
|
||||
|
||||
### 🚀 **Performance & Optimisations**
|
||||
|
||||
| Aspect | Implémentation | Bénéfice |
|
||||
|--------|----------------|----------|
|
||||
| **Debouncing** | Table des matières, sauvegarde | Réduit calculs inutiles |
|
||||
| **Streaming SSE** | Mode Liberté Total | Feedback temps réel |
|
||||
| **Cache LocalStorage** | Préférences thème | Persistance locale |
|
||||
| **Lazy Loading** | Templates à la demande | Chargement optimisé |
|
||||
| **CSS Variables** | Thèmes dynamiques | Basculement instantané |
|
||||
|
||||
## 🤝 Contribution
|
||||
|
||||
1. **Fork** le projet
|
||||
|
186
assets/js/app.js
186
assets/js/app.js
@ -742,39 +742,24 @@ class ConceptionAssistant {
|
||||
this.saveState(true);
|
||||
|
||||
const count = document.getElementById('liberty-repeat-count')?.value || 3;
|
||||
// Mode liberté utilise toujours le document complet
|
||||
result = await this.callAI('/api/ai/liberty-mode', { content: fullContent, iterations: count, focus: 'conception' });
|
||||
const precision = document.getElementById('liberty-precision')?.value || 70;
|
||||
|
||||
// Utiliser le contenu final mis à jour par le backend
|
||||
if (result.finalContent) {
|
||||
this.editor.innerText = result.finalContent;
|
||||
this.generateTOC();
|
||||
// Sauvegarder l'état après les modifications de l'IA
|
||||
this.saveState(true);
|
||||
}
|
||||
|
||||
let libertyHTML = `<strong>Mode Liberté Intelligent (${result.iterations} itérations)</strong><br><br>`;
|
||||
|
||||
// Vérifier si l'IA s'est arrêtée prématurément
|
||||
const lastIteration = result.results[result.results.length - 1];
|
||||
if (lastIteration && lastIteration.stopped) {
|
||||
libertyHTML += `<p>Analyse terminée après ${result.iterations} itérations - Aucune amélioration évidente supplémentaire détectée.</p>`;
|
||||
} else {
|
||||
libertyHTML += `<p>Les ${result.iterations} itérations d'amélioration ont été automatiquement appliquées au document.</p>`;
|
||||
}
|
||||
|
||||
result.results.forEach(iteration => {
|
||||
const borderColor = iteration.stopped ? 'var(--warning-color)' : 'var(--success-color)';
|
||||
const icon = iteration.stopped ? 'STOP' : 'OK';
|
||||
|
||||
libertyHTML += `
|
||||
<div style="background: var(--background-color); padding: 1rem; border-radius: 8px; margin: 0.5rem 0; border-left: 4px solid ${borderColor};">
|
||||
<strong>${icon} Itération ${iteration.iteration} ${iteration.stopped ? '(Arrêt)' : '(Appliquée)'} :</strong><br><br>
|
||||
${this.formatAIResponse(iteration.content)}
|
||||
// Initialiser l'affichage de progression
|
||||
this.showAIFeedback(`
|
||||
<div id="liberty-progress">
|
||||
<strong>🚀 Mode Liberté Total</strong><br>
|
||||
<div style="margin: 0.5rem 0; font-size: 0.9rem; color: var(--text-light);">
|
||||
${count} itérations • Précision: ${precision}% • Focus: conception
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
this.showAIFeedback(libertyHTML);
|
||||
<div class="progress-bar" style="width: 100%; height: 4px; background: var(--background-color); border-radius: 2px; margin: 1rem 0;">
|
||||
<div id="liberty-progress-fill" style="height: 100%; background: var(--primary-color); border-radius: 2px; width: 0%; transition: width 0.3s ease;"></div>
|
||||
</div>
|
||||
<div id="liberty-iterations"></div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
// Utiliser EventSource pour le streaming
|
||||
await this.handleLibertyModeStreaming(fullContent, count, precision);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
@ -783,6 +768,145 @@ class ConceptionAssistant {
|
||||
}
|
||||
}
|
||||
|
||||
async handleLibertyModeStreaming(content, iterations, precision) {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Préparer les données à envoyer
|
||||
const requestData = {
|
||||
content: content,
|
||||
iterations: iterations,
|
||||
precision: precision,
|
||||
focus: 'conception'
|
||||
};
|
||||
|
||||
// Créer une requête fetch pour le streaming
|
||||
fetch('/api/ai/liberty-mode', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(requestData)
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error(`Erreur HTTP: ${response.status}`);
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
const processStream = () => {
|
||||
return reader.read().then(({ done, value }) => {
|
||||
if (done) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
// Décoder les données reçues
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
// Traiter chaque ligne reçue
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || ''; // Garder la dernière ligne incomplète
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.trim().startsWith('data: ')) {
|
||||
try {
|
||||
const data = JSON.parse(line.slice(6)); // Supprimer "data: "
|
||||
this.handleLibertyStreamData(data);
|
||||
} catch (e) {
|
||||
console.error('Erreur parsing JSON:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return processStream();
|
||||
});
|
||||
};
|
||||
|
||||
return processStream();
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erreur streaming:', error);
|
||||
this.showAIFeedback(`<strong>Erreur</strong><br><br>Erreur de streaming: ${error.message}`);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
handleLibertyStreamData(data) {
|
||||
const progressFill = document.getElementById('liberty-progress-fill');
|
||||
const iterationsDiv = document.getElementById('liberty-iterations');
|
||||
|
||||
if (data.error) {
|
||||
// Afficher l'erreur
|
||||
const errorHTML = `
|
||||
<div style="background: var(--danger-color); color: white; padding: 1rem; border-radius: 8px; margin: 0.5rem 0;">
|
||||
<strong>❌ Erreur:</strong> ${data.error}
|
||||
</div>
|
||||
`;
|
||||
iterationsDiv.innerHTML += errorHTML;
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.iteration) {
|
||||
// Mettre à jour la barre de progression
|
||||
const totalIterations = parseInt(document.getElementById('liberty-repeat-count')?.value || 3);
|
||||
const progressPercent = (data.iteration / totalIterations) * 100;
|
||||
|
||||
if (progressFill) {
|
||||
progressFill.style.width = `${progressPercent}%`;
|
||||
}
|
||||
|
||||
// Afficher l'explication de cette itération
|
||||
const iterationHTML = `
|
||||
<div style="background: var(--surface-color); border-left: 4px solid var(--primary-color); padding: 1rem; border-radius: 8px; margin: 0.5rem 0;">
|
||||
<strong>🔄 Itération ${data.iteration}</strong><br><br>
|
||||
${this.formatAIResponse(data.explanation)}
|
||||
</div>
|
||||
`;
|
||||
|
||||
iterationsDiv.innerHTML += iterationHTML;
|
||||
|
||||
// Mettre à jour l'éditeur avec le nouveau markdown si disponible
|
||||
if (data.markdown && data.markdown !== this.editor.innerText) {
|
||||
this.editor.innerText = data.markdown;
|
||||
this.generateTOC();
|
||||
}
|
||||
|
||||
// Scroller vers le bas du feedback pour voir la nouvelle itération
|
||||
const feedback = document.getElementById('ai-assistant-feedback');
|
||||
feedback.scrollTop = feedback.scrollHeight;
|
||||
}
|
||||
|
||||
if (data.completed) {
|
||||
// Finaliser l'affichage
|
||||
if (progressFill) {
|
||||
progressFill.style.width = '100%';
|
||||
}
|
||||
|
||||
if (data.finalMarkdown) {
|
||||
// S'assurer que le contenu final est bien dans l'éditeur
|
||||
this.editor.innerText = data.finalMarkdown;
|
||||
this.generateTOC();
|
||||
// Sauvegarder l'état final
|
||||
this.saveState(true);
|
||||
}
|
||||
|
||||
// Message de fin
|
||||
const completedHTML = `
|
||||
<div style="background: var(--success-color); color: white; padding: 1rem; border-radius: 8px; margin: 1rem 0; text-align: center;">
|
||||
<strong>✅ Mode Liberté Total terminé !</strong><br>
|
||||
${data.totalIterations || 'Toutes les'} itération(s) complétée(s)
|
||||
</div>
|
||||
`;
|
||||
|
||||
iterationsDiv.innerHTML += completedHTML;
|
||||
|
||||
this.showNotification('Mode Liberté Total terminé', 'success');
|
||||
}
|
||||
}
|
||||
|
||||
async callAI(endpoint, data) {
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
|
149
routes/ai.js
149
routes/ai.js
@ -263,10 +263,10 @@ router.post('/give-advice', checkAIEnabled, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/ai/liberty-mode - Mode liberté (génération créative)
|
||||
// POST /api/ai/liberty-mode - Mode liberté total (génération itérative)
|
||||
router.post('/liberty-mode', checkAIEnabled, async (req, res) => {
|
||||
try {
|
||||
const { content, iterations = 1, focus = 'général' } = req.body;
|
||||
const { content, iterations = 1, precision = 70, focus = 'conception' } = req.body;
|
||||
|
||||
if (!content || content.trim().length === 0) {
|
||||
return res.status(400).json({
|
||||
@ -275,91 +275,124 @@ router.post('/liberty-mode', checkAIEnabled, async (req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
const maxIterations = Math.min(parseInt(iterations), 15); // Limite à 15 itérations
|
||||
const results = [];
|
||||
const maxIterations = Math.min(parseInt(iterations), 10); // Limite à 10 itérations
|
||||
const precisionPercent = Math.min(Math.max(parseInt(precision), 10), 100); // Entre 10% et 100%
|
||||
|
||||
// Configuration streaming pour réponses en temps réel
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
});
|
||||
|
||||
let currentContent = content;
|
||||
|
||||
for (let i = 0; i < maxIterations; i++) {
|
||||
try {
|
||||
const messages = [
|
||||
{
|
||||
role: 'system',
|
||||
content: `Tu es un assistant créatif spécialisé en conception technique avec une approche itérative intelligente.
|
||||
content: `Tu es un expert en conception technique avec mode "Liberté Total".
|
||||
|
||||
MISSION: Analyse le document et identifie LE PREMIER point que tu peux compléter, créer ou modifier avec plus de 90% de confiance basé sur les informations existantes dans le texte.
|
||||
MISSION: Améliore et enrichis le document en respectant EXACTEMENT ce niveau de précision: ${precisionPercent}%
|
||||
|
||||
RÈGLES STRICTES:
|
||||
1. Ne traite qu'UN SEUL point par itération
|
||||
2. Choisis le point le plus évident et logique à améliorer
|
||||
3. Utilise uniquement les informations déjà présentes dans le document
|
||||
4. Si rien ne peut être amélioré avec 90%+ de confiance, indique "STOP"
|
||||
RÈGLES DE PRÉCISION:
|
||||
- À ${precisionPercent}%: Tu peux déduire et ajouter du contenu à hauteur de ${precisionPercent}% basé sur les informations existantes
|
||||
- À ${100 - precisionPercent}%: Tu peux créer du contenu logique et pertinent même sans info explicite dans le texte
|
||||
|
||||
STRUCTURE OBLIGATOIRE:
|
||||
CONSIGNES:
|
||||
1. Enrichis TOUT le document de manière cohérente
|
||||
2. Ajoute sections, détails, explications, diagrammes conceptuels
|
||||
3. Développe les idées existantes avec la créativité autorisée
|
||||
4. Maintiens la structure logique
|
||||
|
||||
## 🧠 Analyse (Itération ${i + 1}/${maxIterations})
|
||||
[Identifie et explique le point le plus évident à améliorer]
|
||||
RÉPONSE OBLIGATOIRE EN 2 PARTIES SÉPARÉES PAR "---SPLIT---":
|
||||
|
||||
## 🎯 Point identifié
|
||||
[Le point spécifique que tu vas traiter]
|
||||
## 📊 Explication (Itération ${i + 1}/${maxIterations})
|
||||
[Explique les améliorations apportées, les sections ajoutées, le raisonnement]
|
||||
|
||||
## ✅ Amélioration
|
||||
[Le contenu précis à ajouter/modifier, avec 90%+ de confiance]
|
||||
---SPLIT---
|
||||
|
||||
OU si rien ne peut être amélioré avec assez de confiance:
|
||||
[LE DOCUMENT MARKDOWN COMPLET ET AMÉLIORÉ - SANS TITRE "## Document" - DIRECTEMENT LE CONTENU]
|
||||
|
||||
## 🛑 STOP
|
||||
[Explication pourquoi aucune amélioration évidente n'est possible]
|
||||
|
||||
Focus: ${focus}`
|
||||
Focus: ${focus}
|
||||
Précision: ${precisionPercent}%`
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `Document à analyser (Itération ${i + 1}):\n\n${currentContent}`
|
||||
content: `Document à améliorer (Itération ${i + 1}):\n\n${currentContent}`
|
||||
}
|
||||
];
|
||||
|
||||
const result = await callMistralAPI(messages, 0.2); // Mode itératif intelligent et précis
|
||||
// Temperature basée sur la précision (plus créatif = température plus élevée)
|
||||
const temperature = (100 - precisionPercent) / 100 * 0.8 + 0.1; // Entre 0.1 et 0.9
|
||||
|
||||
// Vérifier si l'IA indique qu'il faut s'arrêter
|
||||
if (result.toLowerCase().includes('🛑 stop') || result.toLowerCase().includes('## 🛑 stop')) {
|
||||
results.push({
|
||||
const result = await callMistralAPI(messages, temperature);
|
||||
|
||||
// Séparer l'explication du markdown
|
||||
const parts = result.split('---SPLIT---');
|
||||
|
||||
let explanation = '';
|
||||
let newMarkdown = currentContent; // Par défaut, garder l'ancien contenu
|
||||
|
||||
if (parts.length >= 2) {
|
||||
explanation = parts[0].trim();
|
||||
newMarkdown = parts[1].trim();
|
||||
// Mettre à jour pour la prochaine itération
|
||||
currentContent = newMarkdown;
|
||||
} else {
|
||||
// Fallback si pas de split trouvé
|
||||
explanation = result;
|
||||
}
|
||||
|
||||
// Envoyer la réponse de cette itération
|
||||
const iterationData = {
|
||||
iteration: i + 1,
|
||||
content: result,
|
||||
stopped: true
|
||||
});
|
||||
explanation: explanation,
|
||||
markdown: newMarkdown,
|
||||
completed: false
|
||||
};
|
||||
|
||||
res.write(`data: ${JSON.stringify(iterationData)}\n\n`);
|
||||
|
||||
// Petit délai pour permettre l'affichage côté client
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
|
||||
} catch (iterationError) {
|
||||
console.error(`Erreur itération ${i + 1}:`, iterationError);
|
||||
|
||||
const errorData = {
|
||||
iteration: i + 1,
|
||||
error: `Erreur itération ${i + 1}: ${iterationError.message}`,
|
||||
completed: true
|
||||
};
|
||||
|
||||
res.write(`data: ${JSON.stringify(errorData)}\n\n`);
|
||||
break;
|
||||
}
|
||||
|
||||
// Extraire l'amélioration de la réponse de l'IA
|
||||
let improvement = '';
|
||||
const improvementMatch = result.match(/## ✅ Amélioration\s*([\s\S]*?)(?=##|$)/i);
|
||||
if (improvementMatch) {
|
||||
improvement = improvementMatch[1].trim();
|
||||
// Mettre à jour le contenu pour la prochaine itération
|
||||
currentContent += '\n\n' + improvement;
|
||||
}
|
||||
|
||||
results.push({
|
||||
iteration: i + 1,
|
||||
content: result,
|
||||
improvement: improvement
|
||||
});
|
||||
}
|
||||
// Signal de fin
|
||||
const finalData = {
|
||||
completed: true,
|
||||
totalIterations: maxIterations,
|
||||
finalMarkdown: currentContent
|
||||
};
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
iterations: results.length,
|
||||
results: results,
|
||||
finalContent: currentContent
|
||||
}
|
||||
});
|
||||
res.write(`data: ${JSON.stringify(finalData)}\n\n`);
|
||||
res.end();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erreur mode liberté:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Erreur lors de la génération: ' + error.message
|
||||
});
|
||||
console.error('Erreur mode liberté total:', error);
|
||||
|
||||
const errorData = {
|
||||
error: 'Erreur lors de la génération: ' + error.message,
|
||||
completed: true
|
||||
};
|
||||
|
||||
res.write(`data: ${JSON.stringify(errorData)}\n\n`);
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -55,9 +55,10 @@ function getMain() {
|
||||
</button>
|
||||
</div>
|
||||
<div class="liberty-mode" style="border-top: 1px solid var(--border-color); padding-top: 1rem;">
|
||||
<div style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
|
||||
<label for="liberty-repeat-count" style="font-size: 0.9rem; color: var(--text-light);">Itérations:</label>
|
||||
<select id="liberty-repeat-count" style="padding: 0.25rem; border: 1px solid var(--border-color); border-radius: 4px; background: var(--surface-color); color: var(--text-color);">
|
||||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; margin-bottom: 0.5rem;">
|
||||
<div style="display: flex; align-items: center; gap: 0.25rem;">
|
||||
<label for="liberty-repeat-count" style="font-size: 0.85rem; color: var(--text-light);">Itérations:</label>
|
||||
<select id="liberty-repeat-count" style="padding: 0.25rem; border: 1px solid var(--border-color); border-radius: 4px; background: var(--surface-color); color: var(--text-color); font-size: 0.85rem;">
|
||||
<option value="1">1</option>
|
||||
<option value="2">2</option>
|
||||
<option value="3" selected>3</option>
|
||||
@ -68,16 +69,21 @@ function getMain() {
|
||||
<option value="8">8</option>
|
||||
<option value="9">9</option>
|
||||
<option value="10">10</option>
|
||||
<option value="11">11</option>
|
||||
<option value="12">12</option>
|
||||
<option value="13">13</option>
|
||||
<option value="14">14</option>
|
||||
<option value="15">15</option>
|
||||
</select>
|
||||
<button id="liberty-mode" class="btn" style="flex: 1;" title="Génération créative">
|
||||
🚀 Mode Liberté
|
||||
</button>
|
||||
</div>
|
||||
<div style="display: flex; align-items: center; gap: 0.25rem;">
|
||||
<label for="liberty-precision" style="font-size: 0.85rem; color: var(--text-light);">Précision:</label>
|
||||
<select id="liberty-precision" style="padding: 0.25rem; border: 1px solid var(--border-color); border-radius: 4px; background: var(--surface-color); color: var(--text-color); font-size: 0.85rem;">
|
||||
<option value="30">30% (Très créatif)</option>
|
||||
<option value="50">50% (Équilibré)</option>
|
||||
<option value="70" selected>70% (Conservateur)</option>
|
||||
<option value="90">90% (Très précis)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<button id="liberty-mode" class="btn" style="width: 100%;" title="Mode Liberté Total - Génération itérative en temps réel">
|
||||
🚀 Mode Liberté Total
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="ai-assistant-feedback" style="flex: 1; padding: 1rem; overflow-y: auto; min-height: 200px;">
|
||||
|
Loading…
x
Reference in New Issue
Block a user