EN ▾
Get API key

Unknown Error From LLM Stream: Causes and Fixes

An unknown error from llm stream output is rarely a real error type. It is a generic message that your client or app shows when a streaming request ends in a way it could not explain. This article shows how to find out what actually happened and fix it.

Updated

A data pipe with a cracked segment carrying glowing blocks toward a terminal, representing a broken stream
per 1M input tokens
$0.15
Output tokens / 1M
$0.50
token context
100,000
trial credit
$0.50
requests per minute
300

Key points

  • Reproduce the call with curl -N first. If curl streams cleanly, the bug is in your client or a proxy.
  • Check the HTTP status before reading the stream: a 429 with rate_limited or concurrency is the most common real cause.
  • A streamed request holds its concurrency slot until the stream ends, so unclosed streams cause later failures.
  • Reverse proxies that buffer responses, short timeouts and sloppy SSE parsing explain most of the rest.

What the message means

Chat front ends and SDK wrappers show "unknown error" when something goes wrong and the underlying cause does not fit a message they recognise. The streaming part matters. A normal request returns once, with a status code and a body, and the error is usually clear. A streaming request returns status 200 first, then sends many small events over a connection that stays open. Failures can occur before the first byte, in the middle, or at the end, and each looks different from the client's side.

Your first job is to turn the vague message into a specific one. That means finding three facts: the HTTP status of the response, whether any data arrived before the failure, and where the failure happened (your app, a proxy in between, or the API). The sections below follow that order. If you want a broader checklist for this API, the troubleshooting guide covers non-streaming errors too.

Step 1: reproduce it with curl

Take your app out of the picture. The command below sends the same kind of streaming request directly. The -N flag turns off curl's output buffering so events print as they arrive, and -i prints the response headers.

curl -N -i https://api.uncensoredaimodel.cc/v1/chat/completions   -H "Authorization: Bearer $UNCENSORED_API_KEY"   -H "Content-Type: application/json"   -d '{
    "model": "uncensored",
    "stream": true,
    "messages": [{"role": "user", "content": "Count from 1 to 10."}]
  }'

Read the result in this order. A first line of HTTP/2 200 followed by lines that begin with data: means the API is fine and your client is the problem. Any other status means you have a real error, and the JSON body tells you which one. Also note the X-Request-Id response header. If you need to contact support, that ID lets them find your request.

It also pays to test with a short prompt first, and then with the real one. A request that fails only with your full production prompt points at size or time: either the body approaches the 8 MB limit, the prompt plus the reply is bigger than the 100,000-token window, or the generation simply runs long enough to hit a timeout somewhere on the path. A request that fails even with "say hi" points at keys, limits or the network.

If curl works from your laptop but fails from your server, compare networks. The difference is almost always a proxy, a firewall or a timeout between the server and the internet.

Step 2: rule out limits and overload

The most common real cause is HTTP 429. This API returns it in three situations, and the body or headers distinguish them.

SituationWhat you seeFix
Too many requests per minute429, error code rate_limitedSlow down; a full key allows 300 per minute, a trial key 60
Too many requests at once429, error code concurrencyLimit parallel calls; a full key allows 8, a trial key 2
Temporary overload429 with Retry-After: 5Wait 5 seconds, then retry

Streaming makes the concurrency case easy to hit by accident. A streamed request keeps its slot until the stream ends. If your UI lets a user fire a second message while the first is still arriving, or if a cancelled stream leaves the connection half open, you can fill the slots with requests that are still alive. A trial key with only 2 slots shows this quickly. The result is a 429 on a request that looks innocent, which a careless client reports as an unknown error.

A quick diagnostic for the slot problem is to stop all your clients, wait a few seconds and send one request. If it succeeds, the earlier failures came from slots held by other streams. Log the start and end of each stream in your app with the request ID. Any stream that starts but never logs an end is leaking a slot, and finding the code path that skips cleanup is usually a one-line fix, such as moving the close call into a finally block.

Check the response headers X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency to confirm which limits apply to your key. X-Balance-USD shows the remaining balance, which helps rule out a funding problem. Failed requests are not charged, so retrying is safe in terms of cost.

Step 3: look for a buffering or timing-out proxy

If the status is 200 but the stream stalls, then dumps everything at once or dies after 30 or 60 seconds, suspect something between you and the API. Reverse proxies and CDNs often buffer responses by default, which breaks streaming, and many apply idle timeouts that cut a connection when no bytes flow for a while.

  • nginx: set proxy_buffering off; for the location that forwards to the API, and raise proxy_read_timeout above the longest reply you expect.
  • Serverless platforms: many have a maximum execution time, and some do not support streamed responses on every runtime. Check your platform's documentation.
  • Corporate proxies and antivirus tools: these can hold a response until it completes. Try another network to confirm.
  • Browser clients: an EventSource only sends GET requests, so a POST stream must use fetch and read response.body.

