--- 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 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 " ``` ## 📖 Utilisation ### Liste des modĂšles disponibles ```bash curl -X GET "http://localhost:7860/models" \ -H "Authorization: Bearer " ``` ### Liste des agents disponibles ```bash curl -X GET "http://localhost:7860/agents" \ -H "Authorization: Bearer " ``` ### Completion simple (non-streaming) ```bash curl -X POST "http://localhost:7860/completion" \ -H "Authorization: Bearer " \ -H "Content-Type: application/json" \ -d '{ "message": "Bonjour, comment vas-tu?", "model": "gpt-4o", "agent": "V2", "stream": false, "temperature": 0.7 }' ``` ### Completion avec streaming (SSE) ```bash curl -X POST "http://localhost:7860/completion" \ -H "Authorization: Bearer " \ -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 " \ -F "file=@audio.mp3" \ -F "language=fr" ``` ### Transcription asynchrone L’API expose Ă©galement des endpoints de transcription **asynchrones** permettant d’uploader un fichier audio, de recevoir immĂ©diatement un **`job_id`**, puis de **poller l’état** du job jusqu’à obtenir la transcription complĂšte. #### Endpoints - **Synchrone (existants)** - `POST /transcription` - `POST /transcription/meeting` - **Asynchrone (nouveaux)** - `POST /transcription/jobs` CrĂ©e un job de transcription audio (`job_type = "transcription_audio"`) et retourne un `job_id`. - `POST /transcription/meeting/jobs` CrĂ©e un job de transcription de rĂ©union (`job_type = "transcription_meeting"`) et retourne un `job_id`. - `GET /transcription/jobs/{job_id}` Retourne l’état du job et, une fois terminĂ©, la transcription. Tous ces endpoints nĂ©cessitent un JWT (`Authorization: Bearer `). #### Gestion des fichiers audio - **Formats supportĂ©s** : `mp3`, `mp4`, `mpeg`, `mpga`, `m4a`, `wav`, `webm`. - **Taille maximale d’upload** : `settings.max_upload_mb_audio` (par dĂ©faut 500 Mo). - **Limite OpenAI (25 Mo)** : le backend dĂ©coupe automatiquement les fichiers audio de grande taille en plusieurs segments (rĂ©-encodĂ©s en MP3 128 kbps) et enchaĂźne les appels Ă  l’API OpenAI, en concatĂ©nant les rĂ©sultats. Un *prompt glissant* (fin du chunk prĂ©cĂ©dent) est utilisĂ© pour conserver le contexte. #### Exemple – crĂ©ation d’un job asynchrone ```bash curl -X POST "http://localhost:7860/transcription/jobs" \ -H "Authorization: Bearer " \ -F "file=@audio.mp3" \ -F "language=fr" \ -F "prompt=Contexte de la rĂ©union" ``` RĂ©ponse (`UploadJobResponse`) : ```json { "job_id": "uuid-...", "status": "queued", "created_at": "2026-03-09T12:34:56Z" } ``` #### Exemple – polling de l’état d’un job ```bash curl -X GET "http://localhost:7860/transcription/jobs/" \ -H "Authorization: Bearer " ``` RĂ©ponse (`JobStatusResponse`) – extrait : ```json { "job_id": "uuid-...", "status": "succeeded", "job_type": "transcription_audio", "progress_percent": 100, "transcript_text": "Texte complet de la transcription...", "transcript_language": "fr", "transcript_duration": 123.45, "transcript_model": "whisper-1" } ``` #### StratĂ©gie cĂŽtĂ© client 1. Appeler `POST /transcription/jobs` ou `/transcription/meeting/jobs` et rĂ©cupĂ©rer `job_id`. 2. Poller rĂ©guliĂšrement `GET /transcription/jobs/{job_id}` (toutes les 2–5 secondes). 3. ArrĂȘter le polling lorsque : - `status = "succeeded"` → utiliser `transcript_text`, - `status = "failed"` → afficher/traiter `error`. 4. PrĂ©voir un timeout global et Ă©ventuellement une barre de progression basĂ©e sur `progress_percent`. ### 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( "my_agent", create_custom_graph, "Description de votre agent" ) ``` 3. Utilisez-le via l'API avec `"agent": "my_agent"` dans la requĂȘte `POST /completion`. ## đŸ§Ș 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 - [ ] Harmoniser la nomenclature du pipeline voix: le champ `agent_type` est encore utilisĂ© dans `services/voice/voice_pipeline.py` pour des Ă©vĂ©nements internes et devra ĂȘtre renommĂ© en `agent` lors d'un prochain refactoring. - [ ] 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.