settings = $settings; } public function get_id(): string { return 'openai'; } public function get_label(): string { return __( 'OpenAI', 'acez-seo' ); } public function generate_text( string $prompt, int $max_tokens = 1024 ): string { $api_key = $this->settings->get_api_key( $this->get_id() ); if ( '' === $api_key ) { throw AiProviderException::missing_api_key( $this->get_label() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $response = wp_remote_post( self::API_URL, array( // Long-form output (M62 articles) needs materially more wall // time than a one-line meta field — same reasoning as the // 60s vision timeout below. 'timeout' => $max_tokens > 1024 ? 90 : 30, 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( array_merge( array( 'model' => $this->model(), 'messages' => array( array( 'role' => 'user', 'content' => $prompt ), ), ), $this->token_limit_param( $max_tokens ) ) ), ) ); return $this->parse_response( $response ); } public function generate_from_image( string $prompt, ImagePayload $image ): string { $api_key = $this->settings->get_api_key( $this->get_id() ); if ( '' === $api_key ) { throw AiProviderException::missing_api_key( $this->get_label() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $response = wp_remote_post( self::API_URL, array( 'timeout' => 60, 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( array_merge( array( 'model' => $this->model(), 'messages' => array( array( 'role' => 'user', 'content' => array( array( 'type' => 'text', 'text' => $prompt ), array( 'type' => 'image_url', 'image_url' => array( 'url' => 'data:' . $image->mime_type . ';base64,' . $image->base64 ), ), ), ), ), ), $this->token_limit_param( 1024 ) ) ), ) ); return $this->parse_response( $response ); } public function test_connection(): void { $result = $this->generate_text( 'Reply with one word: OK.' ); if ( '' === $result ) { throw AiProviderException::unexpected_response( $this->get_label() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } } /** * @return list */ public function list_models(): array { $api_key = $this->settings->get_api_key( $this->get_id() ); if ( '' === $api_key ) { throw AiProviderException::missing_api_key( $this->get_label() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $response = wp_remote_get( 'https://api.openai.com/v1/models', // phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration -- see the class-const declaration above for the full rationale (M67). array( 'timeout' => 20, 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, ), ) ); if ( is_wp_error( $response ) ) { throw AiProviderException::connection_failed( $this->get_label() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $status = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( $status < 200 || $status >= 300 || ! is_array( $body ) ) { $detail = is_array( $body ) ? (string) ( $body['error']['message'] ?? '' ) : ''; throw AiProviderException::from_http_status( $this->get_label(), $status, $detail ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $models = is_array( $body['data'] ?? null ) ? $body['data'] : array(); // Only chat-capable text models make sense here — the account may // also expose embeddings/whisper/tts/dall-e/moderation models, which // would silently break generation if picked from this list. $models = array_filter( $models, static function ( $model ): bool { $id = is_array( $model ) ? (string) ( $model['id'] ?? '' ) : ''; if ( '' === $id ) { return false; } foreach ( array( 'embedding', 'whisper', 'tts', 'dall-e', 'moderation', 'audio', 'realtime', 'transcribe', 'image' ) as $excluded ) { if ( str_contains( $id, $excluded ) ) { return false; } } return true; } ); usort( $models, static function ( $a, $b ): int { return (int) ( $b['created'] ?? 0 ) <=> (int) ( $a['created'] ?? 0 ); } ); $models = array_slice( $models, 0, 10 ); return array_map( static function ( $model ): array { $id = (string) $model['id']; return array( 'id' => $id, 'label' => $id, ); }, array_values( $models ) ); } /** * @param \WP_Error|array $response */ private function parse_response( $response ): string { if ( is_wp_error( $response ) ) { if ( 'http_request_failed' === $response->get_error_code() && str_contains( $response->get_error_message(), 'timed out' ) ) { throw AiProviderException::request_failed( $this->get_label(), __( 'the request timed out', 'acez-seo' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } throw AiProviderException::connection_failed( $this->get_label() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $status = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( (string) wp_remote_retrieve_body( $response ), true ); if ( $status < 200 || $status >= 300 ) { $detail = is_array( $body ) ? (string) ( $body['error']['message'] ?? '' ) : ''; throw AiProviderException::from_http_status( $this->get_label(), $status, $detail ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } $text = is_array( $body ) ? ( $body['choices'][0]['message']['content'] ?? null ) : null; if ( ! is_string( $text ) || '' === trim( $text ) ) { throw AiProviderException::unexpected_response( $this->get_label() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- message reaches only JS textContent/window.alert plain-text sinks, never HTML (see AiProviderException docblock). } return trim( $text ); } private function model(): string { $model = $this->settings->get_model( $this->get_id() ); return '' !== $model ? $model : self::DEFAULT_MODEL; } /** * OpenAI's reasoning models (o1/o3/o4-mini and the gpt-5 family) reject * the classic `max_tokens` parameter outright with a 400 error ("...is * not supported with this model. Use 'max_completion_tokens' instead."), * while some older models (gpt-3.5-turbo and some gpt-4 snapshots) reject * `max_completion_tokens` as an unrecognized argument — the two params * are NOT interchangeable in either direction, so which one to send has * to be decided per model. gpt-4o/gpt-4o-mini (our default) are classic * chat models here, not reasoning models — they keep `max_tokens`. * * @return array{max_tokens?: int, max_completion_tokens?: int} */ private function token_limit_param( int $max_tokens ): array { $model = $this->model(); if ( 1 === preg_match( '/^(o\d|gpt-[5-9](\D|$)|gpt-\d{2,})/', $model ) ) { return array( 'max_completion_tokens' => $max_tokens ); } return array( 'max_tokens' => $max_tokens ); } }