- Send
stream: true. - Keep a 150-second response timeout and a shorter connection timeout.
- Read complete SSE lines and parse only lines beginning with
data:. - Stop on the protocol completion event, not merely when the first text arrives.
- 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.