Notas / 04

Parse an SSE stream with nothing but curl

2026-11-17Notas da Modelry

Before you debug a library, debug the wire. curl sends exactly what you tell it to send and shows you exactly what comes back, which makes it the fastest way to separate "my SDK misbehaves" from "the endpoint buffers" or "usage is missing". This article builds a two-part harness: a curl call that captures the raw event stream and the response headers, and a parser that turns that capture into text plus the final usage block. It also covers the live pipe that prints tokens as they arrive, three failure modes that make an SSE parser return nothing at all, and the request-header details that matter when the endpoint is an OpenAI-compatible gateway rather than OpenAI.

Capture first, parse second

Two files, not one pipe. Capture the body to disk and the headers to a second file, because half the interesting facts — status code, content-type, x-request-id, whether the transfer was chunked — live in the headers and are invisible once you have piped the body into a parser.

#!/usr/bin/env bash
# sse_capture.sh — capture a streaming completion verbatim.
set -euo pipefail
: "${MODELRY_API_KEY:?export MODELRY_API_KEY=sk-live-... first}"

BODY="${1:-raw.sse}"
HDRS="${2:-headers.txt}"

curl -sS -N -f --max-time 180 \
  -D "$HDRS" \
  -o "$BODY" \
  -H "Authorization: Bearer $MODELRY_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{"model":"deepseek-chat",
       "messages":[{"role":"user","content":"Write three haiku about latency."}],
       "stream":true,
       "stream_options":{"include_usage":true},
       "max_tokens":400}' \
  https://api.tokenaimodels.com/v1/chat/completions

printf 'bytes=%s events=%s content-type=%s\n' \\
  "$(wc -c < "$BODY")" \\
  "$(grep -c '^data: ' "$BODY" || true)" \\
  "$(awk -F': ' 'tolower($1)=="content-type"{print $2}' "$HDRS" | tr -d '\r')"

Three flags carry the weight. -N turns off curl's own buffering, so you measure the server and not the client. -f makes curl exit non-zero on an HTTP error, which is the difference between a diagnosable failure and a parser that silently returns zero events. --max-time stops a hung generation from holding a shell forever. Note what is *not* in the response: there are no : keep-alive comment lines, so a long silence means the model is still thinking, and timeouts must be set from measurement.

Extract the text

Every event is data: <json>, events are separated by a blank line, and the stream ends with a literal data: [DONE]. The [DONE] sentinel is not JSON and is the reason naive parsers throw before they print anything.

#!/usr/bin/env bash
# sse_text.sh — print the assistant text from a captured stream.
set -euo pipefail
BODY="${1:-raw.sse}"

sed -n 's/^data: //p' "$BODY" \
  | grep -v '^\[DONE\]$' \
  | jq -r 'select((.choices | length) > 0) | .choices[0].delta.content // empty'
echo

Extract the usage block

Usage arrives in the tail of the stream, and the shape is not guaranteed. On our own endpoint it rode on the final content chunk, the one carrying finish_reason: stop; several other OpenAI-compatible gateways put it in a separate event immediately before [DONE] with an empty choices array. jq '.usage.prompt_tokens' works on both, jq '.choices[0].delta.content' fails on the second — which is the only reason to filter before indexing.

#!/usr/bin/env bash
# sse_usage.sh — pull the final usage block and turn it into a one-line record.
set -euo pipefail
BODY="${1:-raw.sse}"

sed -n 's/^data: //p' "$BODY" \
  | grep -v '^\[DONE\]$' \
  | jq -c 'select(.usage != null) | .usage' \
  | tail -n 1 \
  | jq -r '"in=\(.prompt_tokens) cached=\(.prompt_tokens_details.cached_tokens // .prompt_cache_hit_tokens // 0) out=\(.completion_tokens) total=\(.total_tokens)"'

If that prints nothing, the stream has no usage event: either you did not ask for one (stream_options.include_usage), or the upstream omitted usage entirely — in which case a prepaid gateway will usually mark the request as *estimated* in its own accounting, because no authoritative count arrived. Both are worth knowing before you build a dashboard on the number.

