feat(backend): keep the model resident and load it before it is asked
Ollama drops an idle model after five minutes by default, so the first question after a pause pays the whole several-second load. Every chat request now carries keep_alive (30 minutes by default) and POST /api/chat/warm loads the weights on demand, letting a client wake the model while the user is still writing. A warm-up that fails answers warmed=false instead of an error: it is an optimisation, not a step the answer depends on.
This commit is contained in:
8 files changed
+285
-3
No files matched your search
@@ -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)),
|
||||
};
|
||||
}
|
||||
@@ -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' }] });
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user