JSON streaming from OpenAI and Together AI: NDJSON, TTFT validation and metering
Task
The application generates a list of cards (products, tasks, test questions) through LLM and wants to show them as they appear, rather than waiting for the entire answer. You need to choose a provider and make sure that the streaming output can be safely parsed.
There will be no “who is faster” table here. The speed depends on the model, prompt length, region, provider load and time of day, and other people’s numbers mean little for your scenario. Below is how to make the code independent of the provider and how to measure it yourself.
One client for two providers
Together AI provides an OpenAI-compatible API, so the official SDK openai works with it when changing baseURL:
// lib/llm.ts
import OpenAI from "openai";
export const providers = {
openai: new OpenAI({ apiKey: process.env.OPENAI_API_KEY }),
together: new OpenAI({ apiKey: process.env.TOGETHER_API_KEY, baseURL: "https://api.together.xyz/v1" }),
};
export const models = {
openai: process.env.OPENAI_MODEL!, // идентификатор модели из каталога OpenAI
together: process.env.TOGETHER_MODEL!, // идентификатор модели из каталога Together
};Keep model identifiers in environment variables: catalogs are updated, and switching models should not require deploying code.
Why not stream one big JSON
If you ask the model to return {"items":[...]}, pieces like {"items":[{"title":"Ко come in the stream. JSON.parse throws an exception in such a fragment, and something can be shown to the user only after the closing bracket. There are libraries for parsing partial JSON, but they complicate the code and behave differently on dangling lines.
It's easier to change the format: one line - one full JSON object (NDJSON). Each completed line is parsed and checked independently.
Prompt and parsing
// lib/stream-cards.ts
import { z } from "zod";
import { providers, models } from "./llm";
const Card = z.object({
title: z.string().min(1).max(120),
description: z.string().max(500),
tags: z.array(z.string()).max(5),
});
export type Card = z.infer<typeof Card>;
const SYSTEM = `Отвечай только строками NDJSON. Каждая строка — один JSON-объект вида
{"title": string, "description": string, "tags": string[]}.
Без markdown, без обрамляющего массива, без пояснений до и после.`;
export async function* streamCards(provider: keyof typeof providers, topic: string) {
const stream = await providers[provider].chat.completions.create({
model: models[provider],
stream: true,
temperature: 0.4,
messages: [
{ role: "system", content: SYSTEM },
{ role: "user", content: `Сгенерируй 8 карточек по теме: ${topic}` },
],
});
let buffer = "";
for await (const chunk of stream) {
buffer += chunk.choices[0]?.delta?.content ?? "";
let nl: number;
while ((nl = buffer.indexOf("\n")) !== -1) {
const line = buffer.slice(0, nl).trim();
buffer = buffer.slice(nl + 1);
const card = parseLine(line);
if (card) yield card;
}
}
const last = parseLine(buffer.trim());
if (last) yield last;
}
function parseLine(line: string): Card | null {
if (!line || line.startsWith("```")) return null;
try {
const result = Card.safeParse(JSON.parse(line));
return result.success ? result.data: null;
} catch {
return null; // broken line: skip instead of dropping the entire stream
}
}Модель иногда оборачивает ответ в markdown-блок, несмотря на инструкцию; строки с тройными обратными кавычками отбрасываются. Невалидные строки стоит логировать с указанием провайдера и модели — это лучший индикатор того, что модель плохо держит формат.
Structured Outputs и JSON mode
У OpenAI есть Structured Outputs: response_format: { type: "json_schema", json_schema: { name, schema, strict: true } } гарантирует соответствие ответа схеме. Это надёжнее инструкции в промпте, но результат — один JSON-документ, а не NDJSON, и проблема частичного разбора при стриминге возвращается. Вариант: схема с массивом, а для показа по мере генерации — парсер частичного JSON, понимая его ограничения.
У Together поддержка JSON mode и схем зависит от конкретной модели. Перед тем как полагаться на неё, проверьте в их документации список моделей с поддержкой и протестируйте на своих данных. Валидация Zod на вашей стороне нужна в любом случае: гарантия провайдера не отменяет проверку бизнес-ограничений вроде длины полей.
Измерение: TTFT и полное время
// scripts/bench.ts
import { streamCards } from "../lib/stream-cards";
async function measure(provider: "openai" | "together", topic: string) {
const t0 = performance.now();
let first = 0, count = 0;
for await (const _ of streamCards(provider, topic)) {
if (!first) first = performance.now() - t0;
count++;
}
return { provider, ttftCardMs: Math.round(first), totalMs: Math.round(performance.now() - t0), count };
}
const topics = ["CRM for car service", "checklist for launching an online store", "SQL interview questions"];
for (const p of ["openai", "together"] as const) {
for (const t of topics) console.log(await measure(p, t));
}Здесь измеряется время до первой валидной карточки, а не до первого токена: для пользователя важно именно оно. Запускайте замер несколько раз в разное время суток из того же региона, где работает ваш сервер, и сравнивайте медианы, а не одиночные значения. Учитывайте и долю отброшенных строк: быстрый поток с невалидными объектами хуже медленного с валидными.
Отдача клиенту
Из Route Handler удобно отдавать тот же NDJSON:
export async function POST(req: Request) {
const { topic } = await req.json();
const encoder = new TextEncoder();
const body = new ReadableStream({
async start(controller) {
try {
for await (const card of streamCards("together", topic)) {
controller.enqueue(encoder.encode(JSON.stringify(card) + "\n"));
}
} finally {
controller.close();
}
},
});
return new Response(body, { headers: { "Content-Type": "application/x-ndjson" } });
}Common errors
- The remainder of the buffer after the end of the stream is not processed, and the last card is lost.
- Repeating a request if there is a failure in the middle of the stream duplicates already shown cards. Either deduplicate by header, or start generation again and clear the list.
- Switching to a backup provider without checking that its model supports the same format.
When streaming is not needed
If the answer is short or the result is used programmatically (classification, field extraction), streaming only complicates the code. A regular request with Structured Outputs or JSON mode and one validation at the end is simpler and more reliable.
Нужна реализация под ваш проект или аудит архитектуры?
Разрабатываем сайты на Next.js, Telegram-ботов, интеграции с CRM и ИИ-агентов под ключ.