2023-11-09 14:04:36 -05:00
|
|
|
const OpenAI = require('openai');
|
2025-10-01 23:30:47 -04:00
|
|
|
const { logger } = require('@librechat/data-schemas');
|
2023-11-09 14:04:36 -05:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Handles errors that may occur when making requests to OpenAI's API.
|
|
|
|
|
* It checks the instance of the error and prints a specific warning message
|
|
|
|
|
* to the console depending on the type of error encountered.
|
|
|
|
|
* It then calls an optional error callback function with the error object.
|
|
|
|
|
*
|
|
|
|
|
* @param {Error} err - The error object thrown by OpenAI API.
|
|
|
|
|
* @param {Function} errorCallback - A callback function that is called with the error object.
|
|
|
|
|
* @param {string} [context='stream'] - A string providing context where the error occurred, defaults to 'stream'.
|
|
|
|
|
*/
|
|
|
|
|
async function handleOpenAIErrors(err, errorCallback, context = 'stream') {
|
|
|
|
|
if (err instanceof OpenAI.APIError && err?.message?.includes('abort')) {
|
2023-12-14 07:49:27 -05:00
|
|
|
logger.warn(`[OpenAIClient.chatCompletion][${context}] Aborted Message`);
|
2023-11-09 14:04:36 -05:00
|
|
|
}
|
|
|
|
|
if (err instanceof OpenAI.OpenAIError && err?.message?.includes('missing finish_reason')) {
|
2023-12-14 07:49:27 -05:00
|
|
|
logger.warn(`[OpenAIClient.chatCompletion][${context}] Missing finish_reason`);
|
2023-11-09 14:04:36 -05:00
|
|
|
} else if (err instanceof OpenAI.APIError) {
|
2023-12-14 07:49:27 -05:00
|
|
|
logger.warn(`[OpenAIClient.chatCompletion][${context}] API error`);
|
2023-11-09 14:04:36 -05:00
|
|
|
} else {
|
2023-12-14 07:49:27 -05:00
|
|
|
logger.warn(`[OpenAIClient.chatCompletion][${context}] Unhandled error type`);
|
2023-11-09 14:04:36 -05:00
|
|
|
}
|
|
|
|
|
|
2025-01-17 12:55:48 -05:00
|
|
|
logger.error(err);
|
|
|
|
|
|
2023-11-09 14:04:36 -05:00
|
|
|
if (errorCallback) {
|
|
|
|
|
errorCallback(err);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
module.exports = handleOpenAIErrors;
|