SSE Streaming Guide
BacMR uses Server-Sent Events (SSE) for the /chat endpoint to provide a responsive, "typing" experience.
Protocol Detail
- Endpoint:
POST /chatwithstream: true. - Content-Type:
text/event-stream.
Event Types
event: token: Data is a single string chunk (token).event: sources: Data is a JSON array of source objects.event: error: Data is an error message string.event: done: Data is[DONE].
Security Considerations
- CORS: Ensure the frontend origin is in
CORS_ALLOWED_ORIGINS. - JWT: The Bearer token must be passed in the
Authorizationheader. Note: StandardEventSourcein browsers doesn't support headers; use a library likefetch-event-sourceor pass the token via a cookie/query param (though BacMR currently expects the Header).
Frontend Consumption Pattern (Pseudo-code)
import { fetchEventSource } from '@microsoft/fetch-event-source';
await fetchEventSource('https://api.bacmr.mr/chat', {
method: 'POST',
headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: [...], stream: true }),
onmessage(ev) {
if (ev.event === 'token') updateUI(ev.data);
if (ev.event === 'sources') showSources(JSON.parse(ev.data));
}
});