DocsGuidesStreaming SSE
Guide: Streaming Deep Analysis (SSE)
Learn how to consume live Server-Sent Events from /api/v1/predict/deep in browser and server environments.
Why Server-Sent Events?
Deep analysis orchestrates multi-source web crawlers, text summarizers, and LLM reasoning steps that require 3 to 15 seconds to execute. Instead of a blocking HTTP call, `/api/v1/predict/deep` streams milestone events as each pipeline stage completes.
Client-Side Implementation (`fetch` + `ReadableStream`)
Because standard browser `EventSource` does not support custom headers or POST bodies, use the `fetch()` API with `response.body.getReader()`:
typescript/streamDeepPredict.ts
export async function streamDeepPredict(text: string,token: string,onStageUpdate: (stage: string, status: string) => void,onResult: (result: any) => void,onError: (error: string) => void) {const response = await fetch('https://api.verilens.id/api/v1/predict/deep', {method: 'POST',headers: {'Authorization': `Bearer ${token}`,'Content-Type': 'application/json'},body: JSON.stringify({ text })});if (!response.ok) {const errorData = await response.json();throw new Error(errorData.error || 'Failed to start deep analysis');}const reader = response.body?.getReader();if (!reader) return;const decoder = new TextDecoder();let buffer = '';while (true) {const { done, value } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });const lines = buffer.split('\n');buffer = lines.pop() || '';let currentEvent = '';for (const line of lines) {if (line.startsWith('event: ')) {currentEvent = line.substring(7).trim();} else if (line.startsWith('data: ')) {const data = JSON.parse(line.substring(6));if (currentEvent === 'stage_update') {onStageUpdate(data.stage, data.status);} else if (currentEvent === 'result') {onResult(data);} else if (currentEvent === 'error') {onError(data.error);}}}}}
Handling Network Disconnections
If the user loses internet connection mid-stream, capture the `check_id` from the initial `stage_update` event and poll `GET /api/v1/predict/deep/:id/status` until the status transitions to `completed` or `failed`.
