= $total ) { break; } $i += ( $words_per_chunk - $overlap_words ); } return $chunks; } /** * Appelle l'API OpenAI Embeddings pour un lot de textes (jusqu'à 100 par appel). * * @param string[] $texts Textes à vectoriser. * @param string $openai_key Clé API. * @return array|null Vecteurs (même ordre que $texts), ou null en cas d'échec. */ function askbot_get_embeddings( $texts, $openai_key ) { if ( empty( $openai_key ) || empty( $texts ) ) { return null; } // Nettoyage défensif : un texte mal encodé en UTF-8 ferait échouer l'encodage JSON. $clean_texts = array_map( function ( $t ) { if ( ! mb_check_encoding( $t, 'UTF-8' ) ) { $t = mb_convert_encoding( $t, 'UTF-8', 'UTF-8' ); } return preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', ' ', $t ); }, $texts ); $payload = wp_json_encode( array( 'model' => ASKBOT_EMBEDDING_MODEL, 'input' => array_values( $clean_texts ), ), JSON_UNESCAPED_UNICODE ); if ( false === $payload ) { return null; } $response = wp_remote_post( 'https://api.openai.com/v1/embeddings', array( 'timeout' => 30, 'headers' => array( 'Authorization' => 'Bearer ' . $openai_key, 'Content-Type' => 'application/json', ), 'body' => $payload, ) ); if ( is_wp_error( $response ) ) { return null; } $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( empty( $body['data'] ) || ! is_array( $body['data'] ) ) { return null; } $vectors = array(); foreach ( $body['data'] as $item ) { $vectors[ $item['index'] ] = $item['embedding']; } ksort( $vectors ); return array_values( $vectors ); } /** * Similarité cosinus entre deux vecteurs de même dimension. * * @param float[] $a Vecteur A. * @param float[] $b Vecteur B. */ function askbot_cosine_similarity( $a, $b ) { $dot = 0.0; $norm_a = 0.0; $norm_b = 0.0; $len = min( count( $a ), count( $b ) ); for ( $i = 0; $i < $len; $i++ ) { $dot += $a[ $i ] * $b[ $i ]; $norm_a += $a[ $i ] * $a[ $i ]; $norm_b += $b[ $i ] * $b[ $i ]; } if ( $norm_a <= 0 || $norm_b <= 0 ) { return 0.0; } return $dot / ( sqrt( $norm_a ) * sqrt( $norm_b ) ); } /** * Types de documents pris en compte par la recherche sémantique. * * @return string[] */ function askbot_search_doc_types() { return array_values( array_unique( (array) apply_filters( 'askbot_search_doc_types', array( 'PAGE', 'ARTICLE' ) ) ) ); } /** * (Ré)indexe les pages et articles publiés : découpe en fragments, vectorise * via OpenAI, stocke en base. Remplace l'index existant pour ces types. * * @return int|false Nombre de fragments indexés, ou false (pas de clé). */ function askbot_reindex_site_embeddings() { $openai_key = askbot_get_openai_key(); if ( empty( $openai_key ) ) { return false; } global $wpdb; $table = $wpdb->prefix . 'askbot_embeddings'; $documents = array(); $pages = get_pages( array( 'number' => 0, 'sort_column' => 'menu_order', 'post_status' => 'publish', ) ); foreach ( $pages as $page ) { $content = trim( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $page->post_content ) ) ); if ( '' === $content ) { continue; } $documents[] = array( 'id' => $page->ID, 'type' => 'PAGE', 'title' => $page->post_title, 'content' => $content, ); } $posts = get_posts( array( 'numberposts' => -1, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', ) ); foreach ( $posts as $post ) { $content = trim( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $post->post_content ) ) ); if ( '' === $content ) { continue; } $documents[] = array( 'id' => $post->ID, 'type' => 'ARTICLE', 'title' => $post->post_title, 'content' => $content, ); } /** * Permet d'ajouter d'autres documents à indexer. * Chaque entrée : array( 'id' => …, 'type' => …, 'title' => …, 'content' => … ). */ $documents = (array) apply_filters( 'askbot_reindex_documents', $documents ); if ( empty( $documents ) ) { return 0; } $all_chunks = array(); foreach ( $documents as $doc ) { foreach ( askbot_chunk_text( $doc['content'] ) as $idx => $chunk_text ) { $all_chunks[] = array( 'post_id' => $doc['id'], 'type' => $doc['type'], 'title' => $doc['title'], 'chunk_index' => $idx, 'text' => $chunk_text, ); } } if ( empty( $all_chunks ) ) { return 0; } // Ne purger que les types réindexés ici : les autres (ex. documents ajoutés // par une extension) ont leur propre cycle de vie. $purge_types = array_values( array_unique( (array) apply_filters( 'askbot_reindex_purge_types', array( 'PAGE', 'ARTICLE' ) ) ) ); $placeholders = implode( ', ', array_fill( 0, count( $purge_types ), '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Table propre au plugin, placeholders générés dynamiquement. $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE doc_type IN ({$placeholders})", array_merge( array( $table ), $purge_types ) ) ); $batch_size = 100; $indexed = 0; $total = count( $all_chunks ); for ( $offset = 0; $offset < $total; $offset += $batch_size ) { $batch = array_slice( $all_chunks, $offset, $batch_size ); $texts = array_map( function ( $c ) { return $c['text']; }, $batch ); $vectors = askbot_get_embeddings( $texts, $openai_key ); if ( null === $vectors ) { continue; // Ce lot échoue, on continue avec les suivants. } foreach ( $batch as $i => $chunk ) { if ( ! isset( $vectors[ $i ] ) ) { continue; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Table propre au plugin. $wpdb->insert( $table, array( 'post_id' => $chunk['post_id'], 'doc_type' => $chunk['type'], 'doc_title' => $chunk['title'], 'chunk_index' => $chunk['chunk_index'], 'chunk_text' => $chunk['text'], 'embedding' => wp_json_encode( $vectors[ $i ] ), ), array( '%s', '%s', '%s', '%d', '%s', '%s' ) ); ++$indexed; } } update_option( 'askbot_embeddings_indexed_at', current_time( 'mysql' ) ); return $indexed; } // Cron quotidien : réindexe automatiquement si une clé OpenAI est configurée. add_action( 'askbot_daily_reindex_event', 'askbot_daily_reindex_callback' ); function askbot_daily_reindex_callback() { if ( '' === askbot_get_openai_key() ) { return; } askbot_reindex_site_embeddings(); } /** * Recherche par similarité sémantique : vectorise la question, compare aux * fragments indexés, retourne le contenu des $top_k plus pertinents. * * @param string $user_message Question du visiteur. * @param string $openai_key Clé API. * @param int $top_k Nombre de fragments. * @return string|null */ function askbot_search_embeddings( $user_message, $openai_key, $top_k = ASKBOT_EMBEDDING_TOP_K ) { global $wpdb; $table = $wpdb->prefix . 'askbot_embeddings'; $types = askbot_search_doc_types(); $placeholders = implode( ', ', array_fill( 0, count( $types ), '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- Table propre au plugin, placeholders générés dynamiquement. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT doc_type, doc_title, chunk_text, embedding FROM %i WHERE doc_type IN ({$placeholders})", array_merge( array( $table ), $types ) ), ARRAY_A ); if ( empty( $rows ) ) { return null; } $query_vectors = askbot_get_embeddings( array( $user_message ), $openai_key ); if ( null === $query_vectors || empty( $query_vectors[0] ) ) { return null; } $query_vector = $query_vectors[0]; foreach ( $rows as &$row ) { $vec = json_decode( $row['embedding'], true ); $row['score'] = is_array( $vec ) ? askbot_cosine_similarity( $query_vector, $vec ) : 0; } unset( $row ); usort( $rows, function ( $a, $b ) { return $b['score'] <=> $a['score']; } ); $context = ''; foreach ( array_slice( $rows, 0, $top_k ) as $r ) { $context .= "{$r['doc_type']}: {$r['doc_title']}\nCONTENU: {$r['chunk_text']}\n\n"; } return $context; } /** * Contexte du site envoyé à l'IA : recherche sémantique si l'index existe, * sinon repli sur les pages/articles récents. * * @param string $user_message Question du visiteur. */ function askbot_get_site_context( $user_message = '' ) { $header = '=== CONTENU DE ' . strtoupper( get_bloginfo( 'name' ) ) . " ===\n\n"; $header .= 'Site: ' . get_bloginfo( 'name' ) . "\n"; $header .= 'Description: ' . get_bloginfo( 'description' ) . "\n\n"; $openai_key = askbot_get_openai_key(); if ( ! empty( $openai_key ) && '' !== $user_message ) { global $wpdb; $table = $wpdb->prefix . 'askbot_embeddings'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Table propre au plugin. $has_index = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $table ) ); if ( $has_index > 0 ) { $semantic_context = askbot_search_embeddings( $user_message, $openai_key ); if ( ! empty( $semantic_context ) ) { return $header . $semantic_context; } } } // Repli : pages/articles récents (pas de clé, pas d'index, ou recherche en échec). $context = $header; $pages = get_pages( array( 'number' => 12, 'sort_column' => 'menu_order', 'post_status' => 'publish', ) ); if ( ! empty( $pages ) ) { $context .= "=== PAGES ===\n\n"; foreach ( $pages as $page ) { $content = wp_trim_words( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $page->post_content ) ), 150 ); $context .= "PAGE: {$page->post_title}\nCONTENU: {$content}\n\n"; } } $posts = get_posts( array( 'numberposts' => 10, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', ) ); if ( ! empty( $posts ) ) { $context .= "=== ARTICLES ===\n\n"; foreach ( $posts as $post ) { $content = wp_trim_words( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $post->post_content ) ), 120 ); $context .= "ARTICLE: {$post->post_title}\nCONTENU: {$content}\n\n"; } } return mb_substr( $context, 0, 10000, 'UTF-8' ); }