Streaming also exposes problems in your own hosting. A common one is a function that returns before the stream has finished, so the platform tears down the connection. Another is compression: if a layer compresses the response with gzip and buffers to do it, chunks stop arriving in real time. Disable compression for the streaming route, or confirm that your proxy flushes after each event. Test on the real deployment, not only on localhost, because the problem often appears only behind the production proxy.

Long replies make timeouts more likely. The context window is 100,000 tokens for prompt plus completion, and the completion can use whatever the prompt leaves free, since max_tokens is optional. Setting max_tokens to a sensible limit for your use case keeps replies, and therefore stream durations, predictable.

Step 4: parse the stream correctly

If curl is clean and no proxy interferes, the fault is in how your code reads events. The stream is server-sent events. Each event is a line starting with data: followed by JSON, separated by blank lines, and the stream ends with data: [DONE]. With stream: true the final events also include usage. These are the usual parsing mistakes:

  • Calling JSON.parse on a network chunk instead of on a complete line. A chunk can end in the middle of an event, so you must buffer until you see a full line.
  • Trying to parse [DONE] as JSON.
  • Assuming every event has choices[0].delta.content. Some events carry no text, and the usage event may have an empty choices list.
  • Throwing on the first malformed line instead of skipping it and logging it.

The OpenAI SDKs handle all of this for you, so the simplest fix is often to use them. This Python version also reports the failure in a readable way.

import os
from openai import OpenAI, APIStatusError, APIConnectionError

client = OpenAI(
    base_url="https://api.uncensoredaimodel.cc/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
)

def stream_reply(messages):
    text = ""
    try:
        stream = client.chat.completions.create(
            model="uncensored", messages=messages, stream=True
        )
        for chunk in stream:
            if chunk.choices and chunk.choices[0].delta.content:
                piece = chunk.choices[0].delta.content
                text += piece
                print(piece, end="", flush=True)
    except APIStatusError as e:
        rid = e.response.headers.get("x-request-id")
        print(f"\nHTTP {e.status_code}, request {rid}: {e.message}")
    except APIConnectionError as e:
        print(f"\nConnection dropped after {len(text)} chars: {e}")
    return text

If you are using a third-party chat app rather than your own code, you cannot edit the parsing, but you can still gather the evidence. Open the browser developer tools, go to the network tab and look at the failed request. Its status, its response headers and the last bytes of its response show whether the API returned an error or a proxy cut the connection. Compare that with the curl result from step 1, and you will know which side to blame.

Now the error names a status code and a request ID, or tells you the connection dropped after a certain number of characters. Either result gives you something to act on.

Step 5: retry the right way

Once you know the cause, add a retry that matches it. A 429 should wait and try again, a dropped connection can try again with the same messages, and anything else should surface the error to the user. Here is a compact Node version.

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.uncensoredaimodel.cc/v1",
  apiKey: process.env.UNCENSORED_API_KEY,
  maxRetries: 0,
});

async function streamWithRetry(messages, tries = 4) {
  for (let i = 0; i < tries; i++) {
    try {
      const stream = await client.chat.completions.create({
        model: "uncensored",
        messages,
        stream: true,
      });
      let text = "";
      for await (const chunk of stream) {
        text += chunk.choices?.[0]?.delta?.content ?? "";
      }
      return text;
    } catch (err) {
      if (err.status === 429 || err.code === "ECONNRESET") {
        await new Promise((r) => setTimeout(r, 5000));
        continue;
      }
      throw err;
    }
  }
  throw new Error("stream failed after retries");
}

Retry from the start of the reply, not from the middle. Resuming a partial answer is not supported, so discard the partial text and ask again. Always close or abort a stream you stop reading, because an abandoned one keeps a concurrency slot busy. Other less common causes include a request body above the 8 MB limit and a prompt that exceeds the 100,000-token window. The documentation lists the endpoints and parameters,. Create or check your key on the API key page.

Start with trial credit

Email and password, key on screen right away.

Questions and answers

Why does the error only appear when streaming?

Streaming adds failure points that a single request does not have: proxy buffering, idle timeouts, partial events and slots held open until the stream ends. A non-streaming call can hide all of these.

Does a failed stream cost money?

Failed or refused requests are not charged. Check the X-Balance-USD response header to see your current balance.

How many streams can run at once?

A full key allows 8 concurrent requests and a trial key allows 2. Each stream uses a slot until it ends, and going over returns HTTP 429 with the code concurrency.

What should I send to support?

Send the value of the X-Request-Id response header, the time of the call and what your client printed. That is usually enough to find the request.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.