label. */ public static function get_available_providers(): array { return [ 'openai' => 'OpenAI', 'anthropic' => 'Anthropic', ]; } /** * Determine which provider is active for a given model. * * @param string $model_name The model identifier. * @return string Provider identifier. */ public static function get_provider_for_model( string $model_name ): string { global $wpdb; $table = $wpdb->prefix . 'ai_app_onsite_models'; $provider = $wpdb->get_var( $wpdb->prepare( "SELECT provider FROM {$table} WHERE model = %s LIMIT 1", $model_name ) ); return $provider ?: 'openai'; } } /** * Provider Interface * All providers must implement this contract. */ interface AI_App_Onsite_Provider_Interface { /** * Get the provider identifier. * @return string */ public function get_id(): string; /** * Get the display name. * @return string */ public function get_name(): string; /** * Build request headers. * * @param string $api_key The API key. * @return array Headers array for wp_remote_post. */ public function build_headers( string $api_key ): array; /** * Build request payload. * * @param array $params { * @type string $model Model identifier. * @type string $prompt The user prompt text. * @type string $endpoint API endpoint URL. * @type int $max_tokens Max tokens for response. * @type float $temperature Temperature setting. * @type float $top_p Top-p setting. * @type float $f_penalty Frequency penalty. * @type float $p_penalty Presence penalty. * @type array $supported_parameters Supported params for this model. * @type string $default_tools Default tools config. * } * @return array Request body array (will be JSON-encoded). */ public function build_payload( array $params ): array; /** * Parse the API response and extract the text content. * * @param array $result Decoded JSON response. * @param string $endpoint The endpoint that was called. * @return string|null Extracted text content or null on failure. */ public function parse_response( array $result, string $endpoint = '' ): ?string; /** * Parse error response into a user-friendly message. * * @param array $result Decoded JSON response. * @param int $status_code HTTP status code. * @return string Error message. */ public function parse_error( array $result, int $status_code ): string; /** * Validate API key format (basic client-side check before calling API). * * @param string $key The API key to validate. * @return bool */ public function validate_key_format( string $key ): bool; /** * Get the API key field name used in the model_settings DB table. * @return string Column name for this provider's API key. */ public function get_key_column(): string; /** * Get the key status field name used in the model_settings DB table. * @return string Column name for this provider's key status. */ public function get_key_status_column(): string; } /** * OpenAI Provider Implementation */ class AI_App_Onsite_Provider_OpenAI implements AI_App_Onsite_Provider_Interface { public function get_id(): string { return 'openai'; } public function get_name(): string { return 'OpenAI'; } public function get_key_column(): string { return 'openai_key'; } public function get_key_status_column(): string { return 'key_status'; } public function validate_key_format( string $key ): bool { return ! empty( $key ) && strlen( $key ) > 20; } public function build_headers( string $api_key ): array { return [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key, ]; } public function build_payload( array $params ): array { $model = $params['model']; $prompt = $params['prompt']; $endpoint = $params['endpoint'] ?? ''; $max_tokens = ! empty( $params['max_tokens'] ) ? (int) $params['max_tokens'] : 3000; $temperature = $params['temperature'] ?? ''; $top_p = $params['top_p'] ?? ''; $f_penalty = $params['f_penalty'] ?? ''; $p_penalty = $params['p_penalty'] ?? ''; $supported = $params['supported_parameters'] ?? []; $is_reasoning = ( strpos( $endpoint, '/v1/responses' ) !== false ); if ( $is_reasoning ) { $data = [ 'model' => $model, 'input' => $prompt, 'max_output_tokens' => $max_tokens, ]; // Responses API models (reasoning & GPT-5) do NOT support temperature, // top_p, frequency_penalty, or presence_penalty parameters. } else { $data = [ 'model' => $model, 'messages' => [ [ 'role' => 'user', 'content' => $prompt ], ], 'max_tokens' => $max_tokens, ]; // Add parameters based on model capabilities (Chat Completions API) if ( in_array( 'temperature', $supported ) && ! empty( $temperature ) ) { $data['temperature'] = (float) $temperature; } if ( in_array( 'top_p', $supported ) && ! empty( $top_p ) ) { $data['top_p'] = (float) $top_p; } if ( in_array( 'frequency_penalty', $supported ) && ! empty( $f_penalty ) ) { $data['frequency_penalty'] = (float) $f_penalty; } if ( in_array( 'presence_penalty', $supported ) && ! empty( $p_penalty ) ) { $data['presence_penalty'] = (float) $p_penalty; } } if ( ! empty( $params['default_tools'] ) ) { $data['tools'] = [ [ 'type' => trim( $params['default_tools'] ) ] ]; } return $data; } public function parse_response( array $result, string $endpoint = '' ): ?string { $is_reasoning = ( strpos( $endpoint, '/v1/responses' ) !== false ); if ( $is_reasoning ) { $output = $result['output'] ?? []; foreach ( $output as $item ) { if ( isset( $item['type'], $item['content'] ) && $item['type'] === 'message' && is_array( $item['content'] ) ) { foreach ( $item['content'] as $content ) { if ( ! empty( $content['text'] ) ) { return $content['text']; } } } } return null; } return $result['choices'][0]['message']['content'] ?? null; } /** * Present an API error in the strict format: * () * * The main content is taken verbatim from the API's own error fields * (message, falling back to type, then the raw JSON so nothing is ever * swallowed). Any clarification we add is always accurate and appears * only in the trailing parentheses. * * @param array $result Decoded JSON response. * @param string $clarification Optional accurate clarification we can add. * @return string */ private function format_error( array $result, string $clarification = '' ): string { $error_msg = $result['error']['message'] ?? ''; $error_type = $result['error']['type'] ?? ''; if ( $error_msg !== '' ) { $main = $error_msg; } elseif ( $error_type !== '' ) { $main = $error_type; } else { $main = wp_json_encode( $result ); } $clarification = trim( $clarification ); if ( $clarification === '' ) { return $main; } return $main . ' (' . $clarification . ')'; } public function parse_error( array $result, int $status_code ): string { if ( $status_code === 401 ) { return $this->format_error( $result, 'Check your OpenAI API key in Model Settings.' ); } if ( $status_code === 500 || $status_code === 503 ) { return $this->format_error( $result, 'This is a temporary OpenAI-side error — retry shortly.' ); } // Rate limits and any other case: the API message is already exact // and self-explanatory — present it verbatim. return $this->format_error( $result ); } } /** * Anthropic Provider Implementation */ class AI_App_Onsite_Provider_Anthropic implements AI_App_Onsite_Provider_Interface { const API_VERSION = '2023-06-01'; public function get_id(): string { return 'anthropic'; } public function get_name(): string { return 'Anthropic'; } public function get_key_column(): string { return 'anthropic_key'; } public function get_key_status_column(): string { return 'anthropic_key_status'; } public function validate_key_format( string $key ): bool { // Anthropic keys start with 'sk-ant-' return ! empty( $key ) && strlen( $key ) > 20; } public function build_headers( string $api_key ): array { return [ 'Content-Type' => 'application/json', 'x-api-key' => $api_key, 'anthropic-version' => self::API_VERSION, ]; } public function build_payload( array $params ): array { $model = $params['model']; $prompt = $params['prompt']; $max_tokens = ! empty( $params['max_tokens'] ) ? (int) $params['max_tokens'] : 4096; $temperature = $params['temperature'] ?? ''; $top_p = $params['top_p'] ?? ''; $supported = $params['supported_parameters'] ?? []; $data = [ 'model' => $model, 'max_tokens' => $max_tokens, 'messages' => [ [ 'role' => 'user', 'content' => $prompt ], ], ]; // Add parameters based on model capabilities. // NOTE: Anthropic does not allow `temperature` and `top_p` to be specified // together for some models (e.g. Claude Haiku 4.5, Claude Sonnet 4.6) and // returns an "invalid_request_error". Per Anthropic's guidance we send only // one sampling parameter: prefer `temperature`, and fall back to `top_p` // only when temperature is not provided. $has_temperature = in_array( 'temperature', $supported ) && $temperature !== '' && $temperature !== null; $has_top_p = in_array( 'top_p', $supported ) && $top_p !== '' && $top_p !== null; if ( $has_temperature ) { $data['temperature'] = (float) $temperature; } elseif ( $has_top_p ) { $data['top_p'] = (float) $top_p; } // Anthropic supports system prompt as a top-level parameter if ( in_array( 'system', $supported ) && ! empty( $params['system_prompt'] ) ) { $data['system'] = $params['system_prompt']; } return $data; } public function parse_response( array $result, string $endpoint = '' ): ?string { // Anthropic Messages API response format if ( isset( $result['content'] ) && is_array( $result['content'] ) ) { foreach ( $result['content'] as $block ) { if ( isset( $block['type'] ) && $block['type'] === 'text' && ! empty( $block['text'] ) ) { return $block['text']; } } } return null; } /** * Present an API error in the strict format: * () * * The main content is taken verbatim from the API's own error fields * (message, falling back to type, then the raw JSON so nothing is ever * swallowed). Any clarification we add is always accurate and appears * only in the trailing parentheses. * * @param array $result Decoded JSON response. * @param string $clarification Optional accurate clarification we can add. * @return string */ private function format_error( array $result, string $clarification = '' ): string { $error_msg = $result['error']['message'] ?? ''; $error_type = $result['error']['type'] ?? ''; if ( $error_msg !== '' ) { $main = $error_msg; } elseif ( $error_type !== '' ) { $main = $error_type; } else { $main = wp_json_encode( $result ); } $clarification = trim( $clarification ); if ( $clarification === '' ) { return $main; } return $main . ' (' . $clarification . ')'; } public function parse_error( array $result, int $status_code ): string { $error_msg = $result['error']['message'] ?? ''; $error_type = $result['error']['type'] ?? ''; // Detect provider mismatch: if the error response is from OpenAI (not Anthropic), // it means the request was sent to the wrong endpoint. if ( stripos( $error_msg, 'openai.com' ) !== false || stripos( $error_msg, 'platform.openai.com' ) !== false ) { return $this->format_error( $result, 'An OpenAI model appears to be selected while the provider is set to Anthropic — select an Anthropic (Claude) model in Model Settings.' ); } if ( $status_code === 401 || $error_type === 'authentication_error' ) { return $this->format_error( $result, 'Check your Anthropic API key in Model Settings; it must start with "sk-ant-".' ); } if ( $status_code === 429 || $error_type === 'rate_limit_error' ) { if ( stripos( $error_msg, 'credit' ) !== false || stripos( $error_msg, 'billing' ) !== false ) { return $this->format_error( $result, 'Add credits to your account at console.anthropic.com.' ); } return $this->format_error( $result ); } if ( $status_code === 529 || $error_type === 'overloaded_error' ) { return $this->format_error( $result, 'The API is temporarily overloaded — retry shortly.' ); } if ( $error_type === 'not_found_error' || $status_code === 404 ) { return $this->format_error( $result, 'The model ID may be incorrect, renamed, or deprecated — check the model in Model Settings.' ); } if ( $status_code === 500 || $status_code === 503 || $error_type === 'api_error' ) { return $this->format_error( $result, 'This is a temporary Anthropic-side error — retry shortly.' ); } // invalid_request_error, permission_error, and any other case: the API // message is already exact and self-explanatory — present it verbatim. return $this->format_error( $result ); } } }