How to parse The chat completion chunk object

the object returns as a string, but the string is …unstable.
so ,can someone show me how to parse the return string with javaScript with zero error?
please ? i cant parse it correctly whatever i do.

async function main() {
  const completion = await openai.chat.completions.create({
    messages: [{ role: "system", content: "You are a helpful assistant." }],
    model: "gpt-3.5-turbo",
  });

  console.log(completion.choices[0]);
}

the res comes from this code above using the Create chat completion API
help me please

                    res.data.on('data', (data) => {
                        try {

how do i parse this data???
} catch (e) {
console.log(‘ERROR’, e);
reject(ERROR ${e});
}
})

Hi @whsabtechopenai

Based on this code, you’re not streaming the response. Thus you’d need to parse the chat completions object or modify your code to stream:

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const completion = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",
    messages: [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello!"}
    ],
    stream: true,
  });

  for await (const chunk of completion) {
    console.log(chunk.choices[0].delta.content);
  }
}

main();
1 Like

nonono my dear ,i just sort of ,im sorry ,ok ?
but i am streaming in my own project .look
chatSSE202309(messages) {
return openai.createChatCompletion({
model: “gpt-3.5-turbo”,
messages,
max_tokens: 2048,
temperature: 0.9,
stream: true
}, Object.assign({ responseType: ‘stream’ }, axiosConfig));
}
this .this. right .
so ,we are streaming ,we get the data from the on(‘data’,data=>{})event.

look i cant use the new api system its not working in my old openaiAPIversion .i just …

i cant just undate it if i like .i cant update the api system .i need the old version of how to deal with the old api returned data.

Thanks!!!


I have implemented an stop code into my server logic.

for await (const chunk of completion) {
   ...
   if (chunk.choices[0].finish_reason === 'stop') {
          console.log('stop!!')
          return;
  }
}