settings = $settings; } public function get_id(): string { return 'openrouter'; } public function get_label(): string { return __( 'OpenRouter', 'acez-seo' ); } public function generate_text( string $prompt, int $max_tokens = 1024 ): string { $response = wp_remote_post( self::API_URL, array( // Same long-form allowance as OpenAiProvider (M62 articles). 'timeout' => $max_tokens > 1024 ? 90 : 30, 'headers' => $this->headers(), 'body' => wp_json_encode( array( 'model' => $this->model(), 'max_tokens' => $max_tokens, 'messages' => array( array( 'role' => 'user', 'content' => $prompt ), ), ) ), ) ); return $this->parse_response( $response ); } public function generate_from_image( string $prompt, ImagePayload $image ): string { $response = wp_remote_post( self::API_URL, array( 'timeout' => 60, 'headers' => $this->headers(), 'body' => wp_json_encode( array( 'model' => $this->model(), 'max_tokens' => 1024, '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 ), ), ), ), ), ) ), ) ); 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( self::MODELS_URL, 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'] ?? '' ) : ''; $this->throw_for_status( $status, $detail ); } $models = is_array( $body['data'] ?? null ) ? $body['data'] : array(); // The catalog is huge (350+ entries incl. image/audio-only models) — // keep only text-in/text-out FREE chat models (zero-cost prompt AND // completion pricing — avoids the "Insufficient credits" error on // accounts with no purchased credits), newest first, capped at 10 // like the other providers. Anything else can still be typed into // the "Model" field by hand. $models = array_filter( $models, static function ( $model ): bool { if ( ! is_array( $model ) || '' === (string) ( $model['id'] ?? '' ) ) { return false; } $architecture = is_array( $model['architecture'] ?? null ) ? $model['architecture'] : array(); $inputs = is_array( $architecture['input_modalities'] ?? null ) ? $architecture['input_modalities'] : array(); $outputs = is_array( $architecture['output_modalities'] ?? null ) ? $architecture['output_modalities'] : array(); if ( ! in_array( 'text', $inputs, true ) || ! in_array( 'text', $outputs, true ) ) { return false; } return self::is_free_model( $model ); } ); usort( $models, static function ( $a, $b ): int { return (int) ( $b['created'] ?? 0 ) <=> (int) ( $a['created'] ?? 0 ); } ); $models = array_slice( array_values( $models ), 0, 10 ); return array_map( static function ( $model ): array { $id = (string) $model['id']; $label = '' !== (string) ( $model['name'] ?? '' ) ? (string) $model['name'] : $id; return array( 'id' => $id, /* translators: %s: model name */ 'label' => sprintf( __( '%s (free)', 'acez-seo' ), $label ), ); }, $models ); } /** * @param array $model */ private static function is_free_model( array $model ): bool { if ( str_ends_with( (string) ( $model['id'] ?? '' ), ':free' ) ) { return true; } $pricing = is_array( $model['pricing'] ?? null ) ? $model['pricing'] : array(); $prompt = (float) ( $pricing['prompt'] ?? -1 ); $completion = (float) ( $pricing['completion'] ?? -1 ); return 0.0 === $prompt && 0.0 === $completion; } /** * @return array */ private function headers(): 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). } return array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', // Optional attribution headers from OpenRouter's quickstart — // only used for their public rankings, never required. 'HTTP-Referer' => home_url( '/' ), 'X-Title' => 'Acez SEO AI', ); } /** * @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'] ?? '' ) : ''; $this->throw_for_status( $status, $detail ); } $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 throw_for_status( int $status, string $detail ): never { // Free-model requests get a 404 whose detail mentions "data policy" or // "endpoints" when the account's Privacy settings block them (see // AiProviderException::openrouter_no_free_endpoints()) — a different // cause than an actually-mistyped model name, so it needs its own // message rather than the generic model_not_found() one. if ( 404 === $status && ( false !== stripos( $detail, 'data policy' ) || false !== stripos( $detail, 'endpoints' ) ) ) { throw AiProviderException::openrouter_no_free_endpoints(); } 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). } private function model(): string { $model = $this->settings->get_model( $this->get_id() ); return '' !== $model ? $model : self::DEFAULT_MODEL; } }