Stack logo
Sync up on the latest from Convex.
Ian Macartney's avatar
Ian Macartney
6 months ago

Streaming HTTP Responses using fetch

Icon of a person throwing a ball for a dog to fetch and a stream on the right, representing the post title

This post will look at working with the JavaScript Streams API which allows making a fetch HTTP call and receiving a streaming response in chunks, which allows a client to start responding to a server response more quickly and build UIs like ChatGPT.

As a motivating example, we’ll implement a function to handle the streaming LLM response from OpenAI (or any server using the same http streaming API), using no npm dependencies—just the built-in fetch. The full code is here including retries with exponential backoff, embeddings, non-streaming chat, and a simpler APIs for interacting with chat completions and embeddings.

If you’re interested in seeing how to also return an HTTP stream to clients, check out this post.

Full example code

Here’s the full example. We’ll look at each piece below:

1async function createChatCompletion(body: ChatCompletionCreateParams) {
2  // Making the request
3  const baseUrl = process.env.LLM_BASE_URL || "https://api.openai.com";
4  const response = await fetch(baseUrl + "/v1/chat/completions", {
5    method: "POST",
6    headers: {
7      "Content-Type": "application/json",
8      "Authorization": "Bearer " + process.env.LLM_API_KEY,
9    },
10    body: JSON.stringify(body),
11  });
12  // Handling errors
13  if (!response.ok) {
14    const error = await response.text();
15    throw new Error(`Failed (${response.status}): ${error}`,
16  }
17  if (!body.stream) { // the non-streaming case
18    return response.json();
19  }
20  const stream = response.body;
21  if (!stream) throw new Error("No body in response");
22  // Returning an async iterator
23  return {
24    [Symbol.asyncIterator]: async function* () {
25      for await (const data of splitStream(stream)) {
26        // Handling the OpenAI HTTP streaming protocol
27        if (data.startsWith("data:")) {
28          const json = data.substring("data:".length).trimStart();
29          if (json.startsWith("[DONE]")) {
30            return;
31          }
32          yield JSON.parse(json);
33        }
34      }
35    },
36  };
37}
38
39// Reading the stream  
40async function* splitStream(stream: ReadableStream<Uint8Array>) {
41  const reader = stream.getReader();
42  let lastFragment = "";
43  try {
44    while (true) {
45      const { value, done } = await reader.read();
46      if (done) {
47        // Flush the last fragment now that we're done
48        if (lastFragment !== "") {
49          yield lastFragment;
50        }
51        break;
52      }
53      const data = new TextDecoder().decode(value);
54      lastFragment += data;
55      const parts = lastFragment.split("\n\n");
56      // Yield all except for the last part
57      for (let i = 0; i < parts.length - 1; i += 1) {
58        yield parts[i];
59      }
60      // Save the last part as the new last fragment
61      lastFragment = parts[parts.length - 1];
62    }
63  } finally {
64    reader.releaseLock();
65  }
66}
67

See the code here for a version that has nice typed overloads for streaming & non-streaming parameter variants, along with retries and other improvements.

The rest of the post is about understanding what this code does.

Making the request

This part is actually very easy. A streaming HTTP response comes from a normal HTTP request:

1const baseUrl = process.env.LLM_BASE_URL || "https://api.openai.com";
2const response = await fetch(baseUrl + "/v1/chat/completions", {
3  method: "POST",
4  headers: {
5    "Content-Type": "application/json",
6    "Authorization": "Bearer " + process.env.LLM_API_KEY,
7  },
8  body: JSON.stringify(body),
9});
10

The HTTP headers are sent up per usual, and don’t have to set anything in particular to enable streaming. And you can still leverage regular caching headers for HTTP streaming.

Handling errors

The story around errors on the client side is a little unfortunate for HTTP streaming. The upside is that for HTTP streaming, the client gets status codes right away in the initial response and can detect failure there. The downside to the http protocol is that if the server returns success but then breaks mid-stream, there isn’t anything at the protocol level that will tell the client that the stream was interrupted. We’ll see below how OpenAI encodes an “all done” sentinel at the end to work around this.

1if (!response.ok) {
2  const error = await response.text();
3  throw new Error(`Failed (${response.status}): ${error}`,
4}
5

Reading the stream

In order to read an HTTP streaming response, the client can use the response.body property which is a ReadableStream allowing you to iterate over the chunks as they come in from the server using the .getReader() method.1

1const reader = request.body.getReader();
2try {
3	while (true) {
4	  const { value, done } = await reader.read();
5	  if (done) break;
6	  const text = TextDecoder().decode(value);
7	  //... do something with the chunk
8	}
9} finally {
10  reader.releaseLock();
11}
12

This handles every bit of data that we get back, but for the OpenAI HTTP protocol we are expecting the data to be JSON separated by newlines, so instead we will split up the response body and “yield” each line as they’re completed. We buffer the in-progress line into lastFragment and only return full lines that have been separated by two newlines:

1// stream here is request.body
2async function* splitStream(stream: ReadableStream<Uint8Array>) {
3  const reader = stream.getReader();
4  let lastFragment = "";
5  try {
6    while (true) {
7      const { value, done } = await reader.read();
8      if (done) {
9        // Flush the last fragment now that we're done
10        if (lastFragment !== "") {
11          yield lastFragment;
12        }
13        break;
14      }
15      const data = new TextDecoder().decode(value);
16      lastFragment += data;
17      const parts = lastFragment.split("\n\n");
18      // Yield all except for the last part
19      for (let i = 0; i < parts.length - 1; i += 1) {
20        yield parts[i];
21      }
22      // Save the last part as the new last fragment
23      lastFragment = parts[parts.length - 1];
24    }
25  } finally {
26    reader.releaseLock();
27  }
28}
29

If this function* and yield syntax is unfamiliar to you, just treat function* as a function that can return multiple things in a loop, and yield as the way of returning something multiple times from a function.

You can then loop over this splitStream function like:

1for await (const data of splitStream(response.body)) {
2  // data here is a full line of text. For OpenAI, it might look like
3  // "data: {...some json object...}" or "data: [DONE]" at the end
4}
5

If this "for await" syntax throws you off, it's using what’s called an “async iterator” - like a regular iterator you’d use with a for loop, but every time it gets the next value, it’s awaited.

For our example, when we’ve gotten some text from OpenAI and we’re waiting for more, the for loop will wait until splitStream yields another value, which will happen when await reader.read() returns a value that finishes one or more lines of text.

Next up we’ll look at another way of returning an async iterator that isn’t a function like splitStream, so a caller can use a “for await” loop to iterate over this data.

Returning an async iterator

Now that we have an async iterator returning full lines of text, we could just return splitStream(response.body), but we want to intercept each of the lines and transform them, while still letting the caller of our function to iterate.

The approach is similar to to the async function* syntax above. Here we’ll return an async iterator directly, instead of an async function that returns one when it’s called. The difference is the type is AsyncIterator instead of AsyncGenerator which needs to be called first. An AsyncIterator can be defined by having a certain named function: Symbol.asyncIterator.2

1      return {
2        [Symbol.asyncIterator]: async function* () {
3          for await (const data of splitStream(stream)) {
4            //handle the data
5            yield data;
6          }
7        },
8      };
9

This is useful when you want to return something different from the data coming from splitStream. Every time a new line comes in from the streaming HTTP request, splitStream will yield it, this function will receive it in data and can do something before yielding it to its caller.

Next we’ll look at how to interpret this data specifically in the case of OpenAI’s streaming chat completion API.

Handling the OpenAI HTTP streaming protocol

The OpenAI response protocol is a series of lines that start with data: or event:, but we’ll just handle the data responses, since that’s the useful part for chat completions. There’s a sentinel of [DONE] if the stream is done, otherwise it’s just JSON.

1for await (const data of splitStream(stream)) {
2  if (data.startsWith("data:")) {
3    const json = data.substring("data:".length).trimStart();
4    if (json.startsWith("[DONE]")) {
5      return;
6    }
7    yield JSON.parse(json);
8  } else {
9    console.debug("Unexpected data:", data);
10  }
11}
12

Bringing it all together

Now that you understand HTTP streaming, you can feel confident working directly with streaming APIs without relying on sdks or libraries. This allows you to hide latency, as your UI can immediately start updating, without consuming more bandwidth with multiple requests. You can use the above function like you would with the official openai npm package:

1  const response = await createChatCompletion({
2    model: "llama3",
3    messages: [...your messages...],
4    stream: true,
5  });
6  for await (const chunk of response) {
7    if (chunk.choices[0].delta?.content) {
8      console.log(chunk.choices[0].delta.content);
9    }
10  }
11

See the code here that also lets you make some utility functions to make this even easier by pre-configuring the model and extracting the .choices[0].delta.content:

1const response = await chatStream(messages);
2for await (const content of response) {
3  console.log(content);
4}
5

Before you copy the code, try to implement it yourself as an exercise in async functions.

More resources

  • For information about returning HTTP streaming data from your own server endpoint, check out this post on AI Chat with HTTP Streaming that both streams data from OpenAI (or similar) to your server and simultaneously streams it down to a client, while doing custom logic as it goes (such as saving chunks to a database).
  • The MDN docs, as always, are great. Beyond the links above, here’s a guide on the readable streams API that shows how to connect a readable stream to an <img> tag to stream in an image request. Note: this guide uses response.body as an async iterator, but currently that is not widely implemented and not in the TypeScript types.

Footnotes

  1. Note: you can only have one reader of the stream at a time, so you generally don’t call .getReader() multiple times - you probabaly want .tee() in that case, and if you want to use .getReader() multiple times for some reason, make sure to have the first .releaseLock() first.

  2. Or alternatively you can If you aren’t familiar with Symbol, it’s used in a way to have keys in an object that aren’t strings or numbers. That way they don’t conflict if you added a key named asyncIterator. You could access the function with myIterator[Symbol.asyncIterator]().

Build in minutes, scale forever.

Convex is the sync platform with everything you need to build your full-stack project. Cloud functions, a database, file storage, scheduling, search, and realtime updates fit together seamlessly.

Get started