Skip to Content
NineTwo's

Chat and streaming

Canonical chat requests, strict stream options, and SSE recovery semantics.

Non-streaming request

curl -sS "$NINETWOS_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $NINETWOS_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: chat-001" \
  -d '{
    "model": "zuv-0.5",
    "messages": [{"role": "user", "content": "Summarize this ticket"}],
    "max_completion_tokens": 256
  }'

max_completion_tokens is required unless the max_tokens compatibility alias is supplied. The response id is the gateway execution UUID, not a backend chatcmpl-* identifier.

Streaming request

Set stream to the literal boolean true. Non-boolean values such as "true" or 123 are rejected with 400 invalid_stream and are never coerced. stream_options is strict: only the boolean include_usage is accepted. Unknown properties and non-boolean values are rejected with 400 invalid_stream_options.

Structural validation runs before replay: top-level JSON must be an object (invalid_request), and message entries must be objects (invalid_messages).

curl -N -sS "$NINETWOS_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $NINETWOS_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: chat-stream-001" \
  -d '{
    "model": "zuv-0.5",
    "messages": [{"role": "user", "content": "Write a haiku about retries"}],
    "max_completion_tokens": 256,
    "stream": true,
    "stream_options": {"include_usage": true}
  }'

The response headers include X-Request-Id and Cache-Control: private, no-store. Capture X-Request-Id for recovery.

SSE framing and terminal markers

Frames are data: <json> followed by a blank line:

  1. Zero or more ChatCompletionChunk frames.
  2. If stream_options.include_usage=true, one UsageEvent frame: data: {"usage":{"prompt_tokens":…,"completion_tokens":…,"total_tokens":…}}.
  3. data: [DONE] only after settlement is confirmed.

There is no SSE error frame. Failures surface as an HTTP coded error or a stream error/close. A transport EOF is not terminal: only a backend finish_reason or [DONE] is a terminal marker. If the stream ends without either, treat the execution as recoverable rather than restarting it.

Node.js example

import { randomUUID } from 'node:crypto';

// Reuse this key when retrying the same logical request.
const idempotencyKey =
  process.env.NINETWOS_IDEMPOTENCY_KEY ?? randomUUID();

const response = await fetch(`${process.env.NINETWOS_BASE_URL}/chat/completions`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.NINETWOS_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': idempotencyKey,
  },
  body: JSON.stringify({
    model: 'zuv-0.5',
    messages: [{ role: 'user', content: 'Write a haiku about retries' }],
    max_completion_tokens: 256,
    stream: true,
    stream_options: { include_usage: true },
  }),
});

const requestId = response.headers.get('x-request-id');
const contentType = response.headers.get('content-type') ?? '';

if (!response.ok) {
  const error = await response.json().catch(() => null);
  throw new Error(JSON.stringify(error ?? { status: response.status }));
}

// A completed replay is JSON even when the original request streamed.
if (contentType.includes('application/json')) {
  const replay = await response.json();
  console.log(replay.choices?.[0]?.message?.content ?? '');
  process.exit(0);
}

if (!response.body) throw new Error('Missing response body');

const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
let sawTerminalMarker = false;

while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += value;

  const frames = buffer.split('\n\n');
  buffer = frames.pop() ?? '';

  for (const frame of frames) {
    const line = frame.split('\n').find((l) => l.startsWith('data:'));
    if (!line) continue;
    const data = line.slice(5).trim();

    if (data === '[DONE]') {
      sawTerminalMarker = true;
      break;
    }

    const event = JSON.parse(data);
    if (event.usage) {
      console.error('usage', event.usage);
      continue;
    }

    const choice = event.choices?.[0];
    if (choice?.finish_reason) sawTerminalMarker = true;
    process.stdout.write(choice?.delta?.content ?? '');
  }
}

if (!sawTerminalMarker) {
  // Recover with the same Idempotency-Key and identical payload, or poll
  // GET /v1/requests/{requestId} when the id was captured.
  console.error('Stream ended without a terminal marker', { requestId });
}
```js
const response = await fetch(`${process.env.NINETWOS_BASE_URL}/chat/completions`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.NINETWOS_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': `stream-${Date.now()}`,
  },
  body: JSON.stringify({
    model: 'zuv-0.5',
    messages: [{ role: 'user', content: 'Write a haiku about retries' }],
    max_completion_tokens: 256,
    stream: true,
    stream_options: { include_usage: true },
  }),
});

const requestId = response.headers.get('x-request-id');

if (!response.ok || !response.body) {
  const error = await response.json().catch(() => null);
  throw new Error(JSON.stringify(error ?? { status: response.status }));
}

const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
let sawTerminalMarker = false;

while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += value;

  const frames = buffer.split('\n\n');
  buffer = frames.pop() ?? '';

  for (const frame of frames) {
    const line = frame.split('\n').find((l) => l.startsWith('data:'));
    if (!line) continue;
    const data = line.slice(5).trim();

    if (data === '[DONE]') {
      sawTerminalMarker = true;
      break;
    }

    const event = JSON.parse(data);
    if (event.usage) {
      console.error('usage', event.usage);
      continue;
    }

    const choice = event.choices?.[0];
    if (choice?.finish_reason) sawTerminalMarker = true;
    process.stdout.write(choice?.delta?.content ?? '');
  }
}

if (!sawTerminalMarker) {
  // Recover with the same Idempotency-Key and identical payload, or poll
  // GET /v1/requests/{requestId} when the id was captured.
  console.error('Stream ended without a terminal marker', { requestId });
}

A runnable version uses only Node.js built-ins and is included above.

Replay of a completed streaming request

A retry with the same idempotency key and identical canonical payload after settlement returns the stored JSON chat.completion, even when the original request used stream=true. It does not return an SSE replay.

This replay is resolved from durable identity before endpoint resolution, health checks, tokenization, rate limiting, or new charging. It therefore works during a model/serving outage for requests with durable replay evidence and creates no new financial or metering rows. Historical rows without durable evidence may fall back to the live path.

Clients must inspect Content-Type: a replay may be application/json even though the original response was text/event-stream.

reasoning_content semantics

reasoning_content is an unstable, unmodelled backend passthrough:

  • Non-streaming responses and their replays may preserve message.reasoning_content if the backend returned it.
  • Streaming chunks may carry delta.reasoning_content if the backend emits it; the gateway forwards the chunk but accumulates only delta.content.
  • Gateway-generated stream replays do not include it.
  • It is not generated, validated, separately metered, or guaranteed.

reasoning_effort is a separate request field and accepts only low or xhigh. It is part of the canonical idempotency payload. The serving runtime may apply an independent reasoning budget that is not client-controllable.

Do not blind-restart streams

A disconnected stream may still have reached the GPU. Reuse the original idempotency key and identical payload, or poll GET /v1/requests/{id} with the captured X-Request-Id. Never start a new logical request with a new key just because the transport dropped.

On this page