File size: 7,249 Bytes
3cd7bfc
 
 
 
 
 
 
 
 
 
 
d28f1ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e6b670
 
d28f1ed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
---
title: Routeur Ia Api
emoji: 📊
colorFrom: pink
colorTo: purple
sdk: docker
pinned: false
---

Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference

# CAPL Routeur IA API

API sécurisée pour l'interaction avec des agents IA basés sur LangGraph, avec support multi-modèles (OpenAI et Mistral AI).

## 🚀 Fonctionnalités

-**Authentification JWT** pour sécuriser l'accès
-**Completion texte** avec support du streaming (Server-Sent Events)
-**Multi-modèles**: OpenAI (GPT-4, GPT-3.5) et Mistral AI (Large, Medium, Small, Tiny)
-**Multi-agents**: Architecture extensible pour différents types d'agents LangGraph
-**Transcription audio**: Conversion audio vers texte avec OpenAI Whisper
-**WebSocket**: Communication temps réel bidirectionnelle
-**Architecture Clean**: Séparation domain/services/api selon les principes SOLID

## 📋 Prérequis

- Python 3.12+
- Clés API OpenAI et Mistral AI

## 🛠️ Installation

1. **Cloner le repository**
```bash
git clone <repository-url>
cd routeur_ia_api
```

2. **Créer un environnement virtuel**
```bash
python -m venv venv
source venv/bin/activate  # Linux/Mac
# ou
venv\Scripts\activate  # Windows
```

3. **Installer les dépendances**
```bash
pip install -r requirements.txt
```

4. **Configurer les variables d'environnement**

Créez un fichier `.env` à la racine du projet (voir `.env.example` pour référence):

```env
# API Keys
OPENAI_API_KEY=sk-your-openai-key-here
MISTRALAI_API_KEY=your-mistral-key-here

# JWT Security
JWT_SECRET_KEY=your-secret-key-here-change-in-production
JWT_ALGORITHM=HS256
JWT_EXPIRATION_MINUTES=60

# API Config
API_TITLE=CAPL Routeur IA API
API_VERSION=1.0.0
ENVIRONMENT=development
```

**⚠️ IMPORTANT**: Changez `JWT_SECRET_KEY` en production avec une valeur sécurisée!

## 🚀 Lancement

### Mode développement

```bash
python app.py
```

ou avec uvicorn directement:

```bash
uvicorn app:app --reload --port 7860
```

### Mode production

```bash
uvicorn app:app --host 0.0.0.0 --port 7860 --workers 4
```

### Avec Docker

```bash
docker build -t routeur-ia-api .
docker run -p 7860:7860 --env-file .env routeur-ia-api
```

## 📚 Documentation API

Une fois l'API lancée, accédez à:

- **Swagger UI**: http://localhost:7860/docs
- **ReDoc**: http://localhost:7860/redoc

## 🔐 Authentification

### 1. Obtenir un token JWT

```bash
curl -X POST "http://localhost:7860/auth/token" \
  -H "Content-Type: application/json"
```

Réponse:
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 3600
}
```

### 2. Utiliser le token

Incluez le token dans le header `Authorization` de toutes vos requêtes:

```bash
curl -X GET "http://localhost:7860/models" \
  -H "Authorization: Bearer <votre-token>"
```

## 📖 Utilisation

### Liste des modèles disponibles

```bash
curl -X GET "http://localhost:7860/models" \
  -H "Authorization: Bearer <token>"
```

### Liste des agents disponibles

```bash
curl -X GET "http://localhost:7860/agents" \
  -H "Authorization: Bearer <token>"
```

### Completion simple (non-streaming)

```bash
curl -X POST "http://localhost:7860/completion" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Bonjour, comment vas-tu?",
    "model": "gpt-4o",
    "agent_type": "simple",
    "stream": false,
    "temperature": 0.7
  }'
