Overview
You can send both tool status updates and final text tokens over one Server-Sent Events (SSE) stream by using typed JSON events. Each SSE message carries an event or payload type so the client handles status updates and text deltas separately.
- One stream, clear event types: Send
statusortool_statusevents while tools run, andtextortokenevents as the final answer streams. - Safe stream lifecycle: Flush pending status or text events cleanly and send a
doneorerrorevent when the turn finishes or fails.
Steps
- Set SSE response headers: Send
Content-Type: text/event-stream,Cache-Control: no-cache, andConnection: -alivefrom your Node.js/TypeScript HTTP handler. - Define typed SSE event payloads: Use explicit event types like
tool_start,tool_end,text_delta,done, anderrorwith JSON-encodeddatalines. - Emit tool status events during tool execution: Send a status update right before and right after each tool call runs so the UI shows live progress.
- Stream text tokens and close cleanly: Stream model text deltas over the same connection, send a final
doneevent, and clean up listeners on client disconnect.
Example
import type { IncomingMessage, ServerResponse } from "node:http";
export type SseEventPayload =
| { type: "tool_start"; toolName: string; toolCallId: string; message: string }
| { type: "tool_end"; toolName: string; toolCallId: string; ok: boolean; message: string }
| { type: "text_delta"; delta: string }
| { type: "done"; fullText: string }
| { type: "error"; message: string };
export function writeSseEvent(res: ServerResponse, payload: SseEventPayload): void {
if (res.writableEnded || res.destroyed) return;
res.write(`event: \${payload.type}\n`);
res.write(`data: ${JSON.stringify(payload)}\n\n`); } export interface OrchestratorStreamHooks { onToolStart: (toolCallId: string, toolName: string) => void; onToolEnd: (toolCallId: string, toolName: string, ok: boolean) => void; onTextDelta: (delta: string) => void; } export async function runAgentTurnWithTools( prompt: string, signal: AbortSignal, hooks: OrchestratorStreamHooks ): Promise<string> { // Example tool execution step before streaming final answer const toolCallId = "call_weather_1"; const toolName = "get_weather"; hooks.onToolStart(toolCallId, toolName); await new Promise((resolve) => setTimeout(resolve, 150)); if (signal.aborted) throw new Error("Client disconnected."); hooks.onToolEnd(toolCallId, toolName, true); // Example final streamed answer tokens const chunks = ["The weather ", "in Kasur is ", "clear and mild ", "tonight."]; let fullText = ""; for (const delta of chunks) { if (signal.aborted) throw new Error("Client disconnected."); await new Promise((resolve) => setTimeout(resolve, 50)); fullText += delta; hooks.onTextDelta(delta); } return fullText; } export async function handleSingleSseStream( req: IncomingMessage, res: ServerResponse, prompt: string ): Promise<void> { res.writeHead(200, { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive", }); const controller = new AbortController(); req.on("close", () => { controller.abort(); }); try { const fullText = await runAgentTurnWithTools(prompt, controller.signal, { onToolStart: (toolCallId, toolName) => { writeSseEvent(res, { type: "tool_start", toolCallId, toolName, message: `Running ${toolName}...`,
});
},
onToolEnd: (toolCallId, toolName, ok) => {
writeSseEvent(res, {
type: "tool_end",
toolCallId,
toolName,
ok,
message: ok ? `Finished ${toolName}.` : `${toolName} failed.`,
});
},
onTextDelta: (delta) => {
writeSseEvent(res, {
type: "text_delta",
delta,
});
},
});
writeSseEvent(res, { type: "done", fullText });
res.end();
} catch (err) {
const message = err instanceof Error ? err.message : "Stream failed.";
writeSseEvent(res, { type: "error", message });
res.end();
}
}
Tips
- Do not leak raw internal arguments or secrets in status events: Keep tool status messages short and safe for the client UI.
- Abort upstream work on client disconnect: Listen to
req.on("close")so canceled requests stop wasting tokens and tool calls. - Keep event names and JSON fields consistent: Using a fixed
typefield insidedatamakes client parsing simple across browsers, fetch readers, and mobile apps.
You must log in or register to comment.
