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 { 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, gaps: Set, ): '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 { 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; } } }