kimaai_chat_response_saved

When it fires

Right after an answer was written to the chat history, once per answer: on the path that does not stream and on the streaming one, for the chatbot, the admin assistant and the search answer. It is the one point every completed answer passes, so KimaAI hooks it for its token usage, the daily message count, the conversation insights and the human handoff (Pro). It also fires for a quick action whose callback answers without the provider: with openai as the provider and a response KimaAI built, which has no usage. It does not fire when the provider fails.

$payload['assistant_surface'] is admin_assistant or search outside the chat; in the chat it is not set. $response is the provider’s own format: the Responses API of OpenAI and Chat Completions both report usage with total_tokens. The visitor’s answer is still on its way when the action runs, so keep the work short or schedule it.

Parameters

NameTypeDescription
providerstringThe provider, openai, openrouter or ollama.
payloadarrayThe request as it was saved, keys in snake_case, with session_id, env_id, user_message where the provider needs it, chatbot_settings and assistant_surface outside the chat.
responsearrayThe provider’s raw response, with its usage, and KimaAI’s _kimaai_final_message when kimaai_chatbot_final_message changed the text.

Example

add_action(
  'kimaai_chat_response_saved',
  function (string $provider, array $payload, array $response): void {
    // Tokens per surface, for a report of your own.
    $surface = (string) ($payload['assistant_surface'] ?? 'chatbot');
    $totals = (array) get_option('my_kimaai_tokens', []);
    $totals[$surface] = (int) ($totals[$surface] ?? 0) + (int) ($response['usage']['total_tokens'] ?? 0);
    update_option('my_kimaai_tokens', $totals, false);
  },
  10,
  3
);
  • kimaai_chatbot_final_message: changes the answer text before it is saved.
  • kimaai_chatbot_after_response: fires after the answer with the request’s own payload.

What are your feelings