588 lines
13 KiB
Markdown
588 lines
13 KiB
Markdown
|
|
# Exemples d'utilisation - AI Code Assistant
|
||
|
|
|
||
|
|
## 🔌 Intégrations API
|
||
|
|
|
||
|
|
### 1. Utiliser l'API depuis Python
|
||
|
|
|
||
|
|
```python
|
||
|
|
import requests
|
||
|
|
import json
|
||
|
|
|
||
|
|
API_URL = "http://localhost:9001"
|
||
|
|
|
||
|
|
# Exemple 1: Chat simple
|
||
|
|
def ask_ai(question, model="qwen2.5-coder:7b"):
|
||
|
|
response = requests.post(
|
||
|
|
f"{API_URL}/chat",
|
||
|
|
json={
|
||
|
|
"messages": [{"role": "user", "content": question}],
|
||
|
|
"model": model,
|
||
|
|
"stream": False
|
||
|
|
}
|
||
|
|
)
|
||
|
|
return response.json()["response"]
|
||
|
|
|
||
|
|
# Utilisation
|
||
|
|
result = ask_ai("Écris une fonction pour valider un email")
|
||
|
|
print(result)
|
||
|
|
|
||
|
|
|
||
|
|
# Exemple 2: Exécuter du code
|
||
|
|
def run_code(code, language="python"):
|
||
|
|
response = requests.post(
|
||
|
|
f"{API_URL}/execute",
|
||
|
|
json={"code": code, "language": language}
|
||
|
|
)
|
||
|
|
result = response.json()
|
||
|
|
|
||
|
|
if result["success"]:
|
||
|
|
return result["stdout"]
|
||
|
|
else:
|
||
|
|
return f"Erreur: {result['stderr']}"
|
||
|
|
|
||
|
|
# Utilisation
|
||
|
|
code = """
|
||
|
|
def fibonacci(n):
|
||
|
|
if n <= 1:
|
||
|
|
return n
|
||
|
|
return fibonacci(n-1) + fibonacci(n-2)
|
||
|
|
|
||
|
|
print(fibonacci(10))
|
||
|
|
"""
|
||
|
|
|
||
|
|
output = run_code(code)
|
||
|
|
print(output)
|
||
|
|
|
||
|
|
|
||
|
|
# Exemple 3: Analyse de code
|
||
|
|
def analyze_code(code, language="python"):
|
||
|
|
response = requests.post(
|
||
|
|
f"{API_URL}/analyze-code",
|
||
|
|
json={"code": code, "language": language}
|
||
|
|
)
|
||
|
|
return response.json()["analysis"]
|
||
|
|
|
||
|
|
# Utilisation
|
||
|
|
code_to_analyze = """
|
||
|
|
def divide(a, b):
|
||
|
|
return a / b
|
||
|
|
"""
|
||
|
|
|
||
|
|
analysis = analyze_code(code_to_analyze)
|
||
|
|
print(analysis)
|
||
|
|
```
|
||
|
|
|
||
|
|
### 2. WebSocket en Python
|
||
|
|
|
||
|
|
```python
|
||
|
|
import asyncio
|
||
|
|
import websockets
|
||
|
|
import json
|
||
|
|
|
||
|
|
async def chat_websocket():
|
||
|
|
uri = "ws://localhost:9001/ws/chat"
|
||
|
|
|
||
|
|
async with websockets.connect(uri) as websocket:
|
||
|
|
# Envoyer un message
|
||
|
|
message = {
|
||
|
|
"message": "Explique les decorators Python",
|
||
|
|
"model": "qwen2.5-coder:7b"
|
||
|
|
}
|
||
|
|
await websocket.send(json.dumps(message))
|
||
|
|
|
||
|
|
# Recevoir la réponse en streaming
|
||
|
|
full_response = ""
|
||
|
|
while True:
|
||
|
|
response = await websocket.recv()
|
||
|
|
data = json.loads(response)
|
||
|
|
|
||
|
|
if data["type"] == "stream":
|
||
|
|
full_response += data["content"]
|
||
|
|
print(data["content"], end="", flush=True)
|
||
|
|
|
||
|
|
elif data["type"] == "done":
|
||
|
|
print("\n\nRéponse complète reçue!")
|
||
|
|
break
|
||
|
|
|
||
|
|
elif data["type"] == "error":
|
||
|
|
print(f"\nErreur: {data['content']}")
|
||
|
|
break
|
||
|
|
|
||
|
|
# Exécuter
|
||
|
|
asyncio.run(chat_websocket())
|
||
|
|
```
|
||
|
|
|
||
|
|
### 3. Intégration JavaScript/Node.js
|
||
|
|
|
||
|
|
```javascript
|
||
|
|
// chat.js - Utilisation depuis Node.js
|
||
|
|
const axios = require('axios');
|
||
|
|
|
||
|
|
const API_URL = 'http://localhost:9001';
|
||
|
|
|
||
|
|
// Chat simple
|
||
|
|
async function askAI(question, model = 'qwen2.5-coder:7b') {
|
||
|
|
const response = await axios.post(`${API_URL}/chat`, {
|
||
|
|
messages: [{ role: 'user', content: question }],
|
||
|
|
model: model,
|
||
|
|
stream: false
|
||
|
|
});
|
||
|
|
|
||
|
|
return response.data.response;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Exécution de code
|
||
|
|
async function executeCode(code, language = 'python') {
|
||
|
|
const response = await axios.post(`${API_URL}/execute`, {
|
||
|
|
code: code,
|
||
|
|
language: language
|
||
|
|
});
|
||
|
|
|
||
|
|
return response.data;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Utilisation
|
||
|
|
(async () => {
|
||
|
|
// Question à l'IA
|
||
|
|
const answer = await askAI('Crée une fonction pour trier un array');
|
||
|
|
console.log(answer);
|
||
|
|
|
||
|
|
// Exécuter du code
|
||
|
|
const result = await executeCode('print("Hello from AI!")');
|
||
|
|
console.log(result.stdout);
|
||
|
|
})();
|
||
|
|
```
|
||
|
|
|
||
|
|
### 4. WebSocket depuis le navigateur
|
||
|
|
|
||
|
|
```javascript
|
||
|
|
// Dans votre page HTML
|
||
|
|
const ws = new WebSocket('ws://localhost:9001/ws/chat');
|
||
|
|
|
||
|
|
ws.onopen = () => {
|
||
|
|
console.log('Connecté au serveur');
|
||
|
|
|
||
|
|
// Envoyer un message
|
||
|
|
ws.send(JSON.stringify({
|
||
|
|
message: 'Explique les promises en JavaScript',
|
||
|
|
model: 'qwen2.5-coder:7b'
|
||
|
|
}));
|
||
|
|
};
|
||
|
|
|
||
|
|
ws.onmessage = (event) => {
|
||
|
|
const data = JSON.parse(event.data);
|
||
|
|
|
||
|
|
if (data.type === 'stream') {
|
||
|
|
// Afficher le contenu au fur et à mesure
|
||
|
|
document.getElementById('response').innerHTML += data.content;
|
||
|
|
} else if (data.type === 'done') {
|
||
|
|
console.log('Réponse complète');
|
||
|
|
} else if (data.type === 'error') {
|
||
|
|
console.error('Erreur:', data.content);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
ws.onerror = (error) => {
|
||
|
|
console.error('Erreur WebSocket:', error);
|
||
|
|
};
|
||
|
|
```
|
||
|
|
|
||
|
|
## 🛠️ Scripts utilitaires
|
||
|
|
|
||
|
|
### Script de génération automatique de tests
|
||
|
|
|
||
|
|
```python
|
||
|
|
#!/usr/bin/env python3
|
||
|
|
"""
|
||
|
|
Génère automatiquement des tests unitaires pour un fichier Python
|
||
|
|
"""
|
||
|
|
|
||
|
|
import requests
|
||
|
|
import sys
|
||
|
|
import os
|
||
|
|
|
||
|
|
API_URL = "http://localhost:9001"
|
||
|
|
|
||
|
|
def generate_tests(code_file):
|
||
|
|
# Lire le code
|
||
|
|
with open(code_file, 'r') as f:
|
||
|
|
code = f.read()
|
||
|
|
|
||
|
|
# Demander à l'IA de générer les tests
|
||
|
|
prompt = f"""
|
||
|
|
Génère des tests unitaires complets avec pytest pour ce code:
|
||
|
|
|
||
|
|
```python
|
||
|
|
{code}
|
||
|
|
```
|
||
|
|
|
||
|
|
Inclus:
|
||
|
|
- Tests pour tous les cas normaux
|
||
|
|
- Tests pour les cas limites
|
||
|
|
- Tests pour les erreurs attendues
|
||
|
|
- Fixtures si nécessaire
|
||
|
|
"""
|
||
|
|
|
||
|
|
response = requests.post(
|
||
|
|
f"{API_URL}/chat",
|
||
|
|
json={
|
||
|
|
"messages": [{"role": "user", "content": prompt}],
|
||
|
|
"model": "code-expert",
|
||
|
|
"stream": False
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
tests = response.json()["response"]
|
||
|
|
|
||
|
|
# Sauvegarder les tests
|
||
|
|
test_file = f"test_{os.path.basename(code_file)}"
|
||
|
|
|
||
|
|
# Extraire le code des blocs markdown
|
||
|
|
import re
|
||
|
|
code_blocks = re.findall(r'```python\n(.*?)```', tests, re.DOTALL)
|
||
|
|
|
||
|
|
if code_blocks:
|
||
|
|
with open(test_file, 'w') as f:
|
||
|
|
f.write(code_blocks[0])
|
||
|
|
print(f"✅ Tests générés: {test_file}")
|
||
|
|
else:
|
||
|
|
print("❌ Impossible d'extraire les tests")
|
||
|
|
print(tests)
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
if len(sys.argv) != 2:
|
||
|
|
print("Usage: python generate_tests.py <fichier.py>")
|
||
|
|
sys.exit(1)
|
||
|
|
|
||
|
|
generate_tests(sys.argv[1])
|
||
|
|
```
|
||
|
|
|
||
|
|
### Script de revue de code automatique
|
||
|
|
|
||
|
|
```python
|
||
|
|
#!/usr/bin/env python3
|
||
|
|
"""
|
||
|
|
Effectue une revue de code automatique sur un fichier
|
||
|
|
"""
|
||
|
|
|
||
|
|
import requests
|
||
|
|
import sys
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
API_URL = "http://localhost:9001"
|
||
|
|
|
||
|
|
def review_file(filepath):
|
||
|
|
# Lire le fichier
|
||
|
|
code = Path(filepath).read_text()
|
||
|
|
language = filepath.split('.')[-1]
|
||
|
|
|
||
|
|
# Analyser avec l'IA
|
||
|
|
response = requests.post(
|
||
|
|
f"{API_URL}/analyze-code",
|
||
|
|
json={"code": code, "language": language}
|
||
|
|
)
|
||
|
|
|
||
|
|
analysis = response.json()["analysis"]
|
||
|
|
|
||
|
|
# Afficher la revue
|
||
|
|
print(f"\n{'='*60}")
|
||
|
|
print(f"📝 Revue de code: {filepath}")
|
||
|
|
print(f"{'='*60}\n")
|
||
|
|
print(analysis)
|
||
|
|
print(f"\n{'='*60}\n")
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
if len(sys.argv) != 2:
|
||
|
|
print("Usage: python code_review.py <fichier>")
|
||
|
|
sys.exit(1)
|
||
|
|
|
||
|
|
review_file(sys.argv[1])
|
||
|
|
```
|
||
|
|
|
||
|
|
### Script de documentation automatique
|
||
|
|
|
||
|
|
```python
|
||
|
|
#!/usr/bin/env python3
|
||
|
|
"""
|
||
|
|
Génère automatiquement de la documentation pour un fichier de code
|
||
|
|
"""
|
||
|
|
|
||
|
|
import requests
|
||
|
|
import sys
|
||
|
|
|
||
|
|
API_URL = "http://localhost:9001"
|
||
|
|
|
||
|
|
def generate_docs(code_file):
|
||
|
|
with open(code_file, 'r') as f:
|
||
|
|
code = f.read()
|
||
|
|
|
||
|
|
prompt = f"""
|
||
|
|
Génère une documentation complète en français pour ce code:
|
||
|
|
|
||
|
|
```python
|
||
|
|
{code}
|
||
|
|
```
|
||
|
|
|
||
|
|
Inclus:
|
||
|
|
- Description générale du module
|
||
|
|
- Documentation de chaque fonction/classe
|
||
|
|
- Exemples d'utilisation
|
||
|
|
- Notes importantes
|
||
|
|
- Format: docstrings Google style
|
||
|
|
"""
|
||
|
|
|
||
|
|
response = requests.post(
|
||
|
|
f"{API_URL}/chat",
|
||
|
|
json={
|
||
|
|
"messages": [{"role": "user", "content": prompt}],
|
||
|
|
"model": "code-expert",
|
||
|
|
"stream": False
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
docs = response.json()["response"]
|
||
|
|
|
||
|
|
# Sauvegarder
|
||
|
|
doc_file = f"{code_file}.md"
|
||
|
|
with open(doc_file, 'w') as f:
|
||
|
|
f.write(f"# Documentation - {code_file}\n\n")
|
||
|
|
f.write(docs)
|
||
|
|
|
||
|
|
print(f"✅ Documentation générée: {doc_file}")
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
if len(sys.argv) != 2:
|
||
|
|
print("Usage: python generate_docs.py <fichier.py>")
|
||
|
|
sys.exit(1)
|
||
|
|
|
||
|
|
generate_docs(sys.argv[1])
|
||
|
|
```
|
||
|
|
|
||
|
|
## 🔄 Intégration Git Hooks
|
||
|
|
|
||
|
|
### Pre-commit hook pour revue automatique
|
||
|
|
|
||
|
|
```bash
|
||
|
|
#!/bin/bash
|
||
|
|
# .git/hooks/pre-commit
|
||
|
|
|
||
|
|
# Revue automatique des fichiers Python modifiés
|
||
|
|
|
||
|
|
echo "🔍 Revue de code automatique..."
|
||
|
|
|
||
|
|
# Trouver les fichiers Python modifiés
|
||
|
|
PYTHON_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '\.py$')
|
||
|
|
|
||
|
|
if [ -z "$PYTHON_FILES" ]; then
|
||
|
|
echo "Aucun fichier Python à vérifier"
|
||
|
|
exit 0
|
||
|
|
fi
|
||
|
|
|
||
|
|
# Analyser chaque fichier
|
||
|
|
for file in $PYTHON_FILES; do
|
||
|
|
echo "Analyse: $file"
|
||
|
|
|
||
|
|
# Appeler l'API d'analyse
|
||
|
|
CODE=$(cat "$file")
|
||
|
|
ANALYSIS=$(curl -s -X POST http://localhost:9001/analyze-code \
|
||
|
|
-H "Content-Type: application/json" \
|
||
|
|
-d "{\"code\": $(echo "$CODE" | jq -Rs .), \"language\": \"python\"}" \
|
||
|
|
| jq -r '.analysis')
|
||
|
|
|
||
|
|
# Vérifier si des problèmes critiques sont détectés
|
||
|
|
if echo "$ANALYSIS" | grep -qi "CRITIQUE\|ERREUR\|BUG"; then
|
||
|
|
echo "⚠️ Problèmes détectés dans $file:"
|
||
|
|
echo "$ANALYSIS"
|
||
|
|
echo ""
|
||
|
|
|
||
|
|
read -p "Voulez-vous continuer le commit ? (o/n) " -n 1 -r
|
||
|
|
echo
|
||
|
|
if [[ ! $REPLY =~ ^[Oo]$ ]]; then
|
||
|
|
exit 1
|
||
|
|
fi
|
||
|
|
fi
|
||
|
|
done
|
||
|
|
|
||
|
|
echo "✅ Revue terminée"
|
||
|
|
exit 0
|
||
|
|
```
|
||
|
|
|
||
|
|
## 🎯 Cas d'usage avancés
|
||
|
|
|
||
|
|
### 1. Assistant de refactoring
|
||
|
|
|
||
|
|
```python
|
||
|
|
def refactor_code(code, instructions):
|
||
|
|
prompt = f"""
|
||
|
|
Code actuel:
|
||
|
|
```python
|
||
|
|
{code}
|
||
|
|
```
|
||
|
|
|
||
|
|
Instructions de refactoring: {instructions}
|
||
|
|
|
||
|
|
Fournis le code refactoré en suivant les best practices.
|
||
|
|
"""
|
||
|
|
|
||
|
|
response = requests.post(
|
||
|
|
f"{API_URL}/chat",
|
||
|
|
json={
|
||
|
|
"messages": [{"role": "user", "content": prompt}],
|
||
|
|
"model": "code-expert",
|
||
|
|
"stream": False
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
return response.json()["response"]
|
||
|
|
|
||
|
|
# Exemple
|
||
|
|
old_code = """
|
||
|
|
def calc(x, y, op):
|
||
|
|
if op == '+':
|
||
|
|
return x + y
|
||
|
|
elif op == '-':
|
||
|
|
return x - y
|
||
|
|
elif op == '*':
|
||
|
|
return x * y
|
||
|
|
elif op == '/':
|
||
|
|
return x / y
|
||
|
|
"""
|
||
|
|
|
||
|
|
refactored = refactor_code(old_code, "Utilise un dict avec des lambdas")
|
||
|
|
print(refactored)
|
||
|
|
```
|
||
|
|
|
||
|
|
### 2. Générateur de migrations DB
|
||
|
|
|
||
|
|
```python
|
||
|
|
def generate_migration(old_schema, new_schema):
|
||
|
|
prompt = f"""
|
||
|
|
Ancien schéma:
|
||
|
|
{old_schema}
|
||
|
|
|
||
|
|
Nouveau schéma:
|
||
|
|
{new_schema}
|
||
|
|
|
||
|
|
Génère une migration Alembic pour passer de l'ancien au nouveau schéma.
|
||
|
|
"""
|
||
|
|
|
||
|
|
response = requests.post(
|
||
|
|
f"{API_URL}/chat",
|
||
|
|
json={
|
||
|
|
"messages": [{"role": "user", "content": prompt}],
|
||
|
|
"model": "code-expert",
|
||
|
|
"stream": False
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
return response.json()["response"]
|
||
|
|
```
|
||
|
|
|
||
|
|
### 3. Détection de code dupliqué
|
||
|
|
|
||
|
|
```python
|
||
|
|
def find_duplicates(project_dir):
|
||
|
|
import os
|
||
|
|
|
||
|
|
files_content = {}
|
||
|
|
|
||
|
|
# Lire tous les fichiers Python
|
||
|
|
for root, dirs, files in os.walk(project_dir):
|
||
|
|
for file in files:
|
||
|
|
if file.endswith('.py'):
|
||
|
|
filepath = os.path.join(root, file)
|
||
|
|
with open(filepath, 'r') as f:
|
||
|
|
files_content[filepath] = f.read()
|
||
|
|
|
||
|
|
# Demander à l'IA d'analyser
|
||
|
|
prompt = f"""
|
||
|
|
Analyse ces fichiers et identifie le code dupliqué:
|
||
|
|
|
||
|
|
{json.dumps(files_content, indent=2)}
|
||
|
|
|
||
|
|
Liste:
|
||
|
|
1. Les blocs de code dupliqués
|
||
|
|
2. Les fonctions similaires qui pourraient être mutualisées
|
||
|
|
3. Des suggestions de refactoring
|
||
|
|
"""
|
||
|
|
|
||
|
|
response = requests.post(
|
||
|
|
f"{API_URL}/chat",
|
||
|
|
json={
|
||
|
|
"messages": [{"role": "user", "content": prompt}],
|
||
|
|
"model": "code-expert",
|
||
|
|
"stream": False
|
||
|
|
}
|
||
|
|
)
|
||
|
|
|
||
|
|
return response.json()["response"]
|
||
|
|
```
|
||
|
|
|
||
|
|
## 📱 Intégration VS Code
|
||
|
|
|
||
|
|
### Extension VS Code custom
|
||
|
|
|
||
|
|
```json
|
||
|
|
// .vscode/tasks.json
|
||
|
|
{
|
||
|
|
"version": "2.0.0",
|
||
|
|
"tasks": [
|
||
|
|
{
|
||
|
|
"label": "AI Code Review",
|
||
|
|
"type": "shell",
|
||
|
|
"command": "python",
|
||
|
|
"args": [
|
||
|
|
"${workspaceFolder}/scripts/code_review.py",
|
||
|
|
"${file}"
|
||
|
|
],
|
||
|
|
"presentation": {
|
||
|
|
"reveal": "always",
|
||
|
|
"panel": "new"
|
||
|
|
}
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"label": "Generate Tests",
|
||
|
|
"type": "shell",
|
||
|
|
"command": "python",
|
||
|
|
"args": [
|
||
|
|
"${workspaceFolder}/scripts/generate_tests.py",
|
||
|
|
"${file}"
|
||
|
|
]
|
||
|
|
}
|
||
|
|
]
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
## 🔥 Performance Tips
|
||
|
|
|
||
|
|
### Batch processing de fichiers
|
||
|
|
|
||
|
|
```python
|
||
|
|
async def analyze_multiple_files(files):
|
||
|
|
import aiohttp
|
||
|
|
import asyncio
|
||
|
|
|
||
|
|
async with aiohttp.ClientSession() as session:
|
||
|
|
tasks = []
|
||
|
|
|
||
|
|
for filepath in files:
|
||
|
|
with open(filepath, 'r') as f:
|
||
|
|
code = f.read()
|
||
|
|
|
||
|
|
task = session.post(
|
||
|
|
f"{API_URL}/analyze-code",
|
||
|
|
json={"code": code, "language": "python"}
|
||
|
|
)
|
||
|
|
tasks.append(task)
|
||
|
|
|
||
|
|
results = await asyncio.gather(*tasks)
|
||
|
|
|
||
|
|
return [await r.json() for r in results]
|
||
|
|
|
||
|
|
# Utilisation
|
||
|
|
files = ['file1.py', 'file2.py', 'file3.py']
|
||
|
|
results = asyncio.run(analyze_multiple_files(files))
|
||
|
|
```
|
||
|
|
|
||
|
|
Bon coding avec votre assistant IA ! 🚀
|