SpellcraftAI/openai-streams

How to use in Node?

joni1802 opened this issue · 3 comments

Hello,

I am not quite sure how to use this library in Node. When I try to read data from the stream it says stream.on is not a function. Here is my example code:

import { OpenAI } from "openai-streams";

const stream = OpenAI(
  "chat",
  { model: "gpt-3.5-turbo", messages: [{ role: "user", content: "my question ..." }] },
  { apiKey: "" }
);

stream.on("data", (data) => {
  console.log("DATA:", data);
});

stream.on("end", () => {
  console.log("STREAM END");
});

Am I on the wrong track?

Oh I found the solution. You need to import openai-streams/node and await the response. Now I am able to retrive the chunks of the stream.

import { OpenAI } from "openai-streams/node";

const stream = await OpenAI(
  "chat",
  { model: "gpt-3.5-turbo", messages: [{ role: "user", content: "my question ..." }] },
  { apiKey: "" }
);

stream.on("data", (data) => {
  console.log("DATA:", data);
});

stream.on("end", () => {
  console.log("STREAM END");
});

@joni1802 I am seeing Module '"openai-streams/node"' has no exported member 'OpenAI'. Are you using ESM in your project?

@mattgi Yes I am using ESM in my project and using node version v20.0.0. I had no problem importing the module.