@HamzaM to AI & LLMEnglish • 6 days ago

Why does JSON mode in LLM APIs occasionally truncate closing braces and how do you repair partial JSON?

message-square
0
1
Why does JSON mode in LLM APIs occasionally truncate closing braces and how do you repair partial JSON?
@HamzaM to AI & LLMEnglish • 6 days ago

Why Simple Splitting Breaks SSE Streams

When streaming chat completions from OpenAI in Node.js, data arrives in raw network chunks rather than complete messages. A single chunk might contain half a JSON object, multiple events at once, or a split multi-byte character (like an emoji). Also, OpenAI sends data: [DONE] at the end instead of JSON.

If you call JSON.parse() directly on each raw chunk, your code will crash with syntax errors.

How to Parse SSE Chunks Cleanly

To handle this safely:

  1. Decode with { stream: true }: Use TextDecoder so multi-byte characters split across chunks are decoded properly without breaking.
  2. Keep a string buffer: Append decoded text to a buffer string.
  3. Split on \n\n: In the SSE format, separate events with two newlines. Keep the last piece in buffer because it may still be incomplete.
  4. Extract data: lines: Read lines starting with data:, stop if the payload is [DONE], and parse the JSON to read delta.content.

Node.js Example

async function streamOpenAIChat(apiKey, payload) {
  const response = await fetch("[https://api.openai.com/v1/chat/completions](https://api.openai.com/v1/chat/completions)", {
    method: "POST",
    headers: {
      "Authorization": `Bearer \${apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ ...payload, stream: true }),
  });

  if (!response.ok || !response.body) {
    const errorText = await response.text().catch(() => "");
    throw new Error(`Request failed (${response.status}):${errorText}`);
  }

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

  for await (const chunk of response.body) {
    buffer += decoder.decode(chunk, { stream: true });

    const parts = buffer.split("\n\n");
    // Save the last part in case the event is not finished yet
    buffer = parts.pop() ?? "";

    for (const part of parts) {
      const lines = part
        .split("\n")
        .filter((line) => line.startsWith("data:"))
        .map((line) => line.slice(5).trim());

      if (lines.length === 0) continue;

      const rawData = lines.join("\n");
      if (rawData === "[DONE]") {
        return;
      }

      const parsed = JSON.parse(rawData);
      const token = parsed.choices?.[0]?.delta?.content;
      if (token) {
        process.stdout.write(token);
      }
    }
  }

  // Flush any leftover bytes from the decoder
  decoder.decode();
}

Quick Tips for Real Apps

  • Ignore comment lines: SSE comments start with :. Filtering for data: naturally skips them.
  • Add an AbortController: Pass a signal to fetch so users can stop generation or time out slow streams.
  • Use libraries for bigger apps: Packages like eventsource-parser or the official openai SDK handle edge cases automatically if your streaming logic grows complex.