diff --git a/api_webchat/model-worker.js b/api_webchat/model-worker.js index 6858bd5b..f0277c1d 100644 --- a/api_webchat/model-worker.js +++ b/api_webchat/model-worker.js @@ -89,10 +89,16 @@ self.onmessage = async function(event) { postMessage({ type: 'messageSent' }); if (!response.ok) { - const errorJSON = await response.json(); - const errorDetail = JSON.stringify(errorJSON); - //console.log(">>>>>>>>>>>>> errorJSON.error.message: " + JSON.stringify(errorJSON.error.message)); - postMessage({ type: 'error', payload: errorJSON.error.message }); + let error_message = ''; + if(response.is_exception === true){ + error_message = response.error; + }else{ + const errorJSON = await response.json(); + const errorDetail = JSON.stringify(errorJSON); + error_message = errorJSON.error.message; + //console.log(">>>>>>>>>>>>> errorJSON.error.message: " + JSON.stringify(errorJSON.error.message)); + } + postMessage({ type: 'error', payload: error_message }); throw new Error("[ThunderAI] OpenAI API request failed: " + response.status + " " + response.statusText + ", Detail: " + errorDetail); } diff --git a/js/api/openai.js b/js/api/openai.js index 71616ba6..9eb21fda 100644 --- a/js/api/openai.js +++ b/js/api/openai.js @@ -60,21 +60,29 @@ export class OpenAI { } fetchResponse = async (messages, maxTokens = 0) => { - const response = await fetch("https://api.openai.com/v1/chat/completions", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer "+ this.apiKey - }, - body: JSON.stringify({ - model: this.model, - messages: messages, - stream: this.stream, - ...(maxTokens > 0 ? { 'max_tokens': parseInt(maxTokens) } : {}) - }), - }); - - return response; + try { + const response = await fetch("https://api.openai.com/v1/chat/completions", { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer "+ this.apiKey + }, + body: JSON.stringify({ + model: this.model, + messages: messages, + stream: this.stream, + ...(maxTokens > 0 ? { 'max_tokens': parseInt(maxTokens) } : {}) + }), + }); + return response; + }catch (error) { + console.error("[ThunderAI] OpenAI API request failed: " + error); + let output = {}; + output.is_exception = true; + output.ok = false; + output.error = "OpenAI API request failed: " + error; + return output; + } } async countTokensUsingAPI(model, text) {