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:
william
2026-11-02 09:47:53 +01:00
co-authored by Claude Sonnet 5
parent b5cdc30207
commit 5c00976e8f
10 changed files with 1415 additions and 0 deletions
@@ -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());
}
}