kimaai_chatbot_error

kimaai_chatbot_error Hook #

The kimaai_chatbot_error action fires when the chatbot encounters an error during AI execution—specifically when AiService::run() throws an exception.

Use it for error reporting (Sentry/Bugsnag), alerting, logging, and collecting debugging context (provider/model/session, request payload, exception details).


When it fires #

Inside the REST handler, the plugin calls the AI service in a try/catch:

try {
  $response = $this->ai_service->run($ai_payload, 'chat');
} catch (\Exception $e) {
  $msg = $e->getMessage();

  do_action('kimaai_chatbot_error', 'ai_exception', $msg, [
    'exception' => $e,
    'ai_payload' => $ai_payload,
    'payload' => $payload,
  ]);

  return new WP_REST_Response(['error' => $msg], 500);
}

So this hook fires only when an exception is thrown by the AI service call (not for gate blocks or rate limiting).


Hook signature #

/**
 * Action fired when an AI exception occurs.
 *
 * @param string $msg The error message.
 * @param Exception $e The exception object.
 * @param array $ai_payload The provider payload that was sent.
 * @param array $payload Normalized payload.
 */
do_action('kimaai_chatbot_error', 'ai_exception', $msg, [
  'exception' => $e,
  'ai_payload' => $ai_payload,
  'payload' => $payload,
]);

Parameters #

1) $code (string) #

A short machine-readable error code.

Currently emitted code in the provided implementation:

  • ai_exception — thrown exception during provider execution

Tip: You can treat $code as a category for grouping in logs/monitoring.

2) $message (string) #

The error message (currently the exception message).

This same message is returned to the client in the REST response body:

{ "error": "..." }

(with HTTP status 500)

3) $context (array) #

A structured array of supporting context. The plugin currently provides:

  • exception (\Exception) — the caught exception object
  • ai_payload (array) — the AI request payload that was about to be sent
  • payload (array) — the normalized chatbot payload (prompt/session/tools/postId/settings context)

Basic usage: log errors #

add_action('kimaai_chatbot_error', function ($code, $message, $context) {
  error_log(sprintf('[KimaAI Chatbot Error] %s: %s', $code, $message));

  // Optional: log provider/model (avoid logging full prompt in production).
  $ai_payload = $context['ai_payload'] ?? [];
  error_log(sprintf(
    'provider=%s model=%s session=%s',
    (string) ($ai_payload['aiProvider'] ?? ''),
    (string) ($ai_payload['aiModel'] ?? ''),
    (string) ($ai_payload['sessionId'] ?? '')
  ));
}, 10, 3);

Example: send errors to Sentry (or similar) #

add_action('kimaai_chatbot_error', function ($code, $message, $context) {
  if (!function_exists('sentry_capture_exception')) {
    return;
  }

  $e = $context['exception'] ?? null;
  if ($e instanceof \Throwable) {
    // Attach metadata as tags/extra depending on your integration.
    sentry_capture_exception($e, [
      'tags' => [
        'kimaai_error_code' => $code,
        'ai_provider' => (string) (($context['ai_payload']['aiProvider'] ?? '')),
        'ai_model' => (string) (($context['ai_payload']['aiModel'] ?? '')),
      ],
      'extra' => [
        // Keep this minimal to avoid leaking user data.
        'postId' => (int) (($context['ai_payload']['postId'] ?? 0)),
        'sessionId' => (string) (($context['ai_payload']['sessionId'] ?? '')),
        'tools_count' => !empty($context['ai_payload']['tools'])
          ? count($context['ai_payload']['tools'])
          : 0,
      ],
    ]);
  }
}, 10, 3);

Example: privacy-aware logging (hash the prompt) #

If you need correlation without storing user text:

add_action('kimaai_chatbot_error', function ($code, $message, $context) {
  $ai_payload = $context['ai_payload'] ?? [];
  $prompt = (string) ($ai_payload['prompt'] ?? '');
  $prompt_hash = $prompt !== '' ? hash('sha256', $prompt) : '';

  $entry = [
    'time'        => time(),
    'code'        => $code,
    'message'     => $message,
    'provider'    => (string) ($ai_payload['aiProvider'] ?? ''),
    'model'       => (string) ($ai_payload['aiModel'] ?? ''),
    'sessionId'   => (string) ($ai_payload['sessionId'] ?? ''),
    'postId'      => (int) ($ai_payload['postId'] ?? 0),
    'prompt_hash' => $prompt_hash,
  ];

  error_log('[KimaAI Chatbot Error] ' . wp_json_encode($entry));
}, 10, 3);

Best practices #

  • Do not echo output inside the hook (REST responses must remain valid JSON).
  • Treat $context['ai_payload'] and $context['payload'] as potentially sensitive:
    • avoid storing raw prompts unless you truly need them
    • consider hashing/anonymizing identifiers you log
  • If you need latency metrics, pair this hook with:
    • kimaai_chatbot_before_request (store start time)
    • kimaai_chatbot_after_response (success path)
    • kimaai_chatbot_error (error path)

  • kimaai_chatbot_before_request — fired right before the AI call (good for timing start)
  • kimaai_chatbot_after_response — fired after a successful AI response
  • kimaai_chatbot_blocked — fired when requests are blocked by the gate (not exceptions)
  • kimaai_chatbot_rate_limited — fired when daily message limit is exceeded (not exceptions)
Updated on December 13, 2025