2 min read 2 wks ago

Handle error messages

Most errors come directly from the AI providers you are using, not from the plugin: a wrong API key, a quota reached, an overloaded model, and so on. These messages make sense to you as a developer, but not to the people using your chatbot.

What visitors see by default

Since AI Engine 3.7.1, the real error is no longer shown to visitors. When something fails on the server, in a chatbot or an AI Form, they see a generic message instead:

Oops! Something went wrong on the server. Please try again, and if you are the site developer, check the PHP Error Logs for details.

The real error is written to your PHP error logs. Administrators still see the real error in the chat, so you can find the problem quickly when you test your chatbot while logged in.

Refusals are different: when a message is blocked by your limits, your banned words or IPs, or by your own code (see Chatbot Takeover), the message is written for the visitor, so it is shown as it is.

Change the generic message

Use the mwai_public_error_message filter. It receives the generic message and the original exception, so you can also return a different message depending on the error. This is also how you translate it.

add_filter( 'mwai_public_error_message', function ( $message, $exception ) {
  $error = $exception ? $exception->getMessage() : '';
  if ( stripos( $error, 'quota' ) !== false ) {
    return 'Our assistant is taking a break. Please come back a bit later.';
  }
  return 'Sorry, something went wrong. Please try again in a moment.';
}, 10, 2 );

Change the real error message

The mwai_ai_exception filter still exists. It receives the original error message and runs before everything above, so it changes what administrators see, and the text of refusals shown to visitors. For example, to make a provider error easier to read:

add_filter( 'mwai_ai_exception', function ( $message ) {
  if ( stripos( $message, 'Incorrect API key' ) !== false ) {
    return 'The OpenAI API key is wrong. Check it in AI Engine > Settings > AI.';
  }
  return $message;
} );

Some error messages are written by the chatbot itself, in the visitor’s browser (connection lost, upload failed, and so on). Those are changed with the mwai_chatbot_texts filter: see Translate or Change Chatbot Texts.