feat(sessions): implement Agents 2, 3, 4 (Cartographie, Niveau, Recherche)
Agent 2 (MappingAgent): single-call concept map over real web search (OpenRouter ":online"), code-side validation (>=5 sources total, >=2 per concept, mandatory "etre capable de" wording) with one retry before failing - never trusts the LLM's self-reported compliance. Agent 3 (LevelAgent): 3-5 situational questions built from the concept map, same conversational shape as ObjectiveAgent (ephemeral in-memory history). Produces a 3-dimension profile (mastered/gap/unknown) the user can dispute per concept before confirming. Agent 4 (ResearchAgent): one parallel ":online" call per concept, calibrated by the level profile (mastered->advanced sources, gap->intermediate, unknown->beginner). A failed subtopic never fails the whole batch - it's recorded in the corpus and the rest proceeds. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
b5cdc30207
commit
5c00976e8f
@@ -0,0 +1,201 @@
|
||||
import { ConflictException } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { OpenRouterService } from '../../llm/openrouter.service';
|
||||
import { LevelAgent } from './level.agent';
|
||||
|
||||
describe('LevelAgent', () => {
|
||||
let agent: LevelAgent;
|
||||
const chat = jest.fn<Promise<string>, [number, unknown[], unknown?]>();
|
||||
const create = jest.fn<
|
||||
Promise<unknown>,
|
||||
[{ data: { questionsAsked: string[]; userAnswers: string[] } }]
|
||||
>();
|
||||
const findUnique = jest.fn();
|
||||
const update = jest.fn<
|
||||
Promise<unknown>,
|
||||
[
|
||||
{
|
||||
data: {
|
||||
masteredConcepts: string[];
|
||||
gapConcepts: { concept: string }[];
|
||||
};
|
||||
},
|
||||
]
|
||||
>();
|
||||
const prisma = {
|
||||
sessionLevelAssessment: { create, findUnique, update },
|
||||
};
|
||||
|
||||
const profileJson = JSON.stringify({
|
||||
message: 'Voila, j-ai une idee claire de ton niveau.',
|
||||
done: true,
|
||||
mastered: ['Facturation'],
|
||||
gaps: [{ concept: 'TVA', description: 'Confond taux normal et reduit' }],
|
||||
unknown: ['TVA intracommunautaire'],
|
||||
overall_level: 'intermediate',
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
LevelAgent,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: OpenRouterService, useValue: { chat } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
agent = module.get(LevelAgent);
|
||||
});
|
||||
|
||||
describe('start()', () => {
|
||||
it('should ask the first situational question without any user message', async () => {
|
||||
chat.mockResolvedValueOnce(
|
||||
JSON.stringify({
|
||||
message:
|
||||
'Si un client te demande une facture avec TVA, que fais-tu ?',
|
||||
done: false,
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await agent.start(
|
||||
1,
|
||||
7,
|
||||
'Facturation freelance',
|
||||
'Facturation, TVA',
|
||||
);
|
||||
|
||||
// Pas d'assertion sur le contenu exact du tableau "history" passe a chat() : jest garde une
|
||||
// reference (pas une copie) des arguments, et ce meme tableau est mute juste apres (push de
|
||||
// la reponse assistant) - comparer son contenu ici verifierait son etat final, pas celui au
|
||||
// moment de l'appel.
|
||||
expect(chat).toHaveBeenCalledTimes(1);
|
||||
expect(chat.mock.calls[0][0]).toBe(7);
|
||||
expect(chat.mock.calls[0][2]).toEqual({ jsonResponse: true });
|
||||
expect(result).toEqual({
|
||||
reply: 'Si un client te demande une facture avec TVA, que fais-tu ?',
|
||||
done: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('converse()', () => {
|
||||
it('should throw ConflictException when start() was never called for this session', async () => {
|
||||
await expect(agent.converse(1, 7, 'une reponse')).rejects.toThrow(
|
||||
ConflictException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should keep asking until done, then produce the profile', async () => {
|
||||
chat.mockResolvedValueOnce(
|
||||
JSON.stringify({ message: 'Premiere question ?', done: false }),
|
||||
);
|
||||
await agent.start(1, 7, 'Facturation freelance', 'Facturation, TVA');
|
||||
|
||||
chat.mockResolvedValueOnce(profileJson);
|
||||
const result = await agent.converse(1, 7, 'Ma reponse');
|
||||
|
||||
expect(result.done).toBe(true);
|
||||
expect(result.profile).toEqual({
|
||||
mastered: ['Facturation'],
|
||||
gaps: [
|
||||
{ concept: 'TVA', description: 'Confond taux normal et reduit' },
|
||||
],
|
||||
unknown: ['TVA intracommunautaire'],
|
||||
overallLevel: 'intermediate',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('confirm()', () => {
|
||||
it('should throw ConflictException when no profile is ready', async () => {
|
||||
await expect(agent.confirm(1)).rejects.toThrow(ConflictException);
|
||||
});
|
||||
|
||||
it('should persist the profile with the extracted questions/answers once ready', async () => {
|
||||
chat.mockResolvedValueOnce(
|
||||
JSON.stringify({ message: 'Premiere question ?', done: false }),
|
||||
);
|
||||
await agent.start(1, 7, 'Facturation freelance', 'Facturation, TVA');
|
||||
chat.mockResolvedValueOnce(profileJson);
|
||||
await agent.converse(1, 7, 'Ma reponse');
|
||||
|
||||
create.mockResolvedValueOnce({
|
||||
id: 2,
|
||||
sessionId: 1,
|
||||
masteredConcepts: ['Facturation'],
|
||||
gapConcepts: [
|
||||
{ concept: 'TVA', description: 'Confond taux normal et reduit' },
|
||||
],
|
||||
unknownConcepts: ['TVA intracommunautaire'],
|
||||
overallLevel: 'intermediate',
|
||||
completedAt: new Date('2026-01-01'),
|
||||
});
|
||||
|
||||
const result = await agent.confirm(1);
|
||||
|
||||
expect(create.mock.calls[0][0].data.questionsAsked).toEqual([
|
||||
'Premiere question ?',
|
||||
]);
|
||||
expect(create.mock.calls[0][0].data.userAnswers).toEqual(['Ma reponse']);
|
||||
expect(result.id).toBe(2);
|
||||
|
||||
await expect(agent.confirm(1)).rejects.toThrow(ConflictException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dispute()', () => {
|
||||
it('should throw ConflictException when no level assessment exists yet', async () => {
|
||||
findUnique.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
agent.dispute(1, 7, 'TVA', 'Ma reponse argumentee'),
|
||||
).rejects.toThrow(ConflictException);
|
||||
});
|
||||
|
||||
it('should move a concept into "mastered" when the dispute answer demonstrates mastery', async () => {
|
||||
findUnique.mockResolvedValueOnce({
|
||||
masteredConcepts: ['Facturation'],
|
||||
gapConcepts: [
|
||||
{ concept: 'TVA', description: 'Confond taux normal et reduit' },
|
||||
],
|
||||
unknownConcepts: [],
|
||||
});
|
||||
chat.mockResolvedValueOnce(
|
||||
JSON.stringify({ bucket: 'mastered', description: null }),
|
||||
);
|
||||
update.mockResolvedValueOnce({
|
||||
id: 1,
|
||||
sessionId: 1,
|
||||
masteredConcepts: ['Facturation', 'TVA'],
|
||||
gapConcepts: [],
|
||||
unknownConcepts: [],
|
||||
});
|
||||
|
||||
await agent.dispute(
|
||||
1,
|
||||
7,
|
||||
'TVA',
|
||||
"J'applique le bon taux selon le pays du client.",
|
||||
);
|
||||
|
||||
expect(update.mock.calls[0][0].data.masteredConcepts).toContain('TVA');
|
||||
expect(update.mock.calls[0][0].data.gapConcepts).toEqual([]);
|
||||
});
|
||||
|
||||
it('should default to "gap" when the dispute response is not valid JSON (prudence)', async () => {
|
||||
findUnique.mockResolvedValueOnce({
|
||||
masteredConcepts: [],
|
||||
gapConcepts: [],
|
||||
unknownConcepts: ['TVA'],
|
||||
});
|
||||
chat.mockResolvedValueOnce('reponse non-JSON');
|
||||
update.mockResolvedValueOnce({ id: 1, sessionId: 1 });
|
||||
|
||||
await agent.dispute(1, 7, 'TVA', 'reponse');
|
||||
|
||||
expect(update.mock.calls[0][0].data.gapConcepts[0].concept).toBe('TVA');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,329 @@
|
||||
import { ConflictException, Injectable, Logger } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { ChatMessage, OpenRouterService } from '../../llm/openrouter.service';
|
||||
import { buildAgentPrompt } from '../prompts/base.prompt';
|
||||
import { LEVEL_JSON_CONTRACT, LEVEL_PROMPT } from '../prompts/level.prompt';
|
||||
|
||||
export type OverallLevel = 'beginner' | 'intermediate' | 'advanced';
|
||||
|
||||
export interface LevelGap {
|
||||
concept: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface LevelProfile {
|
||||
mastered: string[];
|
||||
gaps: LevelGap[];
|
||||
unknown: string[];
|
||||
overallLevel: OverallLevel;
|
||||
}
|
||||
|
||||
export interface LevelTurnResult {
|
||||
reply: string;
|
||||
done: boolean;
|
||||
profile?: LevelProfile;
|
||||
}
|
||||
|
||||
export interface StoredLevelAssessment {
|
||||
id: number;
|
||||
sessionId: number;
|
||||
masteredConcepts: unknown;
|
||||
gapConcepts: unknown;
|
||||
unknownConcepts: unknown;
|
||||
overallLevel: string;
|
||||
completedAt: Date | null;
|
||||
}
|
||||
|
||||
interface AgentJsonReply {
|
||||
message?: unknown;
|
||||
done?: unknown;
|
||||
mastered?: unknown;
|
||||
gaps?: unknown;
|
||||
unknown?: unknown;
|
||||
overall_level?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent 3 du pipeline (docs/Max_System_Prompt.md) : 3 a 5 questions situationnelles construites
|
||||
* depuis la carte des concepts de l'Agent 2, jamais un QCM. Meme forme conversationnelle que
|
||||
* ObjectiveAgent (historique ephemere en memoire, par session) : wrap avec buildAgentPrompt() car
|
||||
* ces questions sont posees/lues par l'utilisateur comme venant de Max (contrairement a
|
||||
* MappingAgent/ResearchAgent, qui produisent des donnees que personne n'entend).
|
||||
*/
|
||||
@Injectable()
|
||||
export class LevelAgent {
|
||||
private readonly logger = new Logger(LevelAgent.name);
|
||||
private readonly conversations = new Map<number, ChatMessage[]>();
|
||||
private readonly readyProfiles = new Map<number, LevelProfile>();
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly llm: OpenRouterService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Premier tour, sans message utilisateur : demarre la conversation pour que Max pose
|
||||
* immediatement sa premiere question des que l'Agent 2 a produit la carte (voir
|
||||
* sessions.service.ts, confirmObjective()). C'est le seul moment ou Max parle pendant la
|
||||
* construction, hors reponse directe a l'utilisateur (docs/Max Refonte Coach Freelance.md,
|
||||
* "Garde-fous transversaux").
|
||||
*/
|
||||
async start(
|
||||
sessionId: number,
|
||||
userId: number,
|
||||
objectiveSummary: string,
|
||||
conceptMapSummary: string,
|
||||
): Promise<LevelTurnResult> {
|
||||
const systemPrompt = buildAgentPrompt(
|
||||
`${LEVEL_PROMPT.replace('[OBJECTIF_INJECTÉ_PAR_LE_BACKEND]', objectiveSummary).replace('[CARTE_INJECTÉE_PAR_LE_BACKEND]', conceptMapSummary)}\n\n${LEVEL_JSON_CONTRACT}`,
|
||||
);
|
||||
const history: ChatMessage[] = [{ role: 'system', content: systemPrompt }];
|
||||
const raw = await this.llm.chat(userId, history, { jsonResponse: true });
|
||||
history.push({ role: 'assistant', content: raw });
|
||||
this.conversations.set(sessionId, history);
|
||||
return this.handleReply(sessionId, raw);
|
||||
}
|
||||
|
||||
async converse(
|
||||
sessionId: number,
|
||||
userId: number,
|
||||
userMessage: string,
|
||||
): Promise<LevelTurnResult> {
|
||||
const history = this.conversations.get(sessionId);
|
||||
if (!history) {
|
||||
throw new ConflictException(
|
||||
"L'evaluation de niveau n'a pas encore demarre pour cette session.",
|
||||
);
|
||||
}
|
||||
history.push({ role: 'user', content: userMessage });
|
||||
const raw = await this.llm.chat(userId, history, { jsonResponse: true });
|
||||
history.push({ role: 'assistant', content: raw });
|
||||
this.conversations.set(sessionId, history);
|
||||
return this.handleReply(sessionId, raw);
|
||||
}
|
||||
|
||||
async confirm(sessionId: number): Promise<StoredLevelAssessment> {
|
||||
const profile = this.readyProfiles.get(sessionId);
|
||||
const history = this.conversations.get(sessionId);
|
||||
if (!profile || !history) {
|
||||
throw new ConflictException(
|
||||
"Aucun profil de niveau pret a confirmer pour cette session : continue le dialogue d'abord.",
|
||||
);
|
||||
}
|
||||
|
||||
const { questionsAsked, userAnswers } = this.extractExchanges(history);
|
||||
const record = await this.prisma.sessionLevelAssessment.create({
|
||||
data: {
|
||||
sessionId,
|
||||
questionsAsked: questionsAsked,
|
||||
userAnswers: userAnswers,
|
||||
masteredConcepts: profile.mastered,
|
||||
gapConcepts: profile.gaps as unknown as Prisma.InputJsonValue,
|
||||
unknownConcepts: profile.unknown,
|
||||
overallLevel: profile.overallLevel,
|
||||
completedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
this.conversations.delete(sessionId);
|
||||
this.readyProfiles.delete(sessionId);
|
||||
return record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Contestation d'un concept (docs/Max Refonte Coach Freelance.md : "en cas de correction,
|
||||
* l'agent relance une question ciblee sur le point conteste"). Simplification assumee : un seul
|
||||
* aller-retour (concept + reponse fournis ensemble), pas une sous-conversation a part, pour
|
||||
* rester compatible avec le pipeline vocal/texte unique (pas de sous-etat de routage dedie).
|
||||
*/
|
||||
async dispute(
|
||||
sessionId: number,
|
||||
userId: number,
|
||||
concept: string,
|
||||
answer: string,
|
||||
): Promise<StoredLevelAssessment> {
|
||||
const existing = await this.prisma.sessionLevelAssessment.findUnique({
|
||||
where: { sessionId },
|
||||
});
|
||||
if (!existing) {
|
||||
throw new ConflictException(
|
||||
'Aucun profil de niveau a contester pour cette session.',
|
||||
);
|
||||
}
|
||||
|
||||
const raw = await this.llm.chat(
|
||||
userId,
|
||||
[
|
||||
{
|
||||
role: 'system',
|
||||
content:
|
||||
'Tu evalues si la reponse suivante demontre une maitrise reelle du concept indique. ' +
|
||||
'Reponds UNIQUEMENT avec ce JSON strict : ' +
|
||||
'{"bucket": "mastered" | "gap" | "unknown", "description": "..." | null}. ' +
|
||||
'"description" est obligatoire si bucket="gap" (lacune precise observee), sinon null.',
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: JSON.stringify({ concept, answer }),
|
||||
},
|
||||
],
|
||||
{ jsonResponse: true },
|
||||
);
|
||||
|
||||
const bucket = this.parseDisputeBucket(raw);
|
||||
const mastered = new Set(existing.masteredConcepts as unknown as string[]);
|
||||
const gaps = (existing.gapConcepts as unknown as LevelGap[]).filter(
|
||||
(g) => g.concept !== concept,
|
||||
);
|
||||
const unknown = new Set(existing.unknownConcepts as unknown as string[]);
|
||||
mastered.delete(concept);
|
||||
unknown.delete(concept);
|
||||
|
||||
if (bucket.bucket === 'mastered') mastered.add(concept);
|
||||
else if (bucket.bucket === 'gap') {
|
||||
gaps.push({
|
||||
concept,
|
||||
description:
|
||||
bucket.description ?? 'Lacune confirmee a la contestation.',
|
||||
});
|
||||
} else unknown.add(concept);
|
||||
|
||||
return this.prisma.sessionLevelAssessment.update({
|
||||
where: { sessionId },
|
||||
data: {
|
||||
masteredConcepts: Array.from(mastered),
|
||||
gapConcepts: gaps as unknown as Prisma.InputJsonValue,
|
||||
unknownConcepts: Array.from(unknown),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private handleReply(sessionId: number, raw: string): LevelTurnResult {
|
||||
const parsed = this.parseAgentReply(raw);
|
||||
if (!parsed) return { reply: raw, done: false };
|
||||
|
||||
if (
|
||||
!parsed.done ||
|
||||
!parsed.mastered ||
|
||||
!parsed.gaps ||
|
||||
!parsed.unknown ||
|
||||
!parsed.overallLevel
|
||||
) {
|
||||
return { reply: parsed.message, done: false };
|
||||
}
|
||||
|
||||
const profile: LevelProfile = {
|
||||
mastered: parsed.mastered,
|
||||
gaps: parsed.gaps,
|
||||
unknown: parsed.unknown,
|
||||
overallLevel: parsed.overallLevel,
|
||||
};
|
||||
this.readyProfiles.set(sessionId, profile);
|
||||
return { reply: parsed.message, done: true, profile };
|
||||
}
|
||||
|
||||
private parseAgentReply(raw: string): {
|
||||
message: string;
|
||||
done: boolean;
|
||||
mastered?: string[];
|
||||
gaps?: LevelGap[];
|
||||
unknown?: string[];
|
||||
overallLevel?: OverallLevel;
|
||||
} | null {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as AgentJsonReply;
|
||||
if (typeof parsed.message !== 'string') return null;
|
||||
const done = parsed.done === true;
|
||||
if (!done) return { message: parsed.message, done: false };
|
||||
|
||||
if (
|
||||
!Array.isArray(parsed.mastered) ||
|
||||
!Array.isArray(parsed.gaps) ||
|
||||
!Array.isArray(parsed.unknown) ||
|
||||
!['beginner', 'intermediate', 'advanced'].includes(
|
||||
String(parsed.overall_level),
|
||||
)
|
||||
) {
|
||||
return { message: parsed.message, done: false };
|
||||
}
|
||||
|
||||
return {
|
||||
message: parsed.message,
|
||||
done: true,
|
||||
mastered: (parsed.mastered as unknown[]).map(String),
|
||||
gaps: (parsed.gaps as { concept?: unknown; description?: unknown }[])
|
||||
.filter(
|
||||
(g) =>
|
||||
typeof g.concept === 'string' &&
|
||||
typeof g.description === 'string',
|
||||
)
|
||||
.map((g) => ({
|
||||
concept: String(g.concept),
|
||||
description: String(g.description),
|
||||
})),
|
||||
unknown: (parsed.unknown as unknown[]).map(String),
|
||||
overallLevel: parsed.overall_level as OverallLevel,
|
||||
};
|
||||
} catch {
|
||||
this.logger.warn(
|
||||
`Reponse de l'Agent 3 non-JSON, affichee telle quelle: ${raw}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private parseDisputeBucket(raw: string): {
|
||||
bucket: 'mastered' | 'gap' | 'unknown';
|
||||
description: string | null;
|
||||
} {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as {
|
||||
bucket?: unknown;
|
||||
description?: unknown;
|
||||
};
|
||||
if (!['mastered', 'gap', 'unknown'].includes(String(parsed.bucket))) {
|
||||
return { bucket: 'gap', description: null };
|
||||
}
|
||||
return {
|
||||
bucket: parsed.bucket as 'mastered' | 'gap' | 'unknown',
|
||||
description:
|
||||
typeof parsed.description === 'string' ? parsed.description : null,
|
||||
};
|
||||
} catch {
|
||||
this.logger.warn(
|
||||
`Reponse de contestation non-JSON, classee "gap" par prudence: ${raw}`,
|
||||
);
|
||||
return { bucket: 'gap', description: null };
|
||||
}
|
||||
}
|
||||
|
||||
private extractExchanges(history: ChatMessage[]): {
|
||||
questionsAsked: string[];
|
||||
userAnswers: string[];
|
||||
} {
|
||||
const questionsAsked: string[] = [];
|
||||
const userAnswers: string[] = [];
|
||||
for (const message of history) {
|
||||
if (message.role === 'assistant') {
|
||||
try {
|
||||
const parsed = JSON.parse(message.content) as {
|
||||
message?: unknown;
|
||||
done?: unknown;
|
||||
};
|
||||
// La derniere reponse (done=true) est la phrase de transition du profil, pas une
|
||||
// question posee a l'utilisateur - elle n'a donc pas de reponse correspondante.
|
||||
if (typeof parsed.message === 'string' && parsed.done !== true) {
|
||||
questionsAsked.push(parsed.message);
|
||||
}
|
||||
} catch {
|
||||
// Reponse non-JSON ignoree pour l'historique des questions (deja geree en temps reel
|
||||
// par handleReply, qui a renvoye le texte brut tel quel a l'utilisateur).
|
||||
}
|
||||
} else if (message.role === 'user') {
|
||||
userAnswers.push(message.content);
|
||||
}
|
||||
}
|
||||
return { questionsAsked, userAnswers };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { OpenRouterService } from '../../llm/openrouter.service';
|
||||
import { MappingAgent } from './mapping.agent';
|
||||
|
||||
describe('MappingAgent', () => {
|
||||
let agent: MappingAgent;
|
||||
const chat = jest.fn();
|
||||
const findUnique = jest.fn();
|
||||
const create = jest.fn<Promise<unknown>, [{ data: { sessionId: number } }]>();
|
||||
const prisma = { sessionConceptMap: { findUnique, create } };
|
||||
|
||||
const validConceptMapJson = JSON.stringify({
|
||||
concepts: [
|
||||
{
|
||||
name: 'Facturation',
|
||||
level: 'beginner',
|
||||
prerequisites: [],
|
||||
can_do: 'être capable de facturer un client avec la bonne TVA',
|
||||
market_demand: 'high',
|
||||
sources: [
|
||||
{ title: 'URSSAF', source_tier: 1 },
|
||||
{ title: 'Guide expert-comptable', source_tier: 3 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'TVA intracommunautaire',
|
||||
level: 'intermediate',
|
||||
prerequisites: ['Facturation'],
|
||||
can_do: 'être capable de facturer un client europeen sans TVA',
|
||||
market_demand: 'medium',
|
||||
sources: [
|
||||
{ title: 'Impots.gouv.fr', source_tier: 1 },
|
||||
{ title: "Offre d'emploi comptable", source_tier: 4 },
|
||||
{ title: 'LinkedIn Learning', source_tier: 3 },
|
||||
],
|
||||
},
|
||||
],
|
||||
sources_count: 5,
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
MappingAgent,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: OpenRouterService, useValue: { chat } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
agent = module.get(MappingAgent);
|
||||
});
|
||||
|
||||
describe('runForSession()', () => {
|
||||
it('should do nothing if a concept map already exists for this session (idempotent)', async () => {
|
||||
findUnique.mockResolvedValueOnce({ id: 1 });
|
||||
|
||||
await agent.runForSession(1, 7, 'Facturation freelance');
|
||||
|
||||
expect(chat).not.toHaveBeenCalled();
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should request real web search (":online") and persist a valid concept map', async () => {
|
||||
findUnique.mockResolvedValueOnce(null);
|
||||
chat.mockResolvedValueOnce(validConceptMapJson);
|
||||
|
||||
await agent.runForSession(1, 7, 'Facturation freelance');
|
||||
|
||||
expect(chat).toHaveBeenCalledWith(
|
||||
7,
|
||||
expect.anything(),
|
||||
expect.objectContaining({ online: true }),
|
||||
);
|
||||
expect(create).toHaveBeenCalledTimes(1);
|
||||
expect(create.mock.calls[0][0].data.sessionId).toBe(1);
|
||||
});
|
||||
|
||||
it('should retry once then accept when the first attempt fails the measurable rules (e.g. too few sources)', async () => {
|
||||
findUnique.mockResolvedValueOnce(null);
|
||||
chat
|
||||
.mockResolvedValueOnce(
|
||||
JSON.stringify({
|
||||
concepts: [
|
||||
{
|
||||
name: 'Facturation',
|
||||
level: 'beginner',
|
||||
prerequisites: [],
|
||||
can_do: 'être capable de facturer',
|
||||
sources: [{ title: 'Seule source', source_tier: 1 }],
|
||||
},
|
||||
],
|
||||
sources_count: 1,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(validConceptMapJson);
|
||||
|
||||
await agent.runForSession(1, 7, 'Facturation freelance');
|
||||
|
||||
expect(chat).toHaveBeenCalledTimes(2);
|
||||
expect(create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should throw when the concept map still fails after the retry', async () => {
|
||||
findUnique.mockResolvedValueOnce(null);
|
||||
chat.mockResolvedValue('reponse non-JSON');
|
||||
|
||||
await expect(
|
||||
agent.runForSession(1, 7, 'Facturation freelance'),
|
||||
).rejects.toThrow(/carte conforme/);
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should reject a concept using forbidden wording ("comprendre"/"savoir") even with enough sources', async () => {
|
||||
findUnique.mockResolvedValueOnce(null);
|
||||
const invalidWording = JSON.stringify({
|
||||
concepts: [
|
||||
{
|
||||
name: 'Facturation',
|
||||
level: 'beginner',
|
||||
prerequisites: [],
|
||||
can_do: 'comprendre la facturation',
|
||||
sources: [
|
||||
{ title: 'A', source_tier: 1 },
|
||||
{ title: 'B', source_tier: 3 },
|
||||
],
|
||||
},
|
||||
],
|
||||
sources_count: 5,
|
||||
});
|
||||
chat.mockResolvedValue(invalidWording);
|
||||
|
||||
await expect(
|
||||
agent.runForSession(1, 7, 'Facturation freelance'),
|
||||
).rejects.toThrow(/carte conforme/);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { OpenRouterService } from '../../llm/openrouter.service';
|
||||
import {
|
||||
MAPPING_JSON_CONTRACT,
|
||||
MAPPING_PROMPT,
|
||||
} from '../prompts/mapping.prompt';
|
||||
|
||||
export interface ConceptSource {
|
||||
title: string;
|
||||
sourceTier: 1 | 2 | 3 | 4;
|
||||
}
|
||||
|
||||
export interface Concept {
|
||||
name: string;
|
||||
level: 'beginner' | 'intermediate' | 'advanced';
|
||||
prerequisites: string[];
|
||||
canDo: string;
|
||||
marketDemand: 'low' | 'medium' | 'high';
|
||||
sources: ConceptSource[];
|
||||
}
|
||||
|
||||
export interface ConceptMapResult {
|
||||
concepts: Concept[];
|
||||
sourcesCount: number;
|
||||
}
|
||||
|
||||
interface RawConceptSource {
|
||||
title?: unknown;
|
||||
source_tier?: unknown;
|
||||
}
|
||||
|
||||
interface RawConcept {
|
||||
name?: unknown;
|
||||
level?: unknown;
|
||||
prerequisites?: unknown;
|
||||
can_do?: unknown;
|
||||
market_demand?: unknown;
|
||||
sources?: unknown;
|
||||
}
|
||||
|
||||
interface RawConceptMap {
|
||||
concepts?: unknown;
|
||||
sources_count?: unknown;
|
||||
}
|
||||
|
||||
const SYSTEM_PROMPT_TEMPLATE = `${MAPPING_PROMPT}\n\n${MAPPING_JSON_CONTRACT}`;
|
||||
const MIN_SOURCES_COUNT = 5;
|
||||
const MAX_VALIDATION_RETRIES = 1;
|
||||
const CAN_DO_PATTERN = /etre capable de|être capable de/i;
|
||||
const FORBIDDEN_WORDING_PATTERN = /\b(comprendre|savoir)\b/i;
|
||||
|
||||
/**
|
||||
* Agent 2 du pipeline (docs/Max_System_Prompt.md + docs/Max Refonte Coach Freelance.md) :
|
||||
* cartographie des concepts cles, un seul appel LLM avec recherche web reelle (OpenRouter
|
||||
* ":online", voir openrouter.service.ts) - aucune conversation, aucun tour utilisateur. Pas de
|
||||
* personnalite Max ici (voir buildAgentPrompt) : personne n'entend cet agent, c'est un producteur
|
||||
* de donnees pur, meme choix que intent-router.prompt.ts.
|
||||
*/
|
||||
@Injectable()
|
||||
export class MappingAgent {
|
||||
private readonly logger = new Logger(MappingAgent.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly llm: OpenRouterService,
|
||||
) {}
|
||||
|
||||
async runForSession(
|
||||
sessionId: number,
|
||||
userId: number,
|
||||
objectiveSummary: string,
|
||||
): Promise<void> {
|
||||
const existing = await this.prisma.sessionConceptMap.findUnique({
|
||||
where: { sessionId },
|
||||
});
|
||||
if (existing) return;
|
||||
|
||||
const prompt = SYSTEM_PROMPT_TEMPLATE.replace(
|
||||
'[OBJECTIF_INJECTÉ_PAR_LE_BACKEND]',
|
||||
objectiveSummary,
|
||||
);
|
||||
|
||||
let result = await this.requestAndValidate(userId, prompt);
|
||||
for (
|
||||
let attempt = 0;
|
||||
!result && attempt < MAX_VALIDATION_RETRIES;
|
||||
attempt++
|
||||
) {
|
||||
this.logger.warn(
|
||||
`Carte des concepts non conforme aux regles mesurables, nouvelle tentative (${attempt + 1})`,
|
||||
);
|
||||
result = await this.requestAndValidate(userId, prompt);
|
||||
}
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
"L'Agent 2 (Cartographie) n'a pas produit de carte conforme apres relance.",
|
||||
);
|
||||
}
|
||||
|
||||
const sourcesUsed = this.flattenSources(result.concepts);
|
||||
await this.prisma.sessionConceptMap.create({
|
||||
data: {
|
||||
sessionId,
|
||||
concepts: result.concepts as unknown as Prisma.InputJsonValue,
|
||||
sourcesUsed: sourcesUsed as unknown as Prisma.InputJsonValue,
|
||||
completedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async requestAndValidate(
|
||||
userId: number,
|
||||
prompt: string,
|
||||
): Promise<ConceptMapResult | null> {
|
||||
const raw = await this.llm.chat(
|
||||
userId,
|
||||
[{ role: 'system', content: prompt }],
|
||||
{
|
||||
jsonResponse: true,
|
||||
online: true,
|
||||
},
|
||||
);
|
||||
const parsed = this.parse(raw);
|
||||
if (!parsed) return null;
|
||||
if (!this.passesMeasurableRules(parsed)) return null;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private parse(raw: string): ConceptMapResult | null {
|
||||
try {
|
||||
const data = JSON.parse(raw) as RawConceptMap;
|
||||
if (!Array.isArray(data.concepts)) return null;
|
||||
|
||||
const concepts: Concept[] = [];
|
||||
for (const raw_ of data.concepts as RawConcept[]) {
|
||||
const concept = this.parseConcept(raw_);
|
||||
if (!concept) return null;
|
||||
concepts.push(concept);
|
||||
}
|
||||
if (concepts.length === 0) return null;
|
||||
|
||||
const sourcesCount =
|
||||
Number(data.sources_count) || this.flattenSources(concepts).length;
|
||||
return { concepts, sourcesCount };
|
||||
} catch {
|
||||
this.logger.warn(`Carte des concepts non-JSON, rejetee: ${raw}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private parseConcept(raw: RawConcept): Concept | null {
|
||||
if (typeof raw.name !== 'string' || typeof raw.can_do !== 'string')
|
||||
return null;
|
||||
if (!['beginner', 'intermediate', 'advanced'].includes(String(raw.level))) {
|
||||
return null;
|
||||
}
|
||||
if (!Array.isArray(raw.sources) || raw.sources.length === 0) return null;
|
||||
|
||||
const sources: ConceptSource[] = [];
|
||||
for (const rawSource of raw.sources as RawConceptSource[]) {
|
||||
if (typeof rawSource.title !== 'string') return null;
|
||||
const tier = Number(rawSource.source_tier);
|
||||
sources.push({
|
||||
title: rawSource.title,
|
||||
sourceTier: ([1, 2, 3, 4].includes(tier) ? tier : 3) as 1 | 2 | 3 | 4,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
name: raw.name,
|
||||
level: raw.level as Concept['level'],
|
||||
prerequisites: Array.isArray(raw.prerequisites)
|
||||
? raw.prerequisites.map(String)
|
||||
: [],
|
||||
canDo: raw.can_do,
|
||||
marketDemand: (['low', 'medium', 'high'].includes(
|
||||
String(raw.market_demand),
|
||||
)
|
||||
? raw.market_demand
|
||||
: 'medium') as Concept['marketDemand'],
|
||||
sources,
|
||||
};
|
||||
}
|
||||
|
||||
/** Regles mesurables de docs/Max Refonte Coach Freelance.md : >=5 sources au total, "etre
|
||||
* capable de" obligatoire (0 "comprendre"/"savoir" tolere), >=2 sources par concept cle. */
|
||||
private passesMeasurableRules(result: ConceptMapResult): boolean {
|
||||
if (result.sourcesCount < MIN_SOURCES_COUNT) return false;
|
||||
for (const concept of result.concepts) {
|
||||
if (!CAN_DO_PATTERN.test(concept.canDo)) return false;
|
||||
if (FORBIDDEN_WORDING_PATTERN.test(concept.canDo)) return false;
|
||||
if (concept.sources.length < 2) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private flattenSources(concepts: Concept[]): ConceptSource[] {
|
||||
const deduped = new Map<string, ConceptSource>();
|
||||
for (const concept of concepts) {
|
||||
for (const source of concept.sources) {
|
||||
deduped.set(source.title, source);
|
||||
}
|
||||
}
|
||||
return Array.from(deduped.values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { OpenRouterService } from '../../llm/openrouter.service';
|
||||
import { ResearchAgent } from './research.agent';
|
||||
|
||||
describe('ResearchAgent', () => {
|
||||
let agent: ResearchAgent;
|
||||
const chat = jest.fn();
|
||||
const findUniqueResearch = jest.fn();
|
||||
const create = jest.fn<
|
||||
Promise<unknown>,
|
||||
[
|
||||
{
|
||||
data: {
|
||||
sessionId: number;
|
||||
sourcesCount: number;
|
||||
corpus: { failedSubtopics: string[] };
|
||||
};
|
||||
},
|
||||
]
|
||||
>();
|
||||
const findUniqueConceptMap = jest.fn();
|
||||
const findUniqueLevel = jest.fn();
|
||||
const prisma = {
|
||||
sessionResearch: { findUnique: findUniqueResearch, create },
|
||||
sessionConceptMap: { findUnique: findUniqueConceptMap },
|
||||
sessionLevelAssessment: { findUnique: findUniqueLevel },
|
||||
};
|
||||
|
||||
const conceptMap = {
|
||||
concepts: [{ name: 'Facturation' }, { name: 'TVA' }],
|
||||
};
|
||||
const levelAssessment = {
|
||||
masteredConcepts: ['Facturation'],
|
||||
gapConcepts: [{ concept: 'TVA', description: 'confond les taux' }],
|
||||
unknownConcepts: [],
|
||||
};
|
||||
|
||||
function subtopicJson(subtopic: string): string {
|
||||
return JSON.stringify({
|
||||
subtopic,
|
||||
summary: `Resume sur ${subtopic}`,
|
||||
key_points: ['point 1'],
|
||||
examples: ['exemple 1'],
|
||||
common_mistakes: ['erreur 1'],
|
||||
sources: [
|
||||
{ title: 'Source A', url: 'https://a.example', level: 1 },
|
||||
{ title: 'Source B', url: 'https://b.example', level: 4 },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
ResearchAgent,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: OpenRouterService, useValue: { chat } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
agent = module.get(ResearchAgent);
|
||||
});
|
||||
|
||||
describe('runForSession()', () => {
|
||||
it('should do nothing if research already exists for this session (idempotent)', async () => {
|
||||
findUniqueResearch.mockResolvedValueOnce({ id: 1 });
|
||||
|
||||
await agent.runForSession(1, 7);
|
||||
|
||||
expect(chat).not.toHaveBeenCalled();
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should throw when the concept map or level assessment is missing', async () => {
|
||||
findUniqueResearch.mockResolvedValueOnce(null);
|
||||
findUniqueConceptMap.mockResolvedValueOnce(null);
|
||||
findUniqueLevel.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(agent.runForSession(1, 7)).rejects.toThrow(
|
||||
/carte des concepts ou profil de niveau manquant/,
|
||||
);
|
||||
});
|
||||
|
||||
it('should research every concept in parallel with online search and persist the aggregated corpus', async () => {
|
||||
findUniqueResearch.mockResolvedValueOnce(null);
|
||||
findUniqueConceptMap.mockResolvedValueOnce(conceptMap);
|
||||
findUniqueLevel.mockResolvedValueOnce(levelAssessment);
|
||||
chat
|
||||
.mockResolvedValueOnce(subtopicJson('Facturation'))
|
||||
.mockResolvedValueOnce(subtopicJson('TVA'));
|
||||
|
||||
await agent.runForSession(1, 7);
|
||||
|
||||
expect(chat).toHaveBeenCalledTimes(2);
|
||||
expect(chat).toHaveBeenCalledWith(
|
||||
7,
|
||||
expect.anything(),
|
||||
expect.objectContaining({ online: true }),
|
||||
);
|
||||
expect(create).toHaveBeenCalledTimes(1);
|
||||
expect(create.mock.calls[0][0].data.sessionId).toBe(1);
|
||||
expect(create.mock.calls[0][0].data.sourcesCount).toBe(4);
|
||||
});
|
||||
|
||||
it('should not fail the whole batch when one subtopic fails, and record it as failed', async () => {
|
||||
findUniqueResearch.mockResolvedValueOnce(null);
|
||||
findUniqueConceptMap.mockResolvedValueOnce(conceptMap);
|
||||
findUniqueLevel.mockResolvedValueOnce(levelAssessment);
|
||||
chat
|
||||
.mockResolvedValueOnce(subtopicJson('Facturation'))
|
||||
.mockRejectedValueOnce(new Error('OpenRouter indisponible'));
|
||||
|
||||
await agent.runForSession(1, 7);
|
||||
|
||||
expect(create).toHaveBeenCalledTimes(1);
|
||||
expect(create.mock.calls[0][0].data.corpus.failedSubtopics).toEqual([
|
||||
'TVA',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should throw when every subtopic fails', async () => {
|
||||
findUniqueResearch.mockResolvedValueOnce(null);
|
||||
findUniqueConceptMap.mockResolvedValueOnce(conceptMap);
|
||||
findUniqueLevel.mockResolvedValueOnce(levelAssessment);
|
||||
chat.mockResolvedValue('reponse non-JSON');
|
||||
|
||||
await expect(agent.runForSession(1, 7)).rejects.toThrow(
|
||||
/n'a reussi aucun sous-theme/,
|
||||
);
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { OpenRouterService } from '../../llm/openrouter.service';
|
||||
import { buildResearchPrompt } from '../prompts/research.prompt';
|
||||
import { Concept } from './mapping.agent';
|
||||
import { LevelGap } from './level.agent';
|
||||
|
||||
export interface ResearchSource {
|
||||
title: string;
|
||||
url: string;
|
||||
level: 1 | 2 | 3 | 4;
|
||||
}
|
||||
|
||||
export interface SubtopicResearch {
|
||||
subtopic: string;
|
||||
summary: string;
|
||||
keyPoints: string[];
|
||||
examples: string[];
|
||||
commonMistakes: string[];
|
||||
sources: ResearchSource[];
|
||||
}
|
||||
|
||||
export interface ResearchCorpus {
|
||||
subtopics: SubtopicResearch[];
|
||||
failedSubtopics: string[];
|
||||
}
|
||||
|
||||
interface RawSubtopicResearch {
|
||||
summary?: unknown;
|
||||
key_points?: unknown;
|
||||
examples?: unknown;
|
||||
common_mistakes?: unknown;
|
||||
sources?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent 4 du pipeline (docs/Max_System_Prompt.md + docs/Max Refonte Coach Freelance.md) : un
|
||||
* appel LLM en parallele par concept de la carte (Agent 2), recherche web reelle (":online"),
|
||||
* calibre sur le profil de niveau (Agent 3). Comme MappingAgent, aucune personnalite Max ici :
|
||||
* producteur de donnees pur, personne n'entend cet agent.
|
||||
*/
|
||||
@Injectable()
|
||||
export class ResearchAgent {
|
||||
private readonly logger = new Logger(ResearchAgent.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly llm: OpenRouterService,
|
||||
) {}
|
||||
|
||||
async runForSession(sessionId: number, userId: number): Promise<void> {
|
||||
const existing = await this.prisma.sessionResearch.findUnique({
|
||||
where: { sessionId },
|
||||
});
|
||||
if (existing) return;
|
||||
|
||||
const conceptMap = await this.prisma.sessionConceptMap.findUnique({
|
||||
where: { sessionId },
|
||||
});
|
||||
const levelAssessment = await this.prisma.sessionLevelAssessment.findUnique(
|
||||
{
|
||||
where: { sessionId },
|
||||
},
|
||||
);
|
||||
if (!conceptMap || !levelAssessment) {
|
||||
throw new Error(
|
||||
"Impossible de lancer l'Agent 4 : carte des concepts ou profil de niveau manquant pour cette session.",
|
||||
);
|
||||
}
|
||||
|
||||
const concepts = conceptMap.concepts as unknown as Concept[];
|
||||
const mastered = new Set(
|
||||
levelAssessment.masteredConcepts as unknown as string[],
|
||||
);
|
||||
const gaps = new Set(
|
||||
(levelAssessment.gapConcepts as unknown as LevelGap[]).map(
|
||||
(g) => g.concept,
|
||||
),
|
||||
);
|
||||
|
||||
// Chaque job attrape sa propre erreur et renvoie son nom de concept avec le resultat (ou null)
|
||||
// plutot que de laisser Promise.allSettled rejeter : evite toute correlation par index entre
|
||||
// deux tableaux separes pour retrouver quel concept a echoue.
|
||||
const outcomes = await Promise.all(
|
||||
concepts.map(async (concept) => {
|
||||
try {
|
||||
const research = await this.researchSubtopic(
|
||||
userId,
|
||||
concept.name,
|
||||
this.calibrateLevel(concept.name, mastered, gaps),
|
||||
);
|
||||
return { name: concept.name, research };
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Recherche du sous-theme "${concept.name}" echouee: ${String(error)}`,
|
||||
);
|
||||
return { name: concept.name, research: null };
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const subtopics: SubtopicResearch[] = [];
|
||||
const failedSubtopics: string[] = [];
|
||||
for (const outcome of outcomes) {
|
||||
if (outcome.research) {
|
||||
subtopics.push(outcome.research);
|
||||
} else {
|
||||
failedSubtopics.push(outcome.name);
|
||||
}
|
||||
}
|
||||
|
||||
if (subtopics.length === 0) {
|
||||
throw new Error(
|
||||
"L'Agent 4 (Recherche Approfondie) n'a reussi aucun sous-theme.",
|
||||
);
|
||||
}
|
||||
|
||||
const corpus: ResearchCorpus = { subtopics, failedSubtopics };
|
||||
const sourcesCount = subtopics.reduce(
|
||||
(sum, s) => sum + s.sources.length,
|
||||
0,
|
||||
);
|
||||
|
||||
await this.prisma.sessionResearch.create({
|
||||
data: {
|
||||
sessionId,
|
||||
corpus: corpus as unknown as Prisma.InputJsonValue,
|
||||
subtopicsCovered: subtopics.map((s) => s.subtopic),
|
||||
sourcesCount,
|
||||
completedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Calibrage par le niveau (docs/Max Refonte Coach Freelance.md) : mastered -> sources avancees
|
||||
* pour aller au-dela, gap -> consolidation ciblee, unknown -> progression depuis les
|
||||
* fondamentaux. */
|
||||
private calibrateLevel(
|
||||
name: string,
|
||||
mastered: Set<string>,
|
||||
gaps: Set<string>,
|
||||
): 'beginner' | 'intermediate' | 'advanced' {
|
||||
if (mastered.has(name)) return 'advanced';
|
||||
if (gaps.has(name)) return 'intermediate';
|
||||
return 'beginner';
|
||||
}
|
||||
|
||||
private async researchSubtopic(
|
||||
userId: number,
|
||||
subtopic: string,
|
||||
level: 'beginner' | 'intermediate' | 'advanced',
|
||||
): Promise<SubtopicResearch | null> {
|
||||
const raw = await this.llm.chat(
|
||||
userId,
|
||||
[{ role: 'system', content: buildResearchPrompt(subtopic, level) }],
|
||||
{ jsonResponse: true, online: true },
|
||||
);
|
||||
return this.parse(raw, subtopic);
|
||||
}
|
||||
|
||||
private parse(raw: string, subtopic: string): SubtopicResearch | null {
|
||||
try {
|
||||
const data = JSON.parse(raw) as RawSubtopicResearch;
|
||||
if (typeof data.summary !== 'string') return null;
|
||||
if (!Array.isArray(data.sources) || data.sources.length === 0)
|
||||
return null;
|
||||
|
||||
const sources: ResearchSource[] = [];
|
||||
for (const rawSource of data.sources as {
|
||||
title?: unknown;
|
||||
url?: unknown;
|
||||
level?: unknown;
|
||||
}[]) {
|
||||
if (
|
||||
typeof rawSource.title !== 'string' ||
|
||||
typeof rawSource.url !== 'string'
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const level = Number(rawSource.level);
|
||||
sources.push({
|
||||
title: rawSource.title,
|
||||
url: rawSource.url,
|
||||
level: ([1, 2, 3, 4].includes(level) ? level : 3) as 1 | 2 | 3 | 4,
|
||||
});
|
||||
}
|
||||
if (sources.length === 0) return null;
|
||||
|
||||
return {
|
||||
subtopic,
|
||||
summary: data.summary,
|
||||
keyPoints: Array.isArray(data.key_points)
|
||||
? data.key_points.map(String)
|
||||
: [],
|
||||
examples: Array.isArray(data.examples) ? data.examples.map(String) : [],
|
||||
commonMistakes: Array.isArray(data.common_mistakes)
|
||||
? data.common_mistakes.map(String)
|
||||
: [],
|
||||
sources,
|
||||
};
|
||||
} catch {
|
||||
this.logger.warn(
|
||||
`Recherche du sous-theme "${subtopic}" non-JSON, rejetee: ${raw}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user