array( 'label' => 'OpenAI', 'key_url' => 'https://platform.openai.com/api-keys', 'key_opt' => 'openai_api_key', 'constant' => 'AI_SEO_TOOLS_OPENAI_KEY', 'default' => 'gpt-4o-mini', 'vision' => true, ), 'anthropic' => array( 'label' => 'Anthropic', 'key_url' => 'https://console.anthropic.com/settings/keys', 'key_opt' => 'anthropic_api_key', 'constant' => 'AI_SEO_TOOLS_ANTHROPIC_KEY', 'default' => 'claude-haiku-4-5', 'vision' => true, ), 'gemini' => array( 'label' => 'Google Gemini', 'key_url' => 'https://aistudio.google.com/apikey', 'key_opt' => 'gemini_api_key', 'constant' => 'AI_SEO_TOOLS_GEMINI_KEY', 'default' => 'gemini-2.0-flash', 'vision' => true, ), 'openrouter' => array( 'label' => 'OpenRouter', 'key_url' => 'https://openrouter.ai/settings/keys', 'key_opt' => 'openrouter_api_key', 'constant' => 'AI_SEO_TOOLS_OPENROUTER_KEY', 'default' => 'google/gemini-2.0-flash-exp:free', 'vision' => true, ), ) ); } /** * Approximate USD per million tokens. * * These are estimates used for the in-plugin spend counter only — providers * change prices and the authoritative number is always the provider's own * billing dashboard. Override with the `ai_seo_tools_model_pricing` filter. */ public static function pricing(): array { return apply_filters( 'ai_seo_tools_model_pricing', array( 'gpt-4o' => array( 'in' => 2.50, 'out' => 10.00 ), 'gpt-4o-mini' => array( 'in' => 0.15, 'out' => 0.60 ), 'gpt-4.1' => array( 'in' => 2.00, 'out' => 8.00 ), 'gpt-4.1-mini' => array( 'in' => 0.40, 'out' => 1.60 ), 'gpt-4.1-nano' => array( 'in' => 0.10, 'out' => 0.40 ), 'claude-sonnet-5' => array( 'in' => 3.00, 'out' => 15.00 ), 'claude-haiku-4-5' => array( 'in' => 1.00, 'out' => 5.00 ), 'gemini-2.0-flash' => array( 'in' => 0.10, 'out' => 0.40 ), 'gemini-2.5-flash' => array( 'in' => 0.30, 'out' => 2.50 ), ) ); } /** * Reads a plugin option. * * @param string $key Option key. * @param mixed $default Fallback. * @return mixed */ public static function option( string $key, $default = '' ) { $options = get_option( self::OPTION, array() ); return $options[ $key ] ?? $default; } /** * Currently selected provider slug. */ public static function provider(): string { $provider = self::option( 'ai_provider', 'openai' ); $providers = self::providers(); return isset( $providers[ $provider ] ) ? $provider : 'openai'; } /** * API key for a provider. * * A wp-config.php constant always wins over the stored option, so keys can be * kept out of the database entirely. */ public static function api_key( string $provider = '' ): string { $provider = $provider ?: self::provider(); $providers = self::providers(); if ( ! isset( $providers[ $provider ] ) ) { return ''; } $constant = $providers[ $provider ]['constant']; if ( defined( $constant ) && constant( $constant ) ) { return (string) constant( $constant ); } return (string) self::option( $providers[ $provider ]['key_opt'], '' ); } /** * True when the key comes from wp-config.php rather than the database. */ public static function key_is_constant( string $provider = '' ): bool { $provider = $provider ?: self::provider(); $providers = self::providers(); if ( ! isset( $providers[ $provider ] ) ) { return false; } $constant = $providers[ $provider ]['constant']; return defined( $constant ) && (bool) constant( $constant ); } /** * Model for the active provider. */ public static function model( string $provider = '' ): string { $provider = $provider ?: self::provider(); $providers = self::providers(); $default = $providers[ $provider ]['default'] ?? 'gpt-4o-mini'; // Legacy installs stored the OpenAI model under `openai_model`. $stored = self::option( $provider . '_model', '' ); if ( ! $stored && 'openai' === $provider ) { $stored = self::option( 'openai_model', '' ); } return apply_filters( 'ai_seo_tools_model', $stored ?: $default, $provider ); } /** * Whether the plugin is configured well enough to make a call. */ public static function is_ready(): bool { return '' !== self::api_key(); } /** * Performs an AI request. * * @param array $args { * @type string $module Module slug, used for usage reporting. * @type string $action Short action label for the log. * @type int $object_id Related post/attachment ID. * @type string $system System instruction. * @type string $prompt User prompt. * @type array $image ['base64' => ..., 'mime' => ..., 'detail' => 'low'|'high']. * @type array $schema JSON schema for structured output. * @type int $max_tokens Output cap. * @type float $temperature Sampling temperature. * @type bool $retry Retry transient failures inline (default true). * } * @return array{text:string,json:?array,usage:array,model:string,provider:string}|WP_Error */ public static function request( array $args ) { $args = wp_parse_args( $args, array( 'module' => 'core', 'action' => 'generate', 'object_id' => 0, 'system' => '', 'prompt' => '', 'image' => null, 'schema' => null, 'max_tokens' => 400, 'temperature' => null, 'retry' => true, ) ); $args = apply_filters( 'ai_seo_tools_request_args', $args ); $args['prompt'] = (string) apply_filters( 'ai_seo_tools_prompt', $args['prompt'], $args['module'], $args ); $provider = self::provider(); $model = self::model( $provider ); $key = self::api_key( $provider ); if ( '' === $key ) { return new WP_Error( 'missing_api_key', sprintf( /* translators: %s: provider name. */ __( 'No %s API key configured.', 'ai-seo-tools' ), self::providers()[ $provider ]['label'] ?? $provider ) ); } $budget = self::check_budget(); if ( is_wp_error( $budget ) ) { return $budget; } $attempts = $args['retry'] ? (int) apply_filters( 'ai_seo_tools_max_attempts', 3 ) : 1; $slept = 0; $grew = 0; for ( $attempt = 1; $attempt <= $attempts; $attempt++ ) { $result = self::dispatch( $provider, $model, $key, $args ); if ( ! is_wp_error( $result ) ) { self::log_success( $args, $provider, $model, $result ); return apply_filters( 'ai_seo_tools_response', $result, $args ); } // Rather than making every caller guess a reasoning model's overhead, // hand back a far larger budget and try again. Reasoning traces run to // thousands of tokens, so the step has to be large to be worth taking; // models that answer straight away never hit the cap and never pay for it. // Allowed even when retries are off: growing the budget re-requests // immediately without sleeping, so it is safe inside a queue worker // where the queue itself owns the backoff. if ( 'truncated' === $result->get_error_code() && $grew < 2 ) { $grew++; $args['max_tokens'] = (int) min( 16000, max( 4000, $args['max_tokens'] * 8 ) ); $attempt--; continue; } $data = $result->get_error_data(); $status = is_array( $data ) ? (int) ( $data['status'] ?? 0 ) : 0; $retryable = in_array( $status, array( 408, 409, 429, 500, 502, 503, 504 ), true ) || in_array( $result->get_error_code(), array( 'http_request_failed', 'network_error' ), true ); if ( ! $retryable || $attempt >= $attempts ) { self::log_failure( $args, $provider, $model, $result ); return $result; } $wait = is_array( $data ) && ! empty( $data['retry_after'] ) ? (int) $data['retry_after'] : min( 8, 2 ** ( $attempt - 1 ) ); // Never stall a page load for long; give up and let the queue reschedule. if ( $slept + $wait > 12 ) { self::log_failure( $args, $provider, $model, $result ); return $result; } $slept += $wait; sleep( $wait ); } return new WP_Error( 'unknown', __( 'The request could not be completed.', 'ai-seo-tools' ) ); } /** * Routes to the provider-specific implementation. */ private static function dispatch( string $provider, string $model, string $key, array $args ) { switch ( $provider ) { case 'anthropic': return self::request_anthropic( $model, $key, $args ); case 'gemini': return self::request_gemini( $model, $key, $args ); case 'openrouter': return self::request_openrouter( $model, $key, $args ); case 'openai': default: return self::request_openai( $model, $key, $args ); } } /* --------------------------------------------------------------------- */ /* Providers */ /* --------------------------------------------------------------------- */ /** * Builds the chat-completions message array shared by OpenAI-compatible APIs. * * @param string $prompt Prompt text, which callers may have augmented. */ private static function openai_messages( array $args, string $prompt ): array { $content = array( array( 'type' => 'text', 'text' => $prompt ) ); if ( ! empty( $args['image']['base64'] ) ) { $content[] = array( 'type' => 'image_url', 'image_url' => array( 'url' => 'data:' . $args['image']['mime'] . ';base64,' . $args['image']['base64'], 'detail' => $args['image']['detail'] ?? 'low', ), ); } $messages = array(); if ( $args['system'] ) { $messages[] = array( 'role' => 'system', 'content' => $args['system'] ); } $messages[] = array( 'role' => 'user', 'content' => $content ); return $messages; } private static function request_openai( string $model, string $key, array $args ) { $messages = self::openai_messages( $args, $args['prompt'] ); $payload = array( 'model' => $model, 'messages' => $messages, 'max_completion_tokens' => (int) $args['max_tokens'], ); // Reasoning models reject any temperature but the default. if ( null !== $args['temperature'] && ! self::is_reasoning_model( $model ) ) { $payload['temperature'] = (float) $args['temperature']; } if ( ! empty( $args['schema'] ) ) { $payload['response_format'] = array( 'type' => 'json_schema', 'json_schema' => array( 'name' => $args['schema']['name'] ?? 'result', 'strict' => true, 'schema' => $args['schema']['schema'], ), ); } $response = self::post( 'https://api.openai.com/v1/chat/completions', array( 'Authorization' => 'Bearer ' . $key, 'Content-Type' => 'application/json', ), $payload ); if ( is_wp_error( $response ) ) { return $response; } $body = $response['body']; $text = (string) ( $body['choices'][0]['message']['content'] ?? '' ); if ( '' === trim( $text ) ) { return 'length' === ( $body['choices'][0]['finish_reason'] ?? '' ) ? self::truncated_error() : new WP_Error( 'empty_response', __( 'The model returned no content.', 'ai-seo-tools' ), array( 'status' => 200 ) ); } return self::shape( $text, array( 'input' => (int) ( $body['usage']['prompt_tokens'] ?? 0 ), 'output' => (int) ( $body['usage']['completion_tokens'] ?? 0 ), ), $model, 'openai', $args ); } /** * OpenRouter proxies hundreds of models behind an OpenAI-compatible endpoint. * * The catch is that support for structured output varies per model, and the * free tiers usually lack it. So the schema is always restated in the prompt, * and a rejection of response_format is retried without it rather than * surfaced as a failure. */ private static function request_openrouter( string $model, string $key, array $args ) { $prompt = $args['prompt']; if ( ! empty( $args['schema'] ) ) { $prompt .= "\n\n" . __( 'Reply with a single JSON object matching this schema, and nothing else — no prose, no code fence:', 'ai-seo-tools' ) . "\n" . wp_json_encode( $args['schema']['schema'] ); } $payload = array( 'model' => $model, 'messages' => self::openai_messages( $args, $prompt ), 'max_tokens' => (int) $args['max_tokens'], ); if ( null !== $args['temperature'] && ! self::is_reasoning_model( $model ) ) { $payload['temperature'] = (float) $args['temperature']; } if ( ! empty( $args['schema'] ) ) { $payload['response_format'] = array( 'type' => 'json_schema', 'json_schema' => array( 'name' => $args['schema']['name'] ?? 'result', 'strict' => true, 'schema' => $args['schema']['schema'], ), ); } $headers = array( 'Authorization' => 'Bearer ' . $key, 'Content-Type' => 'application/json', // OpenRouter attributes traffic to the calling site on its dashboards. 'HTTP-Referer' => home_url(), 'X-Title' => get_bloginfo( 'name' ), ); $endpoint = 'https://openrouter.ai/api/v1/chat/completions'; $response = self::post( $endpoint, $headers, $payload ); if ( is_wp_error( $response ) && isset( $payload['response_format'] ) && self::rejects_schema( $response ) ) { unset( $payload['response_format'] ); $response = self::post( $endpoint, $headers, $payload ); } if ( is_wp_error( $response ) ) { return self::explain_openrouter_error( $response, $model ); } $body = $response['body']; // OpenRouter reports upstream failures with a 200 and an error member. if ( isset( $body['error'] ) ) { return new WP_Error( 'api_error', (string) ( $body['error']['message'] ?? __( 'The provider returned an error.', 'ai-seo-tools' ) ), array( 'status' => (int) ( $body['error']['code'] ?? 502 ) ) ); } $text = $body['choices'][0]['message']['content'] ?? ''; if ( '' === trim( (string) $text ) ) { return 'length' === ( $body['choices'][0]['finish_reason'] ?? '' ) ? self::truncated_error() : new WP_Error( 'empty_response', __( 'The model returned no content.', 'ai-seo-tools' ), array( 'status' => 200 ) ); } return self::shape( (string) $text, array( 'input' => (int) ( $body['usage']['prompt_tokens'] ?? 0 ), 'output' => (int) ( $body['usage']['completion_tokens'] ?? 0 ), ), $model, 'openrouter', $args ); } /** * OpenRouter reports upstream failures as a bare "Provider returned error", * which tells the user nothing. Add the part they can act on. */ private static function explain_openrouter_error( WP_Error $error, string $model ): WP_Error { $data = $error->get_error_data(); $status = is_array( $data ) ? (int) ( $data['status'] ?? 0 ) : 0; if ( 429 !== $status ) { return $error; } $hint = str_contains( $model, ':free' ) ? __( 'Free models on OpenRouter have tight rate limits that are shared across everyone using them. Wait a few minutes, raise the pause between items, or switch to a paid model for bulk work.', 'ai-seo-tools' ) : __( 'The provider is rate limiting this key. Wait a few minutes or raise the pause between items.', 'ai-seo-tools' ); return new WP_Error( $error->get_error_code(), sprintf( /* translators: 1: original provider message, 2: advice on what to do. */ __( '%1$s — %2$s', 'ai-seo-tools' ), $error->get_error_message(), $hint ), $data ); } /** * The response came back empty because the model hit its output ceiling. * * Reasoning models spend tokens thinking before they write anything, so a cap * that is generous for a one-line answer can leave nothing for the answer. */ private static function truncated_error(): WP_Error { return new WP_Error( 'truncated', __( 'The model used its whole token budget before writing an answer. This usually means a reasoning model with too small a limit.', 'ai-seo-tools' ), array( 'status' => 200 ) ); } /** * Detects a refusal that is specifically about structured output support. */ private static function rejects_schema( WP_Error $error ): bool { $data = $error->get_error_data(); $status = is_array( $data ) ? (int) ( $data['status'] ?? 0 ) : 0; if ( ! in_array( $status, array( 400, 404, 422 ), true ) ) { return false; } return (bool) preg_match( '/(response_format|json_schema|structured output|schema)/i', $error->get_error_message() ); } /** * True for models that only accept their default sampling settings. */ private static function is_reasoning_model( string $model ): bool { return (bool) preg_match( '/^(o[1-9]|gpt-5)/i', $model ); } private static function request_anthropic( string $model, string $key, array $args ) { $content = array(); if ( ! empty( $args['image']['base64'] ) ) { $content[] = array( 'type' => 'image', 'source' => array( 'type' => 'base64', 'media_type' => $args['image']['mime'], 'data' => $args['image']['base64'], ), ); } $content[] = array( 'type' => 'text', 'text' => $args['prompt'] ); $payload = array( 'model' => $model, 'max_tokens' => (int) $args['max_tokens'], 'messages' => array( array( 'role' => 'user', 'content' => $content ) ), ); // Anthropic has no response_format. A forced tool call is the equivalent: // the schema becomes the tool's input schema, so the API validates the // shape rather than us hoping the prose parses. if ( ! empty( $args['schema'] ) ) { $tool_name = preg_replace( '/[^a-z0-9_-]/i', '_', $args['schema']['name'] ?? 'result' ); $payload['tools'] = array( array( 'name' => $tool_name, 'description' => 'Return the result in this structure.', 'input_schema' => $args['schema']['schema'], ), ); $payload['tool_choice'] = array( 'type' => 'tool', 'name' => $tool_name ); } if ( $args['system'] ) { $payload['system'] = $args['system']; } if ( null !== $args['temperature'] ) { $payload['temperature'] = (float) $args['temperature']; } $response = self::post( 'https://api.anthropic.com/v1/messages', array( 'x-api-key' => $key, 'anthropic-version' => '2023-06-01', 'Content-Type' => 'application/json', ), $payload ); if ( is_wp_error( $response ) ) { return $response; } $body = $response['body']; $text = ''; foreach ( (array) ( $body['content'] ?? array() ) as $block ) { $type = $block['type'] ?? ''; if ( 'tool_use' === $type && isset( $block['input'] ) ) { // The validated tool input is the structured result. $text = wp_json_encode( $block['input'] ); break; } if ( 'text' === $type ) { $text .= $block['text']; } } if ( '' === $text ) { return 'max_tokens' === ( $body['stop_reason'] ?? '' ) ? self::truncated_error() : new WP_Error( 'empty_response', __( 'The model returned no content.', 'ai-seo-tools' ), array( 'status' => 200 ) ); } return self::shape( $text, array( 'input' => (int) ( $body['usage']['input_tokens'] ?? 0 ), 'output' => (int) ( $body['usage']['output_tokens'] ?? 0 ), ), $model, 'anthropic', $args ); } private static function request_gemini( string $model, string $key, array $args ) { $parts = array( array( 'text' => $args['prompt'] ) ); if ( ! empty( $args['image']['base64'] ) ) { $parts[] = array( 'inline_data' => array( 'mime_type' => $args['image']['mime'], 'data' => $args['image']['base64'], ), ); } $payload = array( 'contents' => array( array( 'role' => 'user', 'parts' => $parts ) ), 'generationConfig' => array( 'maxOutputTokens' => (int) $args['max_tokens'] ), ); if ( $args['system'] ) { $payload['systemInstruction'] = array( 'parts' => array( array( 'text' => $args['system'] ) ) ); } if ( null !== $args['temperature'] ) { $payload['generationConfig']['temperature'] = (float) $args['temperature']; } if ( ! empty( $args['schema'] ) ) { $payload['generationConfig']['responseMimeType'] = 'application/json'; $payload['generationConfig']['responseSchema'] = self::gemini_schema( $args['schema']['schema'] ); } $url = sprintf( 'https://generativelanguage.googleapis.com/v1beta/models/%s:generateContent', rawurlencode( $model ) ); $response = self::post( $url, array( 'x-goog-api-key' => $key, 'Content-Type' => 'application/json', ), $payload ); if ( is_wp_error( $response ) ) { return $response; } $body = $response['body']; $text = ''; foreach ( (array) ( $body['candidates'][0]['content']['parts'] ?? array() ) as $part ) { if ( isset( $part['text'] ) ) { $text .= $part['text']; } } if ( '' === $text ) { return 'MAX_TOKENS' === ( $body['candidates'][0]['finishReason'] ?? '' ) ? self::truncated_error() : new WP_Error( 'empty_response', __( 'The model returned no content.', 'ai-seo-tools' ), array( 'status' => 200 ) ); } return self::shape( $text, array( 'input' => (int) ( $body['usageMetadata']['promptTokenCount'] ?? 0 ), 'output' => (int) ( $body['usageMetadata']['candidatesTokenCount'] ?? 0 ), ), $model, 'gemini', $args ); } /** * Gemini rejects the JSON Schema keywords OpenAI requires, so strip them. */ private static function gemini_schema( array $schema ): array { unset( $schema['additionalProperties'], $schema['$schema'] ); if ( isset( $schema['properties'] ) && is_array( $schema['properties'] ) ) { foreach ( $schema['properties'] as $name => $property ) { $schema['properties'][ $name ] = self::gemini_schema( (array) $property ); } } if ( isset( $schema['items'] ) && is_array( $schema['items'] ) ) { $schema['items'] = self::gemini_schema( $schema['items'] ); } return $schema; } /* --------------------------------------------------------------------- */ /* Transport */ /* --------------------------------------------------------------------- */ /** * Posts JSON and normalises transport / HTTP errors. * * @return array{body:array,code:int}|WP_Error */ private static function post( string $url, array $headers, array $payload ) { $response = wp_remote_post( $url, array( 'headers' => $headers, 'body' => wp_json_encode( $payload ), 'timeout' => (int) apply_filters( 'ai_seo_tools_http_timeout', 90 ), 'method' => 'POST', 'data_format' => 'body', ) ); if ( is_wp_error( $response ) ) { return new WP_Error( 'network_error', $response->get_error_message(), array( 'status' => 0 ) ); } $code = (int) wp_remote_retrieve_response_code( $response ); $raw = wp_remote_retrieve_body( $response ); $body = json_decode( $raw, true ); if ( 200 !== $code ) { $message = $body['error']['message'] ?? $body['error']['status'] ?? $body['message'] ?? sprintf( /* translators: %d: HTTP status code. */ __( 'The API returned HTTP %d.', 'ai-seo-tools' ), $code ); $retry_after = wp_remote_retrieve_header( $response, 'retry-after' ); return new WP_Error( 'api_error', $message, array( 'status' => $code, 'retry_after' => $retry_after ? (int) $retry_after : 0, ) ); } if ( ! is_array( $body ) ) { return new WP_Error( 'bad_json', __( 'The API returned a malformed response.', 'ai-seo-tools' ), array( 'status' => $code ) ); } return array( 'body' => $body, 'code' => $code ); } /* --------------------------------------------------------------------- */ /* Result shaping */ /* --------------------------------------------------------------------- */ /** * Normalises a provider response into the plugin's shape. */ private static function shape( string $text, array $tokens, string $model, string $provider, array $args ): array { $text = trim( $text ); $json = null; if ( ! empty( $args['schema'] ) ) { $json = self::parse_json( $text ); } return array( 'text' => $text, 'json' => $json, 'model' => $model, 'provider' => $provider, 'usage' => array( 'input' => $tokens['input'], 'output' => $tokens['output'], 'cost' => self::estimate_cost( $model, $tokens['input'], $tokens['output'], $provider ), ), ); } /** * Extracts a JSON object from a model response. * * With structured outputs the whole body is already JSON; the fence and * brace-matching fallbacks only matter for providers without schema support. */ public static function parse_json( string $text ): ?array { $decoded = json_decode( $text, true ); if ( is_array( $decoded ) ) { return $decoded; } // Strip a ```json fence if the model added one. if ( preg_match( '/```(?:json)?\s*(.+?)```/s', $text, $m ) ) { $decoded = json_decode( trim( $m[1] ), true ); if ( is_array( $decoded ) ) { return $decoded; } } // Last resort: the outermost balanced object. $start = strpos( $text, '{' ); $end = strrpos( $text, '}' ); if ( false !== $start && false !== $end && $end > $start ) { $decoded = json_decode( substr( $text, $start, $end - $start + 1 ), true ); if ( is_array( $decoded ) ) { return $decoded; } } return null; } /** * Estimated USD cost for a call. */ public static function estimate_cost( string $model, int $input, int $output, string $provider = '' ): float { // OpenRouter publishes exact rates per model, so use those when we have them. if ( 'openrouter' === $provider ) { $rates = get_transient( 'ai_seo_tools_openrouter_pricing' ); if ( is_array( $rates ) && isset( $rates[ $model ] ) ) { return round( ( $input / 1000000 ) * $rates[ $model ]['in'] + ( $output / 1000000 ) * $rates[ $model ]['out'], 6 ); } // An unknown OpenRouter model is not necessarily free, but guessing a // price from another provider's table would be worse than reporting none. return 0.0; } $pricing = self::pricing(); $rate = null; if ( isset( $pricing[ $model ] ) ) { $rate = $pricing[ $model ]; } else { // Match on prefix so dated snapshots (gpt-4o-2024-…) still resolve. foreach ( $pricing as $name => $candidate ) { if ( 0 === strpos( $model, $name ) ) { $rate = $candidate; break; } } } if ( ! $rate ) { return 0.0; } return round( ( $input / 1000000 ) * $rate['in'] + ( $output / 1000000 ) * $rate['out'], 6 ); } /* --------------------------------------------------------------------- */ /* Budget + logging */ /* --------------------------------------------------------------------- */ /** * Blocks calls once the monthly cap is reached. * * @return true|WP_Error */ public static function check_budget() { $limit = (float) self::option( 'budget_monthly_usd', 0 ); if ( $limit <= 0 ) { return true; } $spent = AI_SEO_Tools_Log::month_spend(); if ( $spent < $limit ) { return true; } return new WP_Error( 'budget_exceeded', sprintf( /* translators: 1: amount spent, 2: configured monthly limit. */ __( 'Monthly budget reached: $%1$s of $%2$s estimated spend. Raise the limit in Settings to continue.', 'ai-seo-tools' ), number_format_i18n( $spent, $spent < 1 ? 4 : 2 ), number_format_i18n( $limit, $limit < 1 ? 4 : 2 ) ), array( 'status' => 402 ) ); } private static function log_success( array $args, string $provider, string $model, array $result ): void { AI_SEO_Tools_Log::record( array( 'module' => $args['module'], 'action' => $args['action'], 'object_id' => (int) $args['object_id'], 'provider' => $provider, 'model' => $model, 'input_tokens' => $result['usage']['input'], 'output_tokens' => $result['usage']['output'], 'cost' => $result['usage']['cost'], 'status' => 'ok', ) ); } private static function log_failure( array $args, string $provider, string $model, WP_Error $error ): void { AI_SEO_Tools_Log::record( array( 'module' => $args['module'], 'action' => $args['action'], 'object_id' => (int) $args['object_id'], 'provider' => $provider, 'model' => $model, 'status' => 'error', 'message' => $error->get_error_message(), ) ); } /** * Fetches the model list for a provider (cached for a day). * * @return array|WP_Error */ public static function fetch_models( string $provider = '', bool $force = false ) { $provider = $provider ?: self::provider(); $cache_key = 'ai_seo_tools_models_' . $provider; if ( ! $force ) { $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } } $key = self::api_key( $provider ); if ( '' === $key ) { return new WP_Error( 'missing_api_key', __( 'Add an API key first.', 'ai-seo-tools' ) ); } $models = array(); if ( 'openai' === $provider ) { $response = wp_remote_get( 'https://api.openai.com/v1/models', array( 'headers' => array( 'Authorization' => 'Bearer ' . $key ), 'timeout' => 20, ) ); } elseif ( 'anthropic' === $provider ) { $response = wp_remote_get( 'https://api.anthropic.com/v1/models?limit=100', array( 'headers' => array( 'x-api-key' => $key, 'anthropic-version' => '2023-06-01', ), 'timeout' => 20, ) ); } elseif ( 'openrouter' === $provider ) { $response = wp_remote_get( 'https://openrouter.ai/api/v1/models', array( 'headers' => array( 'Authorization' => 'Bearer ' . $key ), 'timeout' => 25, ) ); } else { $response = wp_remote_get( 'https://generativelanguage.googleapis.com/v1beta/models', array( 'headers' => array( 'x-goog-api-key' => $key ), 'timeout' => 20, ) ); } if ( is_wp_error( $response ) ) { return $response; } if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { return new WP_Error( 'api_error', __( 'Could not load the model list. Check the API key.', 'ai-seo-tools' ) ); } $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( 'openrouter' === $provider ) { $rates = array(); foreach ( (array) ( $body['data'] ?? array() ) as $model ) { $id = $model['id'] ?? ''; if ( ! $id ) { continue; } // Prices arrive as USD per token; the plugin works per million. $in = (float) ( $model['pricing']['prompt'] ?? 0 ) * 1000000; $out = (float) ( $model['pricing']['completion'] ?? 0 ) * 1000000; $rates[ $id ] = array( 'in' => $in, 'out' => $out ); $label = $model['name'] ?? $id; if ( $in <= 0 && $out <= 0 ) { $label .= ' — ' . __( 'free', 'ai-seo-tools' ); } $models[ $id ] = $label; } // Real rates beat the built-in estimates, so keep them alongside. set_transient( 'ai_seo_tools_openrouter_pricing', $rates, WEEK_IN_SECONDS ); } elseif ( 'gemini' === $provider ) { foreach ( (array) ( $body['models'] ?? array() ) as $model ) { $id = str_replace( 'models/', '', $model['name'] ?? '' ); if ( $id && ! empty( $model['supportedGenerationMethods'] ) && in_array( 'generateContent', (array) $model['supportedGenerationMethods'], true ) ) { $models[ $id ] = $model['displayName'] ?? $id; } } } else { foreach ( (array) ( $body['data'] ?? array() ) as $model ) { $id = $model['id'] ?? ''; if ( ! $id ) { continue; } // Skip embeddings, audio, moderation and image endpoints. if ( preg_match( '/(embed|whisper|tts|dall-e|moderation|realtime|audio|transcribe|image)/i', $id ) ) { continue; } $models[ $id ] = $model['display_name'] ?? $id; } } if ( empty( $models ) ) { return new WP_Error( 'no_models', __( 'The provider returned no usable models.', 'ai-seo-tools' ) ); } ksort( $models ); set_transient( $cache_key, $models, DAY_IN_SECONDS ); return $models; } /** * Clears every cached model list. */ public static function clear_model_cache(): void { foreach ( array_keys( self::providers() ) as $provider ) { delete_transient( 'ai_seo_tools_models_' . $provider ); } delete_transient( 'ai_seo_tools_openrouter_pricing' ); // Legacy key from before multi-provider support. delete_transient( 'ai_seo_tools_models_cache' ); } } }