The live pipe

Sometimes you want tokens on the terminal as they arrive, not a file. read per line, strip the prefix, and skip anything that is not a JSON object:

#!/usr/bin/env bash
# sse_live.sh — print tokens as they arrive; no temp files.
set -euo pipefail
: "${MODELRY_API_KEY:?export MODELRY_API_KEY first}"
START=$(date +%s%3N)
FIRST=""

curl -sS -N -f \
  -H "Authorization: Bearer $MODELRY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"deepseek-chat","messages":[{"role":"user","content":"Count to eighty, one number per line."}],"stream":true,"max_tokens":500}' \
  https://api.tokenaimodels.com/v1/chat/completions \
| while IFS= read -r line; do
    case "$line" in
      "data: [DONE]") break ;;
      "data: "*)
        payload="${line#data: }"
        out=$(printf '%s' "$payload" | jq -r 'select((.choices|length)>0) | .choices[0].delta.content // empty' 2>/dev/null || true)
        if [ -n "$out" ]; then
          if [ -z "${FIRST:-}" ]; then FIRST=$(date +%s%3N); echo "TTFT $((FIRST-START))ms" >&2; fi
          printf '%s' "$out"
        fi
        ;;
    esac
  done
echo

Failure 1: the parser returns nothing and curl exited 0

Without -f, curl treats an HTTP 402 or 429 as success and writes the JSON error body to your file. sed -n 's/^data: //p' then finds no lines starting with data: , the pipeline produces empty output, and the shell reports success. Always keep the status code: check headers.txt, or add -w '%{http_code}\n'. A gateway returns 402 insufficient_balance when your prepaid balance cannot cover the pre-authorisation and 429 rate_limit_error when the per-key requests-per-minute window is full — both are JSON bodies, not streams, and both look like "empty stream" to a careless pipeline.

Failure 2: jq: error (at <stdin>:1): Cannot index array with string

Three separate mistakes produce this class of error, and they need three different guards. data: [DONE] is not valid JSON, so it must be filtered before jq. Some streams contain SSE comments or empty data: lines. And choices can be an empty array, in which case .choices[0].delta is null and indexing it fails. The robust filter is select((.choices|length) > 0) followed by .choices[0].delta.content // empty — never a bare .choices[0].delta.content.

Failure 3: tokens appear all at once, at the end

Your pipeline is not the problem; something between you and the model is buffering. Three suspects in order: the hostname (an apex domain served through a CDN can buffer, an api. subdomain is normally a direct connection), a proxy you own (proxy_buffering off in nginx, and check proxy_read_timeout), and any tool that collects the body before passing it on (a tee into a formatter, a CI log wrapper). Confirm with the headers: Transfer-Encoding: chunked present and Content-Encoding absent is what a live stream looks like.

What to watch when you speak to a gateway instead of OpenAI

Four header-level facts change. The gateway injects stream_options: {"include_usage": true} itself on some platforms, so the usage event may appear even though you never asked — write the parser to *accept* it rather than to require it. Every response carries x-request-id, which is the only handle for tracing a request through the gateway and the provider; capture it from headers.txt whenever a request fails. A 429 carries Retry-After in seconds and the limiter resets on a fixed one-minute boundary, not a rolling one, so honour the header instead of inventing a sleep. And because there are no keep-alive comments, an idle timeout tuned for OpenAI's stream will occasionally kill a healthy long generation on a reasoning model — measure time-to-first-token and set the timeout above it, not below.

Create a key at https://tokenaimodels.com and run the capture script once against https://api.tokenaimodels.com/v1 — the raw event stream is the ground truth every later debugging step depends on.

A Modelry opera uma plataforma que serve modelos DeepSeek atrás de um único endpoint HTTP, com créditos pré-pagos e impostos tratados pelo merchant of record no checkout, além de uma política de retenção de dados documentada. Comece com $0.50 de crédito de teste: criar uma chave.

Todas as notas

Parse an SSE stream with nothing but curl — Modelry