feat(corrections): Sprint 3.6a — nouveaux prompts + taxonomie erreurs + génération parallèle
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
df7ef2cc31
commit
63bc43ddcf
14 changed files with 2319 additions and 282 deletions
|
|
@ -1,150 +1,425 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { CorrectionRapport } from '../deepseek'
|
||||
|
||||
// ── Fixture correction — Sprint 3.6a, forme nouvelle ──────────────────
|
||||
|
||||
const VALID_RAPPORT = {
|
||||
score: 14.5,
|
||||
nclc: 8,
|
||||
feedback_court:
|
||||
'Bonne production générale. Quelques points à améliorer sur le lexique et la morphosyntaxe.',
|
||||
score: 14,
|
||||
nclc: 9,
|
||||
revelation: {
|
||||
croyance: 'Le candidat pense avoir bien respecté la consigne.',
|
||||
realite: 'Certains éléments de la consigne sont ignorés.',
|
||||
consequence: 'Perte d\'un point en adéquation à la tâche.',
|
||||
},
|
||||
diagnostic: 'Frein principal : pauvreté du lexique et connecteurs répétés.',
|
||||
criteres: [
|
||||
{ nom: 'Coherence et cohesion', score: 4, commentaire: 'Bonne organisation.' },
|
||||
{ nom: 'Lexique', score: 3, commentaire: 'Vocabulaire correct mais limite.' },
|
||||
{ nom: 'Morphosyntaxe', score: 4, commentaire: 'Structures variees.' },
|
||||
{ nom: 'Pertinence', score: 3.5, commentaire: 'Adequation partielle a la consigne.' },
|
||||
{
|
||||
nom: 'Adéquation à la tâche et au registre',
|
||||
score: 4,
|
||||
commentaire: 'Tâche globalement respectée.',
|
||||
exemple: 'Je vous écris pour demander',
|
||||
suggestion: 'Je sollicite votre attention afin de demander',
|
||||
astuce: 'Varier les formules d\'appel.',
|
||||
},
|
||||
{
|
||||
nom: 'Cohérence et cohésion du discours',
|
||||
score: 3,
|
||||
commentaire: 'Connecteurs peu variés.',
|
||||
exemple: 'Et aussi, et puis',
|
||||
suggestion: 'De plus, par ailleurs',
|
||||
astuce: 'Bannir "et" comme connecteur unique.',
|
||||
},
|
||||
{
|
||||
nom: 'Compétence lexicale',
|
||||
score: 3,
|
||||
commentaire: 'Vocabulaire basique.',
|
||||
exemple: 'faire un travail',
|
||||
suggestion: 'effectuer une mission',
|
||||
astuce: 'Substituer "faire" par un verbe précis.',
|
||||
},
|
||||
{
|
||||
nom: 'Compétence grammaticale',
|
||||
score: 4,
|
||||
commentaire: 'Accords globalement corrects.',
|
||||
exemple: 'les enfants joue',
|
||||
suggestion: 'les enfants jouent',
|
||||
astuce: 'Vérifier la terminaison verbale au pluriel.',
|
||||
},
|
||||
],
|
||||
erreurs: ['Connecteurs logiques insuffisants', 'Quelques fautes accord'],
|
||||
modele: 'Texte modele corrige ici.',
|
||||
idees: ['Developper argumentation', 'Ajouter des exemples concrets'],
|
||||
exercices: ['Exercice connecteurs logiques', 'Exercice accords sujet-verbe'],
|
||||
}
|
||||
conseil_nclc: {
|
||||
nclc_cible: 'NCLC 9',
|
||||
ecart: 'objectif atteint',
|
||||
action_prioritaire: 'Enrichir le lexique par thématique.',
|
||||
},
|
||||
erreurs_codes: [
|
||||
{ code: 'accord_sujet_verbe', critere: 'competence_grammaticale', description: null },
|
||||
{ code: 'connecteurs_repetes', critere: 'coherence_cohesion', description: null },
|
||||
{ code: 'vocabulaire_basique', critere: 'competence_lexicale', description: null },
|
||||
],
|
||||
} satisfies Omit<CorrectionRapport, 'nclc_cible'> & { erreurs_codes: unknown[] }
|
||||
|
||||
function mockFetchSuccess(rapport: unknown) {
|
||||
function mockFetchSuccess(payload: unknown) {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
choices: [{ message: { content: JSON.stringify(rapport) } }],
|
||||
}),
|
||||
})
|
||||
json: async () => ({ choices: [{ message: { content: JSON.stringify(payload) } }] }),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
describe('deepseek.correctEE', () => {
|
||||
// ── correctEE (nouvelle signature) ──────────────────────────────────────
|
||||
|
||||
describe('deepseek.correctEE — Sprint 3.6a', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('retourne un rapport avec la bonne structure', async () => {
|
||||
it('retourne un rapport avec la nouvelle structure (revelation, diagnostic, criteres, conseil_nclc, erreurs_codes)', async () => {
|
||||
mockFetchSuccess(VALID_RAPPORT)
|
||||
const { correctEE } = await import('../deepseek')
|
||||
|
||||
const rapport = await correctEE('Mon texte de test', 'EE_T1')
|
||||
const rapport = await correctEE({
|
||||
tache: 'EE_T1',
|
||||
contenu: 'Mon texte de test',
|
||||
sujet: 'Écrivez un message',
|
||||
nclcCible: 9,
|
||||
})
|
||||
|
||||
expect(rapport).toHaveProperty('score')
|
||||
expect(rapport).toHaveProperty('nclc')
|
||||
expect(rapport).toHaveProperty('feedback_court')
|
||||
expect(rapport).toHaveProperty('criteres')
|
||||
expect(rapport).toHaveProperty('erreurs')
|
||||
expect(rapport).toHaveProperty('modele')
|
||||
expect(rapport).toHaveProperty('idees')
|
||||
expect(rapport).toHaveProperty('exercices')
|
||||
expect(rapport.score).toBe(14)
|
||||
expect(rapport.nclc).toBe(9)
|
||||
expect(rapport.nclc_cible).toBe(9)
|
||||
expect(rapport.revelation).toMatchObject({
|
||||
croyance: expect.any(String),
|
||||
realite: expect.any(String),
|
||||
consequence: expect.any(String),
|
||||
})
|
||||
expect(rapport.diagnostic).toBeTypeOf('string')
|
||||
expect(rapport.criteres).toHaveLength(4)
|
||||
expect(typeof rapport.feedback_court).toBe('string')
|
||||
expect(rapport.feedback_court.length).toBeGreaterThan(0)
|
||||
expect(Array.isArray(rapport.erreurs)).toBe(true)
|
||||
expect(Array.isArray(rapport.idees)).toBe(true)
|
||||
expect(Array.isArray(rapport.exercices)).toBe(true)
|
||||
expect(rapport.conseil_nclc.nclc_cible).toBe('NCLC 9')
|
||||
expect(rapport.erreurs_codes.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('score est entre 0 et 20', async () => {
|
||||
mockFetchSuccess(VALID_RAPPORT)
|
||||
it('nclc_cible=10 est propagé dans le rapport', async () => {
|
||||
mockFetchSuccess({ ...VALID_RAPPORT, score: 18 })
|
||||
const { correctEE } = await import('../deepseek')
|
||||
|
||||
const rapport = await correctEE('Mon texte', 'EE_T1')
|
||||
const rapport = await correctEE({
|
||||
tache: 'EE_T1',
|
||||
contenu: 'Texte',
|
||||
sujet: null,
|
||||
nclcCible: 10,
|
||||
})
|
||||
|
||||
expect(rapport.score).toBeGreaterThanOrEqual(0)
|
||||
expect(rapport.score).toBeLessThanOrEqual(20)
|
||||
expect(rapport.nclc_cible).toBe(10)
|
||||
})
|
||||
|
||||
it('nclc est entre 4 et 12', async () => {
|
||||
mockFetchSuccess(VALID_RAPPORT)
|
||||
const { correctEE } = await import('../deepseek')
|
||||
|
||||
const rapport = await correctEE('Mon texte', 'EE_T2')
|
||||
|
||||
expect(rapport.nclc).toBeGreaterThanOrEqual(4)
|
||||
expect(rapport.nclc).toBeLessThanOrEqual(12)
|
||||
})
|
||||
|
||||
it('lance une erreur si score hors bornes', async () => {
|
||||
it('score hors bornes → throw', async () => {
|
||||
mockFetchSuccess({ ...VALID_RAPPORT, score: 25 })
|
||||
const { correctEE } = await import('../deepseek')
|
||||
|
||||
await expect(correctEE('Texte', 'EE_T1')).rejects.toThrow('Score invalide')
|
||||
await expect(
|
||||
correctEE({ tache: 'EE_T1', contenu: 'T', sujet: null, nclcCible: 9 }),
|
||||
).rejects.toThrow('Score invalide')
|
||||
})
|
||||
|
||||
it('lance une erreur si nclc hors bornes', async () => {
|
||||
it('nclc hors bornes → throw', async () => {
|
||||
mockFetchSuccess({ ...VALID_RAPPORT, nclc: 2 })
|
||||
const { correctEE } = await import('../deepseek')
|
||||
|
||||
await expect(correctEE('Texte', 'EE_T1')).rejects.toThrow('NCLC invalide')
|
||||
await expect(
|
||||
correctEE({ tache: 'EE_T1', contenu: 'T', sujet: null, nclcCible: 9 }),
|
||||
).rejects.toThrow('NCLC invalide')
|
||||
})
|
||||
|
||||
it('lance une erreur si feedback_court est absent ou vide', async () => {
|
||||
// Cas 1 : champ absent (JSON.stringify drop les undefined)
|
||||
mockFetchSuccess({ ...VALID_RAPPORT, feedback_court: undefined })
|
||||
it('revelation absente → throw', async () => {
|
||||
const bad = { ...VALID_RAPPORT, revelation: undefined }
|
||||
mockFetchSuccess(bad)
|
||||
const { correctEE } = await import('../deepseek')
|
||||
await expect(correctEE('Texte', 'EE_T1')).rejects.toThrow('feedback_court invalide')
|
||||
|
||||
// Cas 2 : chaîne vide (whitespace uniquement)
|
||||
mockFetchSuccess({ ...VALID_RAPPORT, feedback_court: ' ' })
|
||||
await expect(correctEE('Texte', 'EE_T1')).rejects.toThrow('feedback_court invalide')
|
||||
await expect(
|
||||
correctEE({ tache: 'EE_T1', contenu: 'T', sujet: null, nclcCible: 9 }),
|
||||
).rejects.toThrow('revelation invalide')
|
||||
})
|
||||
|
||||
it('erreur HTTP depuis DeepSeek API', async () => {
|
||||
it('diagnostic vide → throw', async () => {
|
||||
mockFetchSuccess({ ...VALID_RAPPORT, diagnostic: ' ' })
|
||||
const { correctEE } = await import('../deepseek')
|
||||
await expect(
|
||||
correctEE({ tache: 'EE_T1', contenu: 'T', sujet: null, nclcCible: 9 }),
|
||||
).rejects.toThrow('diagnostic invalide')
|
||||
})
|
||||
|
||||
it('criteres doit avoir exactement 4 entrées', async () => {
|
||||
mockFetchSuccess({ ...VALID_RAPPORT, criteres: VALID_RAPPORT.criteres.slice(0, 3) })
|
||||
const { correctEE } = await import('../deepseek')
|
||||
await expect(
|
||||
correctEE({ tache: 'EE_T1', contenu: 'T', sujet: null, nclcCible: 9 }),
|
||||
).rejects.toThrow('criteres invalide')
|
||||
})
|
||||
|
||||
it('erreurs_codes : codes hors taxonomie sont filtrés', async () => {
|
||||
const bad = {
|
||||
...VALID_RAPPORT,
|
||||
erreurs_codes: [
|
||||
{ code: 'code_inexistant_xyz', critere: 'competence_grammaticale', description: null },
|
||||
{ code: 'accord_sujet_verbe', critere: 'competence_grammaticale', description: null },
|
||||
],
|
||||
}
|
||||
mockFetchSuccess(bad)
|
||||
const { correctEE } = await import('../deepseek')
|
||||
const rapport = await correctEE({
|
||||
tache: 'EE_T1',
|
||||
contenu: 'T',
|
||||
sujet: null,
|
||||
nclcCible: 9,
|
||||
})
|
||||
expect(rapport.erreurs_codes).toHaveLength(1)
|
||||
expect(rapport.erreurs_codes[0]?.code).toBe('accord_sujet_verbe')
|
||||
})
|
||||
|
||||
it('erreurs_codes : code "autre" sans description est rejeté', async () => {
|
||||
const bad = {
|
||||
...VALID_RAPPORT,
|
||||
erreurs_codes: [
|
||||
{ code: 'autre', critere: 'coherence_cohesion', description: null },
|
||||
{ code: 'autre', critere: 'coherence_cohesion', description: 'erreur spécifique' },
|
||||
],
|
||||
}
|
||||
mockFetchSuccess(bad)
|
||||
const { correctEE } = await import('../deepseek')
|
||||
const rapport = await correctEE({
|
||||
tache: 'EE_T1',
|
||||
contenu: 'T',
|
||||
sujet: null,
|
||||
nclcCible: 9,
|
||||
})
|
||||
expect(rapport.erreurs_codes).toHaveLength(1)
|
||||
expect(rapport.erreurs_codes[0]).toMatchObject({
|
||||
code: 'autre',
|
||||
description: 'erreur spécifique',
|
||||
})
|
||||
})
|
||||
|
||||
it('critère inconnu → entrée filtrée', async () => {
|
||||
const bad = {
|
||||
...VALID_RAPPORT,
|
||||
erreurs_codes: [
|
||||
{ code: 'accord_sujet_verbe', critere: 'critere_inventé', description: null },
|
||||
],
|
||||
}
|
||||
mockFetchSuccess(bad)
|
||||
const { correctEE } = await import('../deepseek')
|
||||
const rapport = await correctEE({
|
||||
tache: 'EE_T1',
|
||||
contenu: 'T',
|
||||
sujet: null,
|
||||
nclcCible: 9,
|
||||
})
|
||||
expect(rapport.erreurs_codes).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('erreur HTTP DeepSeek → throw', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
statusText: 'Internal Server Error',
|
||||
})
|
||||
vi.fn().mockResolvedValue({ ok: false, status: 500, statusText: 'Internal' }),
|
||||
)
|
||||
const { correctEE } = await import('../deepseek')
|
||||
|
||||
await expect(correctEE('Texte', 'EE_T1')).rejects.toThrow('DeepSeek API error')
|
||||
await expect(
|
||||
correctEE({ tache: 'EE_T1', contenu: 'T', sujet: null, nclcCible: 9 }),
|
||||
).rejects.toThrow('DeepSeek API error')
|
||||
})
|
||||
|
||||
it('erreur si reponse vide', async () => {
|
||||
it('JSON invalide → throw', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ choices: [{ message: { content: '' } }] }),
|
||||
})
|
||||
json: async () => ({ choices: [{ message: { content: 'pas du json' } }] }),
|
||||
}),
|
||||
)
|
||||
const { correctEE } = await import('../deepseek')
|
||||
|
||||
await expect(correctEE('Texte', 'EE_T1')).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('lance une erreur si DeepSeek retourne du JSON invalide', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
choices: [{ message: { content: 'ceci nest pas du json' } }],
|
||||
}),
|
||||
})
|
||||
)
|
||||
const { correctEE } = await import('../deepseek')
|
||||
|
||||
await expect(correctEE('Texte', 'EE_T1')).rejects.toThrow()
|
||||
await expect(
|
||||
correctEE({ tache: 'EE_T1', contenu: 'T', sujet: null, nclcCible: 9 }),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
// ── generateProductionModele — cible fixe NCLC 9 ───────────────────────
|
||||
|
||||
const VALID_MODELE = {
|
||||
production_modele_propre: 'Texte modèle réécrit. '.repeat(10).trim(),
|
||||
notes_pedagogiques: [
|
||||
{ passage: 'extrait 1', explication: 'efficace car…' },
|
||||
{ passage: 'extrait 2', explication: 'efficace car…' },
|
||||
{ passage: 'extrait 3', explication: 'efficace car…' },
|
||||
],
|
||||
transformations: [
|
||||
{ original: 'je fais', ameliore: 'j\'effectue', explication: 'plus précis' },
|
||||
],
|
||||
message: 'Vos idées sont solides, continuez.',
|
||||
}
|
||||
|
||||
describe('deepseek.generateProductionModele', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('renvoie métadonnées avec nclc_modele=9 (fixe)', async () => {
|
||||
mockFetchSuccess(VALID_MODELE)
|
||||
const { generateProductionModele } = await import('../deepseek')
|
||||
|
||||
const result = await generateProductionModele({
|
||||
tache: 'EE_T2',
|
||||
sujet: 'Un article de blog',
|
||||
texte: 'production du candidat',
|
||||
nclcObtenu: 7,
|
||||
})
|
||||
|
||||
expect(result.nclc_modele).toBe(9)
|
||||
expect(result.nclc_obtenu).toBe(7)
|
||||
expect(result.score_cible).toBe(14)
|
||||
expect(result.tcf_word_min).toBe(120)
|
||||
expect(result.tcf_word_max).toBe(150)
|
||||
})
|
||||
|
||||
it('tronque à max mots et renseigne tcf_truncated=true', async () => {
|
||||
const longText = 'mot '.repeat(200).trim() // 200 mots
|
||||
mockFetchSuccess({ ...VALID_MODELE, production_modele_propre: longText })
|
||||
const { generateProductionModele } = await import('../deepseek')
|
||||
|
||||
const result = await generateProductionModele({
|
||||
tache: 'EE_T1', // max 120
|
||||
sujet: null,
|
||||
texte: 'production',
|
||||
nclcObtenu: 8,
|
||||
})
|
||||
|
||||
expect(result.tcf_truncated).toBe(true)
|
||||
expect(result.tcf_word_count).toBe(120)
|
||||
})
|
||||
|
||||
it('supprime les annotations [NOTE: ...] de production_modele_propre', async () => {
|
||||
mockFetchSuccess({
|
||||
...VALID_MODELE,
|
||||
production_modele_propre: 'Bonjour [NOTE: salutation formelle] je vous écris.',
|
||||
})
|
||||
const { generateProductionModele } = await import('../deepseek')
|
||||
|
||||
const result = await generateProductionModele({
|
||||
tache: 'EE_T1',
|
||||
sujet: null,
|
||||
texte: 'p',
|
||||
nclcObtenu: 8,
|
||||
})
|
||||
|
||||
expect(result.production_modele_propre).not.toContain('[NOTE:')
|
||||
expect(result.production_modele_propre).toContain('Bonjour')
|
||||
})
|
||||
})
|
||||
|
||||
// ── generateExercices ───────────────────────────────────────────────────
|
||||
|
||||
describe('deepseek.generateExercices', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('renvoie une liste d\'exercices avec le format attendu', async () => {
|
||||
mockFetchSuccess({
|
||||
exercices: [
|
||||
{
|
||||
difficulte: 'facile',
|
||||
theme: 'accord_sujet_verbe',
|
||||
diagnostic: 'Erreurs d\'accord verbe-sujet.',
|
||||
consigne: 'Corrigez les accords.',
|
||||
extrait: 'les enfants joue',
|
||||
indice: 'Pluriel du sujet ?',
|
||||
correction: 'les enfants jouent',
|
||||
explication: 'Le verbe s\'accorde en nombre avec le sujet.',
|
||||
},
|
||||
{
|
||||
difficulte: 'intermediaire',
|
||||
theme: 'connecteurs_repetes',
|
||||
diagnostic: 'Même connecteur répété.',
|
||||
consigne: 'Variez les connecteurs.',
|
||||
extrait: 'Et puis et aussi',
|
||||
indice: 'Synonymes de "et" ?',
|
||||
correction: 'De plus, par ailleurs',
|
||||
explication: 'Varier lexicalement les connecteurs améliore la cohésion.',
|
||||
},
|
||||
{
|
||||
difficulte: 'difficile',
|
||||
theme: 'vocabulaire_basique',
|
||||
diagnostic: 'Verbe "faire" imprécis.',
|
||||
consigne: 'Remplacez "faire" par un verbe précis.',
|
||||
extrait: 'faire un travail',
|
||||
indice: 'Un verbe de réalisation ?',
|
||||
correction: 'effectuer une mission',
|
||||
explication: '"Effectuer" précise l\'action.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const { generateExercices } = await import('../deepseek')
|
||||
|
||||
const exercices = await generateExercices({
|
||||
tache: 'EE_T1',
|
||||
erreursCodes: VALID_RAPPORT.erreurs_codes as never,
|
||||
criteres: VALID_RAPPORT.criteres,
|
||||
})
|
||||
|
||||
expect(exercices).toHaveLength(3)
|
||||
expect(exercices[0]).toMatchObject({
|
||||
difficulte: 'facile',
|
||||
theme: 'accord_sujet_verbe',
|
||||
consigne: expect.any(String),
|
||||
correction: expect.any(String),
|
||||
})
|
||||
})
|
||||
|
||||
it('difficulte inconnue → fallback "intermediaire"', async () => {
|
||||
mockFetchSuccess({
|
||||
exercices: [
|
||||
{
|
||||
difficulte: 'epique',
|
||||
theme: 't',
|
||||
consigne: 'c',
|
||||
correction: 'r',
|
||||
},
|
||||
],
|
||||
})
|
||||
const { generateExercices } = await import('../deepseek')
|
||||
|
||||
const exercices = await generateExercices({
|
||||
tache: 'EE_T1',
|
||||
erreursCodes: [],
|
||||
criteres: [],
|
||||
})
|
||||
|
||||
expect(exercices[0]?.difficulte).toBe('intermediaire')
|
||||
})
|
||||
|
||||
it('exercices sans consigne/correction sont filtrés', async () => {
|
||||
mockFetchSuccess({
|
||||
exercices: [
|
||||
{ difficulte: 'facile', theme: 't' }, // manque consigne + correction
|
||||
{ difficulte: 'facile', theme: 't', consigne: 'c', correction: 'r' },
|
||||
],
|
||||
})
|
||||
const { generateExercices } = await import('../deepseek')
|
||||
|
||||
const exercices = await generateExercices({
|
||||
tache: 'EE_T1',
|
||||
erreursCodes: [],
|
||||
criteres: [],
|
||||
})
|
||||
|
||||
expect(exercices).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
// ── EO — inchangé par Sprint 3.6a ──────────────────────────────────────
|
||||
|
||||
const VALID_RAPPORT_EO = {
|
||||
score: 12,
|
||||
nclc: 7,
|
||||
|
|
@ -168,81 +443,59 @@ describe('deepseek.correctEO', () => {
|
|||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('retourne un rapport EO avec la bonne structure', async () => {
|
||||
it('retourne un rapport EO avec la structure V1', async () => {
|
||||
mockFetchSuccess(VALID_RAPPORT_EO)
|
||||
const { correctEO } = await import('../deepseek')
|
||||
const rapport = await correctEO('transcription', 'EO_T1')
|
||||
|
||||
const rapport = await correctEO('Ma transcription orale', 'EO_T1')
|
||||
|
||||
expect(rapport).toHaveProperty('score')
|
||||
expect(rapport).toHaveProperty('nclc')
|
||||
expect(rapport).toHaveProperty('feedback_court')
|
||||
expect(rapport).toHaveProperty('criteres')
|
||||
expect(rapport.criteres).toHaveLength(4)
|
||||
expect(rapport).toHaveProperty('erreurs')
|
||||
expect(rapport).toHaveProperty('modele')
|
||||
expect(rapport).toHaveProperty('idees')
|
||||
expect(rapport).toHaveProperty('exercices')
|
||||
expect(typeof rapport.feedback_court).toBe('string')
|
||||
expect(rapport.feedback_court.length).toBeGreaterThan(0)
|
||||
expect(rapport.criteres.find((c) => c.nom === 'Phonologie')?.score).toBe(0)
|
||||
})
|
||||
|
||||
it('phonologie est a 0', async () => {
|
||||
mockFetchSuccess(VALID_RAPPORT_EO)
|
||||
const { correctEO } = await import('../deepseek')
|
||||
|
||||
const rapport = await correctEO('Ma transcription', 'EO_T1')
|
||||
|
||||
const phonologie = rapport.criteres.find((c) => c.nom === 'Phonologie')
|
||||
expect(phonologie).toBeDefined()
|
||||
expect(phonologie!.score).toBe(0)
|
||||
})
|
||||
|
||||
it('score est entre 0 et 20', async () => {
|
||||
mockFetchSuccess(VALID_RAPPORT_EO)
|
||||
const { correctEO } = await import('../deepseek')
|
||||
|
||||
const rapport = await correctEO('Ma transcription', 'EO_T3')
|
||||
|
||||
expect(rapport.score).toBeGreaterThanOrEqual(0)
|
||||
expect(rapport.score).toBeLessThanOrEqual(20)
|
||||
})
|
||||
|
||||
it('nclc est entre 4 et 12', async () => {
|
||||
mockFetchSuccess(VALID_RAPPORT_EO)
|
||||
const { correctEO } = await import('../deepseek')
|
||||
|
||||
const rapport = await correctEO('Ma transcription', 'EO_T1')
|
||||
|
||||
expect(rapport.nclc).toBeGreaterThanOrEqual(4)
|
||||
expect(rapport.nclc).toBeLessThanOrEqual(12)
|
||||
})
|
||||
|
||||
it('lance une erreur si score hors bornes', async () => {
|
||||
it('score hors bornes → throw', async () => {
|
||||
mockFetchSuccess({ ...VALID_RAPPORT_EO, score: 25 })
|
||||
const { correctEO } = await import('../deepseek')
|
||||
|
||||
await expect(correctEO('Transcription', 'EO_T1')).rejects.toThrow('Score invalide')
|
||||
await expect(correctEO('t', 'EO_T1')).rejects.toThrow('Score invalide')
|
||||
})
|
||||
|
||||
it('lance une erreur si nclc hors bornes', async () => {
|
||||
it('nclc hors bornes → throw', async () => {
|
||||
mockFetchSuccess({ ...VALID_RAPPORT_EO, nclc: 2 })
|
||||
const { correctEO } = await import('../deepseek')
|
||||
|
||||
await expect(correctEO('Transcription', 'EO_T1')).rejects.toThrow('NCLC invalide')
|
||||
await expect(correctEO('t', 'EO_T1')).rejects.toThrow('NCLC invalide')
|
||||
})
|
||||
|
||||
it('erreur HTTP depuis DeepSeek API', async () => {
|
||||
it('HTTP error → throw', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
statusText: 'Internal Server Error',
|
||||
})
|
||||
vi.fn().mockResolvedValue({ ok: false, status: 500, statusText: 'I' }),
|
||||
)
|
||||
const { correctEO } = await import('../deepseek')
|
||||
|
||||
await expect(correctEO('Transcription', 'EO_T1')).rejects.toThrow('DeepSeek API error')
|
||||
await expect(correctEO('t', 'EO_T1')).rejects.toThrow('DeepSeek API error')
|
||||
})
|
||||
})
|
||||
|
||||
// ── Post-traitement unitaire ────────────────────────────────────────────
|
||||
|
||||
describe('deepseek — helpers de post-traitement', () => {
|
||||
it('wordCountTCF : apostrophes et tirets ne créent pas de mot', async () => {
|
||||
const { wordCountTCF } = await import('../deepseek')
|
||||
expect(wordCountTCF("c'est")).toBe(1)
|
||||
expect(wordCountTCF("aujourd'hui")).toBe(1)
|
||||
expect(wordCountTCF("c'est-à-dire")).toBe(1)
|
||||
expect(wordCountTCF('il va bien')).toBe(3)
|
||||
expect(wordCountTCF('')).toBe(0)
|
||||
})
|
||||
|
||||
it('stripModelAnnotations retire [NOTE:…]', async () => {
|
||||
const { stripModelAnnotations } = await import('../deepseek')
|
||||
expect(stripModelAnnotations('Bonjour [NOTE: formel] Madame')).toBe('Bonjour Madame')
|
||||
})
|
||||
|
||||
it('truncateToMaxWords tronque au-delà du seuil', async () => {
|
||||
const { truncateToMaxWords } = await import('../deepseek')
|
||||
const { text, truncated } = truncateToMaxWords('a b c d e f', 3)
|
||||
expect(text).toBe('a b c')
|
||||
expect(truncated).toBe(true)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,23 +1,616 @@
|
|||
/**
|
||||
* Client DeepSeek — Sprint 3.6a.
|
||||
*
|
||||
* Expose trois appels dédiés à la correction EE (entraînement / examen) :
|
||||
* 1. `correctEE` → prompt maître (rapport avec revelation, diagnostic,
|
||||
* critères détaillés, conseil_nclc, erreurs_codes)
|
||||
* 2. `generateProductionModele` → production modèle réécrite à NCLC 9 (fixe)
|
||||
* 3. `generateExercices` → 3 exercices ciblés sur les erreurs détectées
|
||||
*
|
||||
* Contrat JSON défini par docs/Prompt_maître.md et docs/Prompt_production_modèle.md.
|
||||
* Codes d'erreurs issus de src/lib/taxonomieErreurs.ts (validation runtime incluse).
|
||||
*
|
||||
* EO (Expression Orale) conserve le pipeline V1 monolithique (hors scope Sprint 3.6a).
|
||||
*/
|
||||
|
||||
import {
|
||||
CRITERES,
|
||||
CRITERE_LABELS,
|
||||
NCLC_MIN_SCORE,
|
||||
buildTaxonomyPromptSection,
|
||||
isValidCode,
|
||||
isValidCritere,
|
||||
type Critere,
|
||||
} from './taxonomieErreurs.js'
|
||||
|
||||
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY ?? ''
|
||||
const DEEPSEEK_BASE_URL = 'https://api.deepseek.com'
|
||||
|
||||
export interface EECritere {
|
||||
// ── Types — Sprint 3.6a ──────────────────────────────────────────────────
|
||||
|
||||
export type TacheEE = 'EE_T1' | 'EE_T2' | 'EE_T3'
|
||||
export type NclcCible = 9 | 10
|
||||
|
||||
export interface CorrectionInput {
|
||||
tache: TacheEE
|
||||
contenu: string
|
||||
sujet: string | null
|
||||
sourceDoc1?: string | null
|
||||
sourceDoc2?: string | null
|
||||
nclcCible: NclcCible
|
||||
}
|
||||
|
||||
export interface CorrectionCritereDetail {
|
||||
nom: string
|
||||
score: number
|
||||
commentaire: string
|
||||
exemple: string
|
||||
suggestion: string
|
||||
astuce: string
|
||||
}
|
||||
|
||||
export interface EERapport {
|
||||
export interface ErreurCode {
|
||||
code: string
|
||||
critere: Critere
|
||||
description: string | null
|
||||
}
|
||||
|
||||
export interface CorrectionRapport {
|
||||
score: number
|
||||
nclc: number
|
||||
feedback_court: string
|
||||
criteres: EECritere[]
|
||||
erreurs: string[]
|
||||
modele: string
|
||||
idees: string[]
|
||||
exercices: string[]
|
||||
nclc_cible: NclcCible
|
||||
revelation: {
|
||||
croyance: string
|
||||
realite: string
|
||||
consequence: string
|
||||
}
|
||||
diagnostic: string
|
||||
criteres: CorrectionCritereDetail[]
|
||||
conseil_nclc: {
|
||||
nclc_cible: string
|
||||
ecart: string
|
||||
action_prioritaire: string
|
||||
}
|
||||
erreurs_codes: ErreurCode[]
|
||||
}
|
||||
|
||||
export interface ProductionModeleInput {
|
||||
tache: TacheEE
|
||||
sujet: string | null
|
||||
texte: string
|
||||
nclcObtenu: number
|
||||
}
|
||||
|
||||
export interface TransformationItem {
|
||||
original: string
|
||||
ameliore: string
|
||||
explication: string
|
||||
}
|
||||
|
||||
export interface NotePedagogique {
|
||||
passage: string
|
||||
explication: string
|
||||
}
|
||||
|
||||
export interface ProductionModele {
|
||||
production_modele_propre: string
|
||||
notes_pedagogiques: NotePedagogique[]
|
||||
transformations: TransformationItem[]
|
||||
message: string
|
||||
// Métadonnées ajoutées par le post-traitement serveur
|
||||
nclc_modele: 9
|
||||
nclc_obtenu: number
|
||||
score_cible: number
|
||||
tcf_word_count: number
|
||||
tcf_word_min: number
|
||||
tcf_word_max: number
|
||||
tcf_truncated: boolean
|
||||
}
|
||||
|
||||
export interface ExercicesInput {
|
||||
tache: TacheEE
|
||||
erreursCodes: ErreurCode[]
|
||||
criteres: CorrectionCritereDetail[]
|
||||
}
|
||||
|
||||
export interface ExerciceItem {
|
||||
difficulte: 'facile' | 'intermediaire' | 'difficile'
|
||||
theme: string
|
||||
diagnostic: string
|
||||
consigne: string
|
||||
extrait: string
|
||||
indice: string
|
||||
correction: string
|
||||
explication: string
|
||||
}
|
||||
|
||||
// Longueurs TCF Canada par tâche (docs/Prompt_production_modèle.md §LONGUEUR)
|
||||
const WORD_LIMITS: Record<TacheEE, { min: number; max: number }> = {
|
||||
EE_T1: { min: 60, max: 120 },
|
||||
EE_T2: { min: 120, max: 150 },
|
||||
EE_T3: { min: 120, max: 180 },
|
||||
}
|
||||
|
||||
const TASK_DESCRIPTIONS: Record<TacheEE, string> = {
|
||||
EE_T1:
|
||||
'Tâche 1 — Message / mail / annonce (60-120 mots) : décrire, raconter, expliquer à un destinataire dont le registre (formel/informel) est précisé dans la consigne.',
|
||||
EE_T2:
|
||||
'Tâche 2 — Article de blog / forum (120-150 mots) : compte rendu d\'expérience ou récit, accompagné de commentaires, opinions ou arguments selon un objectif.',
|
||||
EE_T3:
|
||||
'Tâche 3 — Texte comparatif (120-180 mots) : Partie 1 (40-60 mots) synthèse des deux points de vue des documents sources ; Partie 2 (80-120 mots) prise de position personnelle argumentée.',
|
||||
}
|
||||
|
||||
// ── Prompts builders ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Prompt maître — correction EE.
|
||||
* Retourne le couple (system, user) à envoyer à DeepSeek.
|
||||
*/
|
||||
export function buildCorrectionPrompt(input: CorrectionInput): {
|
||||
system: string
|
||||
user: string
|
||||
} {
|
||||
const { tache, contenu, sujet, sourceDoc1, sourceDoc2, nclcCible } = input
|
||||
const minScore = NCLC_MIN_SCORE[nclcCible]
|
||||
|
||||
const taxonomySection = buildTaxonomyPromptSection()
|
||||
|
||||
const system = `Tu es un correcteur TCF Canada certifié par France Éducation International. Tu corriges avec précision et bienveillance.
|
||||
|
||||
RÈGLES ABSOLUES :
|
||||
- "exemple" = citation textuelle EXACTE, mot pour mot, extraite de la production du candidat. Jamais inventée.
|
||||
- "commentaire" = 2 phrases maximum, directes, sans formule introductive.
|
||||
- Interdit : "Voici", "Bien sûr", "Il convient de", toute formule introductive, tout markdown, tout backtick.
|
||||
- "score" global = somme exacte des 4 scores critères (0 à 20).
|
||||
- JSON strict sans aucun texte avant ni après.
|
||||
|
||||
CRITÈRES OFFICIELS TCF (chacun noté de 0 à 5) :
|
||||
1. ${CRITERE_LABELS.adequation_tache} — respect des consignes, longueur, registre, pertinence du contenu.
|
||||
2. ${CRITERE_LABELS.coherence_cohesion} — structure logique, connecteurs, progression thématique.
|
||||
3. ${CRITERE_LABELS.competence_lexicale} — étendue du vocabulaire, précision, variété, absence de répétitions excessives.
|
||||
4. ${CRITERE_LABELS.competence_grammaticale} — correction des structures, morphologie verbale, syntaxe, ponctuation.
|
||||
|
||||
${taxonomySection}
|
||||
|
||||
FORMAT DE RÉPONSE (JSON strict, aucun autre texte) :
|
||||
{
|
||||
"score": <entier 0-20, somme des 4 critères>,
|
||||
"nclc": <entier 4-12, niveau estimé à partir du score>,
|
||||
"revelation": {
|
||||
"croyance": "<ce que le candidat croit faire bien>",
|
||||
"realite": "<ce que le correcteur observe réellement>",
|
||||
"consequence": "<impact concret sur la note>"
|
||||
},
|
||||
"diagnostic": "<phrase courte et directe identifiant le principal frein>",
|
||||
"criteres": [
|
||||
{ "nom": "${CRITERE_LABELS.adequation_tache}", "score": <0-5>, "commentaire": "<2 phrases max>", "exemple": "<citation exacte>", "suggestion": "<reformulation concrète>", "astuce": "<conseil court>" },
|
||||
{ "nom": "${CRITERE_LABELS.coherence_cohesion}", "score": <0-5>, "commentaire": "<2 phrases max>", "exemple": "<citation exacte>", "suggestion": "<reformulation concrète>", "astuce": "<conseil court>" },
|
||||
{ "nom": "${CRITERE_LABELS.competence_lexicale}", "score": <0-5>, "commentaire": "<2 phrases max>", "exemple": "<citation exacte>", "suggestion": "<reformulation concrète>", "astuce": "<conseil court>" },
|
||||
{ "nom": "${CRITERE_LABELS.competence_grammaticale}", "score": <0-5>, "commentaire": "<2 phrases max>", "exemple": "<citation exacte>", "suggestion": "<reformulation concrète>", "astuce": "<conseil court>" }
|
||||
],
|
||||
"conseil_nclc": {
|
||||
"nclc_cible": "NCLC ${nclcCible}",
|
||||
"ecart": "<manque X points / objectif atteint / X points au-dessus>",
|
||||
"action_prioritaire": "<conseil direct, concret et personnalisé>"
|
||||
},
|
||||
"erreurs_codes": [
|
||||
{ "code": "<code taxonomie>", "critere": "<un des 4 critères>", "description": <null OU texte si code="autre"> }
|
||||
]
|
||||
}`
|
||||
|
||||
const docsBlock =
|
||||
tache === 'EE_T3' && (sourceDoc1 || sourceDoc2)
|
||||
? `\n\nDOCUMENTS SOURCES :
|
||||
Document 1 (point de vue POUR) : ${sourceDoc1 ?? 'Non précisé'}
|
||||
Document 2 (point de vue CONTRE) : ${sourceDoc2 ?? 'Non précisé'}`
|
||||
: ''
|
||||
|
||||
const user = `OBJECTIF DU CANDIDAT : NCLC ${nclcCible} — score minimum requis : ${minScore}/20.
|
||||
|
||||
TÂCHE : ${TASK_DESCRIPTIONS[tache]}${docsBlock}
|
||||
|
||||
CONSIGNE / SUJET : ${sujet ?? 'Non précisé'}
|
||||
|
||||
PRODUCTION DU CANDIDAT :
|
||||
"""
|
||||
${contenu}
|
||||
"""`
|
||||
|
||||
return { system, user }
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt production modèle — cible fixe NCLC 9 (cf. consigne Sprint 3.6a).
|
||||
*/
|
||||
export function buildModelPrompt(input: ProductionModeleInput): {
|
||||
system: string
|
||||
user: string
|
||||
} {
|
||||
const { tache, sujet, texte, nclcObtenu } = input
|
||||
const nclcModele: 9 = 9
|
||||
const scoreCible = NCLC_MIN_SCORE[nclcModele]
|
||||
const { min, max } = WORD_LIMITS[tache]
|
||||
|
||||
const system = `Tu es un correcteur expert TCF Canada.
|
||||
|
||||
Ta mission : réécrire la production du candidat EN CONSERVANT le fond, les idées, le positionnement et les arguments — mais en appliquant parfaitement les 4 critères officiels TCF Canada :
|
||||
1. Réalisation de la tâche — respecter le format, les limites de mots, la consigne, le registre
|
||||
2. Cohérence / Structure — paragraphes clairs, connecteurs logiques variés, progression cohérente
|
||||
3. Étendue du lexique — vocabulaire riche et précis, zéro répétition, registre adapté
|
||||
4. Maîtrise grammaticale — structures complexes, subjonctif, passif, subordination
|
||||
|
||||
RÈGLES ABSOLUES :
|
||||
- Conserver les idées et arguments du candidat — ne pas inventer
|
||||
- Respecter STRICTEMENT les limites de mots pour production_modele_propre (maximum : ${max} mots)
|
||||
- Viser exactement le niveau NCLC ${nclcModele} (score minimum ${scoreCible}/20)
|
||||
- Aucune annotation dans production_modele_propre (pas de [NOTE:], pas de commentaire entre parenthèses)
|
||||
- Exactement 3 entrées dans notes_pedagogiques
|
||||
- Répondre en JSON valide, sans markdown, sans texte avant ni après
|
||||
|
||||
COMPTAGE DES MOTS (TCF Canada) :
|
||||
- Un mot = segment séparé par un espace. L'apostrophe (' ou ') et le tiret (-) ne créent pas un mot supplémentaire.
|
||||
- Exemples : « c'est », « aujourd'hui », « c'est-à-dire », « vas-y » = 1 mot chacun.
|
||||
|
||||
LONGUEUR pour cette tâche : ${min} à ${max} mots — ne pas dépasser ${max}.
|
||||
|
||||
FORMAT JSON (strict) :
|
||||
{
|
||||
"production_modele_propre": "<texte final, prêt pour l'examen, sans annotation>",
|
||||
"notes_pedagogiques": [
|
||||
{ "passage": "<extrait court du texte modèle>", "explication": "<pourquoi efficace au TCF>" }
|
||||
],
|
||||
"transformations": [
|
||||
{ "original": "<extrait du candidat>", "ameliore": "<version améliorée>", "explication": "<pourquoi c'est mieux>" }
|
||||
],
|
||||
"message": "<phrase courte encourageante sur les idées du candidat>"
|
||||
}`
|
||||
|
||||
const user = `SUJET : ${sujet ?? 'Non précisé'}
|
||||
|
||||
TÂCHE : ${TASK_DESCRIPTIONS[tache]}
|
||||
|
||||
PRODUCTION DU CANDIDAT :
|
||||
${texte}
|
||||
|
||||
Le candidat a obtenu NCLC ${nclcObtenu}. Montre-lui comment atteindre NCLC ${nclcModele}.`
|
||||
|
||||
return { system, user }
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt exercices — 3 exercices ciblés sur les erreurs_codes les plus saillantes.
|
||||
* Format aligné sur les captures d'écran (cf. plan session).
|
||||
*/
|
||||
export function buildExercicesPrompt(input: ExercicesInput): {
|
||||
system: string
|
||||
user: string
|
||||
} {
|
||||
const { tache, erreursCodes, criteres } = input
|
||||
|
||||
const system = `Tu es un coach TCF Canada. Tu produis des micro-exercices ciblés pour faire travailler un candidat sur ses erreurs réelles.
|
||||
|
||||
RÈGLES ABSOLUES :
|
||||
- Produire EXACTEMENT 3 exercices, ciblés sur les 3 codes d'erreurs les plus impactants fournis en entrée.
|
||||
- "extrait" = citation textuelle exacte du candidat (tirée des champs "exemple" des critères quand pertinent). Jamais inventée.
|
||||
- "correction" = la version corrigée de "extrait".
|
||||
- Aucune formule introductive, aucun markdown, aucun backtick.
|
||||
- JSON strict sans aucun texte avant ni après.
|
||||
|
||||
FORMAT JSON :
|
||||
{
|
||||
"exercices": [
|
||||
{
|
||||
"difficulte": "facile" | "intermediaire" | "difficile",
|
||||
"theme": "<code taxonomie concerné, ex: accord_sujet_verbe>",
|
||||
"diagnostic": "<1 phrase : quelle erreur cet exercice cible>",
|
||||
"consigne": "<instruction claire donnée au candidat>",
|
||||
"extrait": "<citation exacte du candidat>",
|
||||
"indice": "<piste courte pour corriger sans donner la réponse>",
|
||||
"correction": "<la version corrigée attendue>",
|
||||
"explication": "<pourquoi la correction est meilleure, 2 phrases max>"
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
const erreursBlock = erreursCodes
|
||||
.map((e) => `- ${e.code} (${e.critere})${e.description ? ` : ${e.description}` : ''}`)
|
||||
.join('\n')
|
||||
|
||||
const criteresBlock = criteres
|
||||
.map((c) => `- ${c.nom} (score ${c.score}/5) — exemple : « ${c.exemple} »`)
|
||||
.join('\n')
|
||||
|
||||
const user = `TÂCHE : ${TASK_DESCRIPTIONS[tache]}
|
||||
|
||||
ERREURS DÉTECTÉES DANS LA PRODUCTION :
|
||||
${erreursBlock || '(aucune erreur listée)'}
|
||||
|
||||
EXTRAITS PAR CRITÈRE (pour alimenter "extrait") :
|
||||
${criteresBlock}
|
||||
|
||||
Produis 3 exercices ciblés. Privilégie les codes d'erreurs qui apparaissent le plus souvent, puis les plus impactants pour l'objectif NCLC.`
|
||||
|
||||
return { system, user }
|
||||
}
|
||||
|
||||
// ── Post-traitement production modèle ───────────────────────────────────
|
||||
|
||||
/**
|
||||
* Compte des mots TCF Canada : un mot = segment séparé par un espace.
|
||||
* Apostrophes et tirets ne créent pas de mot supplémentaire.
|
||||
*/
|
||||
export function wordCountTCF(text: string): number {
|
||||
const trimmed = text.trim()
|
||||
if (trimmed.length === 0) return 0
|
||||
return trimmed.split(/\s+/).length
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime les annotations [NOTE: ...] et les commentaires entre parenthèses
|
||||
* ajoutés par erreur par DeepSeek malgré la consigne.
|
||||
*/
|
||||
export function stripModelAnnotations(text: string): string {
|
||||
return text
|
||||
.replace(/\[NOTE:[^\]]*\]/gi, '')
|
||||
.replace(/\s{2,}/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* Tronque à `maxWords` mots TCF. Retourne {text, truncated}.
|
||||
*/
|
||||
export function truncateToMaxWords(text: string, maxWords: number): { text: string; truncated: boolean } {
|
||||
const words = text.trim().split(/\s+/)
|
||||
if (words.length <= maxWords) return { text, truncated: false }
|
||||
return { text: words.slice(0, maxWords).join(' '), truncated: true }
|
||||
}
|
||||
|
||||
// ── Appels DeepSeek ──────────────────────────────────────────────────────
|
||||
|
||||
async function callDeepSeek(system: string, user: string, temperature: number): Promise<string> {
|
||||
try {
|
||||
const response = await fetch(`${DEEPSEEK_BASE_URL}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${DEEPSEEK_API_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'deepseek-chat',
|
||||
messages: [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: user },
|
||||
],
|
||||
temperature,
|
||||
response_format: { type: 'json_object' },
|
||||
}),
|
||||
// Le prompt maître + taxonomie produit une réponse JSON longue : DeepSeek
|
||||
// peut prendre 20-40 s. Le frontend abort à 60 s (CORRECTION_TIMEOUT_MS)
|
||||
// → on abort ici à 55 s pour laisser une marge côté client.
|
||||
signal: AbortSignal.timeout(55_000),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`DeepSeek API error: ${response.status} ${response.statusText}`)
|
||||
}
|
||||
|
||||
const data = (await response.json()) as { choices?: { message?: { content?: string } }[] }
|
||||
const content = data.choices?.[0]?.message?.content
|
||||
|
||||
if (!content) {
|
||||
throw new Error('DeepSeek API: réponse vide')
|
||||
}
|
||||
|
||||
return content
|
||||
} catch (err) {
|
||||
const kind =
|
||||
err instanceof Error && err.name === 'TimeoutError'
|
||||
? 'TIMEOUT'
|
||||
: err instanceof Error && err.name === 'AbortError'
|
||||
? 'ABORT'
|
||||
: err instanceof SyntaxError
|
||||
? 'JSON_PARSE'
|
||||
: err instanceof TypeError
|
||||
? 'NETWORK'
|
||||
: 'OTHER'
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
console.error(`[deepseek.callDeepSeek] ${kind} — ${message}`)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// ── Validation runtime ───────────────────────────────────────────────────
|
||||
|
||||
function validateErreursCodes(raw: unknown): ErreurCode[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const valid: ErreurCode[] = []
|
||||
for (const item of raw) {
|
||||
if (typeof item !== 'object' || item === null) continue
|
||||
const o = item as { code?: unknown; critere?: unknown; description?: unknown }
|
||||
if (typeof o.code !== 'string' || typeof o.critere !== 'string') continue
|
||||
if (!isValidCritere(o.critere)) continue
|
||||
if (!isValidCode(o.critere, o.code)) continue
|
||||
const description =
|
||||
typeof o.description === 'string' && o.description.trim().length > 0 ? o.description : null
|
||||
if (o.code === 'autre' && description === null) continue // autre exige une description
|
||||
valid.push({ code: o.code, critere: o.critere, description })
|
||||
}
|
||||
return valid
|
||||
}
|
||||
|
||||
function validateCorrectionRapport(raw: unknown, nclcCible: NclcCible): CorrectionRapport {
|
||||
if (typeof raw !== 'object' || raw === null) {
|
||||
throw new Error('Réponse DeepSeek invalide : racine non-objet')
|
||||
}
|
||||
const r = raw as Record<string, unknown>
|
||||
|
||||
const score = typeof r.score === 'number' ? r.score : Number(r.score)
|
||||
if (!Number.isFinite(score) || score < 0 || score > 20) {
|
||||
throw new Error(`Score invalide: ${String(r.score)} (attendu 0-20)`)
|
||||
}
|
||||
|
||||
const nclc = typeof r.nclc === 'number' ? r.nclc : Number(r.nclc)
|
||||
if (!Number.isFinite(nclc) || nclc < 4 || nclc > 12) {
|
||||
throw new Error(`NCLC invalide: ${String(r.nclc)} (attendu 4-12)`)
|
||||
}
|
||||
|
||||
const revelation = r.revelation as Record<string, unknown> | undefined
|
||||
if (
|
||||
!revelation ||
|
||||
typeof revelation.croyance !== 'string' ||
|
||||
typeof revelation.realite !== 'string' ||
|
||||
typeof revelation.consequence !== 'string'
|
||||
) {
|
||||
throw new Error('revelation invalide : attendu { croyance, realite, consequence } en chaînes')
|
||||
}
|
||||
|
||||
if (typeof r.diagnostic !== 'string' || r.diagnostic.trim().length === 0) {
|
||||
throw new Error('diagnostic invalide : chaîne non vide attendue')
|
||||
}
|
||||
|
||||
if (!Array.isArray(r.criteres) || r.criteres.length !== 4) {
|
||||
throw new Error('criteres invalide : 4 entrées attendues')
|
||||
}
|
||||
const criteres: CorrectionCritereDetail[] = r.criteres.map((c: unknown, i: number) => {
|
||||
const o = c as Record<string, unknown>
|
||||
if (typeof o?.nom !== 'string') throw new Error(`criteres[${i}].nom invalide`)
|
||||
const cScore = typeof o.score === 'number' ? o.score : Number(o.score)
|
||||
if (!Number.isFinite(cScore) || cScore < 0 || cScore > 5) {
|
||||
throw new Error(`criteres[${i}].score invalide`)
|
||||
}
|
||||
return {
|
||||
nom: o.nom,
|
||||
score: cScore,
|
||||
commentaire: typeof o.commentaire === 'string' ? o.commentaire : '',
|
||||
exemple: typeof o.exemple === 'string' ? o.exemple : '',
|
||||
suggestion: typeof o.suggestion === 'string' ? o.suggestion : '',
|
||||
astuce: typeof o.astuce === 'string' ? o.astuce : '',
|
||||
}
|
||||
})
|
||||
|
||||
const conseil = r.conseil_nclc as Record<string, unknown> | undefined
|
||||
if (
|
||||
!conseil ||
|
||||
typeof conseil.nclc_cible !== 'string' ||
|
||||
typeof conseil.ecart !== 'string' ||
|
||||
typeof conseil.action_prioritaire !== 'string'
|
||||
) {
|
||||
throw new Error('conseil_nclc invalide')
|
||||
}
|
||||
|
||||
const erreursCodes = validateErreursCodes(r.erreurs_codes)
|
||||
|
||||
return {
|
||||
score,
|
||||
nclc,
|
||||
nclc_cible: nclcCible,
|
||||
revelation: {
|
||||
croyance: revelation.croyance,
|
||||
realite: revelation.realite,
|
||||
consequence: revelation.consequence,
|
||||
},
|
||||
diagnostic: r.diagnostic,
|
||||
criteres,
|
||||
conseil_nclc: {
|
||||
nclc_cible: conseil.nclc_cible,
|
||||
ecart: conseil.ecart,
|
||||
action_prioritaire: conseil.action_prioritaire,
|
||||
},
|
||||
erreurs_codes: erreursCodes,
|
||||
}
|
||||
}
|
||||
|
||||
// ── Fonctions exportées — correction + modèle + exercices ───────────────
|
||||
|
||||
export async function correctEE(input: CorrectionInput): Promise<CorrectionRapport> {
|
||||
const { system, user } = buildCorrectionPrompt(input)
|
||||
const content = await callDeepSeek(system, user, 0.2)
|
||||
const parsed: unknown = JSON.parse(content)
|
||||
return validateCorrectionRapport(parsed, input.nclcCible)
|
||||
}
|
||||
|
||||
export async function generateProductionModele(input: ProductionModeleInput): Promise<ProductionModele> {
|
||||
const { system, user } = buildModelPrompt(input)
|
||||
const content = await callDeepSeek(system, user, 0.3)
|
||||
const parsed = JSON.parse(content) as Record<string, unknown>
|
||||
|
||||
if (typeof parsed.production_modele_propre !== 'string') {
|
||||
throw new Error('production_modele_propre invalide : chaîne attendue')
|
||||
}
|
||||
|
||||
const cleaned = stripModelAnnotations(parsed.production_modele_propre)
|
||||
const { min, max } = WORD_LIMITS[input.tache]
|
||||
const { text: final, truncated } = truncateToMaxWords(cleaned, max)
|
||||
const count = wordCountTCF(final)
|
||||
|
||||
const notes = Array.isArray(parsed.notes_pedagogiques)
|
||||
? (parsed.notes_pedagogiques as unknown[])
|
||||
.map((n) => n as Record<string, unknown>)
|
||||
.filter((n) => typeof n.passage === 'string' && typeof n.explication === 'string')
|
||||
.map((n) => ({ passage: n.passage as string, explication: n.explication as string }))
|
||||
: []
|
||||
|
||||
const transformations = Array.isArray(parsed.transformations)
|
||||
? (parsed.transformations as unknown[])
|
||||
.map((t) => t as Record<string, unknown>)
|
||||
.filter(
|
||||
(t) =>
|
||||
typeof t.original === 'string' &&
|
||||
typeof t.ameliore === 'string' &&
|
||||
typeof t.explication === 'string'
|
||||
)
|
||||
.map((t) => ({
|
||||
original: t.original as string,
|
||||
ameliore: t.ameliore as string,
|
||||
explication: t.explication as string,
|
||||
}))
|
||||
: []
|
||||
|
||||
return {
|
||||
production_modele_propre: final,
|
||||
notes_pedagogiques: notes,
|
||||
transformations,
|
||||
message: typeof parsed.message === 'string' ? parsed.message : '',
|
||||
nclc_modele: 9,
|
||||
nclc_obtenu: input.nclcObtenu,
|
||||
score_cible: NCLC_MIN_SCORE[9],
|
||||
tcf_word_count: count,
|
||||
tcf_word_min: min,
|
||||
tcf_word_max: max,
|
||||
tcf_truncated: truncated,
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateExercices(input: ExercicesInput): Promise<ExerciceItem[]> {
|
||||
const { system, user } = buildExercicesPrompt(input)
|
||||
const content = await callDeepSeek(system, user, 0.4)
|
||||
const parsed = JSON.parse(content) as { exercices?: unknown }
|
||||
|
||||
if (!Array.isArray(parsed.exercices)) {
|
||||
throw new Error('exercices invalide : tableau attendu')
|
||||
}
|
||||
|
||||
const DIFFICULTES: ExerciceItem['difficulte'][] = ['facile', 'intermediaire', 'difficile']
|
||||
|
||||
return (parsed.exercices as unknown[])
|
||||
.map((e) => e as Record<string, unknown>)
|
||||
.filter((e) => typeof e.consigne === 'string' && typeof e.correction === 'string')
|
||||
.map((e) => ({
|
||||
difficulte: DIFFICULTES.includes(e.difficulte as ExerciceItem['difficulte'])
|
||||
? (e.difficulte as ExerciceItem['difficulte'])
|
||||
: 'intermediaire',
|
||||
theme: typeof e.theme === 'string' ? e.theme : '',
|
||||
diagnostic: typeof e.diagnostic === 'string' ? e.diagnostic : '',
|
||||
consigne: e.consigne as string,
|
||||
extrait: typeof e.extrait === 'string' ? e.extrait : '',
|
||||
indice: typeof e.indice === 'string' ? e.indice : '',
|
||||
correction: e.correction as string,
|
||||
explication: typeof e.explication === 'string' ? e.explication : '',
|
||||
}))
|
||||
}
|
||||
|
||||
// ── EO (Expression Orale) — inchangé par Sprint 3.6a ────────────────────
|
||||
|
||||
export interface EOCritere {
|
||||
nom: string
|
||||
score: number
|
||||
|
|
@ -35,86 +628,6 @@ export interface EORapport {
|
|||
exercices: string[]
|
||||
}
|
||||
|
||||
const SYSTEM_PROMPT = `Tu es un examinateur officiel du TCF Canada (Test de connaissance du français).
|
||||
Tu évalues une production écrite selon les 4 critères officiels de l'Expression Écrite :
|
||||
1. Cohérence et cohésion
|
||||
2. Lexique (étendue et maîtrise du vocabulaire)
|
||||
3. Morphosyntaxe (grammaire et structures)
|
||||
4. Pertinence (adéquation à la consigne)
|
||||
|
||||
Tu dois retourner un JSON strict avec cette structure exacte :
|
||||
{
|
||||
"score": <number 0-20>,
|
||||
"nclc": <number 4-12>,
|
||||
"feedback_court": "<2 à 3 lignes de feedback global, orientées action>",
|
||||
"criteres": [
|
||||
{ "nom": "Cohérence et cohésion", "score": <number 0-5>, "commentaire": "<string>" },
|
||||
{ "nom": "Lexique", "score": <number 0-5>, "commentaire": "<string>" },
|
||||
{ "nom": "Morphosyntaxe", "score": <number 0-5>, "commentaire": "<string>" },
|
||||
{ "nom": "Pertinence", "score": <number 0-5>, "commentaire": "<string>" }
|
||||
],
|
||||
"erreurs": ["<erreur 1>", "<erreur 2>", ...],
|
||||
"modele": "<texte modèle corrigé>",
|
||||
"idees": ["<idée 1>", "<idée 2>", ...],
|
||||
"exercices": ["<exercice recommandé 1>", "<exercice recommandé 2>", ...]
|
||||
}
|
||||
|
||||
Règles :
|
||||
- score est la note globale sur 20
|
||||
- nclc est le niveau NCLC estimé (entre 4 et 12)
|
||||
- feedback_court est un résumé de 2 à 3 lignes, toujours renseigné (visible pour tous les plans)
|
||||
- Chaque critère a un score de 0 à 5
|
||||
- Retourne UNIQUEMENT le JSON, sans texte avant ni après`
|
||||
|
||||
export async function correctEE(contenu: string, tache: string): Promise<EERapport> {
|
||||
const response = await fetch(`${DEEPSEEK_BASE_URL}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${DEEPSEEK_API_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'deepseek-chat',
|
||||
messages: [
|
||||
{ role: 'system', content: SYSTEM_PROMPT },
|
||||
{
|
||||
role: 'user',
|
||||
content: `Tâche : ${tache}\n\nProduction de l'étudiant :\n${contenu}`,
|
||||
},
|
||||
],
|
||||
temperature: 0.3,
|
||||
response_format: { type: 'json_object' },
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`DeepSeek API error: ${response.status} ${response.statusText}`)
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
choices?: { message?: { content?: string } }[]
|
||||
}
|
||||
const content = data.choices?.[0]?.message?.content
|
||||
|
||||
if (!content) {
|
||||
throw new Error('DeepSeek API: réponse vide')
|
||||
}
|
||||
|
||||
const rapport: EERapport = JSON.parse(content)
|
||||
|
||||
if (rapport.score < 0 || rapport.score > 20) {
|
||||
throw new Error(`Score invalide: ${rapport.score} (attendu 0-20)`)
|
||||
}
|
||||
if (rapport.nclc < 4 || rapport.nclc > 12) {
|
||||
throw new Error(`NCLC invalide: ${rapport.nclc} (attendu 4-12)`)
|
||||
}
|
||||
if (typeof rapport.feedback_court !== 'string' || rapport.feedback_court.trim().length === 0) {
|
||||
throw new Error('feedback_court invalide: attendu une chaîne non vide')
|
||||
}
|
||||
|
||||
return rapport
|
||||
}
|
||||
|
||||
const SYSTEM_PROMPT_EO = `Tu es un examinateur officiel du TCF Canada (Test de connaissance du français).
|
||||
Tu évalues une production orale à partir de sa transcription selon les 4 critères officiels de l'Expression Orale :
|
||||
1. Cohérence et cohésion
|
||||
|
|
@ -255,3 +768,7 @@ export async function correctEO(transcript: string, tache: string): Promise<EORa
|
|||
|
||||
return rapport
|
||||
}
|
||||
|
||||
// Alias legacy — temporairement conservé le temps que correctionController.correctEE
|
||||
// soit migré vers la nouvelle signature (étape E5).
|
||||
export type EERapport = CorrectionRapport
|
||||
|
|
|
|||
151
src/lib/taxonomieErreurs.ts
Normal file
151
src/lib/taxonomieErreurs.ts
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
/**
|
||||
* Taxonomie fermée des erreurs — cf. docs/TAXONOMIE_ERREURS.md v1.0.
|
||||
*
|
||||
* Source unique des codes acceptés dans les rapports DeepSeek. Utilisée par :
|
||||
* 1. le prompt maître (injection de la liste des codes par critère)
|
||||
* 2. la validation runtime des réponses DeepSeek (garde-fou taxonomie)
|
||||
*
|
||||
* Règle : chaque erreur retournée doit avoir un code présent ici, ou `autre`
|
||||
* avec une `description` non vide.
|
||||
*/
|
||||
|
||||
export type Critere =
|
||||
| 'adequation_tache'
|
||||
| 'coherence_cohesion'
|
||||
| 'competence_lexicale'
|
||||
| 'competence_grammaticale'
|
||||
|
||||
export const CRITERES: readonly Critere[] = [
|
||||
'adequation_tache',
|
||||
'coherence_cohesion',
|
||||
'competence_lexicale',
|
||||
'competence_grammaticale',
|
||||
]
|
||||
|
||||
/**
|
||||
* Libellés officiels TCF Canada — affichés côté frontend.
|
||||
* Alignés sur les intitulés du prompt maître (docs/Prompt_maître.md §CRITÈRES).
|
||||
*/
|
||||
export const CRITERE_LABELS: Record<Critere, string> = {
|
||||
adequation_tache: 'Adéquation à la tâche et au registre',
|
||||
coherence_cohesion: 'Cohérence et cohésion du discours',
|
||||
competence_lexicale: 'Compétence lexicale',
|
||||
competence_grammaticale: 'Compétence grammaticale',
|
||||
}
|
||||
|
||||
export const CODES_BY_CRITERE: Record<Critere, readonly string[]> = {
|
||||
adequation_tache: [
|
||||
'hors_sujet_total',
|
||||
'hors_sujet_partiel',
|
||||
'information_manquante',
|
||||
'enonce_copie',
|
||||
'longueur_insuffisante',
|
||||
'longueur_excessive',
|
||||
'format_non_respecte',
|
||||
'salutation_absente',
|
||||
'cloture_absente',
|
||||
'structure_absente',
|
||||
'registre_trop_formel',
|
||||
'registre_trop_familier',
|
||||
'abreviations_sms',
|
||||
'tutoiement_inadequat',
|
||||
'autre',
|
||||
],
|
||||
coherence_cohesion: [
|
||||
'introduction_absente',
|
||||
'conclusion_absente',
|
||||
'paragraphes_absents',
|
||||
'progression_illogique',
|
||||
'connecteurs_absents',
|
||||
'connecteurs_repetes',
|
||||
'connecteurs_inadequats',
|
||||
'connecteurs_insuffisants',
|
||||
'idee_non_developpee',
|
||||
'repetition_idee',
|
||||
'contradiction_interne',
|
||||
'hors_propos',
|
||||
'pronoms_ambigus',
|
||||
'substitution_absente',
|
||||
'rupture_temporelle',
|
||||
'autre',
|
||||
],
|
||||
competence_lexicale: [
|
||||
'vocabulaire_basique',
|
||||
'vocabulaire_insuffisant',
|
||||
'registre_lexical_inadequat',
|
||||
'mot_imprecis',
|
||||
'contresens_lexical',
|
||||
'anglicisme',
|
||||
'calque_syntaxique',
|
||||
'repetition_lexicale',
|
||||
'synonymes_absents',
|
||||
'expressions_figees_absentes',
|
||||
'faute_orthographe_courante',
|
||||
'confusion_homophones',
|
||||
'majuscules_incorrectes',
|
||||
'autre',
|
||||
],
|
||||
competence_grammaticale: [
|
||||
'accord_sujet_verbe',
|
||||
'accord_adjectif_nom',
|
||||
'accord_participe_passe',
|
||||
'accord_determinant_nom',
|
||||
'temps_verbal_inadequat',
|
||||
'subjonctif_absent',
|
||||
'subjonctif_incorrect',
|
||||
'conditionnel_absent',
|
||||
'concordance_temps',
|
||||
'phrase_incomplete',
|
||||
'phrase_trop_longue',
|
||||
'ordre_mots_incorrect',
|
||||
'subordination_absente',
|
||||
'subordination_incorrecte',
|
||||
'virgule_exces',
|
||||
'virgule_absence',
|
||||
'point_absent',
|
||||
'ponctuation_incorrecte',
|
||||
'preposition_absente',
|
||||
'preposition_incorrecte',
|
||||
'preposition_superflue',
|
||||
'genre_incorrect',
|
||||
'nombre_incorrect',
|
||||
'negation_incomplete',
|
||||
'autre',
|
||||
],
|
||||
}
|
||||
|
||||
export function isValidCritere(x: unknown): x is Critere {
|
||||
return typeof x === 'string' && (CRITERES as readonly string[]).includes(x)
|
||||
}
|
||||
|
||||
export function isValidCode(critere: Critere, code: string): boolean {
|
||||
return CODES_BY_CRITERE[critere].includes(code)
|
||||
}
|
||||
|
||||
/**
|
||||
* Bloc texte injecté dans le prompt maître — liste des codes autorisés par critère,
|
||||
* dans le format exact attendu par DeepSeek (`critere: code1, code2, …`).
|
||||
*/
|
||||
export function buildTaxonomyPromptSection(): string {
|
||||
const lines = CRITERES.map((critere) => {
|
||||
const codes = CODES_BY_CRITERE[critere].join(', ')
|
||||
return `- ${critere} : ${codes}`
|
||||
})
|
||||
return `CODES D'ERREURS AUTORISÉS (par critère) :
|
||||
${lines.join('\n')}
|
||||
|
||||
Règles :
|
||||
- Chaque erreur retournée doit utiliser EXACTEMENT un code de la liste du critère concerné.
|
||||
- Le code "autre" est autorisé mais exige une "description" textuelle non vide.
|
||||
- Pour tout code différent de "autre", le champ "description" doit être null.`
|
||||
}
|
||||
|
||||
/**
|
||||
* Barème NCLC → score minimum /20 (cf. Prompt_maître.md §Barème).
|
||||
*/
|
||||
export const NCLC_MIN_SCORE: Record<number, number> = {
|
||||
7: 10,
|
||||
8: 12,
|
||||
9: 14,
|
||||
10: 16,
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue