feat(sessions): implement Agent 1 (Objectif) of the coach pipeline
Add the sessions module (create/fetch session, Agent 1 conversation and confirmation endpoints, all JWT-protected) and a reusable OpenRouter client with DeepSeek/Qwen fallback + backoff on rate-limit/timeout. Agent 1 runs a Socratic dialogue to capture the 3 mandatory pillars (subject, professional goal, duration) and enforces two guardrail levels before any explicit user confirmation: level 1 is hard-coded length/format rules (objective-guardrails.ts), level 2 is an LLM coherence score across 3 dimensions (reject below 0.6). The objective is only persisted to session_objective, and the session only moves to objective_validated, once the user explicitly confirms via POST /sessions/:id/objective/confirm - never on the LLM's say-so alone. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
b321dff3bd
commit
bae5ace70c
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ApiKeysModule } from '../api-keys/api-keys.module';
|
||||
import { OpenRouterService } from './openrouter.service';
|
||||
|
||||
@Module({
|
||||
imports: [ApiKeysModule],
|
||||
providers: [OpenRouterService],
|
||||
exports: [OpenRouterService],
|
||||
})
|
||||
export class LlmModule {}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||
import { ApiError } from '../common/errors/api-error';
|
||||
import { OpenRouterService } from './openrouter.service';
|
||||
|
||||
describe('OpenRouterService', () => {
|
||||
let service: OpenRouterService;
|
||||
const getDecryptedValue = jest.fn(() => Promise.resolve('sk-or-v1-test'));
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
jest.useFakeTimers();
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
OpenRouterService,
|
||||
{ provide: ApiKeysService, useValue: { getDecryptedValue } },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get(OpenRouterService);
|
||||
jest.spyOn(global, 'fetch');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
function mockFetchOnce(impl: () => Promise<Response> | Response): void {
|
||||
(global.fetch as jest.Mock).mockImplementationOnce(impl);
|
||||
}
|
||||
|
||||
describe('chat()', () => {
|
||||
it('should return assistant message when the API responds successfully', async () => {
|
||||
mockFetchOnce(
|
||||
() =>
|
||||
new Response(
|
||||
JSON.stringify({ choices: [{ message: { content: 'Bonjour' } }] }),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
|
||||
const result = await service.chat(1, [
|
||||
{ role: 'user', content: 'Salut' },
|
||||
]);
|
||||
|
||||
expect(result).toBe('Bonjour');
|
||||
expect(getDecryptedValue).toHaveBeenCalledWith(1, 'openrouter_api_key');
|
||||
});
|
||||
|
||||
it('should fall back to Qwen when the primary model errors', async () => {
|
||||
mockFetchOnce(() => new Response('erreur serveur', { status: 500 }));
|
||||
mockFetchOnce(
|
||||
() =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
choices: [{ message: { content: 'Reponse secours' } }],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
|
||||
const result = await service.chat(1, [
|
||||
{ role: 'user', content: 'Salut' },
|
||||
]);
|
||||
|
||||
expect(result).toBe('Reponse secours');
|
||||
expect(global.fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('should retry with backoff on 429 before succeeding', async () => {
|
||||
mockFetchOnce(() => new Response('rate limited', { status: 429 }));
|
||||
mockFetchOnce(
|
||||
() =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
choices: [{ message: { content: 'OK apres attente' } }],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
|
||||
const promise = service.chat(1, [{ role: 'user', content: 'Salut' }]);
|
||||
await jest.runAllTimersAsync();
|
||||
const result = await promise;
|
||||
|
||||
expect(result).toBe('OK apres attente');
|
||||
});
|
||||
|
||||
it('should throw ApiError when every model is unreachable', async () => {
|
||||
mockFetchOnce(() => Promise.reject(new Error('network down')));
|
||||
mockFetchOnce(() => Promise.reject(new Error('network down')));
|
||||
mockFetchOnce(() => Promise.reject(new Error('network down')));
|
||||
mockFetchOnce(() => Promise.reject(new Error('network down')));
|
||||
|
||||
await expect(
|
||||
service.chat(1, [{ role: 'user', content: 'Salut' }]),
|
||||
).rejects.toThrow(ApiError);
|
||||
});
|
||||
|
||||
it('should throw ApiError when the response is HTTP 200 without choices', async () => {
|
||||
mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 }));
|
||||
mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 }));
|
||||
mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 }));
|
||||
mockFetchOnce(() => new Response(JSON.stringify({}), { status: 200 }));
|
||||
|
||||
await expect(
|
||||
service.chat(1, [{ role: 'user', content: 'Salut' }]),
|
||||
).rejects.toThrow(/malformee/);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||
import { ApiError } from '../common/errors/api-error';
|
||||
|
||||
export interface ChatMessage {
|
||||
role: 'system' | 'user' | 'assistant';
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface OpenRouterChoice {
|
||||
message?: { content?: string };
|
||||
}
|
||||
|
||||
interface OpenRouterResponseBody {
|
||||
choices?: OpenRouterChoice[];
|
||||
error?: { message?: string };
|
||||
}
|
||||
|
||||
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';
|
||||
const PRIMARY_MODEL = 'deepseek/deepseek-chat';
|
||||
const FALLBACK_MODEL = 'qwen/qwen-2.5-72b-instruct';
|
||||
const OPENROUTER_KEY_SERVICE = 'openrouter_api_key';
|
||||
const MAX_ATTEMPTS = 4;
|
||||
const RATE_LIMITED_STATUSES = new Set([429, 504]);
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* Client OpenRouter avec bascule DeepSeek -> Qwen (voir CLAUDE.md section 2) : jusqu'a
|
||||
* MAX_ATTEMPTS tentatives en alternant les deux modeles, avec backoff exponentiel sur
|
||||
* rate-limit (429) et timeout (504). Le meme historique de messages est reutilise quel que
|
||||
* soit le modele qui finit par repondre, pour que la bascule reste transparente.
|
||||
*/
|
||||
@Injectable()
|
||||
export class OpenRouterService {
|
||||
private readonly logger = new Logger(OpenRouterService.name);
|
||||
|
||||
constructor(private readonly apiKeysService: ApiKeysService) {}
|
||||
|
||||
async chat(
|
||||
userId: number,
|
||||
messages: ChatMessage[],
|
||||
options: { jsonResponse?: boolean } = {},
|
||||
): Promise<string> {
|
||||
const apiKey = await this.apiKeysService.getDecryptedValue(
|
||||
userId,
|
||||
OPENROUTER_KEY_SERVICE,
|
||||
);
|
||||
|
||||
let lastError = 'raison inconnue';
|
||||
|
||||
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
||||
const model = attempt % 2 === 0 ? PRIMARY_MODEL : FALLBACK_MODEL;
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(OPENROUTER_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages,
|
||||
...(options.jsonResponse
|
||||
? { response_format: { type: 'json_object' } }
|
||||
: {}),
|
||||
}),
|
||||
});
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error.message : String(error);
|
||||
this.logger.warn(`${model} injoignable (${lastError})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (RATE_LIMITED_STATUSES.has(response.status)) {
|
||||
lastError = `${response.status}: rate-limit ou timeout`;
|
||||
this.logger.warn(`${model} ${lastError}, nouvelle tentative`);
|
||||
await delay(2 ** attempt * 250);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
lastError = `${response.status}: ${await response.text()}`;
|
||||
this.logger.warn(`${model} a renvoye une erreur (${lastError})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const parsed = (await response.json()) as OpenRouterResponseBody;
|
||||
const content = parsed.choices?.[0]?.message?.content;
|
||||
if (!content) {
|
||||
lastError = `reponse malformee (${parsed.error?.message ?? 'choices manquant'})`;
|
||||
this.logger.warn(`${model}: ${lastError}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
throw new ApiError(
|
||||
`Aucun modele OpenRouter n'a pu repondre (${lastError})`,
|
||||
'openrouter',
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user