'assistants=v2' ]; private const DEFAULT_TOKS = 300000; // as per spec /** Fetch API key from wp-options; RuntimeException if missing */ private static function key(): string { $key = get_option( 'aipub_openai_api_key' ); if ( empty( $key ) ) { throw new \RuntimeException( 'OpenAI API key not configured.' ); } return $key; } /** * Quick validation check for a given API key. * Performs a lightweight GET request and returns true * if the request succeeds (HTTP <400). * * @param string $key API key to validate. * @return bool */ public static function verify_key( string $key ): bool { $headers = [ 'Authorization' => 'Bearer ' . trim( $key ) ] + self::ASSISTANT_H; $url = self::BASE_URL . 'models?limit=1'; $res = wp_remote_get( $url, [ 'headers' => $headers, 'timeout' => 15 ] ); $code = wp_remote_retrieve_response_code( $res ); return $code > 0 && $code < 400; } /*-------------------------------------------------------------- * Low-level JSON helper *------------------------------------------------------------*/ private static function post_json( string $endpoint, array $body ): array { $headers = array_merge( [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . self::key() ], self::ASSISTANT_H ); $payload = wp_json_encode( $body ); $res = wp_remote_post( self::BASE_URL . $endpoint, [ 'headers' => $headers, 'body' => $payload, 'timeout' => 60, ] ); $code = wp_remote_retrieve_response_code( $res ); $body = wp_remote_retrieve_body( $res ); $data = json_decode( $body, true ); if ( $code >= 400 || empty( $data ) ) { $msg = $data['error']['message'] ?? 'unknown'; throw new \RuntimeException( sprintf( 'OpenAI API error: %s', esc_html( $msg ) ) ); } return $data; } /** * Perform a GET request and parse JSON response. * * @param string $endpoint Relative API endpoint. * @return array */ private static function get_json( string $endpoint ): array { $headers = [ 'Authorization' => 'Bearer ' . self::key() ] + self::ASSISTANT_H; $res = wp_remote_get( self::BASE_URL . $endpoint, [ 'headers' => $headers, 'timeout' => 60, ] ); $code = wp_remote_retrieve_response_code( $res ); $body = wp_remote_retrieve_body( $res ); $data = json_decode( $body, true ); if ( $code >= 400 || empty( $data ) ) { $msg = $data['error']['message'] ?? 'unknown'; throw new \RuntimeException( sprintf( 'OpenAI API error: %s', esc_html( $msg ) ) ); } return $data; } /*-------------------------------------------------------------- * Upload arbitrary file (text / JSON / CSV / sitemap) *------------------------------------------------------------*/ public static function upload_file( string $path ): string { if ( ! file_exists( $path ) ) { throw new \RuntimeException( sprintf( 'File not found: %s', esc_html( $path ) ) ); } $headers = array_merge( [ 'Authorization' => 'Bearer ' . self::key() ], self::ASSISTANT_H ); $boundary = wp_generate_uuid4(); $mime = wp_check_filetype( $path )['type'] ?? 'application/octet-stream'; $body = ''; $body .= "--{$boundary}\r\n"; $body .= 'Content-Disposition: form-data; name="purpose"' . "\r\n\r\n"; $body .= 'assistants' . "\r\n"; $body .= "--{$boundary}\r\n"; $body .= 'Content-Disposition: form-data; name="file"; filename="' . basename( $path ) . '"' . "\r\n"; $body .= 'Content-Type: ' . $mime . "\r\n\r\n"; $body .= file_get_contents( $path ) . "\r\n"; $body .= "--{$boundary}--\r\n"; $headers['Content-Type'] = 'multipart/form-data; boundary=' . $boundary; $res = wp_remote_post( self::BASE_URL . 'files', [ 'headers' => $headers, 'body' => $body, 'timeout' => 60, 'data_format' => 'body', ] ); if ( is_wp_error( $res ) ) { throw new \RuntimeException( sprintf( 'File upload failed: %s', esc_html( $res->get_error_message() ) ) ); } $code = wp_remote_retrieve_response_code( $res ); $data = json_decode( wp_remote_retrieve_body( $res ), true ); if ( $code >= 400 || empty( $data['id'] ) ) { $msg = $data['error']['message'] ?? 'unknown'; throw new \RuntimeException( sprintf( 'File upload failed (HTTP %s): %s', esc_html( (string) $code ), esc_html( $msg ) ) ); } return $data['id']; } /*-------------------------------------------------------------- * Thread helpers *------------------------------------------------------------*/ public static function create_thread(): string { return self::post_json( 'threads', [] )['id']; } public static function delete_thread( string $thread_id ): void { wp_remote_request( self::BASE_URL . 'threads/' . $thread_id, [ 'method' => 'DELETE', 'headers' => [ 'Authorization' => 'Bearer ' . self::key() ] + self::ASSISTANT_H ] ); } public static function add_message( string $thread, string $role, string $content ): string { return self::post_json( "threads/{$thread}/messages", [ 'role' => $role, 'content' => $content ] )['id']; } /*-------------------------------------------------------------- * Vector stores *------------------------------------------------------------*/ public static function create_vector_store( string $name, array $file_ids ): string { return self::post_json( 'vector_stores', [ 'name' => $name, 'file_ids' => $file_ids ] )['id']; } public static function delete_vector_store( string $id ): void { wp_remote_request( self::BASE_URL . 'vector_stores/' . $id, [ 'method' => 'DELETE', 'headers' => [ 'Authorization' => 'Bearer ' . self::key() ] + self::ASSISTANT_H ] ); } /** * Check whether a vector store exists. * * Performs a GET request and returns true if the store * exists (HTTP 200). * * @param string $id Vector store ID. * @return bool */ public static function vector_store_exists( string $id ): bool { $headers = [ 'Authorization' => 'Bearer ' . self::key() ] + self::ASSISTANT_H; $res = wp_remote_get( self::BASE_URL . 'vector_stores/' . $id, [ 'headers' => $headers, 'timeout' => 15 ] ); $code = wp_remote_retrieve_response_code( $res ); return 200 === $code; } /** * Append additional files to an existing vector store. * * @param string $vs_id Vector store ID. * @param string[] $file_ids List of file IDs to add. * @return void */ public static function add_files_to_vector_store( string $vs_id, array $file_ids ): void { foreach ( $file_ids as $fid ) { self::post_json( "vector_stores/{$vs_id}/files", [ 'file_id' => $fid ] ); } } /*-------------------------------------------------------------- * Assistants *------------------------------------------------------------*/ public static function create_assistant( array $payload ): string { return self::post_json( 'assistants', $payload )['id']; } public static function delete_assistant( string $id ): void { wp_remote_request( self::BASE_URL . 'assistants/' . $id, [ 'method' => 'DELETE', 'headers' => [ 'Authorization' => 'Bearer ' . self::key() ] + self::ASSISTANT_H ] ); } /*-------------------------------------------------------------- * Runs & polling *------------------------------------------------------------*/ public static function run_assistant( string $thread, string $assistant_id, string $instructions, array $tools = [], float $temperature = 0.5, ?string $model = null, int $max_prompt_tokens = self::DEFAULT_TOKS ): string { $model = $model ?: get_option( 'aipub_ai_model', 'o1' ); $payload = [ 'assistant_id' => $assistant_id, 'instructions' => $instructions, 'model' => $model, 'tools' => $tools, 'max_prompt_tokens' => $max_prompt_tokens, ]; if ( in_array( $model, [ 'o3-mini', 'o1' ], true ) ) { $payload['reasoning_effort'] = 'medium'; } else { $payload['temperature'] = $temperature; } return self::post_json( "threads/{$thread}/runs", $payload )['id']; } public static function wait_until_complete( string $thread, string $run_id, int $timeout = 300 ): array { $start = time(); do { $data = self::get_run_status( $thread, $run_id ); $status = $data['status'] ?? 'unknown'; if ( in_array( $status, [ 'completed', 'incomplete' ], true ) ) { return $data; } if ( in_array( $status, [ 'failed', 'cancelled', 'expired' ], true ) ) { throw new \RuntimeException( sprintf( 'Run failed with status: %s', esc_html( $status ) ) ); } sleep( 2 ); } while ( time() - $start < $timeout ); throw new \RuntimeException( 'OpenAI run timed out.' ); } public static function get_run_status( string $thread, string $run_id ): array { $headers = [ 'Authorization' => 'Bearer ' . self::key() ] + self::ASSISTANT_H; $url = self::BASE_URL . "threads/{$thread}/runs/{$run_id}"; $res = wp_remote_get( $url, [ 'timeout' => 60, 'headers' => $headers ] ); return json_decode( wp_remote_retrieve_body( $res ), true ); } /*-------------------------------------------------------------- * Messages *------------------------------------------------------------*/ public static function list_messages( string $thread ): array { $headers = [ 'Authorization' => 'Bearer ' . self::key() ] + self::ASSISTANT_H; $res = wp_remote_get( self::BASE_URL . "threads/{$thread}/messages", [ 'timeout' => 60, 'headers' => $headers ] ); $data = json_decode( wp_remote_retrieve_body( $res ), true ); return $data['data'] ?? []; } public static function latest_assistant_message( string $thread ): string { foreach ( self::list_messages( $thread ) as $msg ) { if ( 'assistant' === $msg['role'] ) { return self::clean_text( $msg['content'][0]['text']['value'] ?? '' ); } } return ''; } /*-------------------------------------------------------------- * Utilities required by spec *------------------------------------------------------------*/ public static function clean_text( string $txt ): string { $txt = preg_replace( '/【\d+:\d+†source】/', '', $txt ); $txt = preg_replace( '/【\d+:\d+†[^】]+】/', '', $txt ); $map = [ "–" => '-', "\xC3\xA2\xC2\x80\xC2\x94" => ', ', "\xC3\xA2\xC2\x80\xC2\x99" => "'", "\xC3\xA2\xC2\x80\xC2\x9C" => '"', "\xC3\xA2\xC2\x80\xC2\x9D" => ' ', "```html" => '', "```" => '', "json\n" => '', ]; return str_replace( array_keys( $map ), array_values( $map ), $txt ); } public static function generate_slug( string $text ): string { $text = strtolower( $text ); $text = preg_replace( '~[^\\pL\\d]+~u', '-', $text ); $text = iconv( 'utf-8', 'us-ascii//TRANSLIT', $text ); $text = preg_replace( '~[^-a-z0-9]+~', '', $text ); $text = trim( $text, '-' ); $text = preg_replace( '~-+~', '-', $text ); return $text ?: 'n-a'; } public static function download_file( string $file_id, string $save_path ): void { $headers = [ 'Authorization' => 'Bearer ' . self::key() ]; $url = self::BASE_URL . "files/{$file_id}/content"; $resp = wp_remote_get( $url, [ 'timeout' => 120, 'headers' => $headers ] ); $code = wp_remote_retrieve_response_code( $resp ); if ( $code !== 200 ) { throw new \RuntimeException( sprintf( 'Download failed, HTTP %s', esc_html( (string) $code ) ) ); } wp_mkdir_p( dirname( $save_path ) ); file_put_contents( $save_path, wp_remote_retrieve_body( $resp ) ); } }