Gateway
Production streaming example
Expose a controlled text stream from an authenticated server boundary.
Use a server client configured as in the quickstart. Authenticate the caller, authorize model spend and validate input before invoking this helper. It returns a text Response; integrate it into your framework's handler after those application checks.
import type { Nirmos } from "@nirmos/sdk";
export async function streamReply(client: Nirmos, message: string, signal?: AbortSignal): Promise<Response> {
const abort = new AbortController();
const cancel = () => abort.abort(signal?.reason);
if (signal?.aborted) cancel();
else signal?.addEventListener("abort", cancel, { once: true });
try {
const stream = await client.gateway.chat.stream({
route: "production-chat",
messages: [{ role: "user", content: message }],
}, { signal: abort.signal, timeoutMs: 30_000 });
const iterator = stream[Symbol.asyncIterator]();
const encoder = new TextEncoder();
const cleanup = () => signal?.removeEventListener("abort", cancel);
const body = new ReadableStream<Uint8Array>({
async pull(controller) {
try {
while (true) {
const { value, done } = await iterator.next();
if (done) { cleanup(); controller.close(); return; }
if (value.type === "content.delta" && value.delta) {
controller.enqueue(encoder.encode(value.delta));
return;
}
}
} catch (error) { cleanup(); controller.error(error); }
},
async cancel() {
abort.abort();
cleanup();
await iterator.return?.();
},
});
return new Response(body, { headers: {
"content-type": "text/plain; charset=utf-8", "cache-control": "no-store",
} });
} catch (error) {
signal?.removeEventListener("abort", cancel);
throw error;
}
}Initial HTTP errors reject before creating the response. Stream/body failures error the output stream. Consumer cancellation aborts the SDK request and cleans up the iterator. Runtime/provider cancellation behavior determines how quickly upstream work stops.