Compare commits
27 Commits
bbb5fdec3a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 376844d7e8 | |||
| 3cf1349060 | |||
| 9e754c1bc0 | |||
| f199ce0653 | |||
| e3d392bf08 | |||
| a793b680be | |||
| b96c9e26ff | |||
| 0f88e614f8 | |||
| 2d58bd0f5c | |||
| b0d2a1d12e | |||
| 8c74a843b2 | |||
| 017cb697ba | |||
| bff66c00ee | |||
| a1ef578526 | |||
| b7896e4911 | |||
| deca101d5a | |||
| 37833d9cf0 | |||
| f207a0f0af | |||
| a98c8bc1c6 | |||
| 4ab9900d43 | |||
| 5e86639948 | |||
| 935c8d0f98 | |||
| 7ab227da1f | |||
| f14ffdf35d | |||
| f2832a6300 | |||
| 6d89f99827 | |||
| 21ea13fed3 |
267
api/chatbot.php
Normal file
267
api/chatbot.php
Normal file
@ -0,0 +1,267 @@
|
||||
<?php
|
||||
/**
|
||||
* API Chatbot IA - MVP
|
||||
* Modèle : qwen2-math:1.5b via Ollama local
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config/config.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Vérifier authentification élève
|
||||
if (!isLoggedIn() || !isEleve()) {
|
||||
echo json_encode(['error' => 'Non autorisé']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$user = currentUser();
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Récupérer et valider les données
|
||||
$id_tentative = filter_input(INPUT_POST, 'id_tentative', FILTER_VALIDATE_INT);
|
||||
$id_question = filter_input(INPUT_POST, 'id_question', FILTER_VALIDATE_INT);
|
||||
$message_eleve = trim($_POST['message'] ?? '');
|
||||
|
||||
if (!$id_tentative || !$id_question || empty($message_eleve)) {
|
||||
echo json_encode(['error' => 'Données manquantes']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Vérifier que la tentative appartient à l'élève et est en cours
|
||||
$tentative = $db->fetchOne(
|
||||
"SELECT id_eleve FROM tentatives_eleves WHERE id_tentative = ? AND statut = 'en_cours'",
|
||||
[$id_tentative]
|
||||
);
|
||||
|
||||
if (!$tentative || $tentative['id_eleve'] != $user['id_utilisateur']) {
|
||||
echo json_encode(['error' => 'Tentative invalide']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Vérifier limite (3 messages max par question)
|
||||
$usage = $db->fetchOne(
|
||||
"SELECT messages_count FROM chat_usage_limits WHERE id_tentative = ? AND id_question = ?",
|
||||
[$id_tentative, $id_question]
|
||||
);
|
||||
|
||||
$messages_count = $usage['messages_count'] ?? 0;
|
||||
|
||||
if ($messages_count >= 3) {
|
||||
echo json_encode([
|
||||
'error' => 'Limite atteinte',
|
||||
'message' => 'Tu as utilisé toute ton aide pour cette question (3/3). Continue, tu peux le faire ! 💪',
|
||||
'remaining' => 0
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Récupérer l'énoncé de la question (SANS la réponse)
|
||||
$question = $db->fetchOne(
|
||||
"SELECT q.enonce, q.type_question, e.titre as titre_eval
|
||||
FROM questions q
|
||||
JOIN evaluations e ON q.id_evaluation = e.id_evaluation
|
||||
WHERE q.id_question = ?",
|
||||
[$id_question]
|
||||
);
|
||||
|
||||
if (!$question) {
|
||||
echo json_encode(['error' => 'Question introuvable']);
|
||||
exit;
|
||||
}
|
||||
$enonce_question = $question['enonce'];
|
||||
$titre_eval = $question['titre_eval'];
|
||||
$type_question = $question['type_question'];
|
||||
|
||||
|
||||
// Récupérer ou créer la conversation
|
||||
$conversation = $db->fetchOne(
|
||||
"SELECT id FROM chat_conversations
|
||||
WHERE id_tentative = ? AND id_question = ?",
|
||||
[$id_tentative, $id_question]
|
||||
);
|
||||
|
||||
if (!$conversation) {
|
||||
// Créer nouvelle conversation
|
||||
$id_conversation = $db->insert(
|
||||
"INSERT INTO chat_conversations (id_tentative, id_question, id_eleve, modele_utilise)
|
||||
VALUES (?, ?, ?, 'qwen2-math:1.5b')",
|
||||
[$id_tentative, $id_question, $user['id_utilisateur']]
|
||||
);
|
||||
} else {
|
||||
$id_conversation = $conversation['id'];
|
||||
}
|
||||
|
||||
// Récupérer l'historique de la conversation
|
||||
$historique = $db->fetchAll(
|
||||
"SELECT role, message FROM chat_messages
|
||||
WHERE id_conversation = ?
|
||||
ORDER BY timestamp ASC",
|
||||
[$id_conversation]
|
||||
);
|
||||
|
||||
// Numéro d'aide actuel (1, 2 ou 3)
|
||||
$numero_aide = $messages_count + 1;
|
||||
|
||||
$system_prompt = "Tu es un assistant pédagogique en mathématiques pour collège/lycée.
|
||||
L'élève a droit à exactement 3 aides par question. C'est son aide numéro {$numero_aide}/3.
|
||||
|
||||
═══════════════════════════════════════
|
||||
RÈGLE ABSOLUE : NE JAMAIS DONNER LA RÉPONSE
|
||||
═══════════════════════════════════════
|
||||
Même si l'élève demande directement, même s'il insiste, même s'il dit avoir cherché :
|
||||
TU NE DONNES JAMAIS la réponse, ni le résultat, ni le mot/nombre final attendu.
|
||||
Cela inclut : nommer la transformation, donner le résultat d'un calcul, compléter la phrase avec la solution.
|
||||
|
||||
LONGUEUR : Réponds en 2-4 phrases MAXIMUM. Sois direct et concis.
|
||||
|
||||
SELON LE NUMÉRO D'AIDE :
|
||||
- Aide 1/3 : Question ouverte pour faire réfléchir. Ex: \"Qu'est-ce qui change entre la figure de départ et la figure d'arrivée ?\"
|
||||
- Aide 2/3 : Indice plus ciblé sur la méthode. Ex: \"Regarde si la figure a été déplacée, tournée, ou agrandie...\"
|
||||
- Aide 3/3 : Démarche pas-à-pas SANS donner le mot final. Ex: \"Compare les coordonnées : le point A(1,2) devient A'(4,2). Que remarques-tu sur x ? Sur y ?\"
|
||||
|
||||
CE QUE TU NE FAIS JAMAIS :
|
||||
❌ \"La réponse est...\" / \"C'est une translation\" / \"Le résultat est 17\"
|
||||
❌ Confirmer si l'élève a trouvé la bonne réponse
|
||||
❌ Faire le calcul complet à sa place
|
||||
❌ Réponses de plus de 4 phrases
|
||||
|
||||
CE QUE TU FAIS :
|
||||
✅ Poser UNE question ciblée
|
||||
✅ Donner UN indice de méthode
|
||||
✅ Orienter sans révéler
|
||||
|
||||
ÉNONCÉ DE LA QUESTION (contexte uniquement - NE PAS RÉSOUDRE) :
|
||||
" . strip_tags($enonce_question);
|
||||
|
||||
// Construire l'historique pour Ollama
|
||||
$messages_ollama = [];
|
||||
foreach ($historique as $msg) {
|
||||
$messages_ollama[] = [
|
||||
'role' => $msg['role'],
|
||||
'content' => $msg['message']
|
||||
];
|
||||
}
|
||||
// Ajouter le nouveau message de l'élève
|
||||
$messages_ollama[] = [
|
||||
'role' => 'user',
|
||||
'content' => $message_eleve
|
||||
];
|
||||
|
||||
// Appel à Ollama (qwen2-math:1.5b)
|
||||
$start_time = microtime(true);
|
||||
|
||||
$ch = curl_init('http://localhost:11434/api/chat');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||
CURLOPT_TIMEOUT => 30,
|
||||
CURLOPT_POSTFIELDS => json_encode([
|
||||
'model' => 'ministral-3:3b',
|
||||
'messages' => array_merge([
|
||||
['role' => 'system', 'content' => $system_prompt]
|
||||
], $messages_ollama),
|
||||
'stream' => false,
|
||||
'options' => [
|
||||
'temperature' => 0.7,
|
||||
'num_predict' => 200, // Réponses courtes
|
||||
'top_p' => 0.9
|
||||
]
|
||||
])
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$curl_error = curl_error($ch);
|
||||
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
$end_time = microtime(true);
|
||||
$temps_reponse_ms = round(($end_time - $start_time) * 1000);
|
||||
|
||||
// Gérer les erreurs
|
||||
if ($curl_error) {
|
||||
error_log("Erreur Ollama CURL: $curl_error");
|
||||
echo json_encode(['error' => 'Service temporairement indisponible (connexion)']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($http_code !== 200) {
|
||||
error_log("Erreur Ollama HTTP $http_code: $response");
|
||||
echo json_encode(['error' => 'Service temporairement indisponible (HTTP ' . $http_code . ')']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
|
||||
if (!isset($data['message']['content'])) {
|
||||
error_log("Réponse Ollama invalide: $response");
|
||||
echo json_encode(['error' => 'Erreur de génération']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$reponse_ia = trim($data['message']['content']);
|
||||
|
||||
// ============================================================
|
||||
// DÉTECTION : la réponse de l'IA contient-elle la solution ?
|
||||
// Si oui, on remplace par un message neutre
|
||||
// ============================================================
|
||||
function detecterReponseDirecte($texte, $enonce) {
|
||||
$texte_lower = mb_strtolower($texte);
|
||||
|
||||
// Patterns suspects : formulations qui donnent directement la réponse
|
||||
$patterns_suspects = [
|
||||
'/la\s+r[eé]ponse\s+est/i',
|
||||
'/c\'?est\s+(une?\s+)?(translation|rotation|homoth|sym[eé]trie|vecteur)/i',
|
||||
'/il\s+s\'?agit\s+(d\'?une?|du)/i',
|
||||
'/on\s+obtient\s*:/i',
|
||||
'/le\s+r[eé]sultat\s+est/i',
|
||||
'/donc\s*[=:]\s*\d/i',
|
||||
'/la\s+solution\s+est/i',
|
||||
'/r[eé]ponse\s+correcte/i',
|
||||
];
|
||||
|
||||
foreach ($patterns_suspects as $pattern) {
|
||||
if (preg_match($pattern, $texte)) {
|
||||
error_log("Chatbot: réponse directe détectée, remplacement. Pattern: $pattern");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (detecterReponseDirecte($reponse_ia, $enonce_question)) {
|
||||
$reponse_ia = "Je ne peux pas te donner la réponse directement, mais voici un indice : relis bien l'énoncé et demande-toi quelle transformation modifie la position d'une figure sans changer sa forme ni sa taille. Qu'est-ce que tu remarques ?";
|
||||
}
|
||||
|
||||
// Sauvegarder le message de l'élève
|
||||
$db->query(
|
||||
"INSERT INTO chat_messages (id_conversation, role, message)
|
||||
VALUES (?, 'user', ?)",
|
||||
[$id_conversation, $message_eleve]
|
||||
);
|
||||
|
||||
// Sauvegarder la réponse de l'IA
|
||||
$db->query(
|
||||
"INSERT INTO chat_messages (id_conversation, role, message, temps_reponse_ms)
|
||||
VALUES (?, 'assistant', ?, ?)",
|
||||
[$id_conversation, $reponse_ia, $temps_reponse_ms]
|
||||
);
|
||||
|
||||
// Incrémenter le compteur d'utilisation
|
||||
$db->query(
|
||||
"INSERT INTO chat_usage_limits (id_tentative, id_question, messages_count)
|
||||
VALUES (?, ?, 1)
|
||||
ON DUPLICATE KEY UPDATE messages_count = messages_count + 1",
|
||||
[$id_tentative, $id_question]
|
||||
);
|
||||
|
||||
$messages_restants = 2 - $messages_count;
|
||||
|
||||
// Réponse succès
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'response' => $reponse_ia,
|
||||
'remaining' => $messages_restants,
|
||||
'temps_ms' => $temps_reponse_ms
|
||||
]);
|
||||
36
api/chatbot_check_limit.php
Normal file
36
api/chatbot_check_limit.php
Normal file
@ -0,0 +1,36 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../config/config.php';
|
||||
require_once __DIR__ . '/../config/database.php';
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
if (!isLoggedIn() || !isEleve()) {
|
||||
echo json_encode(['error' => 'Non autorisé']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$id_tentative = filter_input(INPUT_POST, 'id_tentative', FILTER_VALIDATE_INT);
|
||||
$id_question = filter_input(INPUT_POST, 'id_question', FILTER_VALIDATE_INT);
|
||||
|
||||
if (!$id_tentative || !$id_question) {
|
||||
echo json_encode(['error' => 'Données manquantes']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Vérifier limite
|
||||
$usage = $db->fetchOne(
|
||||
"SELECT messages_count FROM chat_usage_limits
|
||||
WHERE id_tentative = ? AND id_question = ?",
|
||||
[$id_tentative, $id_question]
|
||||
);
|
||||
|
||||
$messages_count = $usage['messages_count'] ?? 0;
|
||||
$remaining = max(0, 3 - $messages_count);
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'remaining' => $remaining,
|
||||
'used' => $messages_count
|
||||
]);
|
||||
311
assets/css/chatbot.css
Normal file
311
assets/css/chatbot.css
Normal file
@ -0,0 +1,311 @@
|
||||
/* ====================================
|
||||
CHATBOT IA - STYLES
|
||||
==================================== */
|
||||
|
||||
/* Bouton flottant */
|
||||
.chat-bubble {
|
||||
position: fixed;
|
||||
bottom: 80px;
|
||||
right: 20px;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.btn-chat {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 15px 25px;
|
||||
border-radius: 50px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.btn-chat:hover {
|
||||
transform: translateY(-3px);
|
||||
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
|
||||
}
|
||||
|
||||
.btn-chat:active {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.help-badge {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* Modal chat */
|
||||
#modal-chat {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: none;
|
||||
z-index: 2000;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
#modal-chat.show {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
.chat-container {
|
||||
background: white;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
height: 600px;
|
||||
max-height: 80vh;
|
||||
border-radius: 15px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
|
||||
animation: slideUp 0.3s ease;
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from {
|
||||
transform: translateY(50px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-header {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 20px;
|
||||
border-radius: 15px 15px 0 0;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.chat-header h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-close-chat {
|
||||
background: none;
|
||||
border: none;
|
||||
color: white;
|
||||
font-size: 28px;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.btn-close-chat:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
.chat-messages::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.chat-messages::-webkit-scrollbar-track {
|
||||
background: #f1f1f1;
|
||||
}
|
||||
|
||||
.chat-messages::-webkit-scrollbar-thumb {
|
||||
background: #667eea;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-bottom: 15px;
|
||||
padding: 12px 15px;
|
||||
border-radius: 12px;
|
||||
max-width: 85%;
|
||||
animation: messageAppear 0.3s ease;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
@keyframes messageAppear {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.message-user {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
margin-left: auto;
|
||||
text-align: right;
|
||||
border-bottom-right-radius: 4px;
|
||||
}
|
||||
|
||||
.message-assistant {
|
||||
background: white;
|
||||
color: #333;
|
||||
border: 1px solid #e0e0e0;
|
||||
margin-right: auto;
|
||||
border-bottom-left-radius: 4px;
|
||||
}
|
||||
|
||||
.message-assistant::before {
|
||||
content: "🤖 ";
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.message-system {
|
||||
background: #e3f2fd;
|
||||
color: #1976d2;
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
padding: 10px;
|
||||
margin: 10px auto;
|
||||
border-radius: 8px;
|
||||
max-width: 90%;
|
||||
}
|
||||
|
||||
.chat-loading {
|
||||
text-align: center;
|
||||
padding: 15px;
|
||||
color: #999;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.chat-loading::before {
|
||||
content: "💭 ";
|
||||
}
|
||||
|
||||
.typing-indicator {
|
||||
display: inline-flex;
|
||||
gap: 4px;
|
||||
padding: 10px 15px;
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
border: 1px solid #e0e0e0;
|
||||
}
|
||||
|
||||
.typing-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
background: #667eea;
|
||||
border-radius: 50%;
|
||||
animation: typing 1.4s infinite;
|
||||
}
|
||||
|
||||
.typing-dot:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
|
||||
.typing-dot:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
|
||||
@keyframes typing {
|
||||
0%, 60%, 100% {
|
||||
transform: translateY(0);
|
||||
opacity: 0.5;
|
||||
}
|
||||
30% {
|
||||
transform: translateY(-10px);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-input-zone {
|
||||
padding: 15px;
|
||||
border-top: 1px solid #e0e0e0;
|
||||
background: white;
|
||||
border-radius: 0 0 15px 15px;
|
||||
}
|
||||
|
||||
.chat-input-zone textarea {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
resize: none;
|
||||
font-family: inherit;
|
||||
font-size: 14px;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
.chat-input-zone textarea:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
}
|
||||
|
||||
.chat-input-zone button {
|
||||
margin-top: 10px;
|
||||
width: 100%;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.chat-input-zone button:hover:not(:disabled) {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
.chat-input-zone button:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Responsive */
|
||||
@media (max-width: 600px) {
|
||||
.chat-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.chat-header {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.chat-input-zone {
|
||||
border-radius: 0;
|
||||
}
|
||||
}
|
||||
743
assets/css/chatbot_settings.css
Normal file
743
assets/css/chatbot_settings.css
Normal file
@ -0,0 +1,743 @@
|
||||
/**
|
||||
* Styles pour la configuration API Chatbot
|
||||
* Design moderne avec une palette professionnelle
|
||||
*/
|
||||
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
|
||||
|
||||
:root {
|
||||
--primary: #667eea;
|
||||
--primary-dark: #5568d3;
|
||||
--secondary: #48bb78;
|
||||
--danger: #f56565;
|
||||
--warning: #ed8936;
|
||||
--bg-main: #f7fafc;
|
||||
--bg-card: #ffffff;
|
||||
--text-primary: #2d3748;
|
||||
--text-secondary: #718096;
|
||||
--border: #e2e8f0;
|
||||
--shadow-sm: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
|
||||
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
|
||||
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
|
||||
--radius: 12px;
|
||||
--transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
background: var(--bg-main);
|
||||
color: var(--text-primary);
|
||||
line-height: 1.6;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
.page-header {
|
||||
margin-bottom: 3rem;
|
||||
}
|
||||
|
||||
.header-content {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.back-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
color: var(--text-secondary);
|
||||
text-decoration: none;
|
||||
font-size: 0.875rem;
|
||||
margin-bottom: 1rem;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.back-link:hover {
|
||||
color: var(--primary);
|
||||
transform: translateX(-4px);
|
||||
}
|
||||
|
||||
.page-header h1 {
|
||||
font-size: 2.5rem;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 1.125rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* Stats Banner */
|
||||
.stats-banner {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 1.5rem;
|
||||
margin-bottom: 3rem;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
|
||||
border-radius: var(--radius);
|
||||
padding: 1.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
box-shadow: var(--shadow-md);
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.stat-card:hover {
|
||||
transform: translateY(-4px);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
.stat-icon {
|
||||
font-size: 2.5rem;
|
||||
filter: brightness(0) invert(1);
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.stat-content {
|
||||
color: white;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.875rem;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
/* Content Grid */
|
||||
.content-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 350px;
|
||||
gap: 2rem;
|
||||
margin-bottom: 3rem;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.content-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Section Styling */
|
||||
.section-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.section-header h2,
|
||||
.section-header h3 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn-primary,
|
||||
.btn-secondary,
|
||||
.btn-danger,
|
||||
.btn-test {
|
||||
padding: 0.75rem 1.5rem;
|
||||
border-radius: 8px;
|
||||
border: none;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
cursor: pointer;
|
||||
transition: var(--transition);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: var(--primary-dark);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg-card);
|
||||
color: var(--text-primary);
|
||||
border: 2px solid var(--border);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
border-color: var(--primary);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: var(--danger);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-danger:hover {
|
||||
background: #e53e3e;
|
||||
}
|
||||
|
||||
.btn-test {
|
||||
background: var(--secondary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-test:hover {
|
||||
background: #38a169;
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
/* Keys List */
|
||||
.keys-list {
|
||||
display: grid;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.key-card {
|
||||
background: var(--bg-card);
|
||||
border-radius: var(--radius);
|
||||
border: 2px solid var(--border);
|
||||
overflow: hidden;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.key-card:hover {
|
||||
box-shadow: var(--shadow-lg);
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.key-card.active {
|
||||
border-color: var(--secondary);
|
||||
}
|
||||
|
||||
.key-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1.25rem;
|
||||
background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.key-provider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.provider-icon {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.provider-name {
|
||||
font-weight: 600;
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
padding: 0.375rem 0.75rem;
|
||||
border-radius: 20px;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.status-badge.default {
|
||||
background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
|
||||
color: #744210;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.status-badge.active {
|
||||
background: #c6f6d5;
|
||||
color: #22543d;
|
||||
}
|
||||
|
||||
.status-badge.inactive {
|
||||
background: #fed7d7;
|
||||
color: #742a2a;
|
||||
}
|
||||
|
||||
.status-badge.none {
|
||||
background: #e2e8f0;
|
||||
color: #4a5568;
|
||||
}
|
||||
|
||||
.key-body {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.key-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.info-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
|
||||
.info-row .label {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.info-row .value {
|
||||
font-weight: 500;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.quota-bar {
|
||||
display: inline-block;
|
||||
width: 100px;
|
||||
height: 6px;
|
||||
background: var(--border);
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
margin-left: 0.5rem;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.quota-fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--secondary);
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.key-actions {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.key-empty {
|
||||
text-align: center;
|
||||
padding: 2rem 1rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.key-empty p {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
/* Models Sidebar */
|
||||
.models-sidebar {
|
||||
background: var(--bg-card);
|
||||
border-radius: var(--radius);
|
||||
padding: 1.5rem;
|
||||
border: 2px solid var(--border);
|
||||
position: sticky;
|
||||
top: 2rem;
|
||||
max-height: calc(100vh - 4rem);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.models-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.provider-group h4 {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.75rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.model-item {
|
||||
padding: 0.75rem;
|
||||
background: var(--bg-main);
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.model-item:hover {
|
||||
border-color: var(--primary);
|
||||
background: white;
|
||||
}
|
||||
|
||||
.model-item.recommended {
|
||||
border-color: var(--secondary);
|
||||
background: #f0fff4;
|
||||
}
|
||||
|
||||
.model-name {
|
||||
font-weight: 500;
|
||||
font-size: 0.875rem;
|
||||
margin-bottom: 0.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.model-meta {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.badge-recommended,
|
||||
.badge-free,
|
||||
.badge-paid,
|
||||
.badge-speed {
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.badge-recommended {
|
||||
background: #fef5e7;
|
||||
}
|
||||
|
||||
.badge-free {
|
||||
background: #c6f6d5;
|
||||
color: #22543d;
|
||||
}
|
||||
|
||||
.badge-paid {
|
||||
background: #fed7d7;
|
||||
color: #742a2a;
|
||||
}
|
||||
|
||||
.help-box {
|
||||
margin-top: 1.5rem;
|
||||
padding: 1rem;
|
||||
background: #ebf8ff;
|
||||
border-radius: 8px;
|
||||
border-left: 4px solid var(--primary);
|
||||
}
|
||||
|
||||
.help-box h4 {
|
||||
font-size: 0.875rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.help-box ul {
|
||||
list-style: none;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.help-box li {
|
||||
padding-left: 1rem;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.help-box li::before {
|
||||
content: "→";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
/* Stats Table */
|
||||
.stats-section {
|
||||
background: var(--bg-card);
|
||||
border-radius: var(--radius);
|
||||
padding: 1.5rem;
|
||||
border: 2px solid var(--border);
|
||||
}
|
||||
|
||||
.stats-table-wrapper {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.stats-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.stats-table thead {
|
||||
background: var(--bg-main);
|
||||
}
|
||||
|
||||
.stats-table th {
|
||||
padding: 0.75rem 1rem;
|
||||
text-align: left;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
color: var(--text-secondary);
|
||||
border-bottom: 2px solid var(--border);
|
||||
}
|
||||
|
||||
.stats-table td {
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.stats-table tbody tr:hover {
|
||||
background: var(--bg-main);
|
||||
}
|
||||
|
||||
.provider-badge {
|
||||
padding: 0.375rem 0.75rem;
|
||||
background: var(--bg-main);
|
||||
border-radius: 6px;
|
||||
font-weight: 500;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
/* Modal */
|
||||
.modal {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
z-index: 1000;
|
||||
backdrop-filter: blur(4px);
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
.modal.show {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background: var(--bg-card);
|
||||
border-radius: var(--radius);
|
||||
max-width: 600px;
|
||||
width: 90%;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
|
||||
animation: slideUp 0.3s ease;
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1.5rem;
|
||||
border-bottom: 2px solid var(--border);
|
||||
}
|
||||
|
||||
.modal-header h2 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.modal-close {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 2rem;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.modal-close:hover {
|
||||
color: var(--danger);
|
||||
transform: scale(1.1);
|
||||
}
|
||||
|
||||
/* Form */
|
||||
#keyForm {
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
font-weight: 600;
|
||||
margin-bottom: 0.5rem;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.form-group input[type="text"],
|
||||
.form-group input[type="password"],
|
||||
.form-group input[type="number"],
|
||||
.form-group select {
|
||||
width: 100%;
|
||||
padding: 0.75rem 1rem;
|
||||
border: 2px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-size: 0.875rem;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
|
||||
}
|
||||
|
||||
.input-with-button {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.input-with-button input {
|
||||
padding-right: 3rem;
|
||||
}
|
||||
|
||||
.btn-toggle-visibility {
|
||||
position: absolute;
|
||||
right: 0.5rem;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 1.25rem;
|
||||
cursor: pointer;
|
||||
padding: 0.5rem;
|
||||
opacity: 0.6;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.btn-toggle-visibility:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.help-text {
|
||||
display: block;
|
||||
margin-top: 0.5rem;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: flex-end;
|
||||
margin-top: 2rem;
|
||||
padding-top: 1.5rem;
|
||||
border-top: 2px solid var(--border);
|
||||
}
|
||||
|
||||
.test-result {
|
||||
margin-top: 1rem;
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.test-result.success {
|
||||
background: #c6f6d5;
|
||||
color: #22543d;
|
||||
border: 2px solid #9ae6b4;
|
||||
}
|
||||
|
||||
.test-result.error {
|
||||
background: #fed7d7;
|
||||
color: #742a2a;
|
||||
border: 2px solid #fc8181;
|
||||
}
|
||||
|
||||
/* Toast */
|
||||
#toast-container {
|
||||
position: fixed;
|
||||
bottom: 2rem;
|
||||
right: 2rem;
|
||||
z-index: 2000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.toast {
|
||||
background: white;
|
||||
padding: 1rem 1.5rem;
|
||||
border-radius: 8px;
|
||||
box-shadow: var(--shadow-lg);
|
||||
min-width: 300px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
border-left: 4px solid var(--primary);
|
||||
animation: slideInRight 0.3s ease;
|
||||
}
|
||||
|
||||
@keyframes slideInRight {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(100%);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.toast.success {
|
||||
border-left-color: var(--secondary);
|
||||
}
|
||||
|
||||
.toast.error {
|
||||
border-left-color: var(--danger);
|
||||
}
|
||||
|
||||
.toast-icon {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.toast-message {
|
||||
flex: 1;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
306
assets/js/chatbot.js
Normal file
306
assets/js/chatbot.js
Normal file
@ -0,0 +1,306 @@
|
||||
/**
|
||||
* CHATBOT IA - Client JavaScript
|
||||
*/
|
||||
|
||||
class ChatbotIA {
|
||||
constructor(tentativeId) {
|
||||
this.tentativeId = tentativeId;
|
||||
this.currentQuestionId = null;
|
||||
this.helpRemaining = 3;
|
||||
this.isLoading = false;
|
||||
|
||||
this.initElements();
|
||||
this.attachEvents();
|
||||
}
|
||||
|
||||
initElements() {
|
||||
this.btnOpenChat = document.getElementById('btn-open-chat');
|
||||
this.modalChat = document.getElementById('modal-chat');
|
||||
this.btnCloseChat = document.getElementById('btn-close-chat');
|
||||
this.chatMessages = document.getElementById('chat-messages');
|
||||
this.chatInput = document.getElementById('chat-input');
|
||||
this.btnSend = document.getElementById('btn-send');
|
||||
this.helpRemainingSpan = document.getElementById('help-remaining');
|
||||
}
|
||||
|
||||
attachEvents() {
|
||||
// Ouvrir chat
|
||||
this.btnOpenChat?.addEventListener('click', () => this.ouvrirChat());
|
||||
|
||||
// Fermer chat
|
||||
this.btnCloseChat?.addEventListener('click', () => this.fermerChat());
|
||||
|
||||
// Clic en dehors du modal
|
||||
this.modalChat?.addEventListener('click', (e) => {
|
||||
if (e.target === this.modalChat) this.fermerChat();
|
||||
});
|
||||
|
||||
// Envoyer message
|
||||
this.btnSend?.addEventListener('click', () => this.envoyerMessage());
|
||||
|
||||
// Enter pour envoyer (Shift+Enter pour nouvelle ligne)
|
||||
this.chatInput?.addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
this.envoyerMessage();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ouvrirChat() {
|
||||
// Utiliser la variable globale currentQuestion du formulaire
|
||||
if (typeof window.currentQuestion !== 'undefined' && window.questionsIds) {
|
||||
// currentQuestion est l'index (1-80), on récupère l'ID réel
|
||||
const questionIndex = window.currentQuestion - 1;
|
||||
this.currentQuestionId = window.questionsIds[questionIndex];
|
||||
console.log('💬 Question détectée via currentQuestion:', window.currentQuestion, '→ ID:', this.currentQuestionId);
|
||||
} else {
|
||||
// Fallback sur la détection par classe active
|
||||
this.currentQuestionId = this.detectCurrentQuestion();
|
||||
}
|
||||
|
||||
if (!this.currentQuestionId) {
|
||||
alert('Erreur : impossible de déterminer la question actuelle');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('💬 Ouverture chat - Question:', this.currentQuestionId);
|
||||
|
||||
// Charger l'aide restante pour cette question
|
||||
this.loadHelpRemaining();
|
||||
|
||||
this.modalChat.classList.add('show');
|
||||
this.chatInput.focus();
|
||||
}
|
||||
|
||||
// NOUVELLE MÉTHODE : Détecter la question visible
|
||||
detectCurrentQuestion() {
|
||||
// Trouver la question la plus visible dans le viewport
|
||||
const questionCards = document.querySelectorAll('.question-card[data-question-id]');
|
||||
|
||||
if (questionCards.length === 0) {
|
||||
console.error('❌ Aucune question-card trouvée');
|
||||
return null;
|
||||
}
|
||||
|
||||
let closestQuestion = null;
|
||||
let minDistance = Infinity;
|
||||
const viewportCenter = window.innerHeight / 2;
|
||||
|
||||
questionCards.forEach(card => {
|
||||
const rect = card.getBoundingClientRect();
|
||||
|
||||
// La question est visible dans le viewport
|
||||
if (rect.top < window.innerHeight && rect.bottom > 0) {
|
||||
const cardCenter = rect.top + (rect.height / 2);
|
||||
const distance = Math.abs(cardCenter - viewportCenter);
|
||||
|
||||
if (distance < minDistance) {
|
||||
minDistance = distance;
|
||||
closestQuestion = card;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (closestQuestion) {
|
||||
const qId = parseInt(closestQuestion.dataset.questionId);
|
||||
console.log('✅ Question visible détectée:', qId);
|
||||
return qId;
|
||||
}
|
||||
|
||||
// Fallback : première question
|
||||
const firstCard = questionCards[0];
|
||||
const qId = parseInt(firstCard.dataset.questionId);
|
||||
console.log('⚠️ Fallback première question:', qId);
|
||||
return qId;
|
||||
}
|
||||
|
||||
// NOUVELLE MÉTHODE : Charger l'aide restante via AJAX
|
||||
async loadHelpRemaining() {
|
||||
try {
|
||||
const response = await fetch('/mathematiques/api/chatbot_check_limit.php', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
||||
body: new URLSearchParams({
|
||||
id_tentative: this.tentativeId,
|
||||
id_question: this.currentQuestionId
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.helpRemaining = data.remaining;
|
||||
this.updateHelpBadge();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur chargement limite aide:', error);
|
||||
}
|
||||
}
|
||||
|
||||
fermerChat() {
|
||||
this.modalChat.classList.remove('show');
|
||||
}
|
||||
|
||||
getCurrentQuestionId() {
|
||||
// À adapter selon ton code de passer_evaluation.php
|
||||
// Option 1 : Variable globale JS
|
||||
if (typeof currentQuestionId !== 'undefined') {
|
||||
return currentQuestionId;
|
||||
}
|
||||
|
||||
// Option 2 : Data attribute
|
||||
const questionElement = document.querySelector('[data-question-id]');
|
||||
if (questionElement) {
|
||||
return questionElement.dataset.questionId;
|
||||
}
|
||||
|
||||
// Option 3 : Input hidden
|
||||
const hiddenInput = document.querySelector('input[name="id_question"]');
|
||||
if (hiddenInput) {
|
||||
return hiddenInput.value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async envoyerMessage() {
|
||||
const message = this.chatInput.value.trim();
|
||||
|
||||
if (!message || this.isLoading) return;
|
||||
|
||||
// Afficher message utilisateur
|
||||
this.ajouterMessage(message, 'user');
|
||||
this.chatInput.value = '';
|
||||
|
||||
// Loading
|
||||
this.isLoading = true;
|
||||
this.btnSend.disabled = true;
|
||||
this.afficherTypingIndicator();
|
||||
|
||||
try {
|
||||
const response = await fetch('/mathematiques/api/chatbot.php', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
id_tentative: this.tentativeId,
|
||||
id_question: this.currentQuestionId,
|
||||
message: message
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Retirer typing indicator
|
||||
this.retirerTypingIndicator();
|
||||
|
||||
if (data.error) {
|
||||
this.ajouterMessage(data.message || data.error, 'system');
|
||||
|
||||
if (data.remaining === 0) {
|
||||
this.helpRemaining = 0;
|
||||
this.updateHelpBadge();
|
||||
setTimeout(() => this.fermerChat(), 10000); // 10s au lieu de 3s
|
||||
}
|
||||
} else {
|
||||
this.ajouterMessage(data.response, 'assistant');
|
||||
this.helpRemaining = data.remaining;
|
||||
this.updateHelpBadge();
|
||||
|
||||
// Afficher info modèle dans console
|
||||
console.log('✅ Réponse IA -', 'Modèle:', data.modele || 'qwen2-math:1.5b', '- Temps:', data.temps_ms, 'ms');
|
||||
|
||||
if (this.helpRemaining === 0) {
|
||||
setTimeout(() => {
|
||||
this.ajouterMessage(
|
||||
'⚠️ Tu as utilisé toute ton aide pour cette question (3/3).\n\nLe chat se fermera dans 10 secondes. Continue, tu peux le faire ! 💪',
|
||||
'system'
|
||||
);
|
||||
|
||||
// Bouton fermeture manuelle
|
||||
const btnDiv = document.createElement('div');
|
||||
btnDiv.className = 'message message-system';
|
||||
btnDiv.style.textAlign = 'center';
|
||||
btnDiv.innerHTML = '<button onclick="window.chatbot.fermerChat()" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: 600; margin-top: 10px;">✕ Fermer maintenant</button>';
|
||||
this.chatMessages.appendChild(btnDiv);
|
||||
this.scrollToBottom();
|
||||
|
||||
// Fermeture auto après 10s
|
||||
setTimeout(() => this.fermerChat(), 10000);
|
||||
}, 500);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur chatbot:', error);
|
||||
this.retirerTypingIndicator();
|
||||
this.ajouterMessage('❌ Erreur de connexion au serveur.', 'system');
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
this.btnSend.disabled = false;
|
||||
this.chatInput.focus();
|
||||
}
|
||||
}
|
||||
|
||||
ajouterMessage(texte, type) {
|
||||
const msgDiv = document.createElement('div');
|
||||
msgDiv.className = `message message-${type}`;
|
||||
|
||||
// Convertir le texte brut en HTML avec support LaTeX
|
||||
const htmlContent = this.formatMathText(texte);
|
||||
msgDiv.innerHTML = htmlContent;
|
||||
|
||||
this.chatMessages.appendChild(msgDiv);
|
||||
|
||||
// Rendre les formules mathématiques avec KaTeX
|
||||
if (typeof renderMathInElement !== 'undefined') {
|
||||
renderMathInElement(msgDiv, {
|
||||
delimiters: [
|
||||
{left: '$$', right: '$$', display: true}, // Mode display (centré)
|
||||
{left: '$', right: '$', display: false}, // Mode inline
|
||||
{left: '\\(', right: '\\)', display: false},
|
||||
{left: '\\[', right: '\\]', display: true}
|
||||
],
|
||||
throwOnError: false,
|
||||
trust: true
|
||||
});
|
||||
}
|
||||
|
||||
this.scrollToBottom();
|
||||
}
|
||||
|
||||
// NOUVELLE MÉTHODE : Formater le texte avec support maths
|
||||
formatMathText(texte) {
|
||||
// Juste convertir \n en <br>
|
||||
// Le reste (LaTeX) est géré par KaTeX
|
||||
return texte.replace(/\n/g, '<br>');
|
||||
}
|
||||
|
||||
afficherTypingIndicator() {
|
||||
const typingDiv = document.createElement('div');
|
||||
typingDiv.className = 'typing-indicator';
|
||||
typingDiv.id = 'typing-indicator';
|
||||
typingDiv.innerHTML = `
|
||||
<span class="typing-dot"></span>
|
||||
<span class="typing-dot"></span>
|
||||
<span class="typing-dot"></span>
|
||||
`;
|
||||
this.chatMessages.appendChild(typingDiv);
|
||||
this.scrollToBottom();
|
||||
}
|
||||
|
||||
retirerTypingIndicator() {
|
||||
document.getElementById('typing-indicator')?.remove();
|
||||
}
|
||||
|
||||
scrollToBottom() {
|
||||
this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
|
||||
}
|
||||
|
||||
updateHelpBadge() {
|
||||
if (this.helpRemainingSpan) {
|
||||
this.helpRemainingSpan.textContent = this.helpRemaining;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
439
assets/js/chatbot_settings.js
Normal file
439
assets/js/chatbot_settings.js
Normal file
@ -0,0 +1,439 @@
|
||||
/**
|
||||
* JavaScript pour la gestion des clés API du chatbot
|
||||
*/
|
||||
|
||||
// État global
|
||||
let currentProvider = null;
|
||||
let editMode = false;
|
||||
|
||||
// Helper URLs
|
||||
const API_HELP_URLS = {
|
||||
'gemini': 'https://aistudio.google.com/apikey',
|
||||
'mistral': 'https://console.mistral.ai/api-keys/',
|
||||
'openai': 'https://platform.openai.com/api-keys'
|
||||
};
|
||||
|
||||
// ========== Modal Management ==========
|
||||
|
||||
function openAddKeyModal(provider = null) {
|
||||
const modal = document.getElementById('keyModal');
|
||||
const title = document.getElementById('modalTitle');
|
||||
const form = document.getElementById('keyForm');
|
||||
const providerSelect = document.getElementById('provider');
|
||||
const testResult = document.getElementById('testResult');
|
||||
|
||||
// Reset form
|
||||
form.reset();
|
||||
testResult.style.display = 'none';
|
||||
document.getElementById('keyAction').value = 'add';
|
||||
editMode = false;
|
||||
|
||||
// Important : activer le select AVANT de définir la valeur
|
||||
providerSelect.disabled = false;
|
||||
|
||||
// Pre-select provider if provided
|
||||
if (provider) {
|
||||
providerSelect.value = provider;
|
||||
providerSelect.dispatchEvent(new Event('change')); // Trigger updateModelsList
|
||||
}
|
||||
|
||||
title.textContent = 'Ajouter une clé API';
|
||||
modal.classList.add('show');
|
||||
}
|
||||
|
||||
function editKey(provider) {
|
||||
currentProvider = provider;
|
||||
editMode = true;
|
||||
|
||||
// Récupérer les infos de la clé
|
||||
fetch(`chatbot_api_ajax.php?action=get&provider=${provider}`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
const modal = document.getElementById('keyModal');
|
||||
const title = document.getElementById('modalTitle');
|
||||
const form = document.getElementById('keyForm');
|
||||
const providerSelect = document.getElementById('provider');
|
||||
const modelSelect = document.getElementById('model_default');
|
||||
const testResult = document.getElementById('testResult');
|
||||
|
||||
testResult.style.display = 'none';
|
||||
document.getElementById('keyAction').value = 'edit';
|
||||
|
||||
// Remplir le formulaire
|
||||
providerSelect.value = provider;
|
||||
providerSelect.disabled = true;
|
||||
// Champ hidden pour envoyer provider même si disabled
|
||||
let hiddenProvider = document.getElementById('hidden_provider');
|
||||
if (!hiddenProvider) {
|
||||
hiddenProvider = document.createElement('input');
|
||||
hiddenProvider.type = 'hidden';
|
||||
hiddenProvider.name = 'provider';
|
||||
hiddenProvider.id = 'hidden_provider';
|
||||
document.getElementById('keyForm').appendChild(hiddenProvider);
|
||||
}
|
||||
hiddenProvider.value = provider;
|
||||
updateModelsList();
|
||||
|
||||
// Attendre que la liste des modèles soit chargée
|
||||
setTimeout(() => {
|
||||
modelSelect.value = data.data.model_default;
|
||||
|
||||
if (data.data.quota_max) {
|
||||
document.getElementById('set_quota').checked = true;
|
||||
document.getElementById('quota_max').value = data.data.quota_max;
|
||||
toggleQuotaInput();
|
||||
}
|
||||
}, 100);
|
||||
|
||||
title.textContent = `Modifier la clé ${provider}`;
|
||||
modal.classList.add('show');
|
||||
} else {
|
||||
showToast(data.error || 'Erreur lors du chargement', 'error');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showToast('Erreur de connexion', 'error');
|
||||
});
|
||||
}
|
||||
|
||||
function closeKeyModal() {
|
||||
const modal = document.getElementById('keyModal');
|
||||
modal.classList.remove('show');
|
||||
currentProvider = null;
|
||||
editMode = false;
|
||||
}
|
||||
|
||||
// ========== Form Handling ==========
|
||||
|
||||
function updateModelsList() {
|
||||
const provider = document.getElementById('provider').value;
|
||||
const modelSelect = document.getElementById('model_default');
|
||||
const keyHelp = document.getElementById('keyHelp');
|
||||
|
||||
// Clear current options
|
||||
modelSelect.innerHTML = '<option value="">-- Sélectionner un modèle --</option>';
|
||||
|
||||
if (!provider) {
|
||||
keyHelp.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
// Populate models for selected provider
|
||||
if (models[provider]) {
|
||||
models[provider].forEach(model => {
|
||||
const option = document.createElement('option');
|
||||
option.value = model.model_id;
|
||||
option.textContent = model.display_name;
|
||||
if (model.recommended) {
|
||||
option.textContent += ' ⭐';
|
||||
}
|
||||
modelSelect.appendChild(option);
|
||||
});
|
||||
|
||||
// Auto-select first recommended model
|
||||
const recommended = models[provider].find(m => m.recommended);
|
||||
if (recommended) {
|
||||
modelSelect.value = recommended.model_id;
|
||||
}
|
||||
}
|
||||
|
||||
// Update help text
|
||||
if (API_HELP_URLS[provider]) {
|
||||
keyHelp.innerHTML = `💡 Obtenir une clé : <a href="${API_HELP_URLS[provider]}" target="_blank">${API_HELP_URLS[provider]}</a>`;
|
||||
} else {
|
||||
keyHelp.innerHTML = '';
|
||||
}
|
||||
}
|
||||
|
||||
function toggleQuotaInput() {
|
||||
const checkbox = document.getElementById('set_quota');
|
||||
const quotaGroup = document.getElementById('quotaGroup');
|
||||
quotaGroup.style.display = checkbox.checked ? 'block' : 'none';
|
||||
}
|
||||
|
||||
function toggleKeyVisibility() {
|
||||
const input = document.getElementById('api_key');
|
||||
const button = event.target;
|
||||
|
||||
if (input.type === 'password') {
|
||||
input.type = 'text';
|
||||
button.textContent = '🙈';
|
||||
} else {
|
||||
input.type = 'password';
|
||||
button.textContent = '👁️';
|
||||
}
|
||||
}
|
||||
|
||||
// ========== Form Submission ==========
|
||||
|
||||
document.getElementById('keyForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(this);
|
||||
formData.append('action', 'save');
|
||||
|
||||
// Show loading
|
||||
const submitBtn = this.querySelector('button[type="submit"]');
|
||||
const originalText = submitBtn.innerHTML;
|
||||
submitBtn.innerHTML = '⏳ Enregistrement...';
|
||||
submitBtn.disabled = true;
|
||||
|
||||
fetch('chatbot_api_ajax.php', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
showToast(data.message || 'Clé enregistrée avec succès', 'success');
|
||||
closeKeyModal();
|
||||
|
||||
// Reload page to show updated keys
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
} else {
|
||||
showToast(data.error || 'Erreur lors de l\'enregistrement', 'error');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showToast('Erreur de connexion', 'error');
|
||||
})
|
||||
.finally(() => {
|
||||
submitBtn.innerHTML = originalText;
|
||||
submitBtn.disabled = false;
|
||||
});
|
||||
});
|
||||
|
||||
// ========== Test Connection ==========
|
||||
|
||||
function testKeyBeforeSave() {
|
||||
const provider = document.getElementById('provider').value;
|
||||
const apiKey = document.getElementById('api_key').value;
|
||||
const model = document.getElementById('model_default').value;
|
||||
|
||||
if (!provider || !apiKey || !model) {
|
||||
showToast('Veuillez remplir tous les champs obligatoires', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
testConnectionWithParams(provider, apiKey, model);
|
||||
}
|
||||
|
||||
function testConnection(provider) {
|
||||
testConnectionWithParams(provider, null, null);
|
||||
}
|
||||
|
||||
function testConnectionWithParams(provider, apiKey = null, model = null) {
|
||||
const testResult = document.getElementById('testResult');
|
||||
testResult.style.display = 'block';
|
||||
testResult.className = 'test-result';
|
||||
testResult.innerHTML = '🔄 Test en cours...';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('action', 'test');
|
||||
formData.append('provider', provider);
|
||||
if (apiKey) formData.append('api_key', apiKey);
|
||||
if (model) formData.append('model', model);
|
||||
|
||||
fetch('chatbot_api_ajax.php', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
testResult.className = 'test-result success';
|
||||
testResult.innerHTML = `✅ ${data.message}<br><small>Latence: ${data.latency_ms}ms</small>`;
|
||||
} else {
|
||||
testResult.className = 'test-result error';
|
||||
testResult.innerHTML = `❌ ${data.message}`;
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
testResult.className = 'test-result error';
|
||||
testResult.innerHTML = '❌ Erreur de connexion au serveur';
|
||||
});
|
||||
}
|
||||
|
||||
// ========== Delete Key ==========
|
||||
|
||||
function deleteKey(provider) {
|
||||
if (!confirm(`Êtes-vous sûr de vouloir supprimer la clé ${provider} ?\n\nCette action est irréversible.`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('action', 'delete');
|
||||
formData.append('provider', provider);
|
||||
|
||||
fetch('chatbot_api_ajax.php', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
showToast('Clé supprimée avec succès', 'success');
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
} else {
|
||||
showToast(data.error || 'Erreur lors de la suppression', 'error');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showToast('Erreur de connexion', 'error');
|
||||
});
|
||||
}
|
||||
|
||||
// ========== Set Default Provider ==========
|
||||
|
||||
function setAsDefault(provider, model) {
|
||||
const formData = new FormData();
|
||||
formData.append('action', 'set_default');
|
||||
formData.append('provider', provider);
|
||||
formData.append('model', model);
|
||||
|
||||
fetch('chatbot_api_ajax.php', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
showToast(data.message || 'Provider par défaut mis à jour', 'success');
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
} else {
|
||||
showToast(data.error || 'Erreur', 'error');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showToast('Erreur de connexion', 'error');
|
||||
});
|
||||
}
|
||||
|
||||
// ========== Configure Ollama ==========
|
||||
|
||||
function configureOllama() {
|
||||
const availableModels = models['ollama'] || [];
|
||||
|
||||
if (availableModels.length === 0) {
|
||||
showToast('Aucun modèle Ollama disponible', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Créer une liste des modèles
|
||||
let modelOptions = '<select id="ollama-model-select" style="width: 100%; padding: 0.5rem; margin: 1rem 0; border: 2px solid #e2e8f0; border-radius: 8px;">';
|
||||
availableModels.forEach(model => {
|
||||
modelOptions += `<option value="${model.model_id}">${model.display_name}</option>`;
|
||||
});
|
||||
modelOptions += '</select>';
|
||||
|
||||
// Simple prompt
|
||||
const modelHtml = `
|
||||
<div style="padding: 1rem;">
|
||||
<p style="margin-bottom: 1rem;">Choisir le modèle Ollama par défaut :</p>
|
||||
${modelOptions}
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Utiliser une confirm box simple pour l'instant
|
||||
// (dans une vraie app, utiliser le modal existant)
|
||||
const modal = document.getElementById('keyModal');
|
||||
const modalContent = modal.querySelector('.modal-content');
|
||||
const originalContent = modalContent.innerHTML;
|
||||
|
||||
modalContent.innerHTML = `
|
||||
<div class="modal-header">
|
||||
<h2>Configuration Ollama</h2>
|
||||
<button class="modal-close" onclick="closeKeyModal()">×</button>
|
||||
</div>
|
||||
<div style="padding: 1.5rem;">
|
||||
<p style="margin-bottom: 1rem;">Choisir le modèle Ollama à utiliser par défaut :</p>
|
||||
<select id="ollama-model-select" style="width: 100%; padding: 0.75rem; border: 2px solid #e2e8f0; border-radius: 8px; font-family: 'JetBrains Mono', monospace;">
|
||||
${availableModels.map(m => `<option value="${m.model_id}">${m.display_name}</option>`).join('')}
|
||||
</select>
|
||||
<div style="display: flex; gap: 1rem; justify-content: flex-end; margin-top: 1.5rem; padding-top: 1.5rem; border-top: 2px solid #e2e8f0;">
|
||||
<button class="btn-secondary" onclick="closeKeyModal(); document.querySelector('.modal-content').innerHTML = \`${originalContent.replace(/`/g, '\\`')}\`;">Annuler</button>
|
||||
<button class="btn-primary" onclick="saveOllamaConfig()">💾 Enregistrer</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
modal.classList.add('show');
|
||||
}
|
||||
|
||||
function saveOllamaConfig() {
|
||||
const select = document.getElementById('ollama-model-select');
|
||||
const model = select.value;
|
||||
|
||||
if (!model) {
|
||||
showToast('Veuillez sélectionner un modèle', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setAsDefault('ollama', model);
|
||||
}
|
||||
|
||||
// ========== Toast Notifications ==========
|
||||
|
||||
function showToast(message, type = 'info') {
|
||||
const container = document.getElementById('toast-container');
|
||||
const toast = document.createElement('div');
|
||||
toast.className = `toast ${type}`;
|
||||
|
||||
const icons = {
|
||||
'success': '✅',
|
||||
'error': '❌',
|
||||
'warning': '⚠️',
|
||||
'info': 'ℹ️'
|
||||
};
|
||||
|
||||
toast.innerHTML = `
|
||||
<span class="toast-icon">${icons[type] || icons.info}</span>
|
||||
<span class="toast-message">${message}</span>
|
||||
`;
|
||||
|
||||
container.appendChild(toast);
|
||||
|
||||
// Auto-remove after 4 seconds
|
||||
setTimeout(() => {
|
||||
toast.style.opacity = '0';
|
||||
toast.style.transform = 'translateX(100%)';
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}, 4000);
|
||||
}
|
||||
|
||||
// ========== Close modal on outside click ==========
|
||||
|
||||
document.getElementById('keyModal').addEventListener('click', function(e) {
|
||||
if (e.target === this) {
|
||||
closeKeyModal();
|
||||
}
|
||||
});
|
||||
|
||||
// ========== Keyboard shortcuts ==========
|
||||
|
||||
document.addEventListener('keydown', function(e) {
|
||||
// ESC to close modal
|
||||
if (e.key === 'Escape') {
|
||||
const modal = document.getElementById('keyModal');
|
||||
if (modal.classList.contains('show')) {
|
||||
closeKeyModal();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ========== Initialize ==========
|
||||
|
||||
console.log('✅ Chatbot Settings JS loaded');
|
||||
console.log('Available models:', models);
|
||||
455
config/api_key_manager.php
Normal file
455
config/api_key_manager.php
Normal file
@ -0,0 +1,455 @@
|
||||
<?php
|
||||
/**
|
||||
* Gestionnaire de clés API pour le chatbot
|
||||
* Chiffrement AES-256-CBC des clés API
|
||||
*
|
||||
* @author WebVal
|
||||
* @date 2026-01-04
|
||||
*/
|
||||
|
||||
class APIKeyManager {
|
||||
|
||||
private static $encryption_key = null;
|
||||
private static $db = null;
|
||||
|
||||
/**
|
||||
* Initialiser la connexion BDD
|
||||
*/
|
||||
private static function init() {
|
||||
if (self::$db === null) {
|
||||
self::$db = Database::getInstance();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupérer la clé de chiffrement
|
||||
* Ordre de priorité : ENV > Fichier > Génération
|
||||
*/
|
||||
private static function getEncryptionKey() {
|
||||
if (self::$encryption_key !== null) {
|
||||
return self::$encryption_key;
|
||||
}
|
||||
|
||||
// 1. Variable d'environnement
|
||||
$key = getenv('WEBVAL_API_ENCRYPTION_KEY');
|
||||
|
||||
// 2. Fichier externe (hors webroot)
|
||||
if (!$key && file_exists('/etc/webval/encryption.key')) {
|
||||
$key = file_get_contents('/etc/webval/encryption.key');
|
||||
}
|
||||
|
||||
// 3. Fichier dans config (fallback)
|
||||
$keyFile = __DIR__ . '/../config/.encryption_key';
|
||||
if (!$key && file_exists($keyFile)) {
|
||||
$key = file_get_contents($keyFile);
|
||||
}
|
||||
|
||||
// 4. Générer une nouvelle clé si aucune n'existe
|
||||
if (!$key) {
|
||||
$key = bin2hex(random_bytes(32));
|
||||
|
||||
// Essayer de sauvegarder
|
||||
if (is_writable(__DIR__ . '/../config/')) {
|
||||
file_put_contents($keyFile, $key);
|
||||
chmod($keyFile, 0600);
|
||||
}
|
||||
|
||||
error_log("⚠️ Nouvelle clé de chiffrement générée. Sauvegarde recommandée.");
|
||||
}
|
||||
|
||||
self::$encryption_key = $key;
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Chiffrer une clé API
|
||||
*
|
||||
* @param string $plaintext Clé API en clair
|
||||
* @return string Clé chiffrée (base64)
|
||||
*/
|
||||
public static function encrypt($plaintext) {
|
||||
if (empty($plaintext)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$key = hash('sha256', self::getEncryptionKey(), true);
|
||||
$iv = random_bytes(16);
|
||||
|
||||
$ciphertext = openssl_encrypt(
|
||||
$plaintext,
|
||||
'AES-256-CBC',
|
||||
$key,
|
||||
OPENSSL_RAW_DATA,
|
||||
$iv
|
||||
);
|
||||
|
||||
if ($ciphertext === false) {
|
||||
throw new Exception("Erreur de chiffrement");
|
||||
}
|
||||
|
||||
// Format: IV (16 bytes) + Ciphertext
|
||||
return base64_encode($iv . $ciphertext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Déchiffrer une clé API
|
||||
*
|
||||
* @param string $encrypted Clé chiffrée (base64)
|
||||
* @return string|null Clé API en clair
|
||||
*/
|
||||
public static function decrypt($encrypted) {
|
||||
if (empty($encrypted)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$key = hash('sha256', self::getEncryptionKey(), true);
|
||||
$data = base64_decode($encrypted);
|
||||
|
||||
if ($data === false || strlen($data) < 16) {
|
||||
throw new Exception("Données chiffrées invalides");
|
||||
}
|
||||
|
||||
$iv = substr($data, 0, 16);
|
||||
$ciphertext = substr($data, 16);
|
||||
|
||||
$plaintext = openssl_decrypt(
|
||||
$ciphertext,
|
||||
'AES-256-CBC',
|
||||
$key,
|
||||
OPENSSL_RAW_DATA,
|
||||
$iv
|
||||
);
|
||||
|
||||
if ($plaintext === false) {
|
||||
throw new Exception("Erreur de déchiffrement");
|
||||
}
|
||||
|
||||
return $plaintext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sauvegarder une clé API
|
||||
*
|
||||
* @param int $id_enseignant ID de l'enseignant
|
||||
* @param string $provider Provider (gemini, mistral, etc.)
|
||||
* @param string $api_key Clé API en clair
|
||||
* @param string $model_default Modèle par défaut
|
||||
* @return bool Succès
|
||||
*/
|
||||
public static function saveKey($id_enseignant, $provider, $api_key, $model_default = null) {
|
||||
self::init();
|
||||
|
||||
// Chiffrer la clé
|
||||
$encrypted = self::encrypt($api_key);
|
||||
|
||||
// Upsert (INSERT ... ON DUPLICATE KEY UPDATE)
|
||||
$query = "INSERT INTO api_keys
|
||||
(id_enseignant, provider, api_key_encrypted, model_default, is_active, quota_reset_date)
|
||||
VALUES (?, ?, ?, ?, TRUE, DATE_ADD(CURDATE(), INTERVAL 1 MONTH))
|
||||
ON DUPLICATE KEY UPDATE
|
||||
api_key_encrypted = VALUES(api_key_encrypted),
|
||||
model_default = VALUES(model_default),
|
||||
is_active = TRUE,
|
||||
updated_at = CURRENT_TIMESTAMP";
|
||||
|
||||
return self::$db->query($query, [
|
||||
$id_enseignant,
|
||||
$provider,
|
||||
$encrypted,
|
||||
$model_default
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupérer une clé API déchiffrée
|
||||
*
|
||||
* @param int $id_enseignant ID de l'enseignant
|
||||
* @param string $provider Provider
|
||||
* @return array|null ['api_key' => '...', 'model_default' => '...']
|
||||
*/
|
||||
public static function getKey($id_enseignant, $provider) {
|
||||
self::init();
|
||||
|
||||
$result = self::$db->fetchOne(
|
||||
"SELECT api_key_encrypted, model_default, is_active
|
||||
FROM api_keys
|
||||
WHERE id_enseignant = ? AND provider = ?",
|
||||
[$id_enseignant, $provider]
|
||||
);
|
||||
|
||||
if (!$result || !$result['is_active']) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'api_key' => self::decrypt($result['api_key_encrypted']),
|
||||
'model_default' => $result['model_default']
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprimer une clé API
|
||||
*
|
||||
* @param int $id_enseignant ID de l'enseignant
|
||||
* @param string $provider Provider
|
||||
* @return bool Succès
|
||||
*/
|
||||
public static function deleteKey($id_enseignant, $provider) {
|
||||
self::init();
|
||||
|
||||
return self::$db->query(
|
||||
"DELETE FROM api_keys WHERE id_enseignant = ? AND provider = ?",
|
||||
[$id_enseignant, $provider]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lister toutes les clés d'un enseignant
|
||||
*
|
||||
* @param int $id_enseignant ID de l'enseignant
|
||||
* @return array Liste des clés (sans les clés déchiffrées)
|
||||
*/
|
||||
public static function listKeys($id_enseignant) {
|
||||
self::init();
|
||||
|
||||
return self::$db->fetchAll(
|
||||
"SELECT
|
||||
id,
|
||||
provider,
|
||||
model_default,
|
||||
is_active,
|
||||
quota_max,
|
||||
quota_used,
|
||||
quota_reset_date,
|
||||
last_used,
|
||||
created_at
|
||||
FROM api_keys
|
||||
WHERE id_enseignant = ?
|
||||
ORDER BY provider",
|
||||
[$id_enseignant]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Incrémenter le quota utilisé
|
||||
*
|
||||
* @param int $id_enseignant ID de l'enseignant
|
||||
* @param string $provider Provider
|
||||
* @param int $tokens_used Nombre de tokens utilisés
|
||||
*/
|
||||
public static function incrementQuota($id_enseignant, $provider, $tokens_used = 1) {
|
||||
self::init();
|
||||
|
||||
// Reset quota si date dépassée
|
||||
self::$db->query(
|
||||
"UPDATE api_keys
|
||||
SET quota_used = 0, quota_reset_date = DATE_ADD(CURDATE(), INTERVAL 1 MONTH)
|
||||
WHERE id_enseignant = ? AND provider = ? AND quota_reset_date < CURDATE()",
|
||||
[$id_enseignant, $provider]
|
||||
);
|
||||
|
||||
// Incrémenter
|
||||
return self::$db->query(
|
||||
"UPDATE api_keys
|
||||
SET quota_used = quota_used + ?, last_used = NOW()
|
||||
WHERE id_enseignant = ? AND provider = ?",
|
||||
[$tokens_used, $id_enseignant, $provider]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifier si le quota est dépassé
|
||||
*
|
||||
* @param int $id_enseignant ID de l'enseignant
|
||||
* @param string $provider Provider
|
||||
* @return bool True si quota OK
|
||||
*/
|
||||
public static function checkQuota($id_enseignant, $provider) {
|
||||
self::init();
|
||||
|
||||
$result = self::$db->fetchOne(
|
||||
"SELECT quota_max, quota_used FROM api_keys
|
||||
WHERE id_enseignant = ? AND provider = ?",
|
||||
[$id_enseignant, $provider]
|
||||
);
|
||||
|
||||
if (!$result || $result['quota_max'] === null) {
|
||||
return true; // Pas de limite
|
||||
}
|
||||
|
||||
return $result['quota_used'] < $result['quota_max'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tester une connexion API
|
||||
*
|
||||
* @param string $provider Provider à tester
|
||||
* @param string $api_key Clé API
|
||||
* @param string $model Modèle à tester
|
||||
* @return array ['success' => bool, 'message' => string, 'latency_ms' => int]
|
||||
*/
|
||||
public static function testConnection($provider, $api_key, $model = null) {
|
||||
$start = microtime(true);
|
||||
|
||||
try {
|
||||
switch ($provider) {
|
||||
case 'gemini':
|
||||
$result = self::testGemini($api_key, $model ?? 'gemini-2.0-flash-exp');
|
||||
break;
|
||||
|
||||
case 'mistral':
|
||||
$result = self::testMistral($api_key, $model ?? 'ministral-3b-latest');
|
||||
break;
|
||||
|
||||
case 'openai':
|
||||
$result = self::testOpenAI($api_key, $model ?? 'gpt-4o-mini');
|
||||
break;
|
||||
|
||||
case 'ollama':
|
||||
$result = self::testOllama($model ?? 'ministral-3:3b');
|
||||
break;
|
||||
|
||||
default:
|
||||
return ['success' => false, 'message' => 'Provider inconnu'];
|
||||
}
|
||||
|
||||
$latency = round((microtime(true) - $start) * 1000);
|
||||
$result['latency_ms'] = $latency;
|
||||
|
||||
return $result;
|
||||
|
||||
} catch (Exception $e) {
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Erreur: ' . $e->getMessage(),
|
||||
'latency_ms' => 0
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tester connexion Gemini
|
||||
*/
|
||||
private static function testGemini($api_key, $model) {
|
||||
$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$api_key}";
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_POSTFIELDS => json_encode([
|
||||
'contents' => [['parts' => [['text' => 'Test']]]]
|
||||
])
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($http_code === 200) {
|
||||
return ['success' => true, 'message' => 'Connexion Gemini réussie'];
|
||||
} elseif ($http_code === 400) {
|
||||
return ['success' => false, 'message' => 'Clé API invalide'];
|
||||
} elseif ($http_code === 429) {
|
||||
return ['success' => false, 'message' => 'Quota dépassé'];
|
||||
} else {
|
||||
return ['success' => false, 'message' => "Erreur HTTP $http_code"];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tester connexion Mistral
|
||||
*/
|
||||
private static function testMistral($api_key, $model) {
|
||||
$ch = curl_init('https://api.mistral.ai/v1/chat/completions');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'Authorization: Bearer ' . $api_key
|
||||
],
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_POSTFIELDS => json_encode([
|
||||
'model' => $model,
|
||||
'messages' => [['role' => 'user', 'content' => 'Test']],
|
||||
'max_tokens' => 10
|
||||
])
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($http_code === 200) {
|
||||
return ['success' => true, 'message' => 'Connexion Mistral réussie'];
|
||||
} elseif ($http_code === 401) {
|
||||
return ['success' => false, 'message' => 'Clé API invalide'];
|
||||
} else {
|
||||
return ['success' => false, 'message' => "Erreur HTTP $http_code"];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tester connexion OpenAI
|
||||
*/
|
||||
private static function testOpenAI($api_key, $model) {
|
||||
$ch = curl_init('https://api.openai.com/v1/chat/completions');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'Authorization: Bearer ' . $api_key
|
||||
],
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_POSTFIELDS => json_encode([
|
||||
'model' => $model,
|
||||
'messages' => [['role' => 'user', 'content' => 'Test']],
|
||||
'max_tokens' => 10
|
||||
])
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($http_code === 200) {
|
||||
return ['success' => true, 'message' => 'Connexion OpenAI réussie'];
|
||||
} elseif ($http_code === 401) {
|
||||
return ['success' => false, 'message' => 'Clé API invalide'];
|
||||
} else {
|
||||
return ['success' => false, 'message' => "Erreur HTTP $http_code"];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tester connexion Ollama (local)
|
||||
*/
|
||||
private static function testOllama($model) {
|
||||
$ch = curl_init('http://localhost:11434/api/generate');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
CURLOPT_POSTFIELDS => json_encode([
|
||||
'model' => $model,
|
||||
'prompt' => 'Test',
|
||||
'stream' => false
|
||||
])
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($http_code === 200) {
|
||||
return ['success' => true, 'message' => 'Connexion Ollama réussie'];
|
||||
} else {
|
||||
return ['success' => false, 'message' => 'Ollama non disponible'];
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -32,6 +32,7 @@ if ($isEleveLibre) {
|
||||
$queryEvals = "SELECT DISTINCT e.*,
|
||||
COALESCE(t.statut, 'non_commence') as statut_tentative,
|
||||
t.note as note_obtenue,
|
||||
t.note_sur as note_sur_obtenue,
|
||||
t.date_debut as date_tentative
|
||||
FROM evaluations e
|
||||
INNER JOIN acces_evaluations ae ON e.id_evaluation = ae.id_evaluation
|
||||
@ -53,6 +54,7 @@ if ($isEleveLibre) {
|
||||
ae.date_fin as fin_acces,
|
||||
COALESCE(t.statut, 'non_commence') as statut_tentative,
|
||||
t.note as note_obtenue,
|
||||
t.note_sur as note_sur_obtenue,
|
||||
t.date_debut as date_tentative
|
||||
FROM evaluations e
|
||||
INNER JOIN acces_evaluations ae ON e.id_evaluation = ae.id_evaluation
|
||||
@ -95,7 +97,7 @@ $moyenne4Dernieres = 0;
|
||||
if (!empty($dernieresEvals)) {
|
||||
$somme_notes_sur_20 = 0;
|
||||
foreach ($dernieresEvals as $eval) {
|
||||
$note_sur_20 = $eval['nb_questions'] > 0 ? ($eval['note'] / $eval['nb_questions']) * 20 : 0;
|
||||
$note_sur_20 = $eval['note_sur'] > 0 ? ($eval['note'] / $eval['note_sur']) * 20 : 0;
|
||||
$somme_notes_sur_20 += $note_sur_20;
|
||||
}
|
||||
$moyenne_brute = $somme_notes_sur_20 / count($dernieresEvals);
|
||||
@ -108,6 +110,7 @@ $queryToutesEvals = "SELECT
|
||||
e.titre,
|
||||
e.description,
|
||||
te.note,
|
||||
te.note_sur,
|
||||
te.pourcentage,
|
||||
te.date_fin
|
||||
FROM tentatives_eleves te
|
||||
@ -122,8 +125,8 @@ $toutesEvals = $db->fetchAll($queryToutesEvals, [$user['id_utilisateur']]);
|
||||
$queryStats = "SELECT
|
||||
COUNT(DISTINCT t.id_evaluation) as nb_evaluations_passees,
|
||||
COUNT(CASE WHEN t.statut = 'terminee' THEN 1 END) as nb_evaluations_terminees,
|
||||
AVG(CASE WHEN t.statut = 'terminee'
|
||||
THEN (t.note / (SELECT COUNT(*) FROM questions WHERE id_evaluation = t.id_evaluation)) * 20
|
||||
AVG(CASE WHEN t.statut = 'terminee' AND t.note_sur > 0
|
||||
THEN (t.note / t.note_sur) * 20
|
||||
ELSE NULL END) as moyenne_generale
|
||||
FROM tentatives_eleves t
|
||||
WHERE t.id_eleve = ?";
|
||||
@ -555,8 +558,9 @@ if ($stats['moyenne_generale'] !== null) {
|
||||
|
||||
<div class="dernieres-evals-grid">
|
||||
<?php foreach ($dernieresEvals as $eval):
|
||||
// Convertir la note brute en note sur 20
|
||||
$note_sur_20 = $eval['nb_questions'] > 0 ? ($eval['note'] / $eval['nb_questions']) * 20 : 0;
|
||||
// Convertir la note brute en note sur 20 en utilisant le barème réel
|
||||
// note_sur = barème total (80, 50, 20, etc.)
|
||||
$note_sur_20 = $eval['note_sur'] > 0 ? ($eval['note'] / $eval['note_sur']) * 20 : 0;
|
||||
|
||||
// Arrondir au demi-point supérieur
|
||||
$note_arrondie = ceil($note_sur_20 * 2) / 2;
|
||||
@ -575,7 +579,7 @@ if ($stats['moyenne_generale'] !== null) {
|
||||
<div class="note-display-large">
|
||||
<div>
|
||||
<div class="note-fraction">
|
||||
<?= number_format($questions_reussies, 1) ?>/<?= $eval['nb_questions'] ?> questions
|
||||
<?= number_format($questions_reussies, 1) ?>/<?= number_format($eval['note_sur'], 0) ?> points
|
||||
</div>
|
||||
<div class="note-sur-20">
|
||||
<?= number_format($note_arrondie, 1) ?>/20
|
||||
@ -654,13 +658,16 @@ if ($stats['moyenne_generale'] !== null) {
|
||||
|
||||
<?php if ($statut === 'terminee'): ?>
|
||||
<?php
|
||||
// Récupérer le nombre de questions pour cette évaluation
|
||||
// Utiliser note_sur si disponible, sinon calculer avec nb questions
|
||||
if (isset($eval['note_sur_obtenue']) && $eval['note_sur_obtenue'] > 0) {
|
||||
$note_sur_20 = ($eval['note_obtenue'] / $eval['note_sur_obtenue']) * 20;
|
||||
} else {
|
||||
// Fallback : calculer avec nb questions
|
||||
$queryNbQ = "SELECT COUNT(*) as nb FROM questions WHERE id_evaluation = ?";
|
||||
$resultNbQ = $db->fetchOne($queryNbQ, [$eval['id_evaluation']]);
|
||||
$nb_q = $resultNbQ['nb'] ?? 1;
|
||||
|
||||
// Calculer la note sur 20
|
||||
$note_sur_20 = ($eval['note_obtenue'] / $nb_q) * 20;
|
||||
}
|
||||
$note_affichee = ceil($note_sur_20 * 2) / 2;
|
||||
?>
|
||||
<span class="note-display">
|
||||
@ -705,13 +712,11 @@ if ($stats['moyenne_generale'] !== null) {
|
||||
return `Eval ${index + 1}\n${date.getDate()}/${date.getMonth() + 1}`;
|
||||
});
|
||||
|
||||
// Récupérer le nombre de questions pour chaque évaluation (via AJAX)
|
||||
// Pour simplifier, on utilise le pourcentage pour recalculer
|
||||
// Récupérer le nombre de questions pour chaque évaluation
|
||||
// Utiliser note_sur (barème total) pour calculer la note sur 20
|
||||
const notes = toutesEvaluations.map(e => {
|
||||
// note brute → note sur 20 via le pourcentage
|
||||
// pourcentage = (note / nb_questions) * 100
|
||||
// donc note_sur_20 = (pourcentage / 100) * 20 = pourcentage / 5
|
||||
const note_sur_20 = parseFloat(e.pourcentage) / 5;
|
||||
// note / note_sur * 20
|
||||
const note_sur_20 = (parseFloat(e.note) / parseFloat(e.note_sur)) * 20;
|
||||
return Math.ceil(note_sur_20 * 2) / 2; // Arrondir demi-point sup
|
||||
});
|
||||
|
||||
|
||||
229
enseignant/chatbot_api_ajax.php
Normal file
229
enseignant/chatbot_api_ajax.php
Normal file
@ -0,0 +1,229 @@
|
||||
<?php
|
||||
/**
|
||||
* API AJAX pour la gestion des clés API du chatbot
|
||||
* Actions : save, test, delete, get
|
||||
*/
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
require_once '../config/config.php';
|
||||
require_once '../config/database.php';
|
||||
require_once '../config/session.php';
|
||||
require_once '../config/api_key_manager.php';
|
||||
|
||||
// Vérifier authentification
|
||||
if (!SessionManager::isLoggedIn() || !SessionManager::isEnseignant()) {
|
||||
echo json_encode(['error' => 'Non autorisé']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$user = SessionManager::getUser();
|
||||
$action = $_GET['action'] ?? $_POST['action'] ?? null;
|
||||
|
||||
try {
|
||||
switch ($action) {
|
||||
|
||||
case 'save':
|
||||
// Sauvegarder une clé API
|
||||
$provider = $_POST['provider'] ?? null;
|
||||
$api_key = $_POST['api_key'] ?? null;
|
||||
$model_default = $_POST['model_default'] ?? null;
|
||||
$quota_max = !empty($_POST['quota_max']) ? (int)$_POST['quota_max'] : null;
|
||||
|
||||
if (!$provider || !$api_key || !$model_default) {
|
||||
throw new Exception('Paramètres manquants');
|
||||
}
|
||||
|
||||
// Valider le provider
|
||||
$valid_providers = ['gemini', 'mistral', 'openai', 'ollama'];
|
||||
if (!in_array($provider, $valid_providers)) {
|
||||
throw new Exception('Provider invalide');
|
||||
}
|
||||
|
||||
// Sauvegarder
|
||||
$result = APIKeyManager::saveKey(
|
||||
$user['id_utilisateur'],
|
||||
$provider,
|
||||
$api_key,
|
||||
$model_default
|
||||
);
|
||||
|
||||
if (!$result) {
|
||||
throw new Exception('Erreur lors de la sauvegarde');
|
||||
}
|
||||
|
||||
// Mettre à jour le quota si défini
|
||||
if ($quota_max !== null) {
|
||||
$db = Database::getInstance();
|
||||
$db->query(
|
||||
"UPDATE api_keys SET quota_max = ? WHERE id_enseignant = ? AND provider = ?",
|
||||
[$quota_max, $user['id_utilisateur'], $provider]
|
||||
);
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Clé API enregistrée avec succès'
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'test':
|
||||
// Tester une connexion API
|
||||
$provider = $_POST['provider'] ?? null;
|
||||
$api_key = $_POST['api_key'] ?? null;
|
||||
$model = $_POST['model'] ?? null;
|
||||
|
||||
if (!$provider) {
|
||||
throw new Exception('Provider manquant');
|
||||
}
|
||||
|
||||
// Si pas de clé fournie, récupérer celle enregistrée
|
||||
if (!$api_key) {
|
||||
$key_data = APIKeyManager::getKey($user['id_utilisateur'], $provider);
|
||||
if (!$key_data) {
|
||||
throw new Exception('Aucune clé enregistrée pour ce provider');
|
||||
}
|
||||
$api_key = $key_data['api_key'];
|
||||
$model = $model ?? $key_data['model_default'];
|
||||
}
|
||||
|
||||
// Tester la connexion
|
||||
$result = APIKeyManager::testConnection($provider, $api_key, $model);
|
||||
|
||||
echo json_encode($result);
|
||||
break;
|
||||
|
||||
case 'delete':
|
||||
// Supprimer une clé API
|
||||
$provider = $_POST['provider'] ?? null;
|
||||
|
||||
if (!$provider) {
|
||||
throw new Exception('Provider manquant');
|
||||
}
|
||||
|
||||
$result = APIKeyManager::deleteKey($user['id_utilisateur'], $provider);
|
||||
|
||||
if (!$result) {
|
||||
throw new Exception('Erreur lors de la suppression');
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Clé API supprimée'
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'get':
|
||||
// Récupérer une clé API (pour édition)
|
||||
$provider = $_GET['provider'] ?? null;
|
||||
|
||||
if (!$provider) {
|
||||
throw new Exception('Provider manquant');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$key_data = $db->fetchOne(
|
||||
"SELECT provider, model_default, quota_max, is_active
|
||||
FROM api_keys
|
||||
WHERE id_enseignant = ? AND provider = ?",
|
||||
[$user['id_utilisateur'], $provider]
|
||||
);
|
||||
|
||||
if (!$key_data) {
|
||||
throw new Exception('Clé non trouvée');
|
||||
}
|
||||
|
||||
// Ne pas retourner la clé API elle-même
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'data' => $key_data
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'toggle':
|
||||
// Activer/désactiver une clé
|
||||
$provider = $_POST['provider'] ?? null;
|
||||
$active = isset($_POST['active']) ? (bool)$_POST['active'] : null;
|
||||
|
||||
if (!$provider || $active === null) {
|
||||
throw new Exception('Paramètres manquants');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$result = $db->query(
|
||||
"UPDATE api_keys SET is_active = ? WHERE id_enseignant = ? AND provider = ?",
|
||||
[$active, $user['id_utilisateur'], $provider]
|
||||
);
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => $active ? 'Clé activée' : 'Clé désactivée'
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'set_default':
|
||||
// Définir le provider par défaut
|
||||
$provider = $_POST['provider'] ?? null;
|
||||
$model = $_POST['model'] ?? null;
|
||||
|
||||
if (!$provider || !$model) {
|
||||
throw new Exception('Paramètres manquants');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Upsert dans chatbot_default_provider
|
||||
$result = $db->query(
|
||||
"INSERT INTO chatbot_default_provider (id_enseignant, provider, model_default)
|
||||
VALUES (?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE provider = VALUES(provider), model_default = VALUES(model_default)",
|
||||
[$user['id_utilisateur'], $provider, $model]
|
||||
);
|
||||
|
||||
if (!$result) {
|
||||
throw new Exception('Erreur lors de la mise à jour');
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'Provider par défaut mis à jour'
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'stats':
|
||||
// Récupérer les statistiques d'utilisation
|
||||
$db = Database::getInstance();
|
||||
|
||||
$stats = $db->fetchAll(
|
||||
"SELECT
|
||||
provider,
|
||||
model_used,
|
||||
SUM(total_conversations) as conversations,
|
||||
SUM(total_messages) as messages,
|
||||
AVG(avg_response_time_ms) as avg_latency,
|
||||
month
|
||||
FROM v_chatbot_usage_stats
|
||||
WHERE id_enseignant = ?
|
||||
GROUP BY provider, model_used, month
|
||||
ORDER BY month DESC, conversations DESC
|
||||
LIMIT 50",
|
||||
[$user['id_utilisateur']]
|
||||
);
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'stats' => $stats
|
||||
]);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Exception('Action inconnue');
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => $e->getMessage()
|
||||
]);
|
||||
}
|
||||
430
enseignant/chatbot_api_settings.php
Normal file
430
enseignant/chatbot_api_settings.php
Normal file
@ -0,0 +1,430 @@
|
||||
<?php
|
||||
/**
|
||||
* Configuration des clés API pour le chatbot
|
||||
* Interface de gestion pour les enseignants
|
||||
*/
|
||||
|
||||
require_once '../config/config.php';
|
||||
require_once '../config/database.php';
|
||||
require_once '../config/session.php';
|
||||
require_once '../config/api_key_manager.php';
|
||||
|
||||
// Vérifier authentification et type enseignant
|
||||
if (!SessionManager::isLoggedIn() || !SessionManager::isEnseignant()) {
|
||||
header('Location: ../login.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
$user = SessionManager::getUser();
|
||||
$db = Database::getInstance();
|
||||
|
||||
// Récupérer les clés API de l'enseignant
|
||||
$api_keys = APIKeyManager::listKeys($user['id_utilisateur']);
|
||||
|
||||
// Récupérer le provider par défaut configuré
|
||||
$default_config = $db->fetchOne(
|
||||
"SELECT provider, model_default FROM chatbot_default_provider WHERE id_enseignant = ?",
|
||||
[$user['id_utilisateur']]
|
||||
);
|
||||
|
||||
// Si pas de config, initialiser avec Ollama
|
||||
if (!$default_config) {
|
||||
$db->query(
|
||||
"INSERT INTO chatbot_default_provider (id_enseignant, provider, model_default) VALUES (?, 'ollama', 'ministral-3:3b')",
|
||||
[$user['id_utilisateur']]
|
||||
);
|
||||
$default_config = ['provider' => 'ollama', 'model_default' => 'ministral-3:3b'];
|
||||
}
|
||||
|
||||
$default_provider = $default_config['provider'];
|
||||
$default_model = $default_config['model_default'];
|
||||
|
||||
// Récupérer les modèles disponibles groupés par provider
|
||||
$models_by_provider = [];
|
||||
$all_models = $db->fetchAll(
|
||||
"SELECT * FROM available_models WHERE active = TRUE ORDER BY provider, recommended DESC, display_name"
|
||||
);
|
||||
|
||||
foreach ($all_models as $model) {
|
||||
$models_by_provider[$model['provider']][] = $model;
|
||||
}
|
||||
|
||||
// Récupérer les statistiques d'utilisation (requête directe)
|
||||
$stats = $db->fetchOne(
|
||||
"SELECT
|
||||
COUNT(DISTINCT cc.id) as total_conversations,
|
||||
COUNT(cm.id) as total_messages,
|
||||
cc.provider,
|
||||
cc.model_used
|
||||
FROM chat_conversations cc
|
||||
LEFT JOIN chat_messages cm ON cm.id_conversation = cc.id
|
||||
WHERE cc.id_enseignant = ?
|
||||
GROUP BY cc.provider, cc.model_used
|
||||
ORDER BY total_conversations DESC
|
||||
LIMIT 1",
|
||||
[$user['id_utilisateur']]
|
||||
);
|
||||
|
||||
$stats_detail = $db->fetchAll(
|
||||
"SELECT
|
||||
cc.provider,
|
||||
cc.model_used,
|
||||
COUNT(DISTINCT cc.id) as conversations,
|
||||
COUNT(cm.id) as messages,
|
||||
DATE_FORMAT(cc.date_debut, '%Y-%m') as month
|
||||
FROM chat_conversations cc
|
||||
LEFT JOIN chat_messages cm ON cm.id_conversation = cc.id
|
||||
WHERE cc.id_enseignant = ?
|
||||
GROUP BY cc.provider, cc.model_used, month
|
||||
ORDER BY month DESC, conversations DESC",
|
||||
[$user['id_utilisateur']]
|
||||
);
|
||||
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Configuration API Chatbot - WebVal</title>
|
||||
<link rel="stylesheet" href="../assets/css/chatbot_settings.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<!-- Header -->
|
||||
<header class="page-header">
|
||||
<div class="header-content">
|
||||
<a href="dashboard.php" class="back-link">← Retour au dashboard</a>
|
||||
<h1>⚙️ Configuration API Chatbot</h1>
|
||||
<p class="subtitle">Gérez vos clés API et choisissez les modèles pour vos évaluations</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- Stats overview -->
|
||||
<?php if ($stats): ?>
|
||||
<div class="stats-banner">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">💬</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value"><?= number_format($stats['total_conversations'] ?? 0) ?></div>
|
||||
<div class="stat-label">Conversations</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">📨</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value"><?= number_format($stats['total_messages'] ?? 0) ?></div>
|
||||
<div class="stat-label">Messages</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon">🤖</div>
|
||||
<div class="stat-content">
|
||||
<div class="stat-value"><?= htmlspecialchars($stats['provider'] ?? 'Aucun') ?></div>
|
||||
<div class="stat-label">Provider actuel</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<!-- Main content -->
|
||||
<div class="content-grid">
|
||||
|
||||
<!-- Section clés API -->
|
||||
<section class="api-keys-section">
|
||||
<div class="section-header">
|
||||
<h2>🔑 Mes clés API</h2>
|
||||
<button class="btn-primary" onclick="openAddKeyModal()">
|
||||
➕ Ajouter une clé
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="keys-list">
|
||||
<?php
|
||||
$providers = ['gemini' => 'Gemini', 'mistral' => 'Mistral', 'openai' => 'OpenAI', 'ollama' => 'Ollama'];
|
||||
$provider_icons = [
|
||||
'gemini' => '✨',
|
||||
'mistral' => '⚡',
|
||||
'openai' => '🧠',
|
||||
'ollama' => '🏠'
|
||||
];
|
||||
|
||||
foreach ($providers as $provider_id => $provider_name):
|
||||
$key_info = null;
|
||||
foreach ($api_keys as $key) {
|
||||
if ($key['provider'] === $provider_id) {
|
||||
$key_info = $key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$is_configured = $key_info !== null;
|
||||
$is_active = $is_configured && $key_info['is_active'];
|
||||
?>
|
||||
<div class="key-card <?= $is_active ? 'active' : 'inactive' ?>">
|
||||
<div class="key-header">
|
||||
<div class="key-provider">
|
||||
<span class="provider-icon"><?= $provider_icons[$provider_id] ?></span>
|
||||
<span class="provider-name"><?= $provider_name ?></span>
|
||||
</div>
|
||||
<div class="key-status">
|
||||
<?php if ($is_active): ?>
|
||||
<span class="status-badge active">🟢 Active</span>
|
||||
<?php elseif ($is_configured): ?>
|
||||
<span class="status-badge inactive">🟠 Désactivée</span>
|
||||
<?php else: ?>
|
||||
<span class="status-badge none">⚪ Aucune</span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="key-body">
|
||||
<?php if ($provider_id === 'ollama'): ?>
|
||||
<!-- Card spéciale Ollama (pas de clé API nécessaire) -->
|
||||
<div class="key-info">
|
||||
<div class="info-row">
|
||||
<span class="label">Type :</span>
|
||||
<span class="value">🏠 Local (Jetson)</span>
|
||||
</div>
|
||||
<div class="info-row">
|
||||
<span class="label">Modèle actuel :</span>
|
||||
<span class="value"><?= $default_provider === 'ollama' ? htmlspecialchars($default_model) : 'ministral-3:3b' ?></span>
|
||||
</div>
|
||||
<div class="info-row">
|
||||
<span class="label">Coût :</span>
|
||||
<span class="value">Gratuit ✅</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="key-actions">
|
||||
<button class="btn-secondary btn-sm" onclick="testConnection('ollama')">
|
||||
🔍 Tester
|
||||
</button>
|
||||
<button class="btn-secondary btn-sm" onclick="configureOllama()">
|
||||
⚙️ Changer le modèle
|
||||
</button>
|
||||
<?php if ($default_provider !== 'ollama'): ?>
|
||||
<button class="btn-primary btn-sm" onclick="setAsDefault('ollama', 'ministral-3:3b')">
|
||||
⭐ Définir par défaut
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php elseif ($is_configured): ?>
|
||||
<div class="key-info">
|
||||
<div class="info-row">
|
||||
<span class="label">Modèle par défaut :</span>
|
||||
<span class="value"><?= htmlspecialchars($key_info['model_default'] ?? '-') ?></span>
|
||||
</div>
|
||||
<?php if ($key_info['quota_max']): ?>
|
||||
<div class="info-row">
|
||||
<span class="label">Quota :</span>
|
||||
<span class="value">
|
||||
<?= number_format($key_info['quota_used']) ?> / <?= number_format($key_info['quota_max']) ?>
|
||||
<span class="quota-bar">
|
||||
<span class="quota-fill" style="width: <?= min(100, ($key_info['quota_used'] / $key_info['quota_max']) * 100) ?>%"></span>
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<div class="info-row">
|
||||
<span class="label">Dernière utilisation :</span>
|
||||
<span class="value">
|
||||
<?= $key_info['last_used'] ? date('d/m/Y H:i', strtotime($key_info['last_used'])) : 'Jamais' ?>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="key-actions">
|
||||
<button class="btn-secondary btn-sm" onclick="testConnection('<?= $provider_id ?>')">
|
||||
🔍 Tester
|
||||
</button>
|
||||
<button class="btn-secondary btn-sm" onclick="editKey('<?= $provider_id ?>')">
|
||||
✏️ Modifier
|
||||
</button>
|
||||
<?php if ($default_provider !== $provider_id): ?>
|
||||
<button class="btn-primary btn-sm" onclick="setAsDefault('<?= $provider_id ?>', '<?= htmlspecialchars($key_info['model_default']) ?>')">
|
||||
⭐ Définir par défaut
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
<button class="btn-danger btn-sm" onclick="deleteKey('<?= $provider_id ?>')">
|
||||
🗑️ Supprimer
|
||||
</button>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="key-empty">
|
||||
<p>Aucune clé configurée pour <?= $provider_name ?></p>
|
||||
<button class="btn-primary btn-sm" onclick="openAddKeyModal('<?= $provider_id ?>')">
|
||||
➕ Ajouter
|
||||
</button>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Section modèles disponibles -->
|
||||
<aside class="models-sidebar">
|
||||
<div class="section-header">
|
||||
<h3>📚 Modèles disponibles</h3>
|
||||
</div>
|
||||
|
||||
<div class="models-list">
|
||||
<?php foreach ($models_by_provider as $provider => $models): ?>
|
||||
<div class="provider-group">
|
||||
<h4><?= $provider_icons[$provider] ?? '🤖' ?> <?= ucfirst($provider) ?></h4>
|
||||
<?php foreach ($models as $model): ?>
|
||||
<div class="model-item <?= $model['recommended'] ? 'recommended' : '' ?>">
|
||||
<div class="model-name">
|
||||
<?= htmlspecialchars($model['display_name']) ?>
|
||||
<?php if ($model['recommended']): ?>
|
||||
<span class="badge-recommended">⭐</span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<div class="model-meta">
|
||||
<?php if ($model['is_free']): ?>
|
||||
<span class="badge-free">🆓 Gratuit</span>
|
||||
<?php else: ?>
|
||||
<span class="badge-paid">💰 <?= number_format($model['cost_per_1m_tokens'], 2) ?>€/1M</span>
|
||||
<?php endif; ?>
|
||||
<span class="badge-speed">
|
||||
<?php
|
||||
$speed_icons = ['⏱️', '🐌', '🚶', '🏃', '🚀', '⚡'];
|
||||
echo $speed_icons[$model['speed_rating']] ?? '🚶';
|
||||
?>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
|
||||
<div class="help-box">
|
||||
<h4>💡 Recommandations</h4>
|
||||
<ul>
|
||||
<li><strong>Gemini 2.0 Flash</strong> : Gratuit, rapide, excellent pour les évaluations</li>
|
||||
<li><strong>Ministral 8B</strong> : Bon rapport qualité/prix</li>
|
||||
<li><strong>Ollama local</strong> : Gratuit mais 1 élève à la fois</li>
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<!-- Section statistiques détaillées -->
|
||||
<?php if (!empty($stats_detail)): ?>
|
||||
<section class="stats-section">
|
||||
<div class="section-header">
|
||||
<h2>📊 Historique d'utilisation</h2>
|
||||
</div>
|
||||
<div class="stats-table-wrapper">
|
||||
<table class="stats-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Mois</th>
|
||||
<th>Provider</th>
|
||||
<th>Modèle</th>
|
||||
<th>Conversations</th>
|
||||
<th>Messages</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($stats_detail as $stat): ?>
|
||||
<tr>
|
||||
<td><?= date('M Y', strtotime($stat['month'] . '-01')) ?></td>
|
||||
<td>
|
||||
<span class="provider-badge">
|
||||
<?= $provider_icons[$stat['provider']] ?? '🤖' ?>
|
||||
<?= ucfirst($stat['provider']) ?>
|
||||
</span>
|
||||
</td>
|
||||
<td><?= htmlspecialchars($stat['model_used']) ?></td>
|
||||
<td><?= number_format($stat['conversations']) ?></td>
|
||||
<td><?= number_format($stat['messages']) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<!-- Modal ajout/modification clé API -->
|
||||
<div id="keyModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h2 id="modalTitle">Ajouter une clé API</h2>
|
||||
<button class="modal-close" onclick="closeKeyModal()">×</button>
|
||||
</div>
|
||||
|
||||
<form id="keyForm">
|
||||
<input type="hidden" id="keyAction" value="add">
|
||||
|
||||
<div class="form-group">
|
||||
<label for="provider">Provider *</label>
|
||||
<select id="provider" name="provider" required onchange="updateModelsList()">
|
||||
<option value="">-- Choisir --</option>
|
||||
<option value="gemini">✨ Gemini (Google)</option>
|
||||
<option value="mistral">⚡ Mistral</option>
|
||||
<option value="openai">🧠 OpenAI</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="api_key">Clé API *</label>
|
||||
<div class="input-with-button">
|
||||
<input type="password" id="api_key" name="api_key" required
|
||||
placeholder="AIza... ou sk-... ou votre clé">
|
||||
<button type="button" class="btn-toggle-visibility" onclick="toggleKeyVisibility()">
|
||||
👁️
|
||||
</button>
|
||||
</div>
|
||||
<small class="help-text" id="keyHelp"></small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="model_default">Modèle par défaut *</label>
|
||||
<select id="model_default" name="model_default" required>
|
||||
<option value="">-- Sélectionner un provider d'abord --</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>
|
||||
<input type="checkbox" id="set_quota" onchange="toggleQuotaInput()">
|
||||
Limiter le quota mensuel
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="form-group" id="quotaGroup" style="display: none;">
|
||||
<label for="quota_max">Limite mensuelle (requêtes)</label>
|
||||
<input type="number" id="quota_max" name="quota_max" min="1" placeholder="ex: 1000">
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="button" class="btn-secondary" onclick="closeKeyModal()">
|
||||
Annuler
|
||||
</button>
|
||||
<button type="button" class="btn-test" onclick="testKeyBeforeSave()">
|
||||
🔍 Tester la connexion
|
||||
</button>
|
||||
<button type="submit" class="btn-primary">
|
||||
💾 Enregistrer
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="testResult" class="test-result" style="display: none;"></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Toast notifications -->
|
||||
<div id="toast-container"></div>
|
||||
|
||||
<script>
|
||||
const models = <?= json_encode($models_by_provider) ?>;
|
||||
const userId = <?= $user['id_utilisateur'] ?>;
|
||||
</script>
|
||||
<script src="../assets/js/chatbot_settings.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@ -472,6 +472,9 @@ try {
|
||||
<a href="statistiques/index.php" class="btn btn-secondary">
|
||||
📊 Statistiques détaillées
|
||||
</a>
|
||||
<a href="chatbot_api_settings.php" class="btn btn-secondary">
|
||||
🤖 Configuration IA Chatbot
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -502,13 +505,12 @@ try {
|
||||
<a href="../resultat_evaluation.php?id=<?= $eval['id_evaluation'] ?>" class="btn btn-info btn-sm">
|
||||
📊 Résultats
|
||||
</a>
|
||||
<a href="../passer_evaluation.php?id_evaluation=<?= $eval['id_evaluation'] ?>&apercu=1" target="_blank" class="btn btn-secondary btn-sm">
|
||||
<a href="monitoring.php?id_evaluation=<?= $eval['id_evaluation'] ?>"
|
||||
class="btn-action"
|
||||
style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;"
|
||||
class="btn btn-primary btn-sm"
|
||||
title="Monitoring temps réel">
|
||||
📊 Monitoring
|
||||
</a>
|
||||
<a href="../passer_evaluation.php?id_evaluation=<?= $eval['id_evaluation'] ?>&apercu=1" target="_blank" class="btn btn-secondary btn-sm">
|
||||
👁️ Aperçu
|
||||
</a>
|
||||
<a href="export.php?id_evaluation=<?= $eval['id_evaluation'] ?>&format=csv"
|
||||
|
||||
@ -162,6 +162,7 @@ $stmt->execute([$id_evaluation, $user['id_utilisateur']]);
|
||||
$tentative = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
// Si pas de tentative en cours, en créer une (CORRECTION: utilise nb_tentatives_terminees)
|
||||
// APRÈS (CORRIGÉ)
|
||||
if (!$tentative) {
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO tentatives_eleves (
|
||||
@ -176,6 +177,9 @@ if (!$tentative) {
|
||||
$stmt = $db->prepare("SELECT * FROM tentatives_eleves WHERE id_tentative = ?");
|
||||
$stmt->execute([$id_tentative]);
|
||||
$tentative = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
} else {
|
||||
// Reprendre la tentative existante
|
||||
$id_tentative = $tentative['id_tentative'];
|
||||
}
|
||||
|
||||
// Calculer temps restant
|
||||
@ -589,6 +593,11 @@ $reponses_sauvegardees = json_decode($tentative['reponses_json'] ?? '{}', true)
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<!-- Chatbot IA Styles -->
|
||||
<link rel="stylesheet" href="assets/css/chatbot.css">
|
||||
|
||||
<!-- KaTeX pour le rendu mathématique -->
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
|
||||
</head>
|
||||
<body>
|
||||
<?php if ($apercu_mode): ?>
|
||||
@ -619,8 +628,7 @@ $reponses_sauvegardees = json_decode($tentative['reponses_json'] ?? '{}', true)
|
||||
<input type="hidden" name="id_evaluation" value="<?= $id_evaluation ?>">
|
||||
|
||||
<?php foreach ($questions as $index => $q): ?>
|
||||
<div class="question-card" data-question="<?= $index + 1 ?>" data-id="<?= $q['id_question'] ?>">
|
||||
<div class="question-header">
|
||||
<div class="question-card" data-question="<?= $index + 1 ?>" data-id="<?= $q['id_question'] ?>" data-question-id="<?= $q['id_question'] ?>"> <div class="question-header">
|
||||
<div class="question-number">Question <?= $index + 1 ?> / <?= count($questions) ?></div>
|
||||
<div class="question-meta">
|
||||
<span class="badge badge-points"><?= $q['points'] ?> pts</span>
|
||||
@ -965,5 +973,83 @@ $reponses_sauvegardees = json_decode($tentative['reponses_json'] ?? '{}', true)
|
||||
|
||||
window.addEventListener('beforeunload', handleBeforeUnload);
|
||||
</script>
|
||||
<!-- Chatbot IA Widget -->
|
||||
<div class="chat-bubble">
|
||||
<button class="btn-chat" id="btn-open-chat">
|
||||
💬 Besoin d'aide ? <span class="help-badge"><span id="help-remaining">3</span>/3</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="modal-chat">
|
||||
<div class="chat-container">
|
||||
<div class="chat-header">
|
||||
<h3>🤖 Assistant Mathématiques</h3>
|
||||
<button class="btn-close-chat" id="btn-close-chat">×</button>
|
||||
</div>
|
||||
<div class="chat-messages" id="chat-messages">
|
||||
<div class="message message-assistant">
|
||||
Bonjour ! 👋 Je suis là pour t'aider sur cette question.
|
||||
<br><br>
|
||||
Pose-moi une question et je te guiderai étape par étape, sans te donner la réponse directement. Tu as droit à <strong>3 aides</strong> par question.
|
||||
</div>
|
||||
</div>
|
||||
<div class="chat-input-zone">
|
||||
<textarea id="chat-input" placeholder="Pose ta question ici..." rows="3"></textarea>
|
||||
<button id="btn-send">📤 Envoyer</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- KaTeX JS -->
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
|
||||
|
||||
<!-- Chatbot IA Scripts -->
|
||||
<script src="assets/js/chatbot.js"></script>
|
||||
<script>
|
||||
// Variables globales pour le chatbot
|
||||
const tentativeId = <?= $id_tentative ?? 'null' ?>;
|
||||
const questionsIds = <?= json_encode(array_column($questions ?? [], 'id_question')) ?>;
|
||||
|
||||
console.log('Init chatbot - tentativeId:', tentativeId);
|
||||
console.log('Questions disponibles:', questionsIds);
|
||||
|
||||
// Initialiser le chatbot
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (tentativeId && questionsIds.length > 0) {
|
||||
try {
|
||||
window.chatbot = new ChatbotIA(tentativeId);
|
||||
|
||||
// Fonction pour obtenir la question actuelle
|
||||
window.chatbot.getCurrentQuestionId = function() {
|
||||
// Chercher l'input radio/checkbox sélectionné ou le dernier input
|
||||
const inputs = document.querySelectorAll('input[name^="reponse_"]');
|
||||
if (inputs.length > 0) {
|
||||
// Prendre la première question visible
|
||||
for (let input of inputs) {
|
||||
const match = input.name.match(/reponse_(\d+)/);
|
||||
if (match) {
|
||||
const qId = parseInt(match[1]);
|
||||
console.log('Question actuelle détectée:', qId);
|
||||
return qId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback : première question
|
||||
console.log('Fallback: première question');
|
||||
return questionsIds[0];
|
||||
};
|
||||
|
||||
console.log('✅ Chatbot initialisé avec succès');
|
||||
} catch (error) {
|
||||
console.error('❌ Erreur initialisation chatbot:', error);
|
||||
}
|
||||
} else {
|
||||
console.warn('⚠️ Chatbot non initialisé:', {tentativeId, questionsCount: questionsIds.length});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
136
sql/chatbot_api_management.sql
Normal file
136
sql/chatbot_api_management.sql
Normal file
@ -0,0 +1,136 @@
|
||||
-- ============================================
|
||||
-- WebVal - Gestion API Chatbot
|
||||
-- Tables pour la gestion des clés API et modèles
|
||||
-- Date: 2026-01-04
|
||||
-- ============================================
|
||||
|
||||
-- Table des clés API des enseignants
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
id_enseignant INT NOT NULL,
|
||||
provider ENUM('gemini', 'mistral', 'openai', 'anthropic', 'ollama') NOT NULL,
|
||||
api_key_encrypted TEXT, -- Clé chiffrée avec AES-256-CBC
|
||||
model_default VARCHAR(100), -- Modèle par défaut (ex: 'gemini-2.0-flash-exp')
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
quota_max INT DEFAULT NULL, -- Limite mensuelle optionnelle
|
||||
quota_used INT DEFAULT 0,
|
||||
quota_reset_date DATE, -- Date de reset du quota
|
||||
last_used TIMESTAMP NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (id_enseignant) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
|
||||
UNIQUE KEY unique_provider (id_enseignant, provider),
|
||||
INDEX idx_enseignant (id_enseignant),
|
||||
INDEX idx_active (is_active)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Table des modèles disponibles (catalogue)
|
||||
CREATE TABLE IF NOT EXISTS available_models (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
provider VARCHAR(50) NOT NULL,
|
||||
model_id VARCHAR(100) NOT NULL, -- ID technique du modèle
|
||||
display_name VARCHAR(150) NOT NULL, -- Nom affiché
|
||||
description TEXT,
|
||||
context_length INT DEFAULT 4096, -- Taille contexte en tokens
|
||||
is_free BOOLEAN DEFAULT FALSE,
|
||||
cost_per_1m_tokens DECIMAL(10,4) DEFAULT NULL, -- Coût par million de tokens
|
||||
recommended BOOLEAN DEFAULT FALSE,
|
||||
speed_rating TINYINT DEFAULT 3, -- 1=lent, 5=très rapide
|
||||
quality_rating TINYINT DEFAULT 3, -- 1=basique, 5=excellent
|
||||
active BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY unique_model (provider, model_id),
|
||||
INDEX idx_provider (provider),
|
||||
INDEX idx_recommended (recommended),
|
||||
INDEX idx_active (active)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Table de configuration chatbot par évaluation
|
||||
CREATE TABLE IF NOT EXISTS chatbot_eval_config (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
id_evaluation INT NOT NULL,
|
||||
id_enseignant INT NOT NULL,
|
||||
provider_default VARCHAR(50) DEFAULT 'ollama',
|
||||
model_default VARCHAR(100) DEFAULT 'ministral-3:3b',
|
||||
allow_student_override BOOLEAN DEFAULT FALSE, -- L'élève peut-il choisir ?
|
||||
max_messages_per_question INT DEFAULT 3,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (id_evaluation) REFERENCES evaluations(id_evaluation) ON DELETE CASCADE,
|
||||
FOREIGN KEY (id_enseignant) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
|
||||
UNIQUE KEY unique_eval (id_evaluation),
|
||||
INDEX idx_enseignant (id_enseignant)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Table de configuration par élève (override)
|
||||
CREATE TABLE IF NOT EXISTS chatbot_student_config (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
id_evaluation INT NOT NULL,
|
||||
id_eleve INT NOT NULL,
|
||||
provider_override VARCHAR(50),
|
||||
model_override VARCHAR(100),
|
||||
created_by INT NOT NULL, -- ID enseignant qui a fait l'override
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (id_evaluation) REFERENCES evaluations(id_evaluation) ON DELETE CASCADE,
|
||||
FOREIGN KEY (id_eleve) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
|
||||
FOREIGN KEY (created_by) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
|
||||
UNIQUE KEY unique_student_eval (id_evaluation, id_eleve),
|
||||
INDEX idx_evaluation (id_evaluation),
|
||||
INDEX idx_eleve (id_eleve)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Pré-remplir les modèles disponibles
|
||||
INSERT INTO available_models
|
||||
(provider, model_id, display_name, description, context_length, is_free, cost_per_1m_tokens, recommended, speed_rating, quality_rating)
|
||||
VALUES
|
||||
-- Gemini (Google)
|
||||
('gemini', 'gemini-2.0-flash-exp', 'Gemini 2.0 Flash (Expérimental)', 'Modèle ultra-rapide de Google, gratuit avec quotas généreux', 1000000, TRUE, 0, TRUE, 5, 4),
|
||||
('gemini', 'gemini-1.5-flash', 'Gemini 1.5 Flash', 'Modèle rapide et équilibré', 1000000, TRUE, 0, FALSE, 4, 4),
|
||||
('gemini', 'gemini-1.5-pro', 'Gemini 1.5 Pro', 'Modèle le plus puissant de Google', 2000000, FALSE, 1.25, FALSE, 3, 5),
|
||||
|
||||
-- Mistral
|
||||
('mistral', 'mistral-small-latest', 'Mistral Small', 'Modèle compact et rapide', 32000, FALSE, 0.20, FALSE, 5, 3),
|
||||
('mistral', 'ministral-3b-latest', 'Ministral 3B', 'Petit modèle efficace pour le raisonnement', 128000, FALSE, 0.04, TRUE, 5, 3),
|
||||
('mistral', 'ministral-8b-latest', 'Ministral 8B', 'Meilleur équilibre qualité/vitesse', 128000, FALSE, 0.10, TRUE, 4, 4),
|
||||
('mistral', 'mistral-large-latest', 'Mistral Large', 'Modèle le plus puissant de Mistral', 128000, FALSE, 2.00, FALSE, 3, 5),
|
||||
|
||||
-- OpenAI
|
||||
('openai', 'gpt-4o-mini', 'GPT-4o Mini', 'Petit modèle rapide et économique', 128000, FALSE, 0.15, TRUE, 5, 4),
|
||||
('openai', 'gpt-4o', 'GPT-4o', 'Modèle multimodal puissant', 128000, FALSE, 2.50, FALSE, 4, 5),
|
||||
('openai', 'gpt-4-turbo', 'GPT-4 Turbo', 'Modèle GPT-4 optimisé', 128000, FALSE, 10.00, FALSE, 3, 5),
|
||||
|
||||
-- Ollama (local)
|
||||
('ollama', 'ministral-3:3b', 'Ministral 3B (Local)', 'Modèle local rapide', 128000, TRUE, 0, TRUE, 4, 3),
|
||||
('ollama', 'qwen2-math:1.5b', 'Qwen2 Math 1.5B (Local)', 'Spécialisé en mathématiques', 32000, TRUE, 0, FALSE, 5, 3),
|
||||
('ollama', 'llama3.2:3b', 'Llama 3.2 3B (Local)', 'Modèle généraliste compact', 128000, TRUE, 0, FALSE, 3, 4);
|
||||
|
||||
-- Ajouter colonne provider à la table chat_conversations pour tracking
|
||||
ALTER TABLE chat_conversations
|
||||
ADD COLUMN IF NOT EXISTS provider VARCHAR(50) DEFAULT 'ollama',
|
||||
ADD COLUMN IF NOT EXISTS model_used VARCHAR(100) DEFAULT 'ministral-3:3b',
|
||||
ADD COLUMN IF NOT EXISTS api_response_time_ms INT DEFAULT NULL,
|
||||
ADD INDEX idx_provider (provider);
|
||||
|
||||
-- Ajouter colonne provider à la table chat_messages pour analytics
|
||||
ALTER TABLE chat_messages
|
||||
ADD COLUMN IF NOT EXISTS api_cost DECIMAL(10,6) DEFAULT 0.000000;
|
||||
|
||||
-- Vue pour les stats d'utilisation enseignant
|
||||
CREATE OR REPLACE VIEW v_chatbot_usage_stats AS
|
||||
SELECT
|
||||
cc.id_enseignant,
|
||||
cc.provider,
|
||||
cc.model_used,
|
||||
COUNT(DISTINCT cc.id_conversation) as total_conversations,
|
||||
COUNT(cm.id) as total_messages,
|
||||
AVG(cc.api_response_time_ms) as avg_response_time_ms,
|
||||
SUM(cm.api_cost) as total_cost,
|
||||
DATE_FORMAT(cc.date_debut, '%Y-%m') as month
|
||||
FROM chat_conversations cc
|
||||
LEFT JOIN chat_messages cm ON cc.id_conversation = cm.id_conversation
|
||||
GROUP BY cc.id_enseignant, cc.provider, cc.model_used, month;
|
||||
|
||||
-- ============================================
|
||||
-- FIN DU SCRIPT
|
||||
-- ============================================
|
||||
36
sql/chatbot_default_provider.sql
Normal file
36
sql/chatbot_default_provider.sql
Normal file
@ -0,0 +1,36 @@
|
||||
-- ============================================
|
||||
-- WebVal - Configuration provider par défaut
|
||||
-- Table pour stocker le choix de l'enseignant
|
||||
-- ============================================
|
||||
|
||||
-- Table de configuration par défaut par enseignant
|
||||
CREATE TABLE IF NOT EXISTS chatbot_default_provider (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
id_enseignant INT NOT NULL,
|
||||
provider VARCHAR(50) NOT NULL,
|
||||
model_default VARCHAR(100) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (id_enseignant) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
|
||||
UNIQUE KEY unique_enseignant (id_enseignant)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- Initialiser Ollama comme défaut pour les enseignants existants
|
||||
INSERT IGNORE INTO chatbot_default_provider (id_enseignant, provider, model_default)
|
||||
SELECT DISTINCT id_utilisateur, 'ollama', 'ministral-3:3b'
|
||||
FROM utilisateurs
|
||||
WHERE id_type = 1; -- Type enseignant
|
||||
|
||||
-- Mettre à jour pour ceux qui ont déjà une clé cloud active
|
||||
UPDATE chatbot_default_provider cdp
|
||||
JOIN (
|
||||
SELECT id_enseignant, provider, model_default
|
||||
FROM api_keys
|
||||
WHERE is_active = 1
|
||||
ORDER BY created_at ASC
|
||||
LIMIT 1
|
||||
) ak ON cdp.id_enseignant = ak.id_enseignant
|
||||
SET cdp.provider = ak.provider,
|
||||
cdp.model_default = ak.model_default;
|
||||
|
||||
SELECT '✅ Table chatbot_default_provider créée et initialisée' as Status;
|
||||
44
sql/update_all_models.sql
Normal file
44
sql/update_all_models.sql
Normal file
@ -0,0 +1,44 @@
|
||||
-- ============================================
|
||||
-- WebVal - Mise à jour complète des modèles
|
||||
-- Gemini, Mistral, OpenAI, Ollama
|
||||
-- ============================================
|
||||
|
||||
-- Supprimer les anciens modèles
|
||||
DELETE FROM available_models WHERE provider IN ('gemini', 'mistral', 'openai');
|
||||
|
||||
-- GEMINI (Google) - Modèles gratuits et puissants
|
||||
INSERT INTO available_models
|
||||
(provider, model_id, display_name, description, context_length, is_free, cost_per_1m_tokens, recommended, speed_rating, quality_rating)
|
||||
VALUES
|
||||
('gemini', 'gemini-2.5-flash', 'Gemini 2.5 Flash', 'Dernier modèle rapide de Google (juin 2025)', 1048576, TRUE, 0, TRUE, 5, 5),
|
||||
('gemini', 'gemini-2.0-flash', 'Gemini 2.0 Flash', 'Modèle rapide et polyvalent', 1048576, TRUE, 0, FALSE, 5, 4),
|
||||
('gemini', 'gemini-2.5-pro', 'Gemini 2.5 Pro', 'Modèle le plus puissant (juin 2025)', 1048576, FALSE, 1.25, FALSE, 3, 5);
|
||||
|
||||
-- MISTRAL - Modèles français performants
|
||||
INSERT INTO available_models
|
||||
(provider, model_id, display_name, description, context_length, is_free, cost_per_1m_tokens, recommended, speed_rating, quality_rating)
|
||||
VALUES
|
||||
('mistral', 'mistral-small-latest', 'Mistral Small', 'Modèle compact et rapide', 32000, FALSE, 0.20, FALSE, 5, 3),
|
||||
('mistral', 'ministral-3b-latest', 'Ministral 3B', 'Petit modèle efficace pour le raisonnement', 128000, FALSE, 0.04, TRUE, 5, 3),
|
||||
('mistral', 'ministral-8b-latest', 'Ministral 8B', 'Meilleur équilibre qualité/vitesse', 128000, FALSE, 0.10, TRUE, 4, 4),
|
||||
('mistral', 'mistral-large-latest', 'Mistral Large', 'Modèle le plus puissant de Mistral', 128000, FALSE, 2.00, FALSE, 3, 5);
|
||||
|
||||
-- OPENAI - Modèles de référence
|
||||
INSERT INTO available_models
|
||||
(provider, model_id, display_name, description, context_length, is_free, cost_per_1m_tokens, recommended, speed_rating, quality_rating)
|
||||
VALUES
|
||||
('openai', 'gpt-4o-mini', 'GPT-4o Mini', 'Petit modèle rapide et économique', 128000, FALSE, 0.15, TRUE, 5, 4),
|
||||
('openai', 'gpt-4o', 'GPT-4o', 'Modèle multimodal puissant', 128000, FALSE, 2.50, FALSE, 4, 5),
|
||||
('openai', 'gpt-4-turbo', 'GPT-4 Turbo', 'Modèle GPT-4 optimisé', 128000, FALSE, 10.00, FALSE, 3, 5);
|
||||
|
||||
-- Vérification
|
||||
SELECT
|
||||
provider,
|
||||
COUNT(*) as nb_modeles,
|
||||
SUM(CASE WHEN recommended = 1 THEN 1 ELSE 0 END) as nb_recommandes
|
||||
FROM available_models
|
||||
WHERE provider IN ('gemini', 'mistral', 'openai', 'ollama')
|
||||
GROUP BY provider
|
||||
ORDER BY provider;
|
||||
|
||||
SELECT '✅ Modèles mis à jour : Gemini (3), Mistral (4), OpenAI (3), Ollama (3)' as Status;
|
||||
109
sql/update_chat_tables.sql
Normal file
109
sql/update_chat_tables.sql
Normal file
@ -0,0 +1,109 @@
|
||||
-- ============================================
|
||||
-- WebVal - Mise à jour chat_conversations
|
||||
-- Ajout colonnes pour tracking API (sécurisé)
|
||||
-- ============================================
|
||||
|
||||
-- Désactiver les erreurs temporairement
|
||||
SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0;
|
||||
|
||||
-- Ajouter colonnes une par une (ignore si existe déjà)
|
||||
SET @s = (SELECT IF(
|
||||
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'chat_conversations'
|
||||
AND column_name = 'provider') > 0,
|
||||
'SELECT ''Column provider already exists''',
|
||||
'ALTER TABLE chat_conversations ADD COLUMN provider VARCHAR(50) DEFAULT ''ollama'''
|
||||
));
|
||||
PREPARE stmt FROM @s;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @s = (SELECT IF(
|
||||
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'chat_conversations'
|
||||
AND column_name = 'model_used') > 0,
|
||||
'SELECT ''Column model_used already exists''',
|
||||
'ALTER TABLE chat_conversations ADD COLUMN model_used VARCHAR(100) DEFAULT ''ministral-3:3b'''
|
||||
));
|
||||
PREPARE stmt FROM @s;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @s = (SELECT IF(
|
||||
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'chat_conversations'
|
||||
AND column_name = 'api_response_time_ms') > 0,
|
||||
'SELECT ''Column api_response_time_ms already exists''',
|
||||
'ALTER TABLE chat_conversations ADD COLUMN api_response_time_ms INT DEFAULT NULL'
|
||||
));
|
||||
PREPARE stmt FROM @s;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
SET @s = (SELECT IF(
|
||||
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'chat_conversations'
|
||||
AND column_name = 'id_enseignant') > 0,
|
||||
'SELECT ''Column id_enseignant already exists''',
|
||||
'ALTER TABLE chat_conversations ADD COLUMN id_enseignant INT DEFAULT NULL'
|
||||
));
|
||||
PREPARE stmt FROM @s;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- Index
|
||||
SET @s = (SELECT IF(
|
||||
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'chat_conversations'
|
||||
AND index_name = 'idx_provider') > 0,
|
||||
'SELECT ''Index idx_provider already exists''',
|
||||
'ALTER TABLE chat_conversations ADD INDEX idx_provider (provider)'
|
||||
));
|
||||
PREPARE stmt FROM @s;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- Foreign key (plus complexe, on teste avec SHOW CREATE TABLE)
|
||||
SET @fk_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'chat_conversations'
|
||||
AND referenced_table_name = 'utilisateurs'
|
||||
AND column_name = 'id_enseignant');
|
||||
|
||||
SET @s = IF(@fk_exists > 0,
|
||||
'SELECT ''Foreign key already exists''',
|
||||
'ALTER TABLE chat_conversations ADD FOREIGN KEY (id_enseignant) REFERENCES utilisateurs(id_utilisateur) ON DELETE SET NULL'
|
||||
);
|
||||
PREPARE stmt FROM @s;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- Colonne api_cost dans chat_messages
|
||||
SET @s = (SELECT IF(
|
||||
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'chat_messages'
|
||||
AND column_name = 'api_cost') > 0,
|
||||
'SELECT ''Column api_cost already exists''',
|
||||
'ALTER TABLE chat_messages ADD COLUMN api_cost DECIMAL(10,6) DEFAULT 0.000000'
|
||||
));
|
||||
PREPARE stmt FROM @s;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- Restaurer les notes SQL
|
||||
SET SQL_NOTES=@OLD_SQL_NOTES;
|
||||
|
||||
-- Remplir id_enseignant rétroactivement
|
||||
UPDATE chat_conversations cc
|
||||
JOIN tentatives_eleves te ON cc.id_tentative = te.id_tentative
|
||||
JOIN evaluations e ON te.id_evaluation = e.id_evaluation
|
||||
SET cc.id_enseignant = e.id_enseignant
|
||||
WHERE cc.id_enseignant IS NULL;
|
||||
|
||||
SELECT '✅ Colonnes ajoutées avec succès' as Status;
|
||||
Reference in New Issue
Block a user