Asked what the first message of the conversation was, the assistant answered that it keeps no memory between interactions while the replayed context sat right in front of it. Two causes, both measured on the real model. The system prompt never said the history is its memory, nor who it is, so it fell back on its training habit of denying recall. And Ollama's default context window silently truncates from the beginning: on a 9194-token conversation only 4053 tokens were evaluated, so the oldest messages never reached the model at all. The window is now requested explicitly (16384 by default) and the warm-up asks for the same one, otherwise Ollama reloads the weights and throws the preheat away. The prompt states the identity and forbids the false denial, while still letting the assistant admit a message older than the replayed window.
300 lines
10 KiB
JavaScript
300 lines
10 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 ?'],
|
|
],
|
|
);
|
|
});
|
|
|
|
// A weak model answers « je n'ai pas de mémoire » without being told what the
|
|
// replayed history is and who it is.
|
|
it('tells the model who it is and that the history is its memory', async () => {
|
|
const seen = srv.mock.requests.length;
|
|
const res = await fetch(`${srv.base}/api/chat/stream`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${user.token}` },
|
|
body: JSON.stringify({ message: 'Qui es-tu ?' }),
|
|
});
|
|
await readSse(res);
|
|
|
|
const system = lastMessagesSent(seen)[0];
|
|
assert.equal(system.role, 'system');
|
|
assert.match(system.content, /BlackAngelTV/, 'the identity must be stated');
|
|
assert.match(system.content, /historique .* mémoire/i, 'the history is the memory');
|
|
assert.match(system.content, /messages les plus anciens/, 'old turns count too');
|
|
assert.match(system.content, /jamais que tu n'as pas de mémoire/, 'no false denial');
|
|
});
|
|
|
|
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('system prompt override', () => {
|
|
let srv;
|
|
let user;
|
|
|
|
before(async () => {
|
|
srv = await startServer({ systemPrompt: 'Tu es un modèle de test.' });
|
|
user = await registerUser(srv.base, 'prompt@x.io');
|
|
});
|
|
|
|
after(async () => {
|
|
await srv.close();
|
|
});
|
|
|
|
it('JARVIS_SYSTEM_PROMPT replaces the built-in identity', 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: 'Bonjour' }),
|
|
});
|
|
await readSse(res);
|
|
|
|
const system = srv.mock.requests.at(-1).payload.messages[0];
|
|
assert.equal(system.content, 'Tu es un modèle de test.');
|
|
assert.doesNotMatch(system.content, /BlackAngelTV/);
|
|
});
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|