api_key = $api_key; $this->model = $model; } /** * Factory: returns a configured provider instance for the given name. * * @param string $provider 'core' | 'openai' | 'anthropic' | 'gemini' | 'groq' * @param string $api_key Ignored for 'core', which uses WordPress's own AI Client instead. * @param string $model * @return AIATG_AI_Provider|WP_Error */ public static function get_provider( $provider, $api_key, $model ) { if ( 'core' === $provider ) { return new AIATG_Provider_CoreAI(); } if ( empty( $api_key ) ) { return new WP_Error( 'aiatg_no_api_key', __( 'No API key configured for the selected AI provider. Add one under AI Alt Tags → Settings.', 'fix-experts-ai-image-alt-tag-generator' ) ); } switch ( $provider ) { case 'openai': return new AIATG_Provider_OpenAI( $api_key, $model ); case 'anthropic': return new AIATG_Provider_Anthropic( $api_key, $model ); case 'gemini': return new AIATG_Provider_Gemini( $api_key, $model ); case 'groq': return new AIATG_Provider_Groq( $api_key, $model ); default: return new WP_Error( 'aiatg_unknown_provider', __( 'Unknown AI provider selected.', 'fix-experts-ai-image-alt-tag-generator' ) ); } } /** * Builds the shared instruction prompt from site/page context. * * @param array $context { * @type string $site_name * @type string $site_description * @type string $site_context Homepage/About page summary. * @type string $product_name WooCommerce product name, if any. * @type string $product_categories WooCommerce product categories, if any. * @type string $product_description WooCommerce product description, if any. * @type string $page_title * @type string $excerpt * @type int $max_length * } */ protected function build_prompt( array $context ) { $max_length = isset( $context['max_length'] ) ? (int) $context['max_length'] : 125; $lines = array(); $lines[] = 'You are an expert web accessibility and SEO assistant.'; $lines[] = "Write a single, concise, descriptive alt text for the image shown, under {$max_length} characters."; $lines[] = 'The alt text must accurately describe what is visibly in the image, in plain language suitable for screen readers.'; $lines[] = 'Blend that literal visual description with the site/business context below so the alt text uses the site\'s own terminology (business name, product names, categories) instead of a generic stock-photo caption — but do not invent visual details that aren\'t actually shown.'; $lines[] = 'If a specific WooCommerce product is given below, the alt text should primarily describe that product using its own name/category, not a generic description.'; $lines[] = 'Do not start with phrases like "image of", "photo of", or "picture of". Do not use quotation marks. Do not add a period at the end unless it reads as a full sentence.'; if ( ! empty( $context['site_name'] ) ) { $lines[] = 'Website name: ' . $context['site_name']; } if ( ! empty( $context['site_description'] ) ) { $lines[] = 'Website tagline: ' . $context['site_description']; } if ( ! empty( $context['site_context'] ) ) { $lines[] = 'What this website/business is about (from its homepage/about page): ' . $context['site_context']; } if ( ! empty( $context['product_name'] ) ) { $lines[] = 'This image belongs to the WooCommerce product: ' . $context['product_name']; } if ( ! empty( $context['product_categories'] ) ) { $lines[] = 'Product categories: ' . $context['product_categories']; } if ( ! empty( $context['product_description'] ) ) { $lines[] = 'Product description: ' . $context['product_description']; } if ( ! empty( $context['page_title'] ) ) { $lines[] = 'Page/post title where this image appears: ' . $context['page_title']; } if ( ! empty( $context['excerpt'] ) ) { $lines[] = 'Page/post excerpt: ' . $context['excerpt']; } $lines[] = 'Respond with ONLY the alt text on a single line. No explanation, no labels, no markdown.'; return implode( "\n", $lines ); } /** * Cleans up whatever text the model returns. */ protected function clean_response( $text, $max_length ) { $text = trim( $text ); $text = trim( $text, "\"'“”‘’ \t\n\r\0\x0B" ); $text = preg_replace( '/^(image|photo|picture|graphic|illustration)\s+of\s+/i', '', $text ); $text = preg_replace( '/\s+/', ' ', $text ); if ( $max_length > 0 && function_exists( 'mb_strlen' ) && mb_strlen( $text ) > $max_length ) { $text = mb_substr( $text, 0, $max_length - 1 ); $text = rtrim( $text ) . '…'; } return $text; } /** * @param string $image_data Raw binary image data. * @param string $mime_type e.g. image/jpeg * @param array $context See build_prompt(). * @return string|WP_Error Generated alt text, or WP_Error on failure. */ abstract public function generate( $image_data, $mime_type, array $context ); } /** * WordPress core AI Client (WordPress 7.0+). Routes through whichever * provider the site owner has configured under Settings → Connectors, * so this plugin never handles API keys itself for this path. */ class AIATG_Provider_CoreAI extends AIATG_AI_Provider { public function __construct() { parent::__construct( '', '' ); } /** * True when WordPress's core AI Client is present and at least one * connector is configured for text generation. */ public static function is_available() { if ( ! function_exists( 'wp_ai_client_prompt' ) ) { return false; } $builder = wp_ai_client_prompt( 'availability check' ); return is_object( $builder ) && method_exists( $builder, 'is_supported_for_text_generation' ) ? $builder->is_supported_for_text_generation() : false; } public function generate( $image_data, $mime_type, array $context ) { if ( ! function_exists( 'wp_ai_client_prompt' ) ) { return new WP_Error( 'aiatg_core_ai_unavailable', __( 'The WordPress AI Client requires WordPress 7.0 or newer.', 'fix-experts-ai-image-alt-tag-generator' ) ); } $max_length = isset( $context['max_length'] ) ? (int) $context['max_length'] : 125; $prompt = $this->build_prompt( $context ); $builder = wp_ai_client_prompt( $prompt )->with_file( base64_encode( $image_data ), $mime_type ); if ( ! $builder->is_supported_for_text_generation() ) { return new WP_Error( 'aiatg_core_ai_unsupported', __( 'No AI provider is configured for text generation under Settings → Connectors.', 'fix-experts-ai-image-alt-tag-generator' ) ); } $text = $builder->generate_text(); if ( is_wp_error( $text ) ) { return $text; } if ( empty( $text ) ) { return new WP_Error( 'aiatg_core_ai_empty', __( 'The WordPress AI Client returned an empty response.', 'fix-experts-ai-image-alt-tag-generator' ) ); } return $this->clean_response( $text, $max_length ); } } /** * OpenAI (GPT-4o family) vision provider. Also the base class for any * other provider exposing an OpenAI-compatible chat completions API * with image_url content parts (e.g. Groq). */ class AIATG_Provider_OpenAI extends AIATG_AI_Provider { /** * Chat completions endpoint. Overridable by OpenAI-compatible providers. */ protected function get_api_url() { return 'https://api.openai.com/v1/chat/completions'; } /** * Human-readable name used in error messages/codes. Overridable. */ protected function get_provider_label() { return 'OpenAI'; } public function generate( $image_data, $mime_type, array $context ) { $prompt = $this->build_prompt( $context ); $max_length = isset( $context['max_length'] ) ? (int) $context['max_length'] : 125; $data_uri = 'data:' . $mime_type . ';base64,' . base64_encode( $image_data ); $label = $this->get_provider_label(); $slug = strtolower( $label ); $body = 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_uri ), ), ), ), ), 'max_tokens' => 120, ); $response = wp_remote_post( $this->get_api_url(), array( 'timeout' => 40, 'headers' => array( 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( $body ), ) ); if ( is_wp_error( $response ) ) { return $response; } $code = wp_remote_retrieve_response_code( $response ); $json = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $code < 200 || $code >= 300 ) { $message = $json['error']['message'] ?? wp_remote_retrieve_body( $response ); return new WP_Error( 'aiatg_' . $slug . '_error', sprintf( '%s API error (%d): %s', $label, $code, $message ) ); } $text = $json['choices'][0]['message']['content'] ?? ''; if ( empty( $text ) ) { return new WP_Error( 'aiatg_' . $slug . '_empty', sprintf( __( '%s returned an empty response.', 'fix-experts-ai-image-alt-tag-generator' ), $label ) ); } return $this->clean_response( $text, $max_length ); } } /** * Groq vision provider. Uses Groq's OpenAI-compatible chat completions * API with Llama 4 vision models. Free tier, no billing required. */ class AIATG_Provider_Groq extends AIATG_Provider_OpenAI { protected function get_api_url() { return 'https://api.groq.com/openai/v1/chat/completions'; } protected function get_provider_label() { return 'Groq'; } } /** * Anthropic (Claude) vision provider. */ class AIATG_Provider_Anthropic extends AIATG_AI_Provider { public function generate( $image_data, $mime_type, array $context ) { $prompt = $this->build_prompt( $context ); $max_length = isset( $context['max_length'] ) ? (int) $context['max_length'] : 125; $body = array( 'model' => $this->model, 'max_tokens' => 150, 'messages' => array( array( 'role' => 'user', 'content' => array( array( 'type' => 'image', 'source' => array( 'type' => 'base64', 'media_type' => $mime_type, 'data' => base64_encode( $image_data ), ), ), array( 'type' => 'text', 'text' => $prompt, ), ), ), ), ); $response = wp_remote_post( 'https://api.anthropic.com/v1/messages', array( 'timeout' => 40, 'headers' => array( 'x-api-key' => $this->api_key, 'anthropic-version' => '2023-06-01', 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( $body ), ) ); if ( is_wp_error( $response ) ) { return $response; } $code = wp_remote_retrieve_response_code( $response ); $json = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $code < 200 || $code >= 300 ) { $message = $json['error']['message'] ?? wp_remote_retrieve_body( $response ); return new WP_Error( 'aiatg_anthropic_error', sprintf( 'Anthropic API error (%d): %s', $code, $message ) ); } $text = $json['content'][0]['text'] ?? ''; if ( empty( $text ) ) { return new WP_Error( 'aiatg_anthropic_empty', __( 'Anthropic returned an empty response.', 'fix-experts-ai-image-alt-tag-generator' ) ); } return $this->clean_response( $text, $max_length ); } } /** * Google Gemini vision provider. */ class AIATG_Provider_Gemini extends AIATG_AI_Provider { public function generate( $image_data, $mime_type, array $context ) { $prompt = $this->build_prompt( $context ); $max_length = isset( $context['max_length'] ) ? (int) $context['max_length'] : 125; $body = array( 'contents' => array( array( 'parts' => array( array( 'text' => $prompt ), array( 'inline_data' => array( 'mime_type' => $mime_type, 'data' => base64_encode( $image_data ), ), ), ), ), ), 'generationConfig' => array( 'maxOutputTokens' => 120, 'temperature' => 0.4, ), ); $url = sprintf( 'https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent?key=%s', rawurlencode( $this->model ), rawurlencode( $this->api_key ) ); $response = wp_remote_post( $url, array( 'timeout' => 40, 'headers' => array( 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( $body ), ) ); if ( is_wp_error( $response ) ) { return $response; } $code = wp_remote_retrieve_response_code( $response ); $json = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $code < 200 || $code >= 300 ) { $message = $json['error']['message'] ?? wp_remote_retrieve_body( $response ); return new WP_Error( 'aiatg_gemini_error', sprintf( 'Gemini API error (%d): %s', $code, $message ) ); } $text = $json['candidates'][0]['content']['parts'][0]['text'] ?? ''; if ( empty( $text ) ) { return new WP_Error( 'aiatg_gemini_empty', __( 'Gemini returned an empty response. It may have blocked the image; try again or switch provider.', 'fix-experts-ai-image-alt-tag-generator' ) ); } return $this->clean_response( $text, $max_length ); } }