50 ) { $max_tokens = absint( $saved_tokens ); } if ( '' !== $saved_temp ) { $temperature = (float) $saved_temp; } } // Timeout override. $timeout = absint( get_option( 'wtofe_ai_request_timeout', 30 ) ); if ( $timeout < 10 ) { $timeout = 60; } $model = $credentials['model']; $error_context = self::get_request_error_context( $credentials, $feature, $timeout ); if ( 'google' === $credentials['provider'] ) { return self::call_google_chat_api( $credentials['api_key'], $messages, $max_tokens, $temperature, $timeout, $model, $error_context ); } if ( 'anthropic' === $credentials['provider'] ) { return self::call_anthropic_chat_api( $credentials['api_key'], $messages, $max_tokens, $temperature, $timeout, $model, $error_context ); } return self::call_openai_chat_api( $credentials['api_key'], $messages, $max_tokens, $temperature, $timeout, $model, $error_context ); } /** * Calls OpenAI chat completions. * * @param string $api_key * @param array $messages * @param int $max_tokens * @param float $temperature * @param array $error_context See explain_provider_error(). * @return array|WP_Error */ private static function call_openai_chat_api( $api_key, array $messages, $max_tokens, $temperature, $timeout = 30, $model = 'gpt-4.1-mini', array $error_context = array() ) { // o-series (o1, o3, o4-mini, etc.) and gpt-5+ only accept temperature=1 (the default). // Sending any other value causes a 400 error. Omit the key entirely for those models // so the API uses its default, which works for all model families. // Detect model families that only accept temperature=1 (omit the param entirely for them). // Uses strncmp() so no dependency on str_starts_with() (PHP 8.0 / WP 5.9). $model_lower = strtolower( $model ); $omit_temp = ( (bool) preg_match( '/^o\d/i', $model_lower ) || // o1, o3, o4-mini, o1-mini, etc. (bool) preg_match( '/^gpt-([5-9]|\d{2,})/', $model_lower ) || // gpt-5 and later (gpt-6, ...) 0 === strncmp( $model_lower, 'chatgpt-4o', 10 ) // chatgpt-4o-latest family ); $supports_temp = ! $omit_temp; $body = array( 'model' => $model, 'messages' => $messages, 'max_completion_tokens' => $max_tokens, ); if ( $supports_temp ) { $body['temperature'] = (float) $temperature; } $response = wp_remote_post( 'https://api.openai.com/v1/chat/completions', array( //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_key, ), 'body' => wp_json_encode( $body ), 'timeout' => $timeout, ) ); $data = is_wp_error( $response ) ? $response->get_error_message() : json_decode( wp_remote_retrieve_body( $response ), true ); self::log_debug( 'OpenAI chat API response', array( 'data' => $data, 'model' => $model ) ); if ( self::is_failed_response( $response ) ) { return self::provider_error( 'openai', $response, $error_context ); } if ( ! isset( $data['choices'][0]['message']['content'] ) ) { $msg = isset( $data['error']['message'] ) ? $data['error']['message'] : 'Unknown API error.'; return new WP_Error( 'api_error', $msg ); } return $data; } /** * Calls Google Gemini chat generation. * * @param string $api_key * @param array $messages * @param int $max_tokens * @param float $temperature * @param array $error_context See explain_provider_error(). * @return array|WP_Error */ private static function call_google_chat_api( $api_key, array $messages, $max_tokens, $temperature, $timeout = 30, $model = 'gemini-2.5-flash', array $error_context = array() ) { $system_instruction = ''; $contents = array(); $conversation_started = false; foreach ( $messages as $message ) { if ( ! isset( $message['role'], $message['content'] ) ) { continue; } $role = (string) $message['role']; $content = (string) $message['content']; // Only messages BEFORE the conversation begins are true system instructions. // A 'system' message that shows up mid-conversation (e.g. the chatbot's // action-result feedback loop) has to stay in the turn sequence — Gemini // has no concept of a system turn mid-conversation, and silently folding // it into systemInstruction breaks the user/model turn alternation. if ( 'system' === $role && ! $conversation_started ) { $system_instruction .= ( '' === $system_instruction ? '' : "\n\n" ) . $content; continue; } $conversation_started = true; $contents[] = array( 'role' => 'assistant' === $role ? 'model' : 'user', 'parts' => array( array( 'text' => $content ), ), ); } // Gemini requires strict user/model alternation with no two consecutive // same-role turns. Merge any accidental consecutive same-role turns // (e.g. a 'system' feedback message immediately following a 'user' message) // into a single turn rather than sending them as separate entries. $merged_contents = array(); foreach ( $contents as $turn ) { $last_index = count( $merged_contents ) - 1; if ( $last_index >= 0 && $merged_contents[ $last_index ]['role'] === $turn['role'] ) { $merged_contents[ $last_index ]['parts'][0]['text'] .= "\n\n" . $turn['parts'][0]['text']; } else { $merged_contents[] = $turn; } } $contents = $merged_contents; if ( empty( $contents ) ) { return new WP_Error( 'invalid_prompt', __( 'No valid prompt was provided for Gemini.', 'ai-content-generator-for-woocommerce' ) ); } $payload = array( 'contents' => $contents, 'generationConfig' => array( 'maxOutputTokens' => absint( $max_tokens ), 'temperature' => (float) $temperature, ), ); if ( '' !== $system_instruction ) { $payload['systemInstruction'] = array( 'parts' => array( array( 'text' => $system_instruction ), ), ); } $response = wp_remote_post( 'https://generativelanguage.googleapis.com/v1beta/models/' . $model . ':generateContent?key=' . rawurlencode( $api_key ), //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration array( 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => wp_json_encode( $payload ), 'timeout' => $timeout, ) ); $data = is_wp_error( $response ) ? $response->get_error_message() : json_decode( wp_remote_retrieve_body( $response ), true ); self::log_debug( 'Gemini chat API response', array( 'data' => $data, 'model' => $model ) ); if ( self::is_failed_response( $response ) ) { return self::provider_error( 'google', $response, $error_context ); } $parts = isset( $data['candidates'][0]['content']['parts'] ) && is_array( $data['candidates'][0]['content']['parts'] ) ? $data['candidates'][0]['content']['parts'] : array(); $texts = array(); foreach ( $parts as $part ) { if ( isset( $part['text'] ) && is_string( $part['text'] ) ) { $texts[] = $part['text']; } } if ( empty( $texts ) ) { if ( isset( $data['error']['message'] ) ) { $msg = $data['error']['message']; } elseif ( isset( $data['promptFeedback']['blockReason'] ) ) { $msg = sprintf( /* translators: %s: Gemini block reason, e.g. SAFETY */ __( 'Gemini blocked the prompt (reason: %s).', 'ai-content-generator-for-woocommerce' ), $data['promptFeedback']['blockReason'] ); } elseif ( isset( $data['candidates'][0]['finishReason'] ) ) { $msg = sprintf( /* translators: %s: Gemini finish reason, e.g. SAFETY, MAX_TOKENS, RECITATION */ __( 'Gemini returned no content (finish reason: %s).', 'ai-content-generator-for-woocommerce' ), $data['candidates'][0]['finishReason'] ); } else { $msg = 'Unknown Gemini API error.'; } return new WP_Error( 'api_error', $msg ); } return array( 'choices' => array( array( 'message' => array( 'content' => implode( "\n", $texts ), ), ), ), ); } /** * Calls Anthropic chat generation. * * @param string $api_key * @param array $messages * @param int $max_tokens * @param float $temperature * @param array $error_context See explain_provider_error(). * @return array|WP_Error */ private static function call_anthropic_chat_api( $api_key, array $messages, $max_tokens, $temperature, $timeout = 30, $model = 'claude-3-5-sonnet-latest', array $error_context = array() ) { $system_instruction = ''; $anthropic_messages = array(); foreach ( $messages as $message ) { if ( ! isset( $message['role'], $message['content'] ) ) { continue; } $role = (string) $message['role']; $content = (string) $message['content']; if ( 'system' === $role ) { $system_instruction .= ( '' === $system_instruction ? '' : "\n\n" ) . $content; continue; } $anthropic_messages[] = array( 'role' => 'assistant' === $role ? 'assistant' : 'user', 'content' => $content, ); } if ( empty( $anthropic_messages ) ) { return new WP_Error( 'invalid_prompt', __( 'No valid prompt was provided for Anthropic.', 'ai-content-generator-for-woocommerce' ) ); } $payload = array( 'model' => $model, 'max_tokens' => absint( $max_tokens ), 'temperature' => (float) $temperature, 'messages' => $anthropic_messages, ); if ( '' !== $system_instruction ) { $payload['system'] = $system_instruction; } $response = wp_remote_post( 'https://api.anthropic.com/v1/messages', //phpcs:ignore PluginCheck.CodeAnalysis.AIProvider.DirectIntegration array( 'headers' => array( 'Content-Type' => 'application/json', 'x-api-key' => $api_key, 'anthropic-version' => '2023-06-01', ), 'body' => wp_json_encode( $payload ), 'timeout' => $timeout, ) ); $data = is_wp_error( $response ) ? $response->get_error_message() : json_decode( wp_remote_retrieve_body( $response ), true ); self::log_debug( 'Anthropic chat API response', array( 'data' => $data, 'model' => $model) ); if ( self::is_failed_response( $response ) ) { return self::provider_error( 'anthropic', $response, $error_context ); } $parts = isset( $data['content'] ) && is_array( $data['content'] ) ? $data['content'] : array(); $texts = array(); foreach ( $parts as $part ) { if ( isset( $part['type'], $part['text'] ) && 'text' === $part['type'] && is_string( $part['text'] ) ) { $texts[] = $part['text']; } } if ( empty( $texts ) ) { $msg = isset( $data['error']['message'] ) ? $data['error']['message'] : 'Unknown Anthropic API error.'; return new WP_Error( 'api_error', $msg ); } return array( 'choices' => array( array( 'message' => array( 'content' => implode( "\n", $texts ), ), ), ), ); } }