Public preview: This API is in public preview. Endpoints, schemas, and limits may change before general availability.

Handling streams

Parse SSE without the SDK — for custom clients, edge functions, and language bindings that don't exist yet.

If the official OpenAI SDK fits your stack, use it — it handles SSE parsing and typed events for free. This guide is for the cases where you need to roll your own: a Go service, a Cloudflare Worker, a Rust client, a server forwarding the stream to a browser.

The wire format#

event: message
data: {"type":"response.created","sequence_number":1, …}

event: message
data: {"type":"response.output_text.delta","sequence_number":4, …,"delta":"He"}

: ping - 2026-11-02 12:00:15.012345+00:00

event: message
data: {"type":"response.output_text.delta","sequence_number":5, …,"delta":"llo"}

event: message
data: {"type":"response.completed","sequence_number":7, …}

Three details matter when you parse by hand:

  • Lines end with \r\n, so events are separated by \r\n\r\n, not \n\n. Normalise line endings before you split, as the examples below do.
  • Lines starting with : are comments. EU GPT sends a : ping comment every 15 seconds to keep the connection open. Skip them.
  • The data: line is JSON; the event: line and comments are metadata you can ignore. Discriminate on the JSON type.

Your server: Node.js#

Keep the API key on your server. Call EU GPT from there and send the result, or the stream, on to your users.

// Node 18+ has fetch built in.
const response = await fetch("https://api.eugpt.ai/v1/responses", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.EUGPT_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ input: "Tell me a story.", stream: true }),
});

if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}

const decoder = new TextDecoder();
let buffer = "";

for await (const chunk of response.body) {
  buffer += decoder.decode(chunk, { stream: true });
  buffer = buffer.replace(/\r\n/g, "\n");

  // Events are separated by blank lines.
  let idx;
  while ((idx = buffer.indexOf("\n\n")) !== -1) {
    const raw = buffer.slice(0, idx);
    buffer = buffer.slice(idx + 2);
    handleEvent(raw);
  }
}

function handleEvent(raw) {
  for (const line of raw.split("\n")) {
    if (!line.startsWith("data: ")) continue; // skips "event:" lines and ": ping" comments
    const event = JSON.parse(line.slice(6));
    if (event.type === "response.output_text.delta") {
      process.stdout.write(event.delta);
    } else if (event.type === "error") {
      console.error(`\n[${event.code}] ${event.message}`);
    }
  }
}

Python without the SDK#

httpx splits lines for you and handles \r\n:

import json
import os
import httpx

def stream_response(input_text: str):
    with httpx.stream(
        "POST",
        "https://api.eugpt.ai/v1/responses",
        headers={
            "Authorization": f"Bearer {os.environ['EUGPT_API_KEY']}",
            "Content-Type": "application/json",
        },
        json={"input": input_text, "stream": True},
        timeout=httpx.Timeout(connect=10, read=60, write=10, pool=10),
    ) as response:
        response.raise_for_status()
        for line in response.iter_lines():
            # Skip "event:" lines, ": ping" comments, and the blank lines between events.
            if line.startswith("data: "):
                yield json.loads(line[6:])

Use it as:

for event in stream_response("Tell me a haiku."):
    if event["type"] == "response.output_text.delta":
        print(event["delta"], end="", flush=True)

The read timeout of 60 seconds is safe because of the 15-second pings: a minute without any bytes means the connection is dead.

Forwarding to a browser#

If your server proxies EU GPT to a browser, the cleanest pattern is to not parse — just pipe the bytes through. The browser parses the stream itself. Build the request body on your server, so a visitor cannot send arbitrary requests on your key.

// Cloudflare Worker / edge function
const { question } = await request.json();

const upstream = await fetch("https://api.eugpt.ai/v1/responses", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${env.EUGPT_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ input: question, stream: true }),
});

return new Response(upstream.body, {
  status: upstream.status,
  headers: {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
  },
});

In the browser, read the stream with fetch and a ReadableStream, using the same parsing as the Node.js example. The EventSource API does not work here because it cannot send a POST body. Do not strip or rewrite events on the way: clients that use the OpenAI event shapes expect them as sent.

Handling mid-stream errors#

A stream may contain an error event. Treat the response as failed when you see one, even if response.completed still follows. A stream that ends without response.completed, response.incomplete, or error was cut off by the network — treat it as a retry candidate.

let failed = null;
let finished = false;

for await (const event of events) {
  if (event.type === "error") {
    failed = event;
  } else if (event.type === "response.completed" || event.type === "response.incomplete") {
    finished = true;
  }
  // ... handle other events
}

if (failed) {
  throw new Error(`Stream errored: ${failed.code} ${failed.message}`);
}
if (!finished) {
  throw new Error("Stream closed without a final event");
}