feat(prompts): extract system prompts per docs/Max_System_Prompt.md, add intent router

Add PERSONALITY_PROMPT/buildAgentPrompt (base.prompt.ts) and Agent 1's
role prompt (objective.prompt.ts), replacing objective.agent.ts's
inline ad-hoc prompt string with the documented composition. The JSON
output contract needed by ObjectiveValidationCard/guardrails is kept
as a separate, clearly-labeled technical addition on top of the
document's conversational spec.

Add IntentRouterAgent, the pipeline's entry-gate classifier (learn vs
chat) run before any session exists, per the document's routing flow.
Defaults to "chat" on any ambiguous or malformed output, never creating
a session by mistake.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-11-01 08:53:30 +01:00
co-authored by Claude Sonnet 5
parent c1440f83c0
commit dc368a32f0
6 changed files with 251 additions and 17 deletions
@@ -0,0 +1,66 @@
import { Test, TestingModule } from '@nestjs/testing';
import { OpenRouterService } from '../../llm/openrouter.service';
import { IntentRouterAgent } from './intent-router.agent';
describe('IntentRouterAgent', () => {
let agent: IntentRouterAgent;
const chat = jest.fn();
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
IntentRouterAgent,
{ provide: OpenRouterService, useValue: { chat } },
],
}).compile();
agent = module.get(IntentRouterAgent);
});
describe('analyze()', () => {
it('should return learn with the extracted subject when the model detects a learning intent', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({ intent: 'learn', subject: 'React' }),
);
const result = await agent.analyze(7, 'Apprends-moi React');
expect(result).toEqual({ intent: 'learn', subject: 'React' });
});
it('should return chat with a null subject when the model detects a chat intent', async () => {
chat.mockResolvedValueOnce(
JSON.stringify({ intent: 'chat', subject: null }),
);
const result = await agent.analyze(7, 'Salut Max ça roule ?');
expect(result).toEqual({ intent: 'chat', subject: null });
});
it('should default to chat when the model response is not valid JSON', async () => {
chat.mockResolvedValueOnce('je ne sais pas');
const result = await agent.analyze(7, 'message ambigu');
expect(result).toEqual({ intent: 'chat', subject: null });
});
it('should default to chat when "intent" is neither "learn" nor "chat"', async () => {
chat.mockResolvedValueOnce(JSON.stringify({ intent: 'autre chose' }));
const result = await agent.analyze(7, 'message');
expect(result).toEqual({ intent: 'chat', subject: null });
});
it('should default to a null subject when "learn" is detected but subject is not a string', async () => {
chat.mockResolvedValueOnce(JSON.stringify({ intent: 'learn' }));
const result = await agent.analyze(7, 'message');
expect(result).toEqual({ intent: 'learn', subject: null });
});
});
});
@@ -0,0 +1,50 @@
import { Injectable, Logger } from '@nestjs/common';
import { OpenRouterService } from '../../llm/openrouter.service';
import { buildIntentRouterPrompt } from '../prompts/intent-router.prompt';
export interface IntentRouterResult {
intent: 'learn' | 'chat';
subject: string | null;
}
interface IntentRouterJsonReply {
intent?: unknown;
subject?: unknown;
}
/**
* Porte d'entree du pipeline (docs/Max_System_Prompt.md) : classifie un message quand aucune
* session active n'existe. "En cas de doute -> chat" est applique a la fois par le prompt et par
* ce code : toute reponse non reconnue ou non-JSON est traitee comme "chat", jamais "learn" par
* defaut, pour ne jamais creer de session par erreur.
*/
@Injectable()
export class IntentRouterAgent {
private readonly logger = new Logger(IntentRouterAgent.name);
constructor(private readonly llm: OpenRouterService) {}
async analyze(userId: number, message: string): Promise<IntentRouterResult> {
const raw = await this.llm.chat(
userId,
[{ role: 'system', content: buildIntentRouterPrompt(message) }],
{ jsonResponse: true },
);
try {
const parsed = JSON.parse(raw) as IntentRouterJsonReply;
if (parsed.intent === 'learn') {
return {
intent: 'learn',
subject: typeof parsed.subject === 'string' ? parsed.subject : null,
};
}
return { intent: 'chat', subject: null };
} catch {
this.logger.warn(
`Reponse du routeur d'intention non-JSON, traitee comme "chat" par prudence: ${raw}`,
);
return { intent: 'chat', subject: null };
}
}
}
+8 -17
View File
@@ -1,6 +1,11 @@
import { ConflictException, Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { ChatMessage, OpenRouterService } from '../../llm/openrouter.service';
import { buildAgentPrompt } from '../prompts/base.prompt';
import {
OBJECTIVE_JSON_CONTRACT,
OBJECTIVE_PROMPT,
} from '../prompts/objective.prompt';
import {
checkLevel1Guardrails,
GuardrailFailure,
@@ -39,23 +44,9 @@ interface CoherenceScore {
const COHERENCE_THRESHOLD = 0.6;
const SYSTEM_PROMPT = `Tu es Max, un coach de formation pour freelances. Ton seul objectif dans cet
echange est de reveler et faire formuler par l'utilisateur, par un dialogue socratique (des
questions, jamais un formulaire), un objectif de formation precis compose de 3 piliers
obligatoires :
1. subject : le sujet concret a apprendre (jamais un terme generique isole comme "Excel" ou
"marketing" : il doit designer une competence precise, utilisable dans une mission reelle).
2. professionalGoal : ce que l'utilisateur pourra faire professionnellement une fois la
formation terminee (une situation concrete de mission ou de client, pas juste "progresser").
3. duration : le temps que l'utilisateur veut y consacrer, entre 1 heure et 12 semaines, dans un
format court ("10 heures", "2 semaines", "1 mois").
Pose une question a la fois, rebondis sur les reponses de l'utilisateur, et ne propose
"readyToConfirm": true que lorsque les 3 piliers sont clairement etablis ET que tu as deja
presente un recapitulatif dans "message" en demandant explicitement a l'utilisateur de confirmer.
Reponds TOUJOURS avec un objet JSON strict, sans texte autour, de la forme :
{"message": "...", "subject": "..." | null, "professionalGoal": "..." | null, "duration": "..." | null, "readyToConfirm": true | false}`;
const SYSTEM_PROMPT = buildAgentPrompt(
`${OBJECTIVE_PROMPT}\n\n${OBJECTIVE_JSON_CONTRACT}`,
);
const COHERENCE_SYSTEM_PROMPT = `Tu evalues la coherence d'un objectif de formation freelance
compose de 3 champs (subject, professionalGoal, duration). Note chaque dimension entre 0 et 1 :