Streaming (SSE)

@hyperyai/sdk streaming helpers — consumeSSEStream, parseSSEFrame and parseSSEError read a streaming chat response and classify a mid-stream error the same way as a normal API error.

A request that is refused before streaming starts returns a normal 402/429/403 JSON body, which parseError handles. A failure after the stream has started arrives as an SSE frame instead:

event: error
data: {"error":{"code":"INSUFFICIENT_CREDITS","type":"insufficient_credits_error","message":"…"}}

These helpers read the stream and turn that frame into the same ParsedError, so one piece of UI handles both cases. See Chat streaming for the stream format.

consumeSSEStream

Reads a Response body, splits it into frames, and calls your handlers.

import { consumeSSEStream, parseError, useAuth } from '@hyperyai/sdk';
 
const { authenticatedFetch, gatewayUrl } = useAuth();
 
const res = await authenticatedFetch(`${gatewayUrl}/api/v1/chat/completions`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ model: 'openai/gpt-4o-mini', stream: true, messages }),
});
 
if (!res.ok) {
  showError(parseError({ ...(await res.json()), status: res.status }));
} else {
  await consumeSSEStream(res.body, {
    onData: (data) => {
      const chunk = JSON.parse(data);
      append(chunk.choices?.[0]?.delta?.content ?? '');
    },
    onError: (err) => showError(err), // err.isInsufficientCredits, err.isSpendingLimit, …
    onDone: () => setStreaming(false),
  });
}
ParamTypeDescription
bodyReadableStream<Uint8Array> | null | undefinedresponse.body. A missing body calls onDone immediately.
handlersSSEStreamHandlersBelow.
HandlerTypeCalled
onData(data: string) => voidWith each normal frame's data: payload. [DONE] is skipped.
onError(error: ParsedError) => voidWith a classified error for an error frame. Not thrown.
onDone() => voidOnce, when the body ends.

Returns Promise<void> that resolves when the stream ends. Frames are split on blank lines (\n\n). Errors from reading the stream itself (e.g. a network drop) are thrown.

parseSSEFrame

Parses one raw frame (the text between blank lines).

import { parseSSEFrame } from '@hyperyai/sdk';
 
parseSSEFrame('event: error\ndata: {"error":{"code":"RATE_LIMITED"}}');
// → { event: 'error', data: '{"error":{"code":"RATE_LIMITED"}}' }

parseSSEFrame(block: string): SSEEvent | null — collects event: and joins multiple data: lines with \n. Returns null when the block has neither.

parseSSEError

Classifies a frame as an error, or returns null.

import { parseSSEError } from '@hyperyai/sdk';
 
const err = parseSSEError(rawBlockOrFrame);
if (err?.isSpendingLimit) openLimitsModal();

parseSSEError(frame: SSEEvent | string): ParsedError | null returns a ParsedError when:

  • the frame is event: error (non-JSON data becomes an error with that text as its message), or
  • the data: JSON contains an { error: { code } } envelope.

It returns null for normal data frames and for [DONE].

Types

TypeShape
SSEEvent{ event?: string; data: string }
SSEStreamHandlers{ onData?, onError?, onDone? }

Next steps