feat(backend): stream /api/chat as spec-compliant SSE

Expose the bare `data:`/`[DONE]` contract on the main chat endpoint so
simple clients can consume the stream without parsing named events.
This commit is contained in:
BlackAngelTV committed 2026-10-05 20:40:12 +02:00
1 parent 479a4db786
commit 31e9619727
5 files changed
+269 -22

No files matched your search

+30 -15
View File
@@ -1,5 +1,28 @@
import { streamChatToClient } from '../services/chat-stream.js';
import { OllamaError } from '../lib/errors.js';
import { streamChatToClient, streamChatToClientSpec } from '../services/chat-stream.js';
// Contract of `POST /api/chat`: a non-empty `messages` array, optionally a model.
const specChatSchema = {
type: 'object',
required: ['messages'],
additionalProperties: false,
properties: {
model: { type: 'string', maxLength: 120 },
messages: {
type: 'array',
minItems: 1,
maxItems: 50,
items: {
type: 'object',
required: ['role', 'content'],
additionalProperties: false,
properties: {
role: { type: 'string', enum: ['system', 'user', 'assistant'] },
content: { type: 'string', minLength: 1, maxLength: 32000 },
},
},
},
},
};
const chatSchema = {
type: 'object',
@@ -30,22 +53,14 @@ const chatSchema = {
* @param {import('fastify').FastifyInstance} fastify
*/
export async function chatRoutes(fastify) {
// Spec-compliant endpoint: streams the answer over SSE as bare `data:`
// messages, terminated by `data: [DONE]`.
fastify.post(
'/api/chat',
{ onRequest: [fastify.authenticate], schema: { body: chatSchema } },
{ onRequest: [fastify.authenticate], schema: { body: specChatSchema } },
async (request, reply) => {
const { message, model, history = [] } = request.body;
const messages = [...history, { role: 'user', content: message }];
try {
const result = await fastify.ollama.chat({ messages, model });
return reply.send({ reply: result.reply, model: result.model, user: { id: request.user.sub } });
} catch (error) {
if (error instanceof OllamaError) {
return reply.code(error.status).send({ error: error.message });
}
throw error;
}
const { model, messages } = request.body;
return streamChatToClientSpec({ ollama: fastify.ollama, reply, request, messages, model });
},
);
+83
View File
@@ -88,3 +88,86 @@ export async function streamChatToClient({ ollama, reply, request, messages, mod
if (!raw.writableEnded) raw.end();
}
}
/**
* Streams a stateless answer using the minimal, `data:`-only SSE contract of
* `POST /api/chat`:
*
* data: {"content":"text chunk"}
* data: {"content":"..."}
* data: [DONE]
*
* A failure that happens once the stream is open is reported inline as
* `data: {"error":"..."}`, while an unreachable Ollama is still answered with a
* real HTTP status before any SSE byte is sent. Aborts the Ollama request if the
* client disconnects mid-generation.
*
* @param {object} options
* @param {{ openChatStream: Function, readStream: Function }} options.ollama
* @param {import('fastify').FastifyReply} options.reply
* @param {import('fastify').FastifyRequest} options.request
* @param {Array<{role: string, content: string}>} options.messages
* @param {string} [options.model]
*/
export async function streamChatToClientSpec({ ollama, reply, request, messages, model }) {
const controller = new AbortController();
// Open the Ollama stream before switching to SSE: if Ollama is unreachable we
// can still answer with a real HTTP error code instead of a broken stream.
let opened;
try {
opened = await ollama.openChatStream({ messages, model, signal: controller.signal });
} catch (error) {
const status = error instanceof OllamaError ? error.status : 500;
const message = error instanceof Error ? error.message : 'Internal server error.';
return reply.code(status).send({ error: message });
}
const raw = reply.raw;
reply.hijack();
raw.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no', // disable buffering on reverse proxies (nginx)
});
// Only a close before we finish means the client went away; a close triggered
// by our own raw.end() must not abort anything.
const onClientClose = () => {
if (!raw.writableEnded) controller.abort();
};
raw.on('close', onClientClose);
const sendData = (payload) => {
if (raw.writableEnded) return false;
const text = typeof payload === 'string' ? payload : JSON.stringify(payload);
return raw.write(`data: ${text}\n\n`);
};
// Opening comment: the client receives the headers immediately.
raw.write(': stream open\n\n');
try {
for await (const chunk of ollama.readStream(opened.response)) {
if (raw.writableEnded || controller.signal.aborted) break;
const delta = chunk?.message?.content ?? '';
if (delta) sendData({ content: delta });
if (chunk?.done) break;
}
if (controller.signal.aborted || raw.writableEnded) return;
sendData('[DONE]');
} catch (error) {
if (!controller.signal.aborted) {
request.log.error(error);
sendData({ error: error instanceof Error ? error.message : 'Error while streaming.' });
}
} finally {
raw.off('close', onClientClose);
if (!raw.writableEnded) raw.end();
}
}