Streaming without buffering

Read server-sent events as they arrive so users see progress before the full model response completes.

  1. Send stream: true.
  2. Keep a 150-second response timeout and a shorter connection timeout.
  3. Read complete SSE lines and parse only lines beginning with data:.
  4. Stop on the protocol completion event, not merely when the first text arrives.
  5. Log the response request ID and final usage metadata.
const host = "magnetapi-org.p.rapidapi.com";
const response = await fetch(`https://${host}/v1/responses`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-RapidAPI-Key": process.env.RAPIDAPI_KEY,
    "X-RapidAPI-Host": host,
  },
  body: JSON.stringify({ model: "gpt-5.6", input: "Write three API integration tips.", stream: true })
});

console.log("Request ID:", response.headers.get("X-MagnetAPI-Request-ID"));
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split("
");
  buffer = lines.pop() || "";
  for (const line of lines) {
    if (!line.startsWith("data: ")) continue;
    const payload = line.slice(6);
    if (payload === "[DONE]") continue;
    const event = JSON.parse(payload);
    if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
  }
}

Claude Messages: use the same SSE reader with POST /v1/messages and inspect content_block_delta, message_delta, and message_stop events.

Back to the RapidAPI guide