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.
254 lines
8.6 KiB
JavaScript
254 lines
8.6 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { after, before, describe, it } from 'node:test';
|
|
|
|
import { api, readSse, readSsePayloads, registerUser, startServer } from './helpers.js';
|
|
|
|
const FULL_REPLY = 'Bonjour Tony, je suis Jarvis.';
|
|
|
|
describe('streaming over SSE', () => {
|
|
let srv;
|
|
let user;
|
|
|
|
before(async () => {
|
|
srv = await startServer();
|
|
user = await registerUser(srv.base, 'stream@x.io');
|
|
});
|
|
|
|
after(async () => {
|
|
await srv.close();
|
|
});
|
|
|
|
async function newProject() {
|
|
const res = await api(srv.base, 'POST', '/api/projects', {
|
|
token: user.token,
|
|
body: { name: 'Stream' },
|
|
});
|
|
return res.json.project;
|
|
}
|
|
|
|
it('streams the answer chunk by chunk and persists at the end', async () => {
|
|
const p = await newProject();
|
|
|
|
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: 'Hi' }),
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
assert.match(res.headers.get('content-type') ?? '', /text\/event-stream/);
|
|
|
|
const events = await readSse(res);
|
|
const deltas = events.filter((e) => e.event === 'delta').map((e) => e.data.content);
|
|
const done = events.find((e) => e.event === 'done');
|
|
|
|
assert.ok(deltas.length >= 5, `chunks received: ${deltas.length}`);
|
|
assert.equal(deltas.join(''), FULL_REPLY);
|
|
assert.ok(done, 'expected a done event');
|
|
assert.equal(done.data.reply, FULL_REPLY);
|
|
assert.equal(done.data.projectId, p.id);
|
|
assert.equal(done.data.messages.length, 2);
|
|
|
|
const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: user.token });
|
|
assert.equal(msgs.json.messages.length, 2);
|
|
assert.equal(msgs.json.messages[1].content, FULL_REPLY);
|
|
});
|
|
|
|
it('injects the project context into the stream', async () => {
|
|
const p = await newProject();
|
|
await api(srv.base, 'POST', `/api/projects/${p.id}/messages`, {
|
|
token: user.token,
|
|
body: { role: 'system', content: 'Important note' },
|
|
});
|
|
|
|
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: 'Follow up' }),
|
|
});
|
|
const events = await readSse(res);
|
|
|
|
assert.ok(events.some((e) => e.event === 'done'));
|
|
|
|
const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: user.token });
|
|
assert.deepEqual(
|
|
msgs.json.messages.map((m) => m.content),
|
|
['Important note', 'Follow up', FULL_REPLY],
|
|
);
|
|
});
|
|
|
|
it('Ollama error before the stream: real HTTP error as JSON', async () => {
|
|
const p = await newProject();
|
|
|
|
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: 'boom', model: 'boom' }),
|
|
});
|
|
|
|
assert.ok(res.status >= 400, `status: ${res.status}`);
|
|
assert.match(res.headers.get('content-type') ?? '', /application\/json/);
|
|
assert.ok((await res.json()).error);
|
|
|
|
const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: user.token });
|
|
assert.equal(msgs.json.messages.length, 0, 'no orphan message');
|
|
});
|
|
|
|
it('stateless stream: requires authentication', async () => {
|
|
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',
|
|
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${user.token}` },
|
|
body: JSON.stringify({ message: 'Hello' }),
|
|
});
|
|
assert.equal(res.status, 200);
|
|
|
|
const events = await readSse(res);
|
|
const deltas = events.filter((e) => e.event === 'delta').map((e) => e.data.content);
|
|
assert.equal(deltas.join(''), FULL_REPLY);
|
|
});
|
|
});
|
|
|
|
describe('POST /api/chat (spec SSE contract)', () => {
|
|
let srv;
|
|
let user;
|
|
|
|
before(async () => {
|
|
srv = await startServer();
|
|
user = await registerUser(srv.base, 'chat@x.io');
|
|
});
|
|
|
|
after(async () => {
|
|
await srv.close();
|
|
});
|
|
|
|
function postChat(body, token = user.token) {
|
|
return fetch(`${srv.base}/api/chat`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
},
|
|
body: JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
it('requires authentication', async () => {
|
|
assert.equal((await postChat({ messages: [{ role: 'user', content: 'Hi' }] }, null)).status, 401);
|
|
});
|
|
|
|
it('rejects a missing or empty messages array', async () => {
|
|
assert.equal((await postChat({})).status, 400);
|
|
assert.equal((await postChat({ messages: [] })).status, 400);
|
|
assert.equal((await postChat({ messages: [{ role: 'user' }] })).status, 400);
|
|
});
|
|
|
|
it('streams `data: {"content":...}` chunks then `data: [DONE]`', async () => {
|
|
const res = await postChat({
|
|
model: 'mock:1',
|
|
messages: [{ role: 'user', content: 'Hello' }],
|
|
});
|
|
|
|
assert.equal(res.status, 200);
|
|
assert.match(res.headers.get('content-type') ?? '', /text\/event-stream/);
|
|
assert.match(res.headers.get('cache-control') ?? '', /no-cache/);
|
|
assert.match(res.headers.get('connection') ?? '', /keep-alive/);
|
|
|
|
const payloads = await readSsePayloads(res);
|
|
assert.equal(payloads.at(-1), '[DONE]');
|
|
|
|
const content = payloads
|
|
.slice(0, -1)
|
|
.map((p) => JSON.parse(p).content)
|
|
.join('');
|
|
assert.equal(content, FULL_REPLY);
|
|
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' }] });
|
|
|
|
assert.ok(res.status >= 400, `status: ${res.status}`);
|
|
assert.match(res.headers.get('content-type') ?? '', /application\/json/);
|
|
assert.ok((await res.json()).error);
|
|
});
|
|
});
|