200 ) { $merged = array_slice( $merged, 0, 200 ); } sort( $merged, SORT_FLAG_CASE | SORT_NATURAL ); Context::save_json( 'keywords.json', $merged ); update_option( self::OPTION_KEY, $merged, false ); } /** * Save edited keywords list and mark completion. * * @param array $keywords Raw keywords. */ public static function save( array $keywords ): void { $sanitized = []; foreach ( $keywords as $kw ) { $text = sanitize_text_field( wp_unslash( $kw ) ); if ( '' !== $text && ! in_array( $text, $sanitized, true ) ) { $sanitized[] = $text; } } if ( count( $sanitized ) > 200 ) { $sanitized = array_slice( $sanitized, 0, 200 ); } sort( $sanitized, SORT_FLAG_CASE | SORT_NATURAL ); Context::save_json( 'keywords.json', $sanitized ); update_option( self::OPTION_KEY, $sanitized, false ); update_option( 'aipub_keywords_complete', 'yes' ); } /** * Whether the SEO Keywords step has been completed. * * @return bool */ public static function is_complete(): bool { if ( 'yes' === get_option( 'aipub_keywords_complete' ) ) { return true; } $data = get_option( self::OPTION_KEY, [] ); return ! empty( $data ); } /* ===== Preconditions ===== */ private static function assert_ready(): void { if ( ! get_option( 'aipub_openai_api_key' ) ) throw new \RuntimeException( 'OpenAI key missing.' ); if ( ! Context::load_json( 'brand-strategy.json' ) ) throw new \RuntimeException( 'Brand strategy missing.' ); } /* ===== Context build ===== */ private static function collect_context_files(): array { $dir = Context::dir(); $files = [ $dir . 'brand-strategy.json' ]; /* Snapshot of posts/pages (≤10) with cats & tags */ $snap = []; $q = new \WP_Query( [ 'post_type'=>['post','page'], 'posts_per_page'=>10, 'orderby'=>'date','order'=>'DESC' ] ); foreach ( $q->posts as $p ) { $snap[] = [ 'id'=> $p->ID, 'type'=> $p->post_type, 'title'=> $p->post_title, 'content'=> wp_strip_all_tags( $p->post_content ), 'categories'=> wp_get_post_categories( $p->ID, [ 'fields'=>'names' ] ), 'tags'=> wp_get_post_tags( $p->ID, [ 'fields'=>'names' ] ), ]; } file_put_contents( $dir.'site-snapshot.json', wp_json_encode( $snap, JSON_UNESCAPED_UNICODE ) ); $files[] = $dir.'site-snapshot.json'; /* CPT snapshot */ $cpts = []; foreach ( get_post_types( [ 'public'=>true, '_builtin'=>false ], 'objects' ) as $slug=>$obj ) { $cpts[$slug] = [ 'label'=> $obj->labels->singular_name ?? $slug, 'titles'=> wp_list_pluck( get_posts( [ 'post_type'=>$slug,'posts_per_page'=>10,'fields'=>'post_title' ] ), 'post_title' ), 'tax'=> array_reduce( get_object_taxonomies( $slug ), function($carry,$tax){ $carry[$tax] = wp_list_pluck( get_terms( [ 'taxonomy'=>$tax,'hide_empty'=>false ] ), 'name' ); return $carry; }, [] ), ]; } if ( $cpts ) { file_put_contents( $dir.'cpt-snapshot.json', wp_json_encode( $cpts, JSON_UNESCAPED_UNICODE ) ); $files[] = $dir.'cpt-snapshot.json'; } /* Existing tag baseline */ $all_tags = get_tags( [ 'fields' => 'names', 'hide_empty' => false, ] ); $tags_file = Context::save_json( 'existing-tags.json', $all_tags ); $files[] = $tags_file; /* Ensure baseline keywords.json exists */ if ( ! file_exists( $dir.'keywords.json' ) ) Context::save_json( 'keywords.json', $all_tags ); /* Front-end page snapshot (if available) */ if ( file_exists( $dir . 'pages.json' ) ) { $files[] = $dir . 'pages.json'; } /* Exclude keywords.json itself */ return $files; } /* ===== OpenAI orchestration ===== */ private static function create_thread(): string { return self::post_json( 'https://api.openai.com/v1/threads', (object)[] )['id']; } private static function create_vector_store( array $files ): string { $ids = array_map( fn($f)=>self::upload_file( $f ), $files ); return self::post_json( 'https://api.openai.com/v1/vector_stores', [ 'name'=>'aipub_kw_'.time(),'file_ids'=>$ids ] )['id']; } private static function create_seo_assistant( string $vs_id ): string { $prompts = self::load_seo_keywords_prompts(); $block = $prompts['TransformX SEO']; $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'name' => 'TransformX SEO Expert', 'instructions' => $block['system_message'], 'model' => $model, 'tools' => [ [ 'type' => 'file_search' ] ], 'tool_resources' => [ 'file_search' => [ 'vector_store_ids' => [ $vs_id ] ] ], ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'high'; } else { $payload['temperature'] = 0.5; $payload['top_p'] = 1; } return self::post_json( 'https://api.openai.com/v1/assistants', $payload )['id']; } private static function prompt_keywords( string $thread, string $assistant ): void { $block = self::load_seo_keywords_prompts()['TransformX SEO']; OpenAI::add_message( $thread, 'user', $block['user_message'] ); self::run_assistant( $thread, $assistant, $block['assistant_instructions'] ); } private static function await_csv( string $thread ): string { do { sleep(2); $stat = self::get_json( "https://api.openai.com/v1/threads/{$thread}/runs" )['data'][0]['status']??''; } while ( 'completed' !== $stat ); foreach ( self::get_json( "https://api.openai.com/v1/threads/{$thread}/messages" )['data'] as $m ) { if ( 'assistant' === $m['role'] ) return trim( $m['content'][0]['text']['value'] ); } throw new \RuntimeException( 'Assistant returned no CSV.' ); } /* ===== Helpers ===== */ private static function csv_to_array( string $csv ): array { // Split on commas, semicolons, or newlines to support various list formats. $parts = preg_split('/[\r\n,;]+/', trim( $csv )); if ( false === $parts ) { return []; } $items = []; $seen_lc = []; foreach ( $parts as $raw ) { // If a segment contains multiple quoted phrases, extract each separately. if ( preg_match_all('/"([^"]+)"/', $raw, $m) && count( $m[1] ) > 1 ) { foreach ( $m[1] as $phrase ) { $phrase = trim( stripcslashes( $phrase ) ); if ( '' === $phrase ) { continue; } $phrase = trim( $phrase, "\"' " ); $phrase = sanitize_text_field( $phrase ); if ( '' === $phrase ) { continue; } $lower = mb_strtolower( $phrase ); if ( isset( $seen_lc[ $lower ] ) ) { continue; } $items[] = $phrase; $seen_lc[ $lower ] = true; } continue; } $kw = sanitize_text_field( trim( $raw, "\"' " ) ); if ( '' === $kw ) { continue; } $lower = mb_strtolower( $kw ); if ( isset( $seen_lc[ $lower ] ) ) { continue; } $items[] = $kw; $seen_lc[ $lower ] = true; } return $items; } private static function cleanup_openai( string $aid, string $vs, string $tid ): void { $h=[ 'Authorization'=>'Bearer '.get_option('aipub_openai_api_key'),'OpenAI-Beta'=>'assistants=v2' ]; foreach ( [ "assistants/{$aid}", "vector_stores/{$vs}", "threads/{$tid}" ] as $p ) { wp_remote_request( "https://api.openai.com/v1/{$p}", [ 'method'=>'DELETE','headers'=>$h ] ); } } /* ===== Low-level HTTP ===== */ private static function post_json( string $url, $body ): array { $resp = wp_remote_post( $url, [ 'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . get_option( 'aipub_openai_api_key' ), 'OpenAI-Beta' => 'assistants=v2', ], 'body' => wp_json_encode( $body ), 'timeout' => 60, ] ); if ( is_wp_error( $resp ) ) { throw new \RuntimeException( esc_html( $resp->get_error_message() ) ); } $code = wp_remote_retrieve_response_code( $resp ); $body = wp_remote_retrieve_body( $resp ); $data = json_decode( $body, true ); if ( $code >= 400 || ! is_array( $data ) ) { $msg = $data['error']['message'] ?? 'OpenAI error.'; throw new \RuntimeException( esc_html( $msg ) ); } return $data; } private static function upload_file( string $path ): string { return OpenAI::upload_file( $path ); } private static function run_assistant( string $thread, string $assistant, string $instr ): void { $model = get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'assistant_id' => $assistant, 'instructions' => $instr, 'model' => $model, 'tools' => [ [ 'type' => 'file_search' ] ], ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'medium'; } else { $payload['temperature'] = 0.5; $payload['top_p'] = 1; } self::post_json( "https://api.openai.com/v1/threads/{$thread}/runs", $payload ); } private static function get_json( string $url ): array { $resp = wp_remote_get( $url, [ 'headers' => [ 'Authorization' => 'Bearer ' . get_option( 'aipub_openai_api_key' ), 'OpenAI-Beta' => 'assistants=v2', ], 'timeout' => 60, ] ); if ( is_wp_error( $resp ) ) { throw new \RuntimeException( esc_html( $resp->get_error_message() ) ); } $code = wp_remote_retrieve_response_code( $resp ); $body = wp_remote_retrieve_body( $resp ); $data = json_decode( $body, true ); if ( $code >= 400 || ! is_array( $data ) ) { $msg = $data['error']['message'] ?? 'OpenAI error.'; throw new \RuntimeException( esc_html( $msg ) ); } return $data; } /** * Load SEO keyword prompts from JSON config. */ private static function load_seo_keywords_prompts(): array { static $prompts = null; if ( null === $prompts ) { $path = AIPUB_DIR . 'includes/data/seo_keywords_prompts.json'; if ( ! file_exists( $path ) ) { throw new \RuntimeException( 'Missing seo_keywords_prompts.json file.' ); } $json = file_get_contents( $path ); $data = json_decode( $json, true ); if ( ! is_array( $data ) ) { throw new \RuntimeException( 'Invalid JSON in seo_keywords_prompts.json: ' . esc_html( json_last_error_msg() ) ); } $prompts = $data; } return $prompts; } }