Bachir00 commited on
Commit
d7a85d8
·
0 Parent(s):

Remove secrets from README

Browse files
Files changed (1) hide show
  1. README.md +808 -0
README.md ADDED
@@ -0,0 +1,808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 📚 AI Research Assistant - Documentation Complète
2
+
3
+
4
+
5
+
6
+
7
+ ![Version](https://img.shields.io/badge/version-1.0.0-blue.svg)
8
+ ![Python](https://img.shields.io/badge/python-3.12-green.svg)
9
+ ![LangGraph](https://img.shields.io/badge/LangGraph-enabled-orange.svg)
10
+ ![ChromaDB](https://img.shields.io/badge/ChromaDB-vectorstore-purple.svg)
11
+
12
+ ## 🎯 Vue d'ensemble
13
+
14
+ **AI Research Assistant** est un système intelligent de recherche et d'analyse documentaire utilisant LangGraph, plusieurs agents IA spécialisés, et un système de mémoire vectorielle avancé. Le système automatise l'ensemble du processus de recherche : de la collecte d'informations sur le web jusqu'à la génération de rapports de synthèse structurés.
15
+
16
+ ### ✨ Fonctionnalités principales
17
+
18
+ - 🔍 **Recherche web automatisée** avec extraction de mots-clés intelligente
19
+ - 📄 **Extraction de contenu** depuis des pages web avec parsing avancé
20
+ - 📝 **Génération de résumés** détaillés et structurés
21
+ - 🎯 **Synthèse globale** avec analyse thématique transversale
22
+ - 💾 **Système de mémoire** vectorielle et conversationnelle
23
+ - 🤖 **Orchestration par LLM** via LangGraph
24
+ - 🚫 **Déduplication automatique** des documents
25
+ - ⚡ **Cache intelligent** avec TTL configurable
26
+
27
+ ---
28
+
29
+ ## 🏗️ Architecture du Projet
30
+
31
+ ### Structure des dossiers
32
+
33
+ ```
34
+ langGraphe-ai-research-assistant-main/
35
+
36
+ ├── config/ # Configuration globale
37
+ │ ├── settings.py # Paramètres de l'application
38
+ │ └── prompts.py # Templates de prompts
39
+
40
+ ├── src/ # Code source principal
41
+ │ ├── agents/ # Agents spécialisés
42
+ │ │ ├── base_agent.py # Agent de base
43
+ │ │ ├── researcher_agent.py # Recherche web
44
+ │ │ ├── content_extractor_agent.py # Extraction
45
+ │ │ ├── summarizer_agent.py # Résumés
46
+ │ │ └── global_synthesizer_agent.py # Synthèse
47
+ │ │
48
+ │ ├── services/ # Services partagés
49
+ │ │ ├── search_api.py # APIs de recherche (Tavily, Serper)
50
+ │ │ ├── content_extraction.py # Extraction de contenu web
51
+ │ │ ├── llm_service.py # Service LLM (Groq)
52
+ │ │ └── text_chunking.py # Découpage de texte
53
+ │ │
54
+ │ ├── models/ # Modèles de données
55
+ │ │ ├── research_models.py # Modèles de recherche
56
+ │ │ ├── document_models.py # Modèles de documents
57
+ │ │ ├── synthesis_models.py # Modèles de synthèse
58
+ │ │ ├── report_models.py # Modèles de rapports
59
+ │ │ └── state_models.py # États du graphe
60
+ │ │
61
+ │ ├── graph/ # LangGraph
62
+ │ │ └── nodes.py # Nœuds du graphe
63
+ │ │
64
+ │ ├── core/ # Fonctionnalités de base
65
+ │ │ └── logging.py # Configuration des logs
66
+ │ │
67
+ │ ├── memory_system.py # Système de mémoire vectorielle
68
+ │ ├── memory_integration.py # Intégration de la mémoire
69
+ │ ├── enhanced_system_prompt.py # Prompts avancés
70
+ │ └── graph.py # Graphe LangGraph principal
71
+
72
+ ├── tests/ # Tests unitaires et d'intégration
73
+ │ ├── test_researcher.py
74
+ │ ├── test_content_extractor_agent.py
75
+ │ ├── test_summarizer_agent.py
76
+ │ └── api_tests.py
77
+
78
+ ├── logs/ # Fichiers de logs
79
+ ├── .env # Variables d'environnement
80
+ ├── requirements.txt # Dépendances Python
81
+ └── README.md # Documentation principale
82
+ ```
83
+
84
+ ---
85
+
86
+ ## 🔧 Architecture Technique
87
+
88
+ ### Diagramme du Pipeline
89
+
90
+ ```
91
+ ┌─────────────────────────────────────────────────────────────────┐
92
+ │ UTILISATEUR │
93
+ └──────────────────────────┬──────────────────────────────────────┘
94
+
95
+
96
+ ┌─────────────────────────────────────────────────────────────────┐
97
+ │ LLM ORCHESTRATEUR │
98
+ │ (ChatGroq avec LangGraph) │
99
+ │ • Analyse la requête utilisateur │
100
+ │ • Décide des outils à utiliser │
101
+ │ • Gère le flow de conversation │
102
+ └──────────────────────────┬──────────────────────────────────────┘
103
+
104
+ ┌──────────────┴──────────────┐
105
+ │ │
106
+ ▼ ▼
107
+ ┌─────────────────────┐ ┌─────────────────────┐
108
+ │ RECHERCHE CACHE │ │ NOUVELLE RECHERCHE │
109
+ │ │ │ │
110
+ │ • Vérif. cache 24h │ │ • Pipeline complet │
111
+ │ • Recherche mémoire │ │ • 4 agents séquence │
112
+ │ • Topics similaires │ │ • Stockage mémoire │
113
+ └──────────┬──────────┘ └──────────┬──────────┘
114
+ │ │
115
+ │ ┌────────────────┘
116
+ │ │
117
+ ▼ ▼
118
+ ┌─────────────────────────────────────────────────────────────────┐
119
+ │ SYSTÈME DE MÉMOIRE │
120
+ │ │
121
+ │ ┌─────────────────────┐ ┌──────────────────────┐ │
122
+ │ │ MÉMOIRE VECTORIELLE│ │ MÉMOIRE AGENT │ │
123
+ │ │ (ChromaDB) │ │ (Cache + Historique) │ │
124
+ │ │ │ │ │ │
125
+ │ │ • Embeddings │ │ • Conversations │ │
126
+ │ │ • Recherche top-k │ │ • Cache recherches │ │
127
+ │ │ • Déduplication │◄────────┤ • Topics + keywords │ │
128
+ │ │ • Persistance │ │ • Compression auto │ │
129
+ │ └─────────────────────┘ └──────────────────────┘ │
130
+ └─────────────────────────────────────────────────────────────────┘
131
+
132
+
133
+
134
+ RAPPORT STRUCTURÉ
135
+ (Markdown, HTML, Text, JSON)
136
+
137
+ ┌──────────────────────────────────────────────────────────────────┐
138
+ │ PIPELINE DE RECHERCHE │
139
+ │ │
140
+ │ ┌─────────────┐ ┌─────────────┐ ┌──────────────┐ │
141
+ │ │ AGENT 1 │ │ AGENT 2 │ │ AGENT 3 │ │
142
+ │ │ RESEARCHER │──►│ EXTRACTOR │──►│ SUMMARIZER │ │
143
+ │ │ │ │ │ │ │ │
144
+ │ │ • Tavily │ │ • Parsing │ │ • LLM │ │
145
+ │ │ • Serper │ │ • Nettoyage │ │ • Chunking │ │
146
+ │ │ • Keywords │ │ • Validation│ │ • Points-clés│ │
147
+ │ └─────────────┘ └─────────────┘ └──────┬───────┘ │
148
+ │ │ │
149
+ │ ▼ │
150
+ │ ┌──────────────────┐ │
151
+ │ │ AGENT 4 │ │
152
+ │ │GLOBAL SYNTHESIZER│ │
153
+ │ │ │ │
154
+ │ │ • Thèmes │ │
155
+ │ │ • Consensus │ │
156
+ │ │ • Rapport final │ │
157
+ │ └──────────────────┘ │
158
+ └──────────────────────────────────────────────────────────────────┘
159
+
160
+ ```
161
+
162
+ ---
163
+
164
+ ## 🤖 Description des Agents
165
+
166
+ ### 1. 🔍 ResearcherAgent
167
+ **Rôle** : Recherche web et extraction de mots-clés
168
+
169
+ **Responsabilités** :
170
+ - Extraction automatique de mots-clés via LLM
171
+ - Recherche multi-API (Tavily, Serper)
172
+ - Filtrage et validation des résultats
173
+ - Gestion du rate limiting
174
+
175
+ **Inputs** :
176
+ ```python
177
+ ResearchQuery(
178
+ topic: str,
179
+ keywords: List[str],
180
+ max_results: int = 10,
181
+ search_depth: str = "basic"
182
+ )
183
+ ```
184
+
185
+ **Outputs** :
186
+ ```python
187
+ ResearchOutput(
188
+ results: List[SearchResult],
189
+ total_found: int,
190
+ search_engine: str,
191
+ search_time: float
192
+ )
193
+ ```
194
+
195
+ ### 2. 📄 ContentExtractorAgent
196
+ **Rôle** : Extraction et nettoyage du contenu web
197
+
198
+ **Responsabilités** :
199
+ - Parsing HTML avec BeautifulSoup
200
+ - Nettoyage et normalisation du texte
201
+ - Détection du type de document
202
+ - Validation de la qualité
203
+
204
+ **Inputs** :
205
+ ```python
206
+ ResearchOutput # Provient du ResearcherAgent
207
+ ```
208
+
209
+ **Outputs** :
210
+ ```python
211
+ ExtractionResult(
212
+ documents: List[Document],
213
+ successful_extractions: int,
214
+ failed_urls: List[str],
215
+ extraction_stats: Dict
216
+ )
217
+ ```
218
+
219
+ ### 3. 📝 SummarizerAgent
220
+ **Rôle** : Génération de résumés détaillés
221
+
222
+ **Responsabilités** :
223
+ - Découpage intelligent du texte (chunking)
224
+ - Résumés exécutifs et détaillés
225
+ - Extraction de points-clés et arguments
226
+ - Analyse de sentiment et crédibilité
227
+
228
+ **Inputs** :
229
+ ```python
230
+ ExtractionResult # Provient du ContentExtractorAgent
231
+ ```
232
+
233
+ **Outputs** :
234
+ ```python
235
+ SummarizationOutput(
236
+ summaries: List[DocumentSummary],
237
+ total_documents: int,
238
+ average_credibility: float,
239
+ common_themes: List[str]
240
+ )
241
+ ```
242
+
243
+ ### 4. 🎯 GlobalSynthesizerAgent
244
+ **Rôle** : Synthèse globale et génération de rapport
245
+
246
+ **Responsabilités** :
247
+ - Analyse thématique transversale
248
+ - Identification de consensus et conflits
249
+ - Génération de rapport structuré
250
+ - Export multi-format (Markdown, HTML, Text)
251
+
252
+ **Inputs** :
253
+ ```python
254
+ SummarizationOutput # Provient du SummarizerAgent
255
+ ```
256
+
257
+ **Outputs** :
258
+ ```python
259
+ GlobalSynthesisOutput(
260
+ final_report: FinalReport,
261
+ synthesis_metadata: Dict,
262
+ processing_stats: Dict,
263
+ formatted_outputs: Dict[str, str]
264
+ )
265
+ ```
266
+
267
+ ---
268
+
269
+ ## 💾 Système de Mémoire
270
+
271
+ ### Architecture de la Mémoire
272
+
273
+ Le système utilise **deux types de mémoire complémentaires** :
274
+
275
+ #### 1. 🗄️ Mémoire Vectorielle (ChromaDB)
276
+
277
+ ```python
278
+ VectorMemoryManager(
279
+ persist_directory="./chroma_db",
280
+ collection_name="research_documents",
281
+ embedding_model="sentence-transformers/all-MiniLM-L6-v2"
282
+ )
283
+ ```
284
+
285
+ **Fonctionnalités** :
286
+ - **Embeddings** : Modèles HuggingFace pour représentation vectorielle
287
+ - **Recherche sémantique** : Top-K avec scores de similarité cosinus
288
+ - **Déduplication** : Hash MD5 pour éviter les doublons
289
+ - **Persistance** : Stockage permanent sur disque
290
+ - **Nettoyage auto** : Suppression des documents > 30 jours
291
+
292
+ **Méthodes principales** :
293
+ ```python
294
+ # Ajout de documents
295
+ stats = vector_memory.add_documents(
296
+ documents=[{
297
+ 'content': "...",
298
+ 'title': "...",
299
+ 'url': "..."
300
+ }],
301
+ source='research',
302
+ check_duplicates=True
303
+ )
304
+
305
+ # Recherche sémantique
306
+ results = vector_memory.semantic_search(
307
+ query="intelligence artificielle",
308
+ k=5,
309
+ filter_dict={'source': 'research'}
310
+ )
311
+
312
+ # Nettoyage
313
+ deleted = vector_memory.clear_old_documents(days=30)
314
+ ```
315
+
316
+ #### 2. 🧠 Mémoire d'Agent (Cache + Historique)
317
+
318
+ ```python
319
+ AgentMemoryManager(
320
+ memory_file="./agent_memory.pkl",
321
+ max_history=100,
322
+ compression_threshold=50
323
+ )
324
+ ```
325
+
326
+ **Fonctionnalités** :
327
+ - **Historique conversationnel** : Deque avec limite (100 entrées)
328
+ - **Cache des recherches** : TTL 24h par défaut
329
+ - **Keywords tracking** : Association topic → keywords
330
+ - **Compression auto** : Après 50 entrées
331
+ - **Persistance pickle** : Sauvegarde sur disque
332
+
333
+ **Méthodes principales** :
334
+ ```python
335
+ # Ajouter une conversation
336
+ agent_memory.add_conversation(
337
+ user_message="Résume l'IA",
338
+ assistant_response="...",
339
+ metadata={'sources': 5}
340
+ )
341
+
342
+ # Récupérer du cache
343
+ result = agent_memory.get_research_result(
344
+ topic="intelligence artificielle",
345
+ max_age_hours=24
346
+ )
347
+
348
+ # Topics similaires
349
+ related = agent_memory.get_related_topics(
350
+ topic="IA dans la santé",
351
+ threshold=0.5
352
+ )
353
+ ```
354
+
355
+ ### 🔗 Système Intégré
356
+
357
+ ```python
358
+ IntegratedMemorySystem()
359
+ ```
360
+
361
+ Combine les deux mémoires pour :
362
+ - Stockage automatique de tous les résultats de recherche
363
+ - Récupération intelligente du contexte
364
+ - Vérification du cache avant nouvelle recherche
365
+ - Enrichissement des réponses avec contexte historique
366
+
367
+ ---
368
+
369
+ ## 🛠️ Installation
370
+
371
+ ### Prérequis
372
+
373
+ - **Python** : 3.12+
374
+ - **Pip** : version récente
375
+ - **Git** : pour cloner le projet
376
+
377
+ ### Étapes d'installation
378
+
379
+ ```bash
380
+ # 1. Cloner le projet
381
+ git clone https://github.com/votre-repo/ai-research-assistant.git
382
+ cd ai-research-assistant
383
+
384
+ # 2. Créer un environnement virtuel
385
+ python -m venv venv
386
+
387
+ # Activer l'environnement
388
+ # Windows
389
+ venv\Scripts\activate
390
+ # Linux/Mac
391
+ source venv/bin/activate
392
+
393
+ # 3. Installer les dépendances
394
+ pip install -r requirements.txt
395
+
396
+ # 4. Configurer les variables d'environnement
397
+ cp .env.example .env
398
+ # Éditer .env avec vos clés API
399
+ ```
400
+
401
+ ### Configuration `.env`
402
+
403
+ ```env
404
+ # LLM
405
+ GROQ_API_KEY=your_groq_api_key_here
406
+
407
+ # Search APIs
408
+ TAVILY_API_KEY=your_tavily_api_key_here
409
+ SERPER_API_KEY=your_serper_api_key_here
410
+
411
+ # Optional
412
+ LOG_LEVEL=INFO
413
+ MAX_RETRIES=3
414
+ TIMEOUT=30
415
+ ```
416
+
417
+ ---
418
+ ############################################################################
419
+ ## 🚀 Utilisation
420
+
421
+ ### Mode CLI Direct
422
+
423
+ ```bash
424
+ # Recherche simple
425
+ python src/graph.py "impact de l'IA sur l'emploi"
426
+
427
+ # Mode test
428
+ python src/graph.py test
429
+
430
+ # Statistiques mémoire
431
+ python src/graph.py stats
432
+ ```
433
+
434
+ ### Mode Interactif
435
+
436
+ ```python
437
+ from src.graph import app_with_memory, run_test
438
+
439
+ # Lancer une recherche
440
+ run_test("Résume les énergies renouvelables", "Ma recherche")
441
+
442
+ # Ou utiliser directement le graphe
443
+ inputs = {"messages": [("user", "Résume l'IA dans la santé")]}
444
+ for state in app_with_memory.stream(inputs, stream_mode="values"):
445
+ print(state["messages"][-1])
446
+ ```
447
+
448
+ ### Mode Menu Interactif
449
+
450
+ ```bash
451
+ python tests/test_memory_system.py
452
+ ```
453
+
454
+ Menu disponible :
455
+ ```
456
+ 1. Poser une question / Lancer une recherche
457
+ 2. Rechercher dans la mémoire
458
+ 3. Voir l'historique
459
+ 4. Statistiques de la mémoire
460
+ 5. Lancer la suite de tests
461
+ 6. Réinitialiser la mémoire
462
+ 0. Quitter
463
+ ```
464
+
465
+ ### Intégration dans votre code
466
+
467
+ ```python
468
+
469
+ from src.agents.researcher_agent import ResearcherAgent
470
+ from src.agents.content_extractor_agent import ContentExtractorAgent
471
+ from src.agents.summarizer_agent import SummarizerAgent
472
+ from src.agents.global_synthesizer_agent import GlobalSynthesizerAgent
473
+ from src.models.research_models import ResearchQuery
474
+
475
+ # Initialiser les agents
476
+ researcher = ResearcherAgent()
477
+ extractor = ContentExtractorAgent()
478
+ summarizer = SummarizerAgent()
479
+ synthesizer = GlobalSynthesizerAgent()
480
+
481
+ # Pipeline complet
482
+ async def recherche_complete(topic: str):
483
+ # 1. Recherche
484
+ query = ResearchQuery(
485
+ topic=topic,
486
+ keywords=await researcher.extract_keywords_with_llm(topic),
487
+ max_results=5
488
+ )
489
+ research_data = await researcher.process(query)
490
+
491
+ # 2. Extraction
492
+ extraction_data = await extractor.process_from_research_output(
493
+ research_output=research_data
494
+ )
495
+
496
+ # 3. Résumés
497
+ summarization_data = await summarizer.process_from_extraction_result(
498
+ extraction_result=extraction_data
499
+ )
500
+
501
+ # 4. Synthèse
502
+ synthesis = await synthesizer.process_from_summarization_output(
503
+ summarization_output=summarization_data
504
+ )
505
+
506
+ return synthesis.final_report.formatted_outputs['markdown']
507
+ ```
508
+
509
+ ---
510
+
511
+ ## 📊 Exemples d'Utilisation
512
+
513
+ ### Exemple 1 : Recherche Simple avec Cache
514
+
515
+ ```python
516
+ # Première recherche (pipeline complet)
517
+ inputs = {
518
+ "messages": [
519
+ ("user", "Résume l'impact de l'IA sur le marché du travail")
520
+ ]
521
+ }
522
+
523
+ for state in app_with_memory.stream(inputs):
524
+ print(state["messages"][-1].content)
525
+
526
+ # Résultat : Pipeline complet exécuté, résultats mis en cache
527
+
528
+ # Même recherche 10 minutes après (utilise le cache)
529
+ inputs = {
530
+ "messages": [
531
+ ("user", "Rappelle-moi ce que tu as trouvé sur l'IA et l'emploi")
532
+ ]
533
+ }
534
+
535
+ for state in app_with_memory.stream(inputs):
536
+ print(state["messages"][-1].content)
537
+
538
+ # Résultat : Réponse instantanée depuis le cache
539
+ ```
540
+
541
+ ### Exemple 2 : Recherche dans la Mémoire
542
+
543
+ ```python
544
+ # Après plusieurs recherches sur l'IA
545
+ inputs = {
546
+ "messages": [
547
+ ("user", "Qu'as-tu trouvé sur l'intelligence artificielle ?")
548
+ ]
549
+ }
550
+
551
+ # Le LLM utilise automatiquement search_in_memory
552
+ # au lieu de lancer une nouvelle recherche web
553
+ ```
554
+
555
+ ### Exemple 3 : Historique et Statistiques
556
+
557
+ ```python
558
+ from src.memory_system import memory_system
559
+
560
+ # Voir l'historique
561
+ history = list(memory_system.agent_memory.conversation_history)
562
+ for conv in history[-5:]:
563
+ print(f"{conv['timestamp']}: {conv['user']}")
564
+
565
+ # Statistiques
566
+ print(f"Documents en mémoire: {memory_system.vector_memory.collection.count()}")
567
+ print(f"Recherches en cache: {len(memory_system.agent_memory.research_cache)}")
568
+ ```
569
+
570
+ ### Exemple 4 : Recherche Approfondie
571
+
572
+ ```python
573
+ from src.memory_integration import research_complete_pipeline_with_memory
574
+
575
+ # Recherche avec plus de sources
576
+ result = research_complete_pipeline_with_memory(
577
+ topic="énergies renouvelables et transition écologique",
578
+ max_results=10, # Plus de sources
579
+ use_cache=False # Forcer une nouvelle recherche
580
+ )
581
+
582
+ print(result) # Rapport Markdown complet
583
+ ```
584
+
585
+ ---
586
+
587
+
588
+ ## 📝 Logs et Monitoring
589
+
590
+ ### Structure des logs
591
+
592
+ ```
593
+ logs/
594
+ ├── agent_researcher.log # Recherche web
595
+ ├── agent_content_extractor.log # Extraction
596
+ ├── agent_summarizer.log # R��sumés
597
+ ├── agent_global_synthesizer.log # Synthèse
598
+ ├── search_manager.log # APIs de recherche
599
+ ├── llm_service.log # Appels LLM
600
+ └── complete_pipeline.log # Pipeline complet
601
+ ```
602
+
603
+ ### Niveaux de log
604
+
605
+ ```python
606
+ # Dans config/settings.py
607
+ LOG_LEVEL = "INFO" # DEBUG, INFO, WARNING, ERROR, CRITICAL
608
+ ```
609
+
610
+ ### Exemple de logs
611
+
612
+ ```
613
+ 2025-11-18 10:30:15 | INFO | agent_researcher | Recherche pour: "IA emploi"
614
+ 2025-11-18 10:30:18 | INFO | agent_researcher | Trouvé 5 sources
615
+ 2025-11-18 10:30:20 | INFO | agent_content_extractor | Extraction: 5/5 succès
616
+ 2025-11-18 10:30:45 | INFO | agent_summarizer | 5 résumés générés
617
+ 2025-11-18 10:31:10 | INFO | agent_global_synthesizer | Rapport: 1250 mots
618
+ 2025-11-18 10:31:12 | INFO | memory_system | Stockage en mémoire réussi
619
+ ```
620
+
621
+ ---
622
+
623
+ ## ⚙️ Configuration Avancée
624
+
625
+ ### Personnaliser les prompts
626
+
627
+ ```python
628
+ # config/prompts.py
629
+
630
+ CUSTOM_RESEARCH_PROMPT = """
631
+ Analyse approfondie sur {topic}.
632
+ Focus sur les aspects suivants :
633
+ - Impact économique
634
+ - Implications sociales
635
+ - Perspectives futures
636
+ """
637
+
638
+ # Utilisation
639
+ from config.prompts import CUSTOM_RESEARCH_PROMPT
640
+
641
+ prompt = CUSTOM_RESEARCH_PROMPT.format(topic="IA générative")
642
+ ```
643
+
644
+ ### Ajuster les paramètres LLM
645
+
646
+ ```python
647
+ # src/services/llm_service.py
648
+
649
+ class LLMService:
650
+ def __init__(self):
651
+ self.model = ChatGroq(
652
+ model="llama-3.1-8b-instant",
653
+ temperature=0.3, # Créativité (0-1)
654
+ max_tokens=2048, # Longueur max
655
+ top_p=0.9, # Nucleus sampling
656
+ frequency_penalty=0.5 # Pénalité répétition
657
+ )
658
+ ```
659
+
660
+ ### Configurer la mémoire vectorielle
661
+
662
+ ```python
663
+ # src/memory_system.py
664
+
665
+ vector_memory = VectorMemoryManager(
666
+ persist_directory="./custom_chroma_db",
667
+ collection_name="my_research_docs",
668
+ embedding_model="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" # Multilingue
669
+ )
670
+ ```
671
+
672
+ ---
673
+
674
+ ## 🔌 Intégration API(Futur)
675
+
676
+ ### REST API (FastAPI)
677
+
678
+ ```python
679
+ # api/main.py
680
+ from fastapi import FastAPI
681
+ from src.graph import app_with_memory
682
+
683
+ app = FastAPI()
684
+
685
+ @app.post("/research")
686
+ async def research_endpoint(topic: str, max_results: int = 3):
687
+ inputs = {"messages": [("user", f"Résume: {topic}")]}
688
+ result = []
689
+
690
+ for state in app_with_memory.stream(inputs):
691
+ result.append(state["messages"][-1].content)
692
+
693
+ return {"result": result[-1]}
694
+ ```
695
+
696
+ ### WebSocket (temps réel)
697
+
698
+ ```python
699
+ from fastapi import WebSocket
700
+
701
+ @app.websocket("/ws/research")
702
+ async def websocket_research(websocket: WebSocket):
703
+ await websocket.accept()
704
+
705
+ while True:
706
+ data = await websocket.receive_text()
707
+ inputs = {"messages": [("user", data)]}
708
+
709
+ for state in app_with_memory.stream(inputs):
710
+ await websocket.send_text(
711
+ state["messages"][-1].content
712
+ )
713
+ ```
714
+
715
+ ---
716
+
717
+ ## 🐛 Dépannage
718
+
719
+ ### Problèmes courants
720
+
721
+ #### 1. Erreur de clé API manquante
722
+
723
+ ```
724
+ ValueError: GROQ_API_KEY non définie
725
+ ```
726
+
727
+ **Solution** : Vérifier le fichier `.env` et s'assurer que les clés sont présentes.
728
+
729
+
730
+ #### 3. Rate limit atteint
731
+
732
+ ```
733
+ WARNING | llm_service | Rate limit atteint, attente 12s
734
+ ```
735
+
736
+ **Solution** : C'est normal, le système attend automatiquement. Pour éviter :
737
+ - Réduire `max_results`
738
+
739
+ #### 4. Mémoire saturée
740
+
741
+ ```
742
+ MemoryError: Cannot allocate memory
743
+ ```
744
+
745
+ **Solution** : Nettoyer la mémoire :
746
+ ```
747
+ memory_system.vector_memory.clear_old_documents(days=7)
748
+ ```
749
+
750
+ ---
751
+
752
+ ```bash
753
+ # Build
754
+ docker build -t ai-research-assistant .
755
+
756
+ # Run
757
+ docker run -e GROQ_API_KEY=xxx -e TAVILY_API_KEY=yyy ai-research-assistant
758
+ ```
759
+
760
+ ### Production (Gunicorn)
761
+
762
+ ```bash
763
+ gunicorn api.main:app --workers 4 --bind 0.0.0.0:8000
764
+ ```
765
+
766
+ ---
767
+
768
+ ## 📈 Roadmap
769
+
770
+ ### Version 1.1 (En cours)
771
+ - [ ] Interface web avec Streamlit
772
+ - [ ] Support multilingue complet
773
+ - [ ] Export PDF des rapports
774
+ - [ ] Notifications par email
775
+
776
+ ### Version 2.0 (Futur)
777
+ - [ ] Agents spécialisés par domaine (santé, finance, tech)
778
+ - [ ] Intégration avec bases de données externes
779
+ - [ ] Système de fact-checking automatique
780
+ - [ ] API GraphQL
781
+
782
+ ---
783
+
784
+ ## 🤝 Contribution
785
+
786
+ Les contributions sont les bienvenues !
787
+
788
+ ---
789
+
790
+ ## 👥 Auteurs
791
+
792
+ - **Bachir** - *Développeur Principal* - [GitHub](https://github.com/bachir00)
793
+
794
+ ---
795
+
796
+ ## 🙏 Remerciements
797
+
798
+ - LangChain & LangGraph pour le framework
799
+ - Groq pour l'accès aux LLMs
800
+ - ChromaDB pour le stockage vectoriel
801
+ - Tavily & Serper pour les APIs de recherche
802
+ - La communauté open-source
803
+
804
+ ---
805
+
806
+ ## 📞 Support
807
+
808
+ - 📧 Email : bassiroukane@esp.sn