GPT Turbo LogoGPT Turbo Logo
GPT Turbo LogoGPT Turbo Logo

Message Streaming

Get the message content as it is being created, like ChatGPT.

By default, messsage responses are returned in a single string. However, you can also stream a message as it is generated, just like ChatGPT.

To do this, you need to set the stream option to true when creating a Conversation instance. Then, you can use the onContentStream method to listen for new content as it is generated.

import { Conversation } from "gpt-turbo";

const conversation = new Conversation({
    config: {
        apiKey,
        stream: true,
    },
});

const response = await conversation.prompt(
    "How can I make my code more efficient than a droid army?"
);

response.onContentStream(async (content, isStreaming) => {
    console.log(content);
});

Legacy Method (v4)

If you are using v4, you can use the onUpdate method to listen for new content as it is generated. Just don't forget to unsubscribe when you are done.

// ...

const unsubscribeUpdate = response.onUpdate((content) => {
    console.log(content);
});

const unsubscribeStop = response.onStreamingStop(() => {
    unsubscribeUpdate();
    unsubscribeStop();
});

this method also works in v5, but onContentStream is preferred.