ノート / 05
OpenAI Node SDK vs raw fetch for streaming
Both paths speak the same protocol and neither is faster; what differs is where the complexity lives. The openai package gives you typed responses, retries, timeouts and an async iterator over events — and hides the raw stream, which is exactly what you need when a non-OpenAI upstream returns a field the types do not know about. Raw fetch gives you bytes and full control, and hands you the job of framing SSE correctly, decoding UTF-8 across chunk boundaries and reading x-request-id yourself. This article implements both against the same endpoint, compares them line by line, and covers the three TypeScript failures that only surface in production.
Setup
mkdir stream-demo && cd stream-demo
npm init -y >/dev/null
npm i openai@^4
npm i -D typescript tsx @types/node
npx tsc --init --target es2022 --module nodenext --moduleResolution nodenext --strict
export MODELRY_API_KEY="sk-live-..."
Node 20 or later: fetch is stable there, and AbortSignal.timeout behaves consistently. On Node 18 you will meet keep-alive and undici edge cases that have nothing to do with the model.
Path A: the SDK
// sdk.ts
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.MODELRY_API_KEY!,
baseURL: process.env.BASE_URL ?? "https://api.tokenaimodels.com/v1",
timeout: 120_000,
maxRetries: 0,
});
export type StreamResult = {
text: string;
ttftMs: number | null;
usage: Record<string, unknown> | null;
};
export async function sdkStream(prompt: string): Promise<StreamResult> {
const t0 = performance.now();
let ttftMs: number | null = null;
let text = "";
let usage: Record<string, unknown> | null = null;
const stream = await client.chat.completions.create({
model: "deepseek-chat",
messages: [{ role: "user", content: prompt }],
stream: true,
stream_options: { include_usage: true },
max_tokens: 400,
});
for await (const ev of stream) {
if (!ev.choices || ev.choices.length === 0) { // usage-only event
usage = (ev.usage as unknown as Record<string, unknown>) ?? usage;
continue;
}
const piece = ev.choices[0]?.delta?.content;
if (!piece) continue;
ttftMs ??= performance.now() - t0;
text += piece;
}
return { text, ttftMs, usage };
}
Path B: raw fetch
The work here is SSE framing: bytes arrive in arbitrary slices, a slice can end mid-line and mid-UTF-8-sequence, and a JSON payload can be split across two slices. Buffer, split on newlines, keep the remainder.
// fetch.ts
type SseEvent = { event?: string; data: string };
async function* readSse(res: Response): AsyncGenerator<SseEvent> {
if (!res.body) throw new Error("response has no body");
const reader = res.body.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let idx: number;
while ((idx = buffer.indexOf("\n")) !== -1) {
const line = buffer.slice(0, idx).replace(/\r$/, "");
buffer = buffer.slice(idx + 1);
if (line.startsWith("data:")) {
yield { data: line.slice(5).trimStart() };
}
}
}
} finally {
reader.releaseLock();
}
}
export async function fetchStream(prompt: string) {
const base = process.env.BASE_URL ?? "https://api.tokenaimodels.com/v1";
const t0 = performance.now();
const res = await fetch(base + "/chat/completions", {
method: "POST",
headers: {
Authorization: "Bearer " + process.env.MODELRY_API_KEY,
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify({
model: "deepseek-chat",
messages: [{ role: "user", content: prompt }],
stream: true,
stream_options: { include_usage: true },
max_tokens: 400,
}),
signal: AbortSignal.timeout(180_000),
});
if (!res.ok) {
const rid = res.headers.get("x-request-id") ?? "-";
throw new Error("HTTP " + res.status + " rid=" + rid + " " + (await res.text()));
}
let ttftMs: number | null = null;
let text = "";
let usage: unknown = null;
for await (const ev of readSse(res)) {
if (ev.data === "[DONE]") break;
let json: any;
try { json = JSON.parse(ev.data); } catch { continue; }
if (!json.choices?.length) { usage = json.usage ?? usage; continue; }
const piece = json.choices[0]?.delta?.content;
if (!piece) continue;
ttftMs ??= performance.now() - t0;
text += piece;
}
return { text, ttftMs, usage };
}
Which one to use
Use the SDK when you want typed usage, built-in retry with backoff, and a stream you can consume with for await. Use fetch when you need exact control — custom timeouts per knob, proxy agents, header inspection, or a runtime where the SDK's node-only dependencies are awkward (edge workers). The practical compromise most teams land on: SDK in the application, fetch in a smoke-test script that runs in CI, because the raw path proves the endpoint really streams and the SDK path proves your code really handles it.
Failure 1: Type error: Property 'reasoning_content' does not exist
The SDK's types describe OpenAI's schema. A reasoning model behind a compatible gateway returns its trace as reasoning_content, usually next to content, and TypeScript is right to complain. Read it from the raw object rather than fighting the types:
const choice = (resp.choices[0].message as any);
const reasoning: string = choice.reasoning_content ?? "";
const answer: string = choice.content ?? "";
If you want it typed, declare a local interface that extends the SDK message and cast once at the boundary — do not as any your way through the whole module.
Failure 2: SyntaxError: Unexpected end of JSON input in the fetch path
You are parsing per chunk instead of per line. A single reader.read() can deliver half of a data: {...} payload, so JSON.parse sees an unbalanced object and throws — usually on the longest, most interesting response. The fix is the line buffer above: accumulate, split on newline, keep the tail, and only ever parse complete lines. Wrap the parse in try/catch and continue; a malformed line should never abort a generation you have already paid for.
Failure 3: the timeout that kills a healthy generation
AbortSignal.timeout(30_000) is a *total* deadline, not an idle timeout. A reasoning request that legitimately spends 45 seconds before its first token will be aborted while it is working perfectly. Either stream and set the deadline above your measured worst-case time-to-first-token, or implement an idle timer that resets on every chunk. The same mistake appears in reverse with the SDK: timeout there is a per-request budget with retries on top, so timeout: 10_000, maxRetries: 3 can spend 40 seconds failing.
What to watch when you speak to a gateway instead of OpenAI
Two SDK-level assumptions break quietly. baseURL (capital URL, SDK v4) is a constructor option, but the SDK also honours OPENAI_BASE_URL from the environment — a stale export in a container image silently overrides your code and sends the key to the wrong host, and the resulting 401 is blamed on the key. Second, retry semantics belong to the transport, not to the model: retrying after the first token duplicates text and, on a prepaid gateway, bills the overlap twice. Set maxRetries: 0 while you are diagnosing, then reintroduce retries only for 429, 502 and 503 with backoff. Keep x-request-id from every failed response in your logs; it is the only identifier that survives the two hops between your code and the model.
One operational detail per path
In the SDK path, a corporate egress proxy needs a dispatcher or agent passed to the constructor; environment variables alone are not always enough on Node, and the resulting failure is a bare ECONNRESET with no mention of the proxy. In the fetch path, the same proxy needs undici's ProxyAgent, and the difference between "works on a laptop" and "works in the cluster" is usually one line you have already written twice.
Grab a key at https://tokenaimodels.com and run both implementations side by side against https://api.tokenaimodels.com/v1 — the diff in time-to-first-token between them is your own client overhead, and it is usually smaller than you expect.
Modelry は、1つの HTTP endpoint の背後で DeepSeek モデルを提供するプラットフォームを運営しています。前払いクレジットと税務は購入時に merchant of record が処理し、データ保持方針も文書で公開しています。$0.50 分のトライアルクレジットから始められます: キーを作成する。