From d4a4971db9997719d8043f8f51dd4c8d4f380f10 Mon Sep 17 00:00:00 2001 From: Peter Dave Hello Date: Sun, 12 May 2024 18:58:28 +0800 Subject: [PATCH] Fix handling of empty choices array in Azure OpenAI API integration This commit refines the error handling for the Azure OpenAI API integration to address the 'n.choices[0] is undefined' error by ensuring 'data.choices' and 'data.choices[0]' are properly checked before access. This update is necessary due to the behavior changes introduced in the API version update (#684), which can result in empty 'choices' arrays. Fix #698. --- src/services/apis/azure-openai-api.mjs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/services/apis/azure-openai-api.mjs b/src/services/apis/azure-openai-api.mjs index ef1f306..e7255dd 100644 --- a/src/services/apis/azure-openai-api.mjs +++ b/src/services/apis/azure-openai-api.mjs @@ -47,11 +47,18 @@ export async function generateAnswersWithAzureOpenaiApi(port, question, session) console.debug('json error', error) return } - if ('content' in data.choices[0].delta) { + if ( + data.choices && + data.choices.length > 0 && + data.choices[0] && + data.choices[0].delta && + 'content' in data.choices[0].delta + ) { answer += data.choices[0].delta.content port.postMessage({ answer: answer, done: false, session: null }) } - if (data.choices[0]?.finish_reason) { + + if (data.choices && data.choices.length > 0 && data.choices[0]?.finish_reason) { pushRecord(session, question, answer) console.debug('conversation history', { content: session.conversationRecords }) port.postMessage({ answer: null, done: true, session: session })