diff --git a/backend/.env.example b/backend/.env.example index 46001da..bff0ab6 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -25,4 +25,6 @@ RATE_LIMIT_WINDOW=60000 # OLLAMA_HOST est aussi accepté (variable standard de l'écosystème Ollama). OLLAMA_URL=http://localhost:11434 OLLAMA_MODEL=qwen2.5:3b +# Durée pendant laquelle Ollama garde le modèle en mémoire après le dernier appel +OLLAMA_KEEP_ALIVE=30m # JARVIS_SYSTEM_PROMPT=Tu es Jarvis... diff --git a/backend/README.md b/backend/README.md index 21a0ba4..0c0e5d8 100644 --- a/backend/README.md +++ b/backend/README.md @@ -46,6 +46,7 @@ ne peut donc pas faire grossir `jarvise.db` sans limite. | POST | `/api/chat/stream` | oui | Chat streamé en SSE (sans état) | | POST | `/api/projects/:id/chat/stream` | oui | Chat streamé en SSE dans le projet | | POST | `/api/projects/:id/context/recall` | oui | Récite le contexte reçu (rien n'est enregistré) | +| POST | `/api/chat/warm` | oui | Charge le modèle en mémoire avant qu'il serve | Les routes protégées attendent le header `Authorization: Bearer `. Un projet n'est accessible qu'à son propriétaire : toute autre tentative renvoie `404`. @@ -75,12 +76,25 @@ curl -N -X POST http://localhost:3000/api/projects/1/context/recall \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{}' + +# Charger le modèle en mémoire avant la question (one shot sur /api/generate) +curl -X POST http://localhost:3000/api/chat/warm \ + -H 'Authorization: Bearer ' \ + -H 'Content-Type: application/json' \ + -d '{"model":"qwen2.5:3b"}' ``` `POST /api/projects/:id/context/recall` relit le contexte depuis la base à chaque appel et demande à Jarvis de le réciter : l'événement `done` renvoie `contextMessages`, le nombre exact de messages réellement renvoyés au modèle (40 au maximum). Rien n'est écrit dans le -projet, ce qui en fait une sonde de vérificationpurement lecture. +projet, ce qui en fait une sonde de vérification purement lecture. + +`POST /api/chat/warm` charge le modèle **sans rien générer** (`/api/generate`, réponse +`done_reason: "load"`) : le client l'appelle dès que l'utilisateur commence à écrire ou à +enregistrer, pour ne pas payer le chargement au moment de la réponse. La route répond +toujours **200** — `"warmed": false` quand Ollama est injoignable, car un réveil raté n'est +pas une erreur. Chaque requête de chat envoie en plus `keep_alive` (`OLLAMA_KEEP_ALIVE`, +défaut `30m`) pour que les poids ne soient pas déchargés entre deux questions. ### Exemple diff --git a/backend/src/config.js b/backend/src/config.js index 5a7b256..a55478b 100644 --- a/backend/src/config.js +++ b/backend/src/config.js @@ -78,6 +78,13 @@ export function loadConfig(overrides = {}) { 'http://localhost:11434' ).replace(/\/+$/, ''), model: overrides.ollamaModel ?? process.env.OLLAMA_MODEL ?? 'llama3.2', + /** + * How long Ollama keeps the model in memory after the last call. Its own + * default (`5m`) lets a long pause unload the weights, and the next + * question then pays the several-second load. A longer lease keeps the + * model ready between two exchanges. + */ + keepAlive: overrides.ollamaKeepAlive ?? process.env.OLLAMA_KEEP_ALIVE ?? '30m', systemPrompt: overrides.systemPrompt ?? process.env.JARVIS_SYSTEM_PROMPT ?? diff --git a/backend/src/routes/chat.js b/backend/src/routes/chat.js index bfab676..8d2de86 100644 --- a/backend/src/routes/chat.js +++ b/backend/src/routes/chat.js @@ -24,6 +24,15 @@ const specChatSchema = { }, }; +// Contract of `POST /api/chat/warm`: the model to load, or the configured one. +const warmSchema = { + type: 'object', + additionalProperties: false, + properties: { + model: { type: 'string', maxLength: 120 }, + }, +}; + const chatSchema = { type: 'object', required: ['message'], @@ -76,6 +85,26 @@ export async function chatRoutes(fastify) { }, ); + // Loads the model into memory before it is needed. The client fires this as + // soon as the user starts writing or recording, because a cold load takes + // seconds while a resident model answers immediately. + fastify.post( + '/api/chat/warm', + { onRequest: [fastify.authenticate], schema: { body: warmSchema } }, + async (request, reply) => { + const { model } = request.body; + try { + const loaded = await fastify.ollama.warm({ model }); + return { model: loaded.model, warmed: true }; + } catch (error) { + // Warming is best effort: answering 200 lets the client carry on, and + // the chat request that follows reports the real problem. + request.log.warn({ err: error }, 'model warm-up failed'); + return reply.code(200).send({ model: model ?? null, warmed: false }); + } + }, + ); + fastify.get('/api/chat/models', { onRequest: [fastify.authenticate] }, async () => { return fastify.ollama.listModels(); }); diff --git a/backend/src/services/ollama.js b/backend/src/services/ollama.js index 18c9b74..8ba43f5 100644 --- a/backend/src/services/ollama.js +++ b/backend/src/services/ollama.js @@ -18,6 +18,9 @@ export function createOllama(config) { return { model: model ?? config.ollama.model, stream, + // Keep the weights resident between two questions: reloading them costs + // seconds and is what makes a cold answer feel slow. + keep_alive: config.ollama.keepAlive, messages: [{ role: 'system', content: config.ollama.systemPrompt }, ...messages], }; } @@ -67,6 +70,39 @@ export function createOllama(config) { return { model: payload.model, response }; } + /** + * Loads the model into memory without generating anything: Ollama answers + * `done_reason: "load"` as soon as the weights are resident. Called when the + * user starts typing or recording, so the load happens while the sentence is + * still being written instead of after it is sent. + */ + async function warm({ model } = {}) { + const target = model ?? config.ollama.model; + + let response; + try { + response = await fetch(`${baseUrl}/api/generate`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ model: target, keep_alive: config.ollama.keepAlive }), + }); + } catch (cause) { + throw new OllamaError(`Cannot reach Ollama (${baseUrl}).`, 502); + } + + if (!response.ok) { + const detail = await response.text().catch(() => ''); + throw new OllamaError( + `Ollama refused to load ${target} (${response.status})${detail ? `: ${detail}` : ''}.`, + 502, + ); + } + + // The body is drained so the connection can be kept alive. + await response.json().catch(() => null); + return { model: target }; + } + /** Checks that Ollama answers and lists the available models. */ async function listModels() { try { @@ -79,7 +115,7 @@ export function createOllama(config) { } } - return { chat, openChatStream, readStream, listModels }; + return { chat, openChatStream, readStream, listModels, warm }; } /** diff --git a/backend/test/mock-ollama.js b/backend/test/mock-ollama.js index ce5491e..5fb2178 100644 --- a/backend/test/mock-ollama.js +++ b/backend/test/mock-ollama.js @@ -4,9 +4,15 @@ const DEFAULT_PIECES = ['Bon', 'jour', ' ', 'Tony', ', ', 'je ', 'suis ', 'Jarvi /** * Faux serveur Ollama : répond en NDJSON morceau par morceau quand `stream` - * est vrai, et renvoie une erreur si le modèle vaut "boom". + * est vrai, renvoie `done_reason: "load"` sur `/api/generate`, et renvoie une + * erreur si le modèle vaut "boom". Chaque requête reçue est conservée dans + * `requests` pour que les tests vérifient ce qui part réellement vers Ollama. */ export async function startMockOllama({ pieces = DEFAULT_PIECES, delay = 2 } = {}) { + // Every payload the backend sent, so a test can check what Ollama received + // (the model, `keep_alive`, the replayed context…). + const requests = []; + const server = http.createServer((req, res) => { if (req.method === 'GET' && req.url === '/api/tags') { res.writeHead(200, { 'Content-Type': 'application/json' }); @@ -14,11 +20,38 @@ export async function startMockOllama({ pieces = DEFAULT_PIECES, delay = 2 } = { return; } + // "Load the model": Ollama answers as soon as the weights are resident. + if (req.method === 'POST' && req.url === '/api/generate') { + let body = ''; + req.on('data', (c) => (body += c)); + req.on('end', () => { + const payload = JSON.parse(body || '{}'); + requests.push({ url: req.url, payload }); + + if (payload.model === 'boom') { + res.writeHead(500, { 'Content-Type': 'application/json' }).end('{"error":"boom"}'); + return; + } + + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end( + JSON.stringify({ + model: payload.model, + response: '', + done: true, + done_reason: 'load', + }), + ); + }); + return; + } + if (req.method === 'POST' && req.url === '/api/chat') { let body = ''; req.on('data', (c) => (body += c)); req.on('end', () => { const payload = JSON.parse(body || '{}'); + requests.push({ url: req.url, payload }); if (payload.model === 'boom') { res.writeHead(500, { 'Content-Type': 'application/json' }).end('{"error":"boom"}'); @@ -60,6 +93,7 @@ export async function startMockOllama({ pieces = DEFAULT_PIECES, delay = 2 } = { return { url: `http://127.0.0.1:${port}`, + requests, close: () => new Promise((resolve) => server.close(resolve)), }; } diff --git a/backend/test/stream.test.js b/backend/test/stream.test.js index 6fe6701..5ed0388 100644 --- a/backend/test/stream.test.js +++ b/backend/test/stream.test.js @@ -98,6 +98,51 @@ describe('streaming over SSE', () => { assert.equal((await fetch(`${srv.base}/api/chat/stream`, { method: 'POST' })).status, 401); }); + /** The last payload Ollama received, to check what the model was told. */ + function lastMessagesSent(seen) { + const chat = srv.mock.requests + .slice(seen) + .filter((r) => r.url === '/api/chat') + .at(-1); + assert.ok(chat, 'Ollama should have received a chat request'); + return chat.payload.messages; + } + + // The whole point of a project: the model answers with its stored memory. + it('replays the stored context to the model, in order', async () => { + const p = await newProject(); + await api(srv.base, 'POST', `/api/projects/${p.id}/messages`, { + token: user.token, + body: { role: 'user', content: 'Mon code secret est BANANE42.' }, + }); + await api(srv.base, 'POST', `/api/projects/${p.id}/messages`, { + token: user.token, + body: { role: 'assistant', content: "C'est noté." }, + }); + + const seen = srv.mock.requests.length; + const res = await fetch(`${srv.base}/api/projects/${p.id}/chat/stream`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${user.token}` }, + body: JSON.stringify({ message: 'Quel est le code secret ?' }), + }); + await readSse(res); + + const messages = lastMessagesSent(seen); + const system = messages.shift(); + assert.equal(system.role, 'system', 'the system prompt comes first'); + assert.ok(system.content.length > 0); + + assert.deepEqual( + messages.map((m) => [m.role, m.content]), + [ + ['user', 'Mon code secret est BANANE42.'], + ['assistant', "C'est noté."], + ['user', 'Quel est le code secret ?'], + ], + ); + }); + it('stateless stream: works', async () => { const res = await fetch(`${srv.base}/api/chat/stream`, { method: 'POST', @@ -168,6 +213,36 @@ describe('POST /api/chat (spec SSE contract)', () => { assert.ok(payloads.length - 1 >= 5, `chunks received: ${payloads.length - 1}`); }); + // `POST /api/chat` has no database: the client's own history is what the + // model sees, so it has to arrive whole and in order. + it('forwards the whole conversation to the model', async () => { + const seen = srv.mock.requests.length; + const res = await postChat({ + messages: [ + { role: 'user', content: 'Mon prénom est Damien.' }, + { role: 'assistant', content: 'Enchanté Damien.' }, + { role: 'user', content: 'Quel est mon prénom ?' }, + ], + }); + await readSsePayloads(res); + + const chat = srv.mock.requests + .slice(seen) + .filter((r) => r.url === '/api/chat') + .at(-1); + const messages = chat.payload.messages; + + assert.equal(messages[0].role, 'system'); + assert.deepEqual( + messages.slice(1).map((m) => [m.role, m.content]), + [ + ['user', 'Mon prénom est Damien.'], + ['assistant', 'Enchanté Damien.'], + ['user', 'Quel est mon prénom ?'], + ], + ); + }); + it('answers with a real HTTP error when Ollama fails before the stream', async () => { const res = await postChat({ model: 'boom', messages: [{ role: 'user', content: 'boom' }] }); diff --git a/backend/test/warm.test.js b/backend/test/warm.test.js new file mode 100644 index 0000000..330f5d8 --- /dev/null +++ b/backend/test/warm.test.js @@ -0,0 +1,85 @@ +import assert from 'node:assert/strict'; +import { after, before, describe, it } from 'node:test'; + +import { api, registerUser, startServer } from './helpers.js'; + +/** + * Warming the model: the client asks for the weights to be resident before the + * question that needs them, because a cold load costs seconds. + */ +describe('model warm-up', () => { + let srv; + let user; + + before(async () => { + srv = await startServer(); + user = await registerUser(srv.base, 'warm@x.io'); + }); + + after(async () => { + await srv.close(); + }); + + it('loads the requested model through /api/generate', async () => { + const seen = srv.mock.requests.length; + + const res = await api(srv.base, 'POST', '/api/chat/warm', { + token: user.token, + body: { model: 'qwen2.5:3b' }, + }); + + assert.equal(res.status, 200); + assert.deepEqual(res.json, { model: 'qwen2.5:3b', warmed: true }); + + const warm = srv.mock.requests.slice(seen).find((r) => r.url === '/api/generate'); + assert.ok(warm, 'Ollama should have received a /api/generate call'); + assert.equal(warm.payload.model, 'qwen2.5:3b'); + assert.equal(warm.payload.keep_alive, '30m'); + assert.equal(warm.payload.prompt, undefined, 'nothing should be generated'); + }); + + it('falls back to the configured model when none is named', async () => { + const res = await api(srv.base, 'POST', '/api/chat/warm', { + token: user.token, + body: {}, + }); + + assert.equal(res.status, 200); + assert.equal(res.json.warmed, true); + assert.equal(res.json.model, 'mock:1'); + }); + + it('stays best effort when Ollama refuses to load the model', async () => { + const res = await api(srv.base, 'POST', '/api/chat/warm', { + token: user.token, + body: { model: 'boom' }, + }); + + // A warm-up that fails must not look like an error to the client: the real + // chat request reports the problem. + assert.equal(res.status, 200); + assert.deepEqual(res.json, { model: 'boom', warmed: false }); + }); + + it('keeps the model resident on every chat request', async () => { + const seen = srv.mock.requests.length; + + const res = await api(srv.base, 'POST', '/api/chat', { + token: user.token, + body: { messages: [{ role: 'user', content: 'Bonjour' }] }, + }); + assert.equal(res.status, 200); + + const chat = srv.mock.requests.slice(seen).find((r) => r.url === '/api/chat'); + assert.ok(chat, 'Ollama should have received a /api/chat call'); + assert.equal(chat.payload.keep_alive, '30m'); + }); + + it('requires a token', async () => { + const res = await api(srv.base, 'POST', '/api/chat/warm', { + body: { model: 'qwen2.5:3b' }, + }); + + assert.equal(res.status, 401); + }); +});