From 2821bf0b1ba6c16ea2523a4b087dab78fe82ddcc Mon Sep 17 00:00:00 2001 From: Stef Dunlap Date: Mon, 6 Mar 2023 22:59:22 -0500 Subject: [PATCH] Initial working commit --- index.js | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/index.js b/index.js index 91477bb..97cfb2b 100644 --- a/index.js +++ b/index.js @@ -18,7 +18,7 @@ client.addListener('message', async (from, to, message) => { }); // function that calls the chatgpt streaming api (with server send events) and calls the callback function for each line -function chatgpt(query, callback) { +async function chatgpt(query, callback) { const apiUrl = 'https://api.openai.com/v1/chat/completions'; const response = await axios.post(apiUrl, { @@ -40,17 +40,19 @@ function chatgpt(query, callback) { // parse if starts with data: for(part of parts) { if(part === 'data: [DONE]') { - process.stdout.write('\n'); + callback(line); + line = ''; } else if(part.startsWith('data: ')) { let jsonString = part.slice(part.indexOf('{'), part.lastIndexOf('}') + 1); try { let json = JSON.parse(jsonString); let chunk = json.choices[0].delta.content; + if(!chunk) { return; } //split the chunk into lines leaving the delimiter in the array - const lines = str.split(/\r?\n/); // split by new lines + const lines = chunk.split(/\r?\n/); // split by new lines - let hasStartNewline = str.startsWith("\n"); - let hasEndNewline = str.endsWith("\n"); + let hasStartNewline = chunk.startsWith("\n"); + let hasEndNewline = chunk.endsWith("\n"); if(hasStartNewline) { callback(line); @@ -58,7 +60,7 @@ function chatgpt(query, callback) { } for (let i = 0; i < lines.length - 1; i++) { - callback(lines[i]); + callback(line+lines[i]); line = ''; } @@ -75,4 +77,4 @@ function chatgpt(query, callback) { } } }); -} \ No newline at end of file +}