[ 'name' => 'anthropic/claude-opus-4.8', 'max_tokens' => 8192, 'temperature' => 0.8, 'supports_system_message' => true, 'has_temperature' => false, ], 'anthropic/claude-opus-4.7' => [ 'name' => 'anthropic/claude-opus-4.7', 'max_tokens' => 8192, 'temperature' => 0.8, 'supports_system_message' => true, 'has_temperature' => false, ], 'anthropic/claude-sonnet-4.6' => [ 'name' => 'anthropic/claude-sonnet-4.6', 'max_tokens' => 8192, 'temperature' => 0.8, 'supports_system_message' => true ], 'openai/gpt-5.5' => [ 'name' => 'openai/gpt-5.5', 'max_tokens' => 8192, 'temperature' => 0.8, 'supports_system_message' => true, 'has_temperature' => false, ], 'openai/gpt-5.4-mini' => [ 'name' => 'openai/gpt-5.4-mini', 'max_tokens' => 8192, 'temperature' => 0.8, 'supports_system_message' => true, 'has_temperature' => false, ], 'google/gemini-3.5-flash' => [ 'name' => 'google/gemini-3.5-flash', 'max_tokens' => 8192, 'temperature' => 0.8, 'supports_system_message' => true, 'has_temperature' => false, ], 'google/gemini-3.1-pro-preview' => [ 'name' => 'google/gemini-3.1-pro-preview', 'max_tokens' => 8192, 'temperature' => 0.8, 'supports_system_message' => true, 'has_temperature' => false, ], 'deepseek/deepseek-v3.2' => [ 'name' => 'deepseek/deepseek-v3.2', 'max_tokens' => 8192, 'temperature' => 0.8, 'supports_system_message' => true ], 'google/gemma-4-31b-it:free' => [ 'name' => 'google/gemma-4-31b-it:free', 'max_tokens' => 8192, 'temperature' => 0.7, 'supports_system_message' => true ], 'openrouter/free' => [ 'name' => 'openrouter/free', 'max_tokens' => 8192, 'temperature' => 0.7, 'supports_system_message' => true ], ]; public function __construct($api_key) { $this->api_key = $api_key; } private function getModelConfig(string $model): array { if (isset($this->models[$model])) { return $this->models[$model]; } try { $metadata = self::get_model_metadata($model); } catch ( \RuntimeException $e ) { throw new ProviderCallException( $e->getMessage(), ProviderCallException::PROVIDER_UNAVAILABLE, null, '', null, 'openrouter', $e ); } if ($metadata === null) { throw new ProviderCallException( 'Invalid model selected: ' . esc_html($model), ProviderCallException::MODEL_NOT_FOUND, null, '', null, 'openrouter' ); } $supported_parameters = $metadata['supported_parameters']; $max_tokens = $metadata['max_output_tokens'] > 0 ? min(8192, $metadata['max_output_tokens']) : 8192; $config = [ 'name' => $metadata['id'], 'max_tokens' => $max_tokens, 'temperature' => 0.8, 'supports_system_message' => true, 'has_temperature' => in_array('temperature', $supported_parameters, true), 'supports_top_p' => in_array('top_p', $supported_parameters, true), ]; if (isset($this->requested_parameters['temperature']) && $config['has_temperature']) { $config['temperature'] = $this->requested_parameters['temperature']; } if (isset($this->requested_parameters['top_p']) && $config['supports_top_p']) { $config['top_p'] = $this->requested_parameters['top_p']; } return $config; } public static function get_model_metadata(string $model): ?array { if (!self::is_valid_model_id($model)) { return null; } $catalog = get_transient(self::MODEL_CATALOG_CACHE); if (!is_array($catalog)) { $stale_catalog = get_transient(self::MODEL_CATALOG_STALE_CACHE); if (get_transient(self::MODEL_CATALOG_FAILURE_BACKOFF)) { $stale_metadata = self::find_model_metadata($stale_catalog, $model); if ($stale_metadata !== null) { return $stale_metadata; } throw new \RuntimeException('OpenRouter model catalog is unavailable.'); } $catalog = self::refresh_model_catalog(); if ($catalog === null) { set_transient(self::MODEL_CATALOG_FAILURE_BACKOFF, 1, self::MODEL_CATALOG_FAILURE_TTL); $stale_metadata = self::find_model_metadata($stale_catalog, $model); if ($stale_metadata !== null) { return $stale_metadata; } throw new \RuntimeException('OpenRouter model catalog is unavailable.'); } } return self::find_model_metadata($catalog, $model); } private static function find_model_metadata($catalog, string $model): ?array { return is_array($catalog) && isset($catalog[$model]) && is_array($catalog[$model]) ? $catalog[$model] : null; } private static function refresh_model_catalog(): ?array { $response = wp_remote_get(self::MODEL_CATALOG_URL, [ 'headers' => [ 'Accept' => 'application/json', ], 'timeout' => 15, ]); if ($response instanceof \WP_Error || wp_remote_retrieve_response_code($response) !== 200) { return null; } $decoded = json_decode((string) wp_remote_retrieve_body($response), true); if (!is_array($decoded) || !isset($decoded['data']) || !is_array($decoded['data'])) { return null; } $catalog = []; foreach ($decoded['data'] as $entry) { if (!is_array($entry) || !isset($entry['id']) || !is_string($entry['id'])) { continue; } $model_id = trim($entry['id']); $output_modalities = isset($entry['architecture']['output_modalities']) && is_array($entry['architecture']['output_modalities']) ? $entry['architecture']['output_modalities'] : []; $expiration_date = isset($entry['expiration_date']) && is_string($entry['expiration_date']) ? $entry['expiration_date'] : ''; $expires_soon = $expiration_date !== '' && strtotime($expiration_date) <= time() + (90 * DAY_IN_SECONDS); if (!self::is_valid_model_id($model_id) || !in_array('text', $output_modalities, true) || $expires_soon) { continue; } $parameters = isset($entry['supported_parameters']) && is_array($entry['supported_parameters']) ? array_values(array_filter($entry['supported_parameters'], 'is_string')) : []; $max_output_tokens = isset($entry['top_provider']['max_completion_tokens']) ? absint($entry['top_provider']['max_completion_tokens']) : 0; $catalog[$model_id] = [ 'id' => $model_id, 'label' => isset($entry['name']) && is_string($entry['name']) ? sanitize_text_field($entry['name']) : $model_id, 'supported_parameters' => $parameters, 'max_output_tokens' => $max_output_tokens, 'expiration_date' => $expiration_date, ]; } if (!$catalog) { return null; } set_transient(self::MODEL_CATALOG_CACHE, $catalog, self::MODEL_CATALOG_TTL); set_transient(self::MODEL_CATALOG_STALE_CACHE, $catalog, self::MODEL_CATALOG_STALE_TTL); return $catalog; } private static function is_valid_model_id(string $model): bool { return (bool) preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._:-]*$/', $model); } public function generate_description(string $system_prompt, string $user_prompt, string $model = 'openrouter/free', ?int $maximum_length = null): string { $model = '' !== $model ? $model : 'openrouter/free'; $model_config = $this->getModelConfig($model); $messages = []; $system_prompt = $this->sanitize_prompt_content($system_prompt); $user_prompt = $this->sanitize_prompt_content($user_prompt); if ($model_config['supports_system_message']) { $messages[] = [ 'role' => 'system', 'content' => $system_prompt ]; $messages[] = [ 'role' => 'user', 'content' => $user_prompt ]; } else { $messages[] = [ 'role' => 'user', 'content' => $system_prompt . "\n\n" . $user_prompt ]; } $has_temperature = ! array_key_exists('has_temperature', $model_config) || $model_config['has_temperature'] !== false; $request_body = [ 'model' => $model_config['name'], 'messages' => $messages, ]; if ($has_temperature) { $request_body['temperature'] = $model_config['temperature']; } if ($has_temperature && (!isset($model_config['supports_top_p']) || $model_config['supports_top_p']) && isset($model_config['top_p']) && ! $this->is_anthropic_route($model_config['name'])) { $request_body['top_p'] = $model_config['top_p']; } $json_body = wp_json_encode($request_body, JSON_UNESCAPED_UNICODE); if ( false === $json_body ) { throw new ProviderCallException( esc_html__( 'Failed to encode request body as JSON. The product data may contain invalid characters.', 'ai-product-tools' ), ProviderCallException::BAD_REQUEST, null, '', null, 'openrouter' ); } $response = wp_remote_post($this->api_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json', 'HTTP-Referer' => self::get_site_url_value(), 'X-OpenRouter-Title' => 'AI Product Tools WordPress Plugin' ], 'body' => $json_body, 'timeout' => 30, ]); if ($response instanceof \WP_Error) { $error_message = $response->get_error_message(); $detailed_error = 'WP Error: ' . esc_html($error_message); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'openrouter' ); } $response_code = wp_remote_retrieve_response_code($response); $content_type = (string) wp_remote_retrieve_header($response, 'content-type'); $body_str = (string) wp_remote_retrieve_body($response); $retry_after_header = ErrorHandler::parse_retry_after_header( wp_remote_retrieve_header( $response, 'retry-after' ) ); self::throwIfHtmlBody( $content_type, $body_str, (int) $response_code ); $body = json_decode($body_str, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new ProviderCallException( sprintf( /* translators: %s: JSON error message */ __('Invalid JSON response from the API: %s', 'ai-product-tools'), json_last_error_msg() ), ProviderCallException::MALFORMED_RESPONSE, (int) $response_code, '', null, 'openrouter' ); } if (isset($body['error'])) { $error_data = $body['error']; $detailed_error = ErrorHandler::format_api_response_error($error_data, 'OpenRouter', $response_code); throw self::providerErrorFromResponse( $error_data, (int) $response_code, $detailed_error, $retry_after_header ); } $this->throwForChoiceLevelError( $body, (int) $response_code, $retry_after_header ); $this->throwIfRefused( $body, (int) $response_code ); $message_content = $body['choices'][0]['message']['content'] ?? null; if ( null === $message_content || '' === trim( (string) $message_content ) ) { $finish_reason = isset( $body['choices'][0]['finish_reason'] ) && is_string( $body['choices'][0]['finish_reason'] ) ? $body['choices'][0]['finish_reason'] : ''; throw new ProviderCallException( 'Invalid response from OpenRouter API: Response structure is not as expected', $this->classifyEmptyContentReason( $finish_reason ), (int) $response_code, $finish_reason, null, 'openrouter' ); } $finish_reason = isset( $body['choices'][0]['finish_reason'] ) && is_string( $body['choices'][0]['finish_reason'] ) ? $body['choices'][0]['finish_reason'] : ''; self::throwIfNonEmptyContentWasCutOff( $finish_reason, (int) $response_code ); \AIPT\Core\Services\UsageTracker::trackApiCall( 'openrouter', (string) ( $body['model'] ?? $model ), (int) ( $body['usage']['prompt_tokens'] ?? 0 ), (int) ( $body['usage']['completion_tokens'] ?? 0 ) ); return trim($body['choices'][0]['message']['content']); } public function generate_faq_content(string $system_prompt, string $user_prompt, ?string $model = null): string { $resolved_model = $model ?: 'openrouter/free'; return $this->generate_description($system_prompt, $user_prompt, $resolved_model); } public function generate_from_vision(string $system_prompt, string $user_prompt, string $image_url, ?string $model = null): string { $resolved_model = $model ?: 'openrouter/free'; $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { throw ProviderCallException::aiDisabled( $ai_gate, 'openrouter' ); } try { $encoded_image = VisionImageEncoder::fetchAndEncode( $image_url ); $image_data_uri = 'data:' . $encoded_image['mime_type'] . ';base64,' . $encoded_image['data']; } catch ( \RuntimeException $e ) { $detailed_error = ErrorHandler::format_api_response_error( [ 'code' => 'aipt_vision_fetch_failed', 'message' => esc_html( $e->getMessage() ), 'type' => 'vision_image_fetch_failed', ], 'OpenRouter', 0 ); throw new ProviderCallException( $detailed_error, ProviderCallException::IMAGE_UNAVAILABLE, null, 'vision_image_fetch_failed', null, 'openrouter', $e ); } $messages = [ [ 'role' => 'system', 'content' => $this->sanitize_prompt_content( $system_prompt ), ], [ 'role' => 'user', 'content' => [ [ 'type' => 'text', 'text' => $this->sanitize_prompt_content( $user_prompt ), ], [ 'type' => 'image_url', 'image_url' => [ 'url' => $image_data_uri ], ], ], ], ]; $model_config = $this->getModelConfig($resolved_model); $has_temperature = ! array_key_exists('has_temperature', $model_config) || $model_config['has_temperature'] !== false; $request_body = [ 'model' => $model_config['name'], 'messages' => $messages, ]; if ($has_temperature) { $request_body['temperature'] = 0.3; } $json_body = wp_json_encode( $request_body, JSON_UNESCAPED_UNICODE ); if ( false === $json_body ) { throw new ProviderCallException( esc_html__( 'Failed to encode vision request body as JSON.', 'ai-product-tools' ), ProviderCallException::BAD_REQUEST, null, '', null, 'openrouter' ); } $response = wp_remote_post( $this->api_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json', 'HTTP-Referer' => self::get_site_url_value(), 'X-OpenRouter-Title' => 'AI Product Tools WordPress Plugin', ], 'body' => $json_body, 'timeout' => 60, ] ); if ( $response instanceof \WP_Error ) { $error_message = $response->get_error_message(); $detailed_error = 'WP Error: ' . esc_html( $error_message ); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'openrouter' ); } $response_code = wp_remote_retrieve_response_code( $response ); $content_type = (string) wp_remote_retrieve_header( $response, 'content-type' ); $body_str = (string) wp_remote_retrieve_body( $response ); $retry_after_header = ErrorHandler::parse_retry_after_header( wp_remote_retrieve_header( $response, 'retry-after' ) ); self::throwIfHtmlBody( $content_type, $body_str, (int) $response_code ); $body = json_decode( $body_str, true ); if ( json_last_error() !== JSON_ERROR_NONE ) { throw new ProviderCallException( sprintf( /* translators: %s: JSON error message */ esc_html__( 'Invalid JSON response from the API: %s', 'ai-product-tools' ), esc_html( json_last_error_msg() ) ), ProviderCallException::MALFORMED_RESPONSE, (int) $response_code, '', null, 'openrouter' ); } if ( isset( $body['error'] ) ) { $detailed_error = ErrorHandler::format_api_response_error( $body['error'], 'OpenRouter', $response_code ); throw self::providerErrorFromResponse( $body['error'], (int) $response_code, $detailed_error, $retry_after_header ); } $this->throwForChoiceLevelError( $body, (int) $response_code, $retry_after_header ); $this->throwIfRefused( $body, (int) $response_code ); $vision_content = $body['choices'][0]['message']['content'] ?? null; if ( null === $vision_content || '' === trim( (string) $vision_content ) ) { $finish_reason = isset( $body['choices'][0]['finish_reason'] ) && is_string( $body['choices'][0]['finish_reason'] ) ? $body['choices'][0]['finish_reason'] : ''; throw new ProviderCallException( 'Invalid response from OpenRouter vision API: unexpected structure', $this->classifyEmptyContentReason( $finish_reason ), (int) $response_code, $finish_reason, null, 'openrouter' ); } $finish_reason = isset( $body['choices'][0]['finish_reason'] ) && is_string( $body['choices'][0]['finish_reason'] ) ? $body['choices'][0]['finish_reason'] : ''; self::throwIfNonEmptyContentWasCutOff( $finish_reason, (int) $response_code ); \AIPT\Core\Services\UsageTracker::trackApiCall( 'openrouter', (string) ( $body['model'] ?? $resolved_model ), (int) ( $body['usage']['prompt_tokens'] ?? 0 ), (int) ( $body['usage']['completion_tokens'] ?? 0 ) ); return trim( (string) $body['choices'][0]['message']['content'] ); } /** * Generate a structured (JSON-schema-shaped) answer. * * Additive method for StructuredOutputClientInterface. When * $options['native'] is true this forwards OpenAI-shaped * `response_format: { type: 'json_schema', strict: true }` (OpenRouter's * chat/completions endpoint is OpenAI-compatible); otherwise it sends a * plain prompt call (the caller has already appended the JSON * instruction to $user_prompt) and returns `decoded: null`. The caller * (StructuredCaller) decides `native` only after checking * self::supports_structured_output() for the resolved model, so this * method trusts $options['native'] as-is rather than re-deciding it. * Does not change generate_description()'s request body or behavior. * * @param string $system_prompt System instructions. * @param string $user_prompt User message/prompt. * @param array $json_schema JSON schema of the expected answer. * @param string $model Model ID ('' = default). * @param array $options See StructuredOutputClientInterface. * @return array{raw_text: string, decoded: array|null, used_native: bool, model: string} */ public function generate_structured( string $system_prompt, string $user_prompt, array $json_schema, string $model = '', array $options = array() ): array { $resolved_model = '' !== $model ? $model : 'openrouter/free'; $model_config = $this->getModelConfig( $resolved_model ); $native = ! empty( $options['native'] ); $schema_name = $this->sanitize_schema_name( $options['schema_name'] ?? '' ); $system_prompt = $this->sanitize_prompt_content( $system_prompt ); $user_prompt = $this->sanitize_prompt_content( $user_prompt ); $user_content = $user_prompt; if ( ! empty( $options['image']['url'] ) ) { $user_content = $this->build_vision_content( $user_prompt, (string) $options['image']['url'] ); } $messages = []; if ($model_config['supports_system_message']) { $messages[] = [ 'role' => 'system', 'content' => $system_prompt ]; $messages[] = [ 'role' => 'user', 'content' => $user_content ]; } else { $messages[] = [ 'role' => 'user', 'content' => is_array( $user_content ) ? $user_content : ( $system_prompt . "\n\n" . $user_content ) ]; } $has_temperature = ! array_key_exists('has_temperature', $model_config) || $model_config['has_temperature'] !== false; $request_body = [ 'model' => $model_config['name'], 'messages' => $messages, ]; if ($has_temperature) { $request_body['temperature'] = $model_config['temperature']; } if ($has_temperature && (!isset($model_config['supports_top_p']) || $model_config['supports_top_p']) && isset($model_config['top_p']) && ! $this->is_anthropic_route($model_config['name'])) { $request_body['top_p'] = $model_config['top_p']; } if ( $native ) { $request_body['response_format'] = [ 'type' => 'json_schema', 'json_schema' => [ 'name' => $schema_name, 'strict' => true, 'schema' => $json_schema, ], ]; } $max_tokens = isset( $options['max_tokens'] ) ? (int) $options['max_tokens'] : 0; if ( $max_tokens > 0 ) { $request_body['max_tokens'] = $max_tokens; } $json_body = wp_json_encode($request_body, JSON_UNESCAPED_UNICODE); if ( false === $json_body ) { throw new ProviderCallException( esc_html__( 'Failed to encode request body as JSON. The product data may contain invalid characters.', 'ai-product-tools' ), ProviderCallException::BAD_REQUEST, null, '', null, 'openrouter' ); } $timeout = isset( $options['timeout'] ) && (int) $options['timeout'] > 0 ? (int) $options['timeout'] : 30; $response = wp_remote_post($this->api_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json', 'HTTP-Referer' => self::get_site_url_value(), 'X-OpenRouter-Title' => 'AI Product Tools WordPress Plugin' ], 'body' => $json_body, 'timeout' => $timeout, ]); if ($response instanceof \WP_Error) { $error_message = $response->get_error_message(); $detailed_error = 'WP Error: ' . esc_html($error_message); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'openrouter' ); } $response_code = wp_remote_retrieve_response_code($response); $content_type = (string) wp_remote_retrieve_header($response, 'content-type'); $body_str = (string) wp_remote_retrieve_body($response); $retry_after_header = ErrorHandler::parse_retry_after_header( wp_remote_retrieve_header( $response, 'retry-after' ) ); self::throwIfHtmlBody( $content_type, $body_str, (int) $response_code ); $body = json_decode($body_str, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new ProviderCallException( sprintf( /* translators: %s: JSON error message */ __('Invalid JSON response from the API: %s', 'ai-product-tools'), json_last_error_msg() ), ProviderCallException::MALFORMED_RESPONSE, (int) $response_code, '', null, 'openrouter' ); } if (isset($body['error'])) { $detailed_error = ErrorHandler::format_api_response_error($body['error'], 'OpenRouter', $response_code); throw self::providerErrorFromResponse( $body['error'], (int) $response_code, $detailed_error, $retry_after_header ); } $this->throwForChoiceLevelError( $body, (int) $response_code, $retry_after_header ); $this->throwIfRefused( $body, (int) $response_code ); $message_content = $body['choices'][0]['message']['content'] ?? null; if ( null === $message_content || '' === trim( (string) $message_content ) ) { $finish_reason = isset( $body['choices'][0]['finish_reason'] ) && is_string( $body['choices'][0]['finish_reason'] ) ? $body['choices'][0]['finish_reason'] : ''; throw new ProviderCallException( 'Invalid response from OpenRouter API: Response structure is not as expected', $this->classifyEmptyContentReason( $finish_reason ), (int) $response_code, $finish_reason, null, 'openrouter' ); } $finish_reason = isset( $body['choices'][0]['finish_reason'] ) && is_string( $body['choices'][0]['finish_reason'] ) ? $body['choices'][0]['finish_reason'] : ''; self::throwIfTruncatedAndUndecodable( $finish_reason, (string) $message_content, (int) $response_code ); $content = (string) $body['choices'][0]['message']['content']; $decoded = null; if ( $native ) { $maybe = json_decode( $content, true ); if ( JSON_ERROR_NONE === json_last_error() && is_array( $maybe ) ) { $decoded = $maybe; } } \AIPT\Core\Services\UsageTracker::trackApiCall( 'openrouter', (string) ( $body['model'] ?? $resolved_model ), (int) ( $body['usage']['prompt_tokens'] ?? 0 ), (int) ( $body['usage']['completion_tokens'] ?? 0 ) ); return [ 'raw_text' => trim( $content ), 'decoded' => $decoded, 'used_native' => $native, 'model' => $resolved_model, ]; } /** * Build a ProviderCallException from an OpenRouter error response body, * classifying its reason from the HTTP status plus whatever the real * upstream provider's own error type/code carries, when OpenRouter * passed one through in `metadata.raw.error` (see ErrorHandler's same * unwrapping for the human-readable message). * * @param mixed $error_data `$body['error']` from the response. * @param int $response_code HTTP status code. * @param string $detailed_error Already-formatted technical message (unchanged `getMessage()`). * @return ProviderCallException */ private static function providerErrorFromResponse( $error_data, int $response_code, string $detailed_error, ?int $retry_after_header = null ): ProviderCallException { $data = is_array( $error_data ) ? $error_data : array(); $message = isset( $data['message'] ) && is_string( $data['message'] ) ? $data['message'] : ''; $upstream_type = ''; $upstream_code = ''; if ( isset( $data['metadata']['raw']['error'] ) && is_array( $data['metadata']['raw']['error'] ) ) { $upstream = $data['metadata']['raw']['error']; if ( isset( $upstream['type'] ) && is_string( $upstream['type'] ) ) { $upstream_type = $upstream['type']; } if ( isset( $upstream['code'] ) && is_string( $upstream['code'] ) ) { $upstream_code = $upstream['code']; } if ( isset( $upstream['message'] ) && is_string( $upstream['message'] ) && '' !== $upstream['message'] ) { $message = $upstream['message']; } } $upstream_signal = '' !== $upstream_type ? $upstream_type : $upstream_code; return new ProviderCallException( $detailed_error, self::classifyErrorReason( $response_code, $upstream_signal, $message, $upstream_code ), $response_code, $upstream_signal, $retry_after_header ?? ErrorHandler::extract_retry_after( $error_data ), 'openrouter' ); } /** * OpenRouter's documented shape for a failure that happens mid-generation * (a provider error after the response already started, or an exhausted * fallback chain) nests the error inside the chosen `choices[0]` entry * instead of the top-level `error` field, while `message.content` can * still hold whatever partial text was produced before the failure. * Checking this BEFORE the content-emptiness check keeps that * partial/broken text from being handed back as a normal successful * answer. * * @param mixed $body Decoded response body; not necessarily an array (a * provider can return a bare JSON scalar that still * decodes without error). * @param int $response_code Outer HTTP status code. * @param int|null $retry_after_header Retry-After HTTP header, already parsed. * @return void * @throws ProviderCallException When the chosen choice reports a provider failure. */ private function throwForChoiceLevelError( $body, int $response_code, ?int $retry_after_header ): void { $choices = is_array( $body ) && is_array( $body['choices'] ?? null ) ? $body['choices'] : array(); $choice = is_array( $choices[0] ?? null ) ? $choices[0] : array(); $finish_reason = isset( $choice['finish_reason'] ) && is_string( $choice['finish_reason'] ) ? $choice['finish_reason'] : ''; $choice_error = is_array( $choice['error'] ?? null ) ? $choice['error'] : array(); if ( 'error' !== $finish_reason && empty( $choice_error ) ) { return; } $has_code = isset( $choice_error['code'] ) && is_numeric( $choice_error['code'] ); $has_message = isset( $choice_error['message'] ) && is_string( $choice_error['message'] ) && '' !== $choice_error['message']; if ( ! $has_code && ! $has_message ) { throw new ProviderCallException( 'Invalid response from OpenRouter API: the provider reported a mid-generation failure with no further detail', ProviderCallException::PROVIDER_UNAVAILABLE, $response_code, 'error', $retry_after_header, 'openrouter' ); } $effective_code = $has_code ? (int) $choice_error['code'] : $response_code; $detailed_error = ErrorHandler::format_api_response_error( $choice_error, 'OpenRouter', $effective_code ); throw self::providerErrorFromResponse( $choice_error, $effective_code, $detailed_error, $retry_after_header ); } /** * Classify an OpenRouter error response into a stable ProviderCallException reason. * * @param int $response_code HTTP status code OpenRouter itself answered with. * @param string $upstream_type The real provider's error type/code, when OpenRouter passed one through. * @param string $message Error message, used to tell quota exhaustion from a transient rate limit and to spot a schema-shaped 400. * @return string */ private static function classifyErrorReason( int $response_code, string $upstream_type, string $message, string $upstream_code = '' ): string { if ( 401 === $response_code ) { return ProviderCallException::AUTH_INVALID_KEY; } if ( 403 === $response_code ) { $lower_msg = strtolower( $message ); $is_moderation = false !== strpos( $lower_msg, 'flagged' ) || false !== strpos( $lower_msg, 'moderation' ) || false !== strpos( $lower_msg, 'guardrail' ); return $is_moderation ? ProviderCallException::CONTENT_BLOCKED : ProviderCallException::AUTH_FORBIDDEN; } if ( 404 === $response_code ) { return false !== stripos( $message, 'data policy' ) ? ProviderCallException::DATA_POLICY_BLOCKED : ProviderCallException::MODEL_NOT_FOUND; } if ( 402 === $response_code ) { return ProviderCallException::QUOTA_EXHAUSTED; } if ( 408 === $response_code ) { return ProviderCallException::NETWORK_TIMEOUT; } if ( 429 === $response_code ) { $lower_msg = strtolower( $message ); $is_quota = 'insufficient_quota' === $upstream_type || false !== strpos( $lower_msg, 'insufficient_quota' ) || ( false !== strpos( $lower_msg, 'quota' ) && ( false !== strpos( $lower_msg, 'billing' ) || false !== strpos( $lower_msg, 'plan' ) || false !== strpos( $lower_msg, 'credit' ) ) ); return $is_quota ? ProviderCallException::QUOTA_EXHAUSTED : ProviderCallException::RATE_LIMITED; } if ( 413 === $response_code || 'context_length_exceeded' === $upstream_type || 'context_length_exceeded' === $upstream_code ) { return ProviderCallException::REQUEST_TOO_LARGE; } if ( 400 === $response_code ) { $looks_like_schema = false !== stripos( $message, 'response_format' ) || false !== stripos( $message, 'json_schema' ) || false !== stripos( $message, 'schema' ); return $looks_like_schema ? ProviderCallException::INVALID_SCHEMA_REQUEST : ProviderCallException::BAD_REQUEST; } if ( $response_code >= 500 ) { return ProviderCallException::PROVIDER_UNAVAILABLE; } return ProviderCallException::BAD_REQUEST; } /** * A security plugin or hosting firewall that intercepts the call answers * with an HTML page instead of the provider's JSON. Every call path * reports that as a network failure with the firewall guidance, rather * than as a broken provider response. * * @param string $content_type Response content-type header. * @param string $body_str Raw response body. * @param int $response_code HTTP status code. * @throws ProviderCallException When the body is an HTML page. */ private static function throwIfHtmlBody( string $content_type, string $body_str, int $response_code ): void { if ( ! ErrorHandler::looks_like_html_body( $content_type, $body_str ) ) { return; } throw new ProviderCallException( esc_html__('The API response was not valid JSON. This is often caused by a server firewall or security plugin blocking outbound requests. Please contact your hosting provider or check your security plugin settings.', 'ai-product-tools'), ProviderCallException::NETWORK_ERROR, $response_code, '', null, 'openrouter' ); } /** * A non-empty answer can still be a cutoff or a safety block rather than a * complete success: `finish_reason` describes how generation ended, * independent of whether any text came back with it. * * @param string $finish_reason OpenRouter `choices[0].finish_reason`. * @param int $response_code HTTP status code. * @throws ProviderCallException When the answer was cut off or blocked mid-generation. */ private static function throwIfNonEmptyContentWasCutOff( string $finish_reason, int $response_code ): void { $normalized = strtolower( $finish_reason ); if ( 'length' === $normalized ) { throw new ProviderCallException( 'Invalid response from OpenRouter API: the answer was cut off before it finished', ProviderCallException::TRUNCATED_OUTPUT, $response_code, $finish_reason, null, 'openrouter' ); } self::throwIfBlocked( $finish_reason, $response_code ); } /** * A safety finish means the model declined part way through: whatever * text came back is never a usable answer, plain or structured. * * @param string $finish_reason OpenRouter finish reason. * @param int $response_code HTTP status code. * @throws ProviderCallException When the model declined to finish. */ private static function throwIfBlocked( string $finish_reason, int $response_code ): void { $normalized = strtolower( $finish_reason ); if ( 'content_filter' === $normalized ) { throw new ProviderCallException( 'Invalid response from OpenRouter API: the model declined partway through the answer', ProviderCallException::CONTENT_BLOCKED, $response_code, $finish_reason, null, 'openrouter' ); } } /** * generate_structured()'s own truncation rule: a length cutoff only fails * the call when the text it cut off does not even decode as JSON. * * @param string $finish_reason OpenRouter `choices[0].finish_reason`. * @param string $content Raw text content. * @param int $response_code HTTP status code. * @throws ProviderCallException When a length cutoff left undecodable JSON. */ private static function throwIfTruncatedAndUndecodable( string $finish_reason, string $content, int $response_code ): void { self::throwIfBlocked( $finish_reason, $response_code ); if ( 'length' !== strtolower( $finish_reason ) ) { return; } $maybe = json_decode( $content, true ); if ( JSON_ERROR_NONE === json_last_error() && is_array( $maybe ) ) { return; } throw new ProviderCallException( 'Invalid response from OpenRouter API: the answer was cut off before it finished', ProviderCallException::TRUNCATED_OUTPUT, $response_code, $finish_reason, null, 'openrouter' ); } /** * A model that declines a request for safety reasons can answer with * `message.refusal` and no content on any chat completion, not only a * structured one, and finish_reason is not guaranteed to be * 'content_filter'. That is a permanent content block, not a broken * response worth retrying. * * @param mixed $body Decoded response body. * @param int $response_code HTTP status code. * @throws ProviderCallException When the model refused. */ private function throwIfRefused( $body, int $response_code ): void { $refusal = $body['choices'][0]['message']['refusal'] ?? null; if ( ! is_string( $refusal ) || '' === trim( $refusal ) ) { return; } throw new ProviderCallException( 'Invalid response from OpenRouter API: the model refused the request', ProviderCallException::CONTENT_BLOCKED, $response_code, 'refusal', null, 'openrouter' ); } /** * Classify why the model's content came back empty: a safety refusal and * a length cutoff both need their own reason instead of the generic * "unexpected structure" bucket. OpenRouter's chat/completions response * is OpenAI-compatible, so `finish_reason` uses the same values. * * @param string $finish_reason `choices[0].finish_reason`. * @return string */ private function classifyEmptyContentReason( string $finish_reason ): string { $normalized = strtolower( $finish_reason ); if ( 'content_filter' === $normalized ) { return ProviderCallException::CONTENT_BLOCKED; } if ( 'length' === $normalized ) { return ProviderCallException::TRUNCATED_OUTPUT; } return ProviderCallException::MALFORMED_RESPONSE; } /** * Whether a resolved OpenRouter model route currently advertises * structured-output support, checked against its cached * `supported_parameters` (the same remote catalog generate_description()'s * dynamic routes already use). * * The exact flag name OpenRouter uses for this was not confirmed against * a live catalog fetch, so both plausible names are checked. Metadata * that is unavailable (cache miss and the catalog fetch also fails, with * no stale copy either) fails closed to false so callers fall back to * the plain JSON-in-prompt contract instead of guessing. * * @param string $model Model ID (static curated or a custom vendor/model route). * @return bool */ public static function supports_structured_output( string $model ): bool { try { $metadata = self::get_model_metadata( $model ); } catch ( \RuntimeException $e ) { return false; } if ( null === $metadata || empty( $metadata['supported_parameters'] ) || ! is_array( $metadata['supported_parameters'] ) ) { return false; } return in_array( 'response_format', $metadata['supported_parameters'], true ) || in_array( 'structured_outputs', $metadata['supported_parameters'], true ); } /** * Build an OpenAI-shaped multi-part user content array carrying the text * plus one vision image, reusing the same fetch/encode path as * generate_from_vision(). * * @param string $text User prompt text. * @param string $image_url Image URL or data URI. * @return array */ private function build_vision_content( string $text, string $image_url ): array { try { $encoded_image = VisionImageEncoder::fetchAndEncode( $image_url ); } catch ( \RuntimeException $e ) { $detailed_error = ErrorHandler::format_api_response_error( [ 'code' => 'aipt_vision_fetch_failed', 'message' => esc_html( $e->getMessage() ), 'type' => 'vision_image_fetch_failed', ], 'OpenRouter', 0 ); throw new ProviderCallException( $detailed_error, ProviderCallException::IMAGE_UNAVAILABLE, null, 'vision_image_fetch_failed', null, 'openrouter', $e ); } $image_data_uri = 'data:' . $encoded_image['mime_type'] . ';base64,' . $encoded_image['data']; return [ [ 'type' => 'text', 'text' => $text, ], [ 'type' => 'image_url', 'image_url' => [ 'url' => $image_data_uri ], ], ]; } /** * Sanitize a caller-supplied schema name to OpenAI's allowed charset * (OpenRouter forwards this unchanged to the OpenAI-shaped backend). * * @param mixed $name Raw schema name. * @return string */ private function sanitize_schema_name( $name ): string { $name = is_string( $name ) ? trim( $name ) : ''; $name = (string) preg_replace( '/[^A-Za-z0-9_-]/', '_', $name ); $name = substr( $name, 0, 64 ); return '' !== $name ? $name : 'aipt_blueprint_schema'; } /** * Prompt içeriğini temizler ve API için hazırlar * * Outbound prompt text, not AI output: cleanOutboundPrompt() skips * cleanContent()'s "repair unclosed markdown" step, which otherwise * deletes a prompt's own literal ** / * characters (e.g. an * anti-markdown rule) before the model ever sees them. * * @param string $content Temizlenecek prompt içeriği * @return string Temizlenmiş içerik */ private function sanitize_prompt_content(string $content): string { return PromptFormatter::cleanOutboundPrompt($content); } /** * Whether an OpenRouter model route targets Anthropic's Claude backend. * * Anthropic rejects requests carrying BOTH temperature and top_p (HTTP 400), * so anthropic/* routes must send at most one sampling param. Other OpenRouter * providers (OpenAI, Gemini, etc.) accept both together. * * @param string $model_name Resolved model id (e.g. 'anthropic/claude-sonnet-4.6'). * @return bool True when the route is an Anthropic model. */ private function is_anthropic_route(string $model_name): bool { return strpos($model_name, 'anthropic/') === 0; } private static function get_site_url_value(): string { return (string) \get_site_url(); } public static function validate_api_key(string $api_key): bool { $api_key = trim($api_key); if ($api_key === '') { throw new ProviderCallException( __( 'OpenRouter API key cannot be empty.', 'ai-product-tools' ), ProviderCallException::KEY_MISSING, null, '', null, 'openrouter' ); } if (strlen($api_key) < 20) { throw new ProviderCallException( __( 'Invalid OpenRouter API key format. Keys are at least 20 characters long.', 'ai-product-tools' ), ProviderCallException::KEY_INVALID_FORMAT, null, '', null, 'openrouter' ); } $key_validation_response = wp_remote_get('https://openrouter.ai/api/v1/key', [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'HTTP-Referer' => self::get_site_url_value(), 'X-Title' => 'AI Product Tools' ], 'timeout' => 20 ]); if (is_wp_error($key_validation_response)) { $error_message = $key_validation_response->get_error_message(); $detailed_error = sprintf( /* translators: %s: WP_Error message. */ __( 'Network error contacting OpenRouter: %s', 'ai-product-tools' ), $error_message ); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $key_validation_response ), null, '', null, 'openrouter' ); } if ( ! is_array( $key_validation_response ) ) { throw new ProviderCallException( __( 'OpenRouter API returned an invalid response', 'ai-product-tools' ), ProviderCallException::MALFORMED_RESPONSE, null, '', null, 'openrouter' ); } $key_response_code = (int) wp_remote_retrieve_response_code($key_validation_response); $content_type = (string) wp_remote_retrieve_header( $key_validation_response, 'content-type' ); $key_body_str = (string) wp_remote_retrieve_body($key_validation_response); self::throwIfHtmlBody( $content_type, $key_body_str, $key_response_code ); $key_body = json_decode($key_body_str, true); if (json_last_error() !== JSON_ERROR_NONE || ! is_array( $key_body ) ) { throw new ProviderCallException( sprintf( /* translators: %s: JSON error message. */ __( 'OpenRouter API returned invalid JSON: %s', 'ai-product-tools' ), json_last_error_msg() ), ProviderCallException::MALFORMED_RESPONSE, $key_response_code, '', null, 'openrouter' ); } if ($key_response_code === 200 && isset($key_body['data'])) { return true; } if ( isset( $key_body['error'] ) ) { $detailed_error = ErrorHandler::format_api_response_error( $key_body['error'], 'OpenRouter', $key_response_code ); throw self::providerErrorFromResponse( $key_body['error'], $key_response_code, $detailed_error, null ); } throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code. */ __( 'OpenRouter API returned unexpected status: %d', 'ai-product-tools' ), $key_response_code ), $key_response_code >= 500 ? ProviderCallException::PROVIDER_UNAVAILABLE : ProviderCallException::MALFORMED_RESPONSE, $key_response_code, '', null, 'openrouter' ); } public function get_available_models(): array { return $this->models; } /** * API istekleri için parametre ayarlarını yapar * * @param array $parameters Ayarlanacak parametreler * @return void */ public function setParameters(array $parameters): void { if (empty($parameters)) { return; } try { foreach ($this->models as &$model_config) { if (isset($parameters['temperature']) && is_numeric($parameters['temperature'])) { $temperature = floatval($parameters['temperature']); if ($temperature >= 0.0 && $temperature <= 2.0) { $this->requested_parameters['temperature'] = $temperature; $model_config['temperature'] = $temperature; } } if (isset($parameters['top_p']) && is_numeric($parameters['top_p'])) { $topP = floatval($parameters['top_p']); if ($topP >= 0.0 && $topP <= 1.0) { $this->requested_parameters['top_p'] = $topP; $model_config['top_p'] = $topP; } } if (isset($parameters['frequency_penalty']) && is_numeric($parameters['frequency_penalty'])) { $freqPenalty = floatval($parameters['frequency_penalty']); if ($freqPenalty >= -2.0 && $freqPenalty <= 2.0) { $model_config['frequency_penalty'] = $freqPenalty; } } if (isset($parameters['presence_penalty']) && is_numeric($parameters['presence_penalty'])) { $presPenalty = floatval($parameters['presence_penalty']); if ($presPenalty >= -2.0 && $presPenalty <= 2.0) { $model_config['presence_penalty'] = $presPenalty; } } } } catch (\Exception $e) { } } }