api_key = $api_key; $this->initializeModels(); } /** * Base request configuration for a model: the legacy sampling set for * gpt-4 ids, the reasoning-model set for everything else. * * @param string $model OpenAI model ID. * @param int $max_completion_tokens Output ceiling of the reasoning-model set. * @return array */ private static function baseConfig( string $model, int $max_completion_tokens ): array { if ( ModelCatalog::uses_legacy_openai_parameters( $model ) ) { return [ 'max_tokens' => 32768, 'temperature' => 0.7, 'use_legacy_params' => true, 'has_temperature' => true, 'supports_system_message' => true, ]; } return [ 'max_completion_tokens' => $max_completion_tokens, 'use_legacy_params' => false, 'has_temperature' => false, 'supports_system_message' => true, ]; } /** * Initialize model configurations using shared base configurations * This eliminates code duplication and makes maintenance easier */ private function initializeModels(): void { $this->models = []; foreach ( ModelCatalog::get_models( 'openai' ) as $model ) { $capabilities = ModelCatalog::get_capabilities( 'openai', $model ); $this->models[ $model ] = [ 'name' => $model ] + self::baseConfig( $model, 128000 ) + $capabilities; } } /** * The configuration of a catalog model or of a model the site owner added * ({@see \AIPT\Api\CustomModelStore}). A custom id gets a 16384 output * ceiling (a lower-cap model would reject the catalog's 128000) and no * sampling unless it is a gpt-4 id. * * @param string $model OpenAI model ID. * @return array * @throws ProviderCallException MODEL_NOT_FOUND for an id that is neither. */ private function getModelConfig( string $model ): array { if ( isset( $this->models[ $model ] ) ) { return $this->models[ $model ]; } if ( ! ModelCatalog::is_custom_model( 'openai', $model ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( 'Invalid model selected: ' . esc_html( $model ), ProviderCallException::MODEL_NOT_FOUND, null, '', null, 'openai' ); } return $this->withSamplingParameters( [ 'name' => $model ] + self::baseConfig( $model, 16384 ) + ModelCatalog::get_capabilities( 'openai', $model ) ); } public function generate_description(string $system_prompt, string $user_prompt, string $model = '', ?int $maximum_length = null): string { $model = '' !== $model ? $model : ModelCatalog::get_default_model( 'openai' ); $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 ]; } $request_body = [ 'model' => $model_config['name'], 'messages' => $messages ]; if ($model_config['has_temperature']) { $request_body['temperature'] = $model_config['temperature']; } if ( ! empty( $model_config['supports_top_p'] ) && isset( $model_config['top_p'] ) ) { $request_body['top_p'] = $model_config['top_p']; } if ( ! empty( $model_config['supports_frequency_penalty'] ) && isset( $model_config['frequency_penalty'] ) ) { $request_body['frequency_penalty'] = $model_config['frequency_penalty']; } if ( ! empty( $model_config['supports_presence_penalty'] ) && isset( $model_config['presence_penalty'] ) ) { $request_body['presence_penalty'] = $model_config['presence_penalty']; } $timeout = 30; if (preg_match('/^gpt-(\d+)/', $model, $model_major) && (int) $model_major[1] >= 5) { $timeout = 120; } $json_body = RequestBodyEncoder::encode( $request_body, 'openai', __( 'Failed to encode request body as JSON. The product data may contain invalid characters.', 'ai-product-tools' ), JSON_UNESCAPED_UNICODE ); $response = wp_remote_post($this->api_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json', ], 'body' => $json_body, 'timeout' => $timeout, ]); if ( $response instanceof \WP_Error ) { $error_message = $response->get_error_message(); $detailed_error = sprintf( /* translators: %s: WP Error message */ esc_html__('WP Error: %s', 'ai-product-tools'), esc_html($error_message) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw TransportFailure::withMessage( 'openai', $response, $detailed_error ); } $decoded = DecodedResponse::read( $response, 'openai', false, false ); $response_code = $decoded->code(); $retry_after_header = $decoded->retryAfter(); $body = $decoded->body(); if (isset($body['error'])) { $error_data = $body['error']; $detailed_error = ErrorHandler::format_api_response_error($error_data, 'OpenAI', $response_code); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $error_data, (int) $response_code, $detailed_error, $retry_after_header ); } $message_content = ChatCompletionReader::content( $body, (int) $response_code, 'openai', 'OpenAI', 'Invalid response from OpenAI API: Response structure is not as expected', false ); self::trackUsage( $body, (string) ( $model_config['name'] ?? $model ) ); return trim( $message_content ); } public function generate_faq_content(string $system_prompt, string $user_prompt, ?string $model = null): string { $resolved_model = $model ?: ModelCatalog::get_default_model( 'openai' ); 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 ?: ModelCatalog::get_default_model( 'openai' ); $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw ProviderCallException::aiDisabled( $ai_gate, 'openai' ); } try { $encoded_image = VisionImageEncoder::fetchAndEncode( $image_url ); $image_data_uri = 'data:' . $encoded_image['mime_type'] . ';base64,' . $encoded_image['data']; } catch ( \RuntimeException $e ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw VisionImageFailure::exception( 'OpenAI', $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 ); $request_body = [ 'model' => $model_config['name'], 'messages' => $messages, ]; if ( ! empty( $model_config['has_temperature'] ) ) { $request_body['temperature'] = (float) ( $model_config['temperature'] ?? 0.3 ); } $json_body = RequestBodyEncoder::encode( $request_body, 'openai', esc_html__( 'Failed to encode vision request body as JSON.', 'ai-product-tools' ), JSON_UNESCAPED_UNICODE ); $response = wp_remote_post( $this->api_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json', ], 'body' => $json_body, 'timeout' => 60, ] ); if ( $response instanceof \WP_Error ) { $error_message = $response->get_error_message(); $detailed_error = sprintf( /* translators: %s: error message */ esc_html__( 'WP Error: %s', 'ai-product-tools' ), esc_html( $error_message ) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw TransportFailure::withMessage( 'openai', $response, $detailed_error ); } $decoded = DecodedResponse::read( $response, 'openai', false, true ); $response_code = $decoded->code(); $retry_after_header = $decoded->retryAfter(); $body = $decoded->body(); if ( isset( $body['error'] ) ) { $detailed_error = ErrorHandler::format_api_response_error( $body['error'], 'OpenAI', $response_code ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $body['error'], (int) $response_code, $detailed_error, $retry_after_header ); } $message_content = ChatCompletionReader::content( $body, (int) $response_code, 'openai', 'OpenAI', 'Invalid response from OpenAI vision API: unexpected structure', false ); self::trackUsage( $body, (string) $resolved_model ); return trim( (string) $message_content ); } /** * Generate a structured (JSON-schema-shaped) answer. * * Additive method for StructuredOutputClientInterface. When * $options['native'] is true this sends OpenAI's Structured Outputs * `response_format: { type: 'json_schema', strict: true }`; otherwise it * sends a plain prompt call (the caller has already appended the JSON * instruction to $user_prompt) and returns `decoded: null` so the caller's * own strict parser validates the answer. 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 : ModelCatalog::get_default_model( 'openai' ); $model_config = $this->getModelConfig( $resolved_model ); $native = ! empty( $options['native'] ); $schema_name = SchemaName::sanitize( $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'], 'OpenAI' ); } $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 ) ]; } $request_body = [ 'model' => $model_config['name'], 'messages' => $messages ]; if ($model_config['has_temperature']) { $request_body['temperature'] = $model_config['temperature']; } if ( ! empty( $model_config['supports_top_p'] ) && isset( $model_config['top_p'] ) ) { $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 ) { $token_param = $model_config['max_token_parameter'] ?? ( ! empty( $model_config['use_legacy_params'] ) ? 'max_tokens' : 'max_completion_tokens' ); $request_body[ $token_param ] = $max_tokens; } $json_body = RequestBodyEncoder::encode( $request_body, 'openai', __( 'Failed to encode request body as JSON. The product data may contain invalid characters.', 'ai-product-tools' ), JSON_UNESCAPED_UNICODE ); $timeout = isset( $options['timeout'] ) && (int) $options['timeout'] > 0 ? (int) $options['timeout'] : $this->default_timeout_for( $resolved_model ); $response = wp_remote_post($this->api_url, [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json', ], 'body' => $json_body, 'timeout' => $timeout, ]); if ( $response instanceof \WP_Error ) { $error_message = $response->get_error_message(); $detailed_error = sprintf( /* translators: %s: WP Error message */ esc_html__('WP Error: %s', 'ai-product-tools'), esc_html($error_message) ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw TransportFailure::withMessage( 'openai', $response, $detailed_error ); } $decoded = DecodedResponse::read( $response, 'openai', false, false ); $response_code = $decoded->code(); $retry_after_header = $decoded->retryAfter(); $body = $decoded->body(); if (isset($body['error'])) { $detailed_error = ErrorHandler::format_api_response_error($body['error'], 'OpenAI', $response_code); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $body['error'], (int) $response_code, $detailed_error, $retry_after_header ); } $message_content = ChatCompletionReader::content( $body, (int) $response_code, 'openai', 'OpenAI', 'Invalid response from OpenAI API: Response structure is not as expected', true ); $content = (string) $message_content; $decoded = null; if ( $native ) { $maybe = json_decode( $content, true ); if ( JSON_ERROR_NONE === json_last_error() && is_array( $maybe ) ) { $decoded = $maybe; } } self::trackUsage( $body, (string) ( $model_config['name'] ?? $resolved_model ) ); return [ 'raw_text' => trim( $content ), 'decoded' => $decoded, 'used_native' => $native, 'model' => $resolved_model, ]; } /** * Default request timeout for generate_structured(), mirroring * generate_description()'s reasoning-model bump without touching that * method's own inline logic. * * @param string $model Model ID. * @return int Seconds. */ private function default_timeout_for( string $model ): int { if ( preg_match( '/^gpt-(\d+)/', $model, $model_major ) && (int) $model_major[1] >= 5 ) { return 120; } return 30; } /** * 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. * @param string $provider_label Provider label for error formatting. * @return array */ private function build_vision_content( string $text, string $image_url, string $provider_label ): array { try { $encoded_image = VisionImageEncoder::fetchAndEncode( $image_url ); } catch ( \RuntimeException $e ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw VisionImageFailure::exception( $provider_label, $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 ], ], ]; } /** * Cleans the prompt content and prepares it for the API * * 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 Prompt content to clean * @return string Cleaned content */ private function sanitize_prompt_content(string $content): string { return PromptFormatter::cleanOutboundPrompt($content); } /** * Record one answered call. prompt_tokens counts every prompt token, the * ones OpenAI read from or wrote to its prompt cache included; the two * cache counts let the cost price those at their own rates. * * @param array $body Decoded response body. * @param string $model Model identifier, when the response names none. * @return void */ private static function trackUsage( array $body, string $model ): void { $usage = is_array( $body['usage'] ?? null ) ? $body['usage'] : []; $details = is_array( $usage['prompt_tokens_details'] ?? null ) ? $usage['prompt_tokens_details'] : []; UsageTracker::trackApiCall( 'openai', (string) ( $body['model'] ?? $model ), (int) ( $usage['prompt_tokens'] ?? 0 ), (int) ( $usage['completion_tokens'] ?? 0 ), (int) ( $details['cache_write_tokens'] ?? 0 ), (int) ( $details['cached_tokens'] ?? 0 ) ); } /** * Build a ProviderCallException from an OpenAI error response body, * classifying its reason from the HTTP status plus whatever `code`/`type` * OpenAI's own error object carries. * * @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(); $code = isset( $data['code'] ) && is_string( $data['code'] ) ? $data['code'] : ''; $type = isset( $data['type'] ) && is_string( $data['type'] ) ? $data['type'] : ''; $message = isset( $data['message'] ) && is_string( $data['message'] ) ? $data['message'] : ''; return new ProviderCallException( $detailed_error, self::classifyErrorReason( $response_code, $code, $type, $message ), $response_code, '' !== $type ? $type : $code, $retry_after_header ?? ErrorHandler::extract_retry_after( $error_data ), 'openai' ); } /** * Classify an OpenAI error response into a stable ProviderCallException reason. * * @param int $response_code HTTP status code. * @param string $code `error.code`, e.g. "invalid_api_key", "insufficient_quota". * @param string $type `error.type`, e.g. "insufficient_quota", "invalid_request_error". * @param string $message `error.message`, used only to spot a schema-shaped 400. * @return string */ private static function classifyErrorReason( int $response_code, string $code, string $type, string $message ): string { if ( 401 === $response_code ) { return ProviderCallException::AUTH_INVALID_KEY; } if ( 403 === $response_code ) { return ProviderCallException::AUTH_FORBIDDEN; } if ( 404 === $response_code || 'model_not_found' === $code ) { return ProviderCallException::MODEL_NOT_FOUND; } if ( 429 === $response_code ) { $is_quota = 'insufficient_quota' === $code || 'insufficient_quota' === $type; return $is_quota ? ProviderCallException::QUOTA_EXHAUSTED : ProviderCallException::RATE_LIMITED; } if ( 413 === $response_code || 'context_length_exceeded' === $code || 'context_length_exceeded' === $type ) { 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; } public static function validate_api_key(string $api_key): bool { $validation_timeout = 20; $response = wp_remote_get('https://api.openai.com/v1/models', [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, ], 'timeout' => $validation_timeout ]); if (is_wp_error($response)) { /** @var \WP_Error $response */ $error_message = $response->get_error_message(); $detailed_error = sprintf( /* translators: %s: Error message from API request */ __( 'OpenAI API request failed: %s', 'ai-product-tools' ), $error_message ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'openai' ); } $response_code = (int) wp_remote_retrieve_response_code($response); $content_type = (string) wp_remote_retrieve_header( $response, 'content-type' ); $body_str = (string) wp_remote_retrieve_body($response); HtmlBodyGuard::throwIfHtml( 'openai', $content_type, $body_str, $response_code, false ); if ( 429 === $response_code || $response_code >= 500 ) { $failure = json_decode( $body_str, true ); if ( ! is_array( $failure ) || ! isset( $failure['error'] ) ) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code */ __( 'Unexpected response from OpenAI API (HTTP %d).', 'ai-product-tools' ), $response_code ), 429 === $response_code ? ProviderCallException::RATE_LIMITED : ProviderCallException::PROVIDER_UNAVAILABLE, $response_code, '', null, 'openai' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } } $body = json_decode($body_str, true); if (json_last_error() !== JSON_ERROR_NONE || !is_array($body)) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %s: JSON error message */ __('Invalid response from OpenAI API: %s', 'ai-product-tools'), json_last_error_msg() ), ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'openai' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ($response_code === 200 && isset( $body['data'] ) && is_array( $body['data'] ) ) { return true; } if (isset($body['error'])) { $detailed_error = ErrorHandler::format_api_response_error( $body['error'], 'OpenAI', $response_code ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $body['error'], $response_code, $detailed_error, null ); } // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code */ __( 'Unexpected response from OpenAI API (HTTP %d).', 'ai-product-tools' ), $response_code ), $response_code >= 500 ? ProviderCallException::PROVIDER_UNAVAILABLE : ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'openai' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } /** * Look a model id up with the Models API before the site owner adds it * ({@see CustomModelStore}): one metadata GET with the key check's header * and timeout, which costs no tokens. * * The answer only says the model exists for this key, so the id must not * be in a family this client cannot call, and `shutdown_date` decides the * status: none is active, a later day is deprecated, that day or an * earlier one (in UTC) is retired. The stored capabilities are fixed: * nothing in the answer describes the model. * * @param string $model Model id. * @return array{label: string, status: string, caps: array} * @throws ModelLookupRefusal Why the id cannot be added. */ public function lookup_model( string $model ): array { try { $body = $this->fetchModel( $model ); } catch ( ProviderCallException $e ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception; a refusal carries its own fixed sentence. throw ModelLookupRefusal::fromProviderFailure( $e ); } return self::modelLookupResult( $body, $model, time() ); } /** * The decoded Model object of a 200 answer. * * @param string $model Model id. * @return array * @throws ProviderCallException When the call failed. * @throws ModelLookupRefusal NOT_FOUND when OpenAI answered model_not_found. */ private function fetchModel( string $model ): array { $response = wp_remote_get( 'https://api.openai.com/v1/models/' . rawurlencode( $model ), [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->api_key, ], 'timeout' => 20, ] ); if ( is_wp_error( $response ) ) { $detailed_error = sprintf( /* translators: %s: Error message from API request */ __( 'OpenAI API request failed: %s', 'ai-product-tools' ), $response->get_error_message() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'openai' ); } $response_code = (int) wp_remote_retrieve_response_code( $response ); $content_type = (string) wp_remote_retrieve_header( $response, 'content-type' ); $body_str = (string) wp_remote_retrieve_body( $response ); HtmlBodyGuard::throwIfHtml( 'openai', $content_type, $body_str, $response_code, false ); if ( 429 === $response_code || $response_code >= 500 ) { $failure = json_decode( $body_str, true ); if ( ! is_array( $failure ) || ! isset( $failure['error'] ) ) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code */ __( 'Unexpected response from OpenAI API (HTTP %d).', 'ai-product-tools' ), $response_code ), 429 === $response_code ? ProviderCallException::RATE_LIMITED : ProviderCallException::PROVIDER_UNAVAILABLE, $response_code, '', null, 'openai' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } } $body = json_decode( $body_str, true ); if ( json_last_error() !== JSON_ERROR_NONE || ! is_array( $body ) ) { // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %s: JSON error message */ __( 'Invalid response from OpenAI API: %s', 'ai-product-tools' ), json_last_error_msg() ), ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'openai' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } if ( 200 === $response_code ) { return $body; } if ( 404 === $response_code && is_array( $body['error'] ?? null ) && 'model_not_found' === ( $body['error']['code'] ?? null ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exception; a refusal carries its own fixed sentence. throw new ModelLookupRefusal( ModelLookupRefusal::NOT_FOUND, 'OpenAI answered model_not_found (HTTP 404)' ); } if ( isset( $body['error'] ) ) { $detailed_error = ErrorHandler::format_api_response_error( $body['error'], 'OpenAI', $response_code ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw self::providerErrorFromResponse( $body['error'], $response_code, $detailed_error, null ); } // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal API client exception, caught and logged internally throw new ProviderCallException( sprintf( /* translators: %d: HTTP status code */ __( 'Unexpected response from OpenAI API (HTTP %d).', 'ai-product-tools' ), $response_code ), ProviderCallException::MALFORMED_RESPONSE, $response_code, '', null, 'openai' ); // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped } // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal exceptions below; a refusal carries its own fixed sentence. /** * What the store keeps for a Model object, read strictly: a missing or * mistyped field refuses the id. * * @param array $body Decoded Model object. * @param string $model Requested model id. * @param int $now Unix time of the lookup. * @return array{label: string, status: string, caps: array} * @throws ModelLookupRefusal UNEXPECTED_ANSWER, NOT_A_CHAT_MODEL or RETIRED. */ private static function modelLookupResult( array $body, string $model, int $now ): array { $id = $body['id'] ?? null; if ( 'model' !== ( $body['object'] ?? null ) || ! is_string( $id ) || '' === $id ) { throw new ModelLookupRefusal( ModelLookupRefusal::UNEXPECTED_ANSWER, 'OpenAI model answer without object model or an id' ); } $shutdown_date = $body['shutdown_date'] ?? null; if ( null !== $shutdown_date && ! self::isCalendarDate( $shutdown_date ) ) { throw new ModelLookupRefusal( ModelLookupRefusal::UNEXPECTED_ANSWER, 'OpenAI model answer with a shutdown_date that is not a YYYY-MM-DD date' ); } if ( self::isNonChatModelId( $model ) || self::isNonChatModelId( $id ) ) { throw new ModelLookupRefusal( ModelLookupRefusal::NOT_A_CHAT_MODEL, 'OpenAI model id in a family the chat completions client cannot call' ); } $status = 'active'; if ( null !== $shutdown_date ) { if ( $shutdown_date <= gmdate( 'Y-m-d', $now ) ) { throw new ModelLookupRefusal( ModelLookupRefusal::RETIRED, 'OpenAI shutdown_date ' . $shutdown_date . ' has come' ); } $status = 'deprecated'; } return [ 'label' => CustomModelStore::clean_label( $model, $model ), 'status' => $status, 'caps' => [ 'max_tokens' => 16384, 'vision' => false, 'structured_output' => 'json_schema', 'thinking_off' => null, ], ]; } // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped /** * @param mixed $value Field value. * @return bool Whether the value is a real calendar day written YYYY-MM-DD. */ private static function isCalendarDate( $value ): bool { return is_string( $value ) && 1 === preg_match( '/^(\d{4})-(\d{2})-(\d{2})\z/', $value, $parts ) && checkdate( (int) $parts[2], (int) $parts[3], (int) $parts[1] ); } /** * @param string $id Model id. * @return bool Whether the id belongs to a family this client cannot call. */ private static function isNonChatModelId( string $id ): bool { $id = strtolower( $id ); foreach ( self::NON_CHAT_ID_PARTS as $part ) { if ( false !== strpos( $id, $part ) ) { return true; } } return [] !== array_intersect( explode( '-', $id ), self::NON_CHAT_ID_SEGMENTS ); } /** * A configuration with every setParameters() call so far applied, in order. * * @param array $model_config Model configuration. * @return array */ private function withSamplingParameters( array $model_config ): array { foreach ( $this->sampling_calls as $parameters ) { $model_config = $this->applySamplingParameters( $model_config, $parameters ); } return $model_config; } /** * Apply merchant sampling parameters to one model configuration, within * the ranges each provider accepts. The configuration is left untyped so * a write it refuses fails with its own error inside setParameters()'s * catch, as before this helper existed. * * @template T of array|\ArrayAccess * @param T $model_config Model configuration. * @param array $parameters Sampling parameters. * @return T The configuration with the parameters applied. */ private function applySamplingParameters( $model_config, array $parameters ) { if (isset($parameters['temperature']) && is_numeric($parameters['temperature'])) { $temperature = floatval($parameters['temperature']); if ($temperature >= 0.0 && $temperature <= 2.0) { if (!isset($model_config['has_temperature']) || $model_config['has_temperature'] === true) { $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) { $model_config['top_p'] = $topP; } } if (isset($model_config['use_legacy_params']) && $model_config['use_legacy_params']) { 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; } } } return $model_config; } public function get_available_models(): array { return $this->models; } /** * Apply sampling parameters to every model of this client. * * @param array $parameters Parameters to apply. * @return void */ public function setParameters(array $parameters): void { if (empty($parameters)) { return; } $this->sampling_calls[] = $parameters; try { foreach ($this->models as $model_id => $model_config) { $this->models[ $model_id ] = $this->applySamplingParameters( $model_config, $parameters ); } } catch (\Throwable $e) { Logger::warn( 'provider', 'OpenAI sampling parameters could not be applied', array( 'error' => $e->getMessage() ) ); } } }