* @license GPL-2.0+ https://www.gnu.org/licenses/gpl-2.0.html * @link https://aisk.chat */ /** * AISK_Help_Questions Class * * @category WordPress * @package AISK * @author Aisk Team * @license GPL-2.0+ https://www.gnu.org/licenses/gpl-2.0.html * @link https://aisk.chat */ class AISK_Help_Questions { const HASH_OPTION = 'aisk_help_questions_hash'; const MAX_QUESTIONS = 10; // Indexed content types sampled for questions, with their prompt headings const SOURCE_TYPES = [ 'external_url' => 'EXTERNAL SOURCES', 'page' => 'WEBSITE PAGES', 'post' => 'BLOG POSTS', ]; const MAX_ITEMS_PER_TYPE = 15; const MIN_CHARS_PER_ITEM = 80; const MAX_CHARS_PER_ITEM = 1000; const MAX_CHARS_PER_TYPE = 4000; private static $instance = null; private $table; /** * Get the singleton instance * * @return AISK_Help_Questions */ public static function get_instance() { if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * Class constructor * * @return void */ private function __construct() { global $wpdb; $this->table = $wpdb->prefix . 'aisk_help_questions'; add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] ); } /** * Register admin REST routes * * @return void */ public function register_rest_routes() { $admin_only = function () { return current_user_can( 'manage_options' ); }; register_rest_route( 'aisk/v1', '/help-questions', [ [ 'methods' => 'GET', 'callback' => [ $this, 'rest_list' ], 'permission_callback' => $admin_only, ], [ 'methods' => 'POST', 'callback' => [ $this, 'rest_create' ], 'permission_callback' => $admin_only, 'args' => [ 'question' => [ 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ], ], ], ] ); register_rest_route( 'aisk/v1', '/help-questions/regenerate', [ 'methods' => 'POST', 'callback' => [ $this, 'rest_regenerate' ], 'permission_callback' => $admin_only, ] ); register_rest_route( 'aisk/v1', '/help-questions/(?P\d+)', [ [ 'methods' => 'POST', 'callback' => [ $this, 'rest_update' ], 'permission_callback' => $admin_only, 'args' => [ 'question' => [ 'required' => false, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ], 'is_active' => [ 'required' => false, 'type' => 'boolean', ], ], ], [ 'methods' => 'DELETE', 'callback' => [ $this, 'rest_delete' ], 'permission_callback' => $admin_only, ], ] ); } /** * List all questions for the admin screen * * @return WP_REST_Response */ public function rest_list() { return rest_ensure_response( $this->get_all() ); } /** * Add a manual question * * @param WP_REST_Request $request Request object * * @return WP_REST_Response|WP_Error */ public function rest_create( $request ) { global $wpdb; $question = $this->clean_question( $request->get_param( 'question' ) ); if ( '' === $question ) { return new WP_Error( 'empty_question', __( 'Question cannot be empty.', 'aisk-ai-chat' ), [ 'status' => 400 ] ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table $wpdb->insert( $this->table, [ 'question' => $question, 'source' => 'manual', 'is_active' => 1, 'sort_order' => $this->next_sort_order(), ], [ '%s', '%s', '%d', '%d' ] ); return rest_ensure_response( $this->get_all() ); } /** * Edit a question or toggle its visibility * * @param WP_REST_Request $request Request object * * @return WP_REST_Response|WP_Error */ public function rest_update( $request ) { global $wpdb; $id = (int) $request->get_param( 'id' ); $data = []; $format = []; if ( null !== $request->get_param( 'question' ) ) { $question = $this->clean_question( $request->get_param( 'question' ) ); if ( '' === $question ) { return new WP_Error( 'empty_question', __( 'Question cannot be empty.', 'aisk-ai-chat' ), [ 'status' => 400 ] ); } $data['question'] = $question; // An edited question is owned by the admin, so regeneration keeps it $data['source'] = 'manual'; $format[] = '%s'; $format[] = '%s'; } if ( null !== $request->get_param( 'is_active' ) ) { $data['is_active'] = rest_sanitize_boolean( $request->get_param( 'is_active' ) ) ? 1 : 0; $format[] = '%d'; } if ( ! empty( $data ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table $wpdb->update( $this->table, $data, [ 'id' => $id ], $format, [ '%d' ] ); } return rest_ensure_response( $this->get_all() ); } /** * Delete a question * * @param WP_REST_Request $request Request object * * @return WP_REST_Response */ public function rest_delete( $request ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table $wpdb->delete( $this->table, [ 'id' => (int) $request->get_param( 'id' ) ], [ '%d' ] ); return rest_ensure_response( $this->get_all() ); } /** * Regenerate the automatic questions on demand * * @return WP_REST_Response|WP_Error */ public function rest_regenerate() { $result = $this->maybe_generate( true ); if ( is_wp_error( $result ) ) { return $result; } return rest_ensure_response( $this->get_all() ); } /** * Get every question, ordered for display * * @return array */ public function get_all() { global $wpdb; $table = esc_sql( $this->table ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name cannot be parameterized, admin list needs fresh data $rows = $wpdb->get_results( "SELECT id, question, source, is_active, sort_order FROM {$table} ORDER BY sort_order ASC, id ASC", ARRAY_A ); return array_map( function ( $row ) { return [ 'id' => (int) $row['id'], 'question' => $row['question'], 'source' => $row['source'], 'is_active' => (bool) $row['is_active'], ]; }, $rows ? $rows : [] ); } /** * Get the visible questions for the chat widget * * @param int $limit Maximum number of questions * * @return string[] */ public function get_active_questions( $limit = 6 ) { global $wpdb; $table = esc_sql( $this->table ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name cannot be parameterized $questions = $wpdb->get_col( $wpdb->prepare( "SELECT question FROM {$table} WHERE is_active = 1 ORDER BY sort_order ASC, id ASC LIMIT %d", $limit ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching return $questions ? array_values( $questions ) : []; } /** * Generate questions from Contact Information, Custom Content and the * indexed External Sources, pages and posts. * Skips the API call when the content has not changed since the last run. * * @param bool $force Regenerate even if the content is unchanged * * @return true|WP_Error */ public function maybe_generate( $force = false ) { $settings = get_option( 'aisk_settings', [] ); $contact_info = isset( $settings['ai_config']['contact_info'] ) ? trim( $settings['ai_config']['contact_info'] ) : ''; $custom_content = isset( $settings['ai_config']['custom_content'] ) ? trim( $settings['ai_config']['custom_content'] ) : ''; $api_key = isset( $settings['general']['openai_key'] ) ? $settings['general']['openai_key'] : ''; $indexed_content = $this->get_indexed_content(); if ( '' === $contact_info && '' === $custom_content && '' === $indexed_content ) { $this->replace_auto_questions( [] ); delete_option( self::HASH_OPTION ); return true; } $hash = md5( $contact_info . '|' . $custom_content . '|' . $indexed_content ); if ( ! $force && get_option( self::HASH_OPTION ) === $hash ) { return true; } if ( empty( $api_key ) ) { return new WP_Error( 'missing_api_key', __( 'OpenAI API key is not configured', 'aisk-ai-chat' ), [ 'status' => 400 ] ); } $questions = $this->request_questions( $api_key, $contact_info, $custom_content, $indexed_content ); if ( is_wp_error( $questions ) ) { return $questions; } $this->replace_auto_questions( $questions ); update_option( self::HASH_OPTION, $hash, false ); return true; } /** * Build a compact sample of the indexed External Sources, pages and posts. * Uses the first stored chunk of each item, which holds its title and opening text. * * @return string */ private function get_indexed_content() { global $wpdb; $table = esc_sql( $wpdb->prefix . 'aisk_embeddings' ); $content = ''; foreach ( self::SOURCE_TYPES as $content_type => $heading ) { // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name cannot be parameterized, generation needs fresh data $chunks = $wpdb->get_col( $wpdb->prepare( "SELECT LEFT(e.content_chunk, %d) FROM {$table} e INNER JOIN ( SELECT MIN(id) AS id FROM {$table} WHERE content_type = %s GROUP BY content_id, crawled_url ORDER BY MAX(updated_at) DESC LIMIT %d ) first_chunks ON first_chunks.id = e.id ORDER BY e.id ASC", self::MAX_CHARS_PER_ITEM, $content_type, self::MAX_ITEMS_PER_TYPE ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching $section = ''; foreach ( (array) $chunks as $chunk ) { $chunk = html_entity_decode( wp_strip_all_tags( strip_shortcodes( (string) $chunk ) ), ENT_QUOTES, 'UTF-8' ); $chunk = trim( preg_replace( '/\s+/u', ' ', $chunk ) ); // Skip items with no real text, e.g. Cart or Checkout pages that only hold a shortcode if ( strlen( $chunk ) < self::MIN_CHARS_PER_ITEM ) { continue; } if ( strlen( $section ) + strlen( $chunk ) > self::MAX_CHARS_PER_TYPE ) { break; } $section .= '- ' . $chunk . "\n"; } if ( '' !== $section ) { $content .= $heading . ":\n" . $section . "\n"; } } return trim( $content ); } /** * Ask OpenAI for customer questions answerable from the given content * * @param string $api_key OpenAI API key * @param string $contact_info Contact information * @param string $custom_content Custom business content * @param string $indexed_content Sample of External Sources, pages and posts * * @return string[]|WP_Error */ private function request_questions( $api_key, $contact_info, $custom_content, $indexed_content = '' ) { $content = ''; if ( '' !== $contact_info ) { $content .= "CONTACT INFORMATION:\n" . $contact_info . "\n\n"; } if ( '' !== $custom_content ) { $content .= "BUSINESS INFORMATION:\n" . $custom_content . "\n\n"; } if ( '' !== $indexed_content ) { $content .= $indexed_content . "\n\n"; } // Name every section sent, so the questions cover all of them, not just contact details preg_match_all( '/^([A-Z ]+):$/m', $content, $matches ); $sections = implode( ', ', $matches[1] ); $system_prompt = 'You write the short questions a store customer would tap in a support chat. ' . 'Only write questions that the provided content can answer. ' . 'The content has these sections: ' . $sections . '. ' . 'Write at least 2 questions for each section, so every section is covered. ' . 'For EXTERNAL SOURCES, WEBSITE PAGES and BLOG POSTS, ask about the specific products, topics or facts they describe ' . '(e.g. "What are the [product name] specs?" with the real name), ignoring navigation menus and boilerplate. ' . 'Never ask about a page or post itself (e.g. "What is on your Sample Page?"); ask about its subject. ' . 'Cover different products or topics rather than several questions about one. ' . 'Write 5 to ' . self::MAX_QUESTIONS . ' questions, each under 60 characters, in the same language as the content, ' . 'phrased in first person or as a direct question (e.g. "What are your store hours?"). ' . 'Do not invent facts. Respond only with JSON: {"questions": ["..."]}'; $request_id = uniqid( 'hq_', true ); $start = microtime( true ); $response = wp_remote_post( AISK_OPENAI_API_URL . '/chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ], 'body' => wp_json_encode( [ 'model' => AISK_Model_Manager::get_chat_model(), 'messages' => [ [ 'role' => 'system', 'content' => $system_prompt ], [ 'role' => 'user', 'content' => $content ], ], 'temperature' => 0.4, 'max_tokens' => 500, 'response_format' => [ 'type' => 'json_object' ], ] ), 'timeout' => 30, ] ); $status_code = is_wp_error( $response ) ? 0 : wp_remote_retrieve_response_code( $response ); $body = is_wp_error( $response ) ? [] : json_decode( wp_remote_retrieve_body( $response ), true ); $this->log_usage( $request_id, $start, $status_code, $body ); if ( is_wp_error( $response ) ) { return new WP_Error( 'openai_request_failed', 'Failed to connect to OpenAI: ' . esc_html( $response->get_error_message() ), [ 'status' => 502 ] ); } if ( 200 !== $status_code ) { $message = isset( $body['error']['message'] ) ? $body['error']['message'] : 'Unexpected response'; return new WP_Error( 'openai_error', 'OpenAI error: ' . esc_html( $message ), [ 'status' => 502 ] ); } $content_json = isset( $body['choices'][0]['message']['content'] ) ? json_decode( $body['choices'][0]['message']['content'], true ) : null; $raw_questions = isset( $content_json['questions'] ) && is_array( $content_json['questions'] ) ? $content_json['questions'] : []; $questions = []; foreach ( $raw_questions as $question ) { $question = $this->clean_question( is_string( $question ) ? $question : '' ); if ( '' !== $question && ! in_array( $question, $questions, true ) ) { $questions[] = $question; } } return array_slice( $questions, 0, self::MAX_QUESTIONS ); } /** * Swap the automatic questions for a new set, keeping admin-owned ones * * @param string[] $questions New questions * * @return void */ private function replace_auto_questions( $questions ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table $wpdb->delete( $this->table, [ 'source' => 'auto' ], [ '%s' ] ); $sort_order = $this->next_sort_order(); foreach ( $questions as $question ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table $wpdb->insert( $this->table, [ 'question' => $question, 'source' => 'auto', 'is_active' => 1, 'sort_order' => $sort_order++, ], [ '%s', '%s', '%d', '%d' ] ); } } /** * Next sort position at the end of the list * * @return int */ private function next_sort_order() { global $wpdb; $table = esc_sql( $this->table ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table name cannot be parameterized return (int) $wpdb->get_var( "SELECT COALESCE(MAX(sort_order), -1) + 1 FROM {$table}" ); } /** * Normalize a question string * * @param string $question Raw question * * @return string */ private function clean_question( $question ) { $question = trim( sanitize_text_field( (string) $question ) ); return function_exists( 'mb_substr' ) ? mb_substr( $question, 0, 255 ) : substr( $question, 0, 255 ); } /** * Record the OpenAI call in the API usage log * * @param string $request_id Request ID * @param float $start Start time * @param int $status_code HTTP status * @param array $body Decoded response body * * @return void */ private function log_usage( $request_id, $start, $status_code, $body ) { if ( ! class_exists( 'AISK_API_Usage_Tracker' ) ) { return; } AISK_API_Usage_Tracker::get_instance()->log_usage( [ 'request_id' => $request_id, 'channel' => 'admin', 'feature' => 'help_questions', 'provider' => 'openai', 'endpoint' => 'chat/completions', 'model' => AISK_Model_Manager::get_chat_model(), 'status' => 200 === $status_code ? 'success' : 'error', 'error_code' => 200 === $status_code ? null : 'http_' . $status_code, 'latency_ms' => (int) ( ( microtime( true ) - $start ) * 1000 ), 'tokens_in' => isset( $body['usage']['prompt_tokens'] ) ? (int) $body['usage']['prompt_tokens'] : 0, 'tokens_out' => isset( $body['usage']['completion_tokens'] ) ? (int) $body['usage']['completion_tokens'] : 0, ] ); } }