```

### Completion avec streaming (SSE)

```bash
curl -X POST "http://localhost:7860/completion" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -N \
  -d '{
    "message": "Raconte-moi une histoire",
    "model": "gpt-4o",
    "stream": true
  }'
```

### Transcription audio

```bash
curl -X POST "http://localhost:7860/transcription" \
  -H "Authorization: Bearer <token>" \
  -F "file=@audio.mp3" \
  -F "language=fr"
```

### WebSocket temps réel

```javascript
const ws = new WebSocket('ws://localhost:7860/realtime/ws');

ws.onopen = () => {
  console.log('Connected');
  
  // Envoyer un message
  ws.send(JSON.stringify({
    type: 'message',
    payload: { text: 'Hello!' }
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
};
```

## 🏗️ Architecture

```
routeur_ia_api/
├── config/           # Configuration et settings
├── core/             # Sécurité JWT et dépendances
├── domain/           # Modèles et enums du domaine
├── services/         # Services métier (LLM, Agent, Transcription)
├── graphs/           # Graphes LangGraph
├── api/
│   ├── routes/       # Routes API
│   └── middleware.py # Middleware personnalisé
├── app.py            # Point d'entrée FastAPI
└── requirements.txt  # Dépendances Python
```

### Principes SOLID appliqués

- **Single Responsibility**: Chaque service a une responsabilité unique
- **Open/Closed**: Agents extensibles via le registre sans modifier l'API
- **Liskov Substitution**: Tous les LLM respectent l'interface `BaseChatModel`
- **Interface Segregation**: Interfaces minimales et spécifiques
- **Dependency Inversion**: Dépendances abstraites via injection

## 🤖 Ajouter un nouvel agent

1. Créez un nouveau graphe dans `graphs/`:

```python
# graphs/custom_graph.py
from langgraph.graph import StateGraph, END

def create_custom_graph(llm):
    # Votre logique
    workflow = StateGraph(CustomState)
    workflow.add_node("custom", custom_node)
    workflow.set_entry_point("custom")
    workflow.add_edge("custom", END)
    return workflow.compile()
```

2. Enregistrez-le dans le registre:

```python
# services/agent_registry.py
from graphs.custom_graph import create_custom_graph

agent_registry.register_agent(
    AgentType.CUSTOM,
    create_custom_graph,
    "Description de votre agent"
)
```

3. Utilisez-le via l'API sans changement de code!

## 🧪 Tests

```bash
# À implémenter
pytest tests/
```

## 📊 Monitoring avec LangSmith

Activez LangSmith dans `.env`:

```env
LANGCHAIN_TRACING_V2=true
LANGCHAIN_API_KEY=your-langsmith-key
LANGCHAIN_PROJECT=routeur-ia
```

## 🔒 Sécurité

- ✅ Authentification JWT obligatoire
- ✅ Validation Pydantic stricte
- ✅ Headers de sécurité (CORS, CSP, etc.)
- ✅ Gestion des erreurs sécurisée
- ⚠️ En production: Utilisez HTTPS uniquement
- ⚠️ En production: Restreignez CORS aux origines autorisées
- ⚠️ En production: Utilisez un secret JWT robuste

## 📝 TODO / Roadmap

- [ ] Tests unitaires et d'intégration
- [ ] Implémentation complète WebRTC avec aiortc
- [ ] Agent RAG avec base vectorielle
- [ ] Agent avec outils (recherche web, calculatrice)
- [ ] Rate limiting
- [ ] Cache des réponses
- [ ] Métriques Prometheus
- [ ] CI/CD pipeline

## 🤝 Contribution

Les contributions sont les bienvenues! Veuillez suivre les principes SOLID et Clean Architecture.

## 📄 Licence

[À définir]

## 👥 Auteurs

CAPL - Routeur IA Team

---

**Note**: Cette API est en développement actif. Certaines fonctionnalités (notamment WebRTC complet) sont des placeholders et nécessitent une implémentation complète pour la production.