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.
This commit is contained in:
Peter Dave Hello
2024-05-12 18:58:28 +08:00
committed by josc146
parent f177a3340c
commit d4a4971db9
+9 -2
View File
@@ -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 })