API / STREAMING

Muse Wonder Streaming API: Parse SSE and Handle Interruptions

A successful streaming HTTP response opens a channel; it does not prove generation completed. Muse Wonder Network sends Server-Sent Events containing text deltas, optional usage and a final completion marker. Your application must distinguish a completed answer from a partial response.

Quick answer

Send stream: true, validate HTTP status and text/event-stream, decode bytes incrementally, and parse data: lines. Check chunk.error as well as HTTP errors. Treat a missing [DONE] marker or missing visible content as incomplete and review usage before retrying.

Understand this endpoint’s event format

Text arrives in choices[0].delta.content. Usage may arrive in a later chunk with an empty choices array, so stopping at the last text token can lose billing information. The final data: [DONE] marker terminates the protocol; do not JSON.parse that marker. A stream error can precede the marker, so receiving [DONE] alone is insufficient. This tutorial targets the website’s data-line protocol rather than every possible SSE provider.

ILLUSTRATIVE SSE / EACH EVENT ENDS WITH A BLANK LINE
data: {"choices":[{"delta":{"content":"Hello"}}]}

data: {"choices":[],"usage":{"credits_charged":2,"billing_status":"settled"}}

data: [DONE]

Continue your evaluation: Website API contract

Use a chunk-safe reader

Save the example as muse-stream.mjs, set your website API key on a Node.js 22+ server and run node muse-stream.mjs. It keeps a decoder across byte chunks, buffers unfinished lines and rejects oversized pending lines. It prints text as it arrives, records the final usage object and always releases the reader. The request is potentially billable; there is no retry loop.

JAVASCRIPT / SSE READER
// Save as muse-stream.mjs. Node.js 22+, server-side only.
const base = process.env.MUSEWONDER_BASE_URL || 'https://musewonder.network';
const key = process.env.MUSEWONDER_API_KEY;
if (!key) throw new Error('Set MUSEWONDER_API_KEY.');
const response = await fetch(base.replace(/\/$/, '') + '/api/v1/chat/completions', {
  method: 'POST',
  headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json' },
  signal: AbortSignal.timeout(120000),
  body: JSON.stringify({ model: 'meta/muse-wonder',
    messages: [{ role: 'user', content: 'Give me a short code review checklist.' }],
    max_tokens: 1024, stream: true })
});
if (!response.ok) {
  const error = await response.json().catch(() => null);
  throw new Error('HTTP ' + response.status + ': ' + (error?.error?.message || 'Request failed'));
}
if (!response.body || !response.headers.get('content-type')?.includes('text/event-stream')) {
  throw new Error('Expected an SSE response.');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '', complete = false, visible = false, usage;
function line(text) {
  if (!text.startsWith('data:')) return;
  const raw = text.slice(5).trim();
  if (raw === '[DONE]') { complete = true; return; }
  if (!raw) return;
  const chunk = JSON.parse(raw);
  if (chunk.error) throw new Error(chunk.error.message || 'Stream failed');
  const delta = chunk.choices?.[0]?.delta?.content;
  if (typeof delta === 'string') {
    visible ||= Boolean(delta.trim());
    process.stdout.write(delta);
  }
  if (chunk.usage) usage = chunk.usage;
}
try {
  while (!complete) {
    const { value, done } = await reader.read();
    if (done) { buffer += decoder.decode(); if (buffer.trim()) line(buffer); break; }
    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split('\n');
    buffer = lines.pop() || '';
    if (buffer.length > 131072) throw new Error('Stream line exceeded the client buffer.');
    for (const text of lines) { line(text.trimEnd()); if (complete) break; }
  }
  if (!complete || !visible) throw new Error('Incomplete response; review usage before retrying.');
  console.log('\nCharged credits:', usage?.credits_charged ?? 'pending review');
} finally {
  await reader.cancel().catch(() => {});
  reader.releaseLock();
}

Treat HTTP errors and stream errors separately

Before reading the body, check response.ok. A 401 or 402 normally returns an error JSON response rather than SSE. After the stream starts with HTTP 200, inspect every parsed object for error. Do not mark a job successful merely because some text arrived. Keep partial content visibly marked as incomplete when parsing fails, the connection ends early or no visible content is produced.

Continue your evaluation: Status-by-status troubleshooting

Cancellation changes delivery, not the billing guarantee

A browser can stop reading, a proxy can disconnect or the caller can abort. Website-credit requests can still require reconciliation with the provider after delivery stops. Do not refund your own end user or immediately send another model request on the assumption that the first request cost nothing. Store your application’s request time and completion state; check Account → Usage for the website’s billing result.

Continue your evaluation: Review account usage · Estimate website credit usage

Proxy a stream without exposing your key

Keep the website key on your server and forward only the response needed by your authenticated application user. Configure your hosting proxy to avoid buffering the whole answer, and verify its timeout behavior. Test a text delta split across byte boundaries, an error after visible content, missing usage and premature EOF before deployment. The displayed reader is protocol-tested with fixtures; it does not claim a live latency or throughput measurement.

Continue your evaluation: Start with non-streaming JavaScript · Production checklist

YOUR NEXT STEP

Connect your application.

Create a website key and fund the shared account balance. Start with the API contract, then test one small server-side request.

VERIFY THE DETAILS

Sources & update notes.

Specifications and availability can change. Follow the source for the exact model and provider. Model capabilities are separate from the features offered by this website.

Related reading.