api_key = $api_key; $this->idempotency_context = $idempotency_context; $this->initializeModels(); } /** * Initialize model configurations using shared base configurations * This eliminates code duplication and makes maintenance easier */ private function initializeModels(): void { $gpt5Config = [ 'max_completion_tokens' => 128000, 'use_legacy_params' => false, 'has_temperature' => false, 'supports_system_message' => true ]; $legacyConfig = [ 'max_tokens' => 32768, 'temperature' => 0.7, 'use_legacy_params' => true, 'has_temperature' => true, 'supports_system_message' => true ]; $this->models = []; foreach ( ModelCatalog::get_models( 'openai' ) as $model ) { $capabilities = ModelCatalog::get_capabilities( 'openai', $model ); $config = ModelCatalog::uses_legacy_openai_parameters( $model ) ? $legacyConfig : $gpt5Config; $this->models[ $model ] = [ 'name' => $model ] + $config + $capabilities; } } public function generate_description(string $system_prompt, string $user_prompt, string $model = 'gpt-5.6-terra', ?int $maximum_length = null): string { $model = '' !== $model ? $model : 'gpt-5.6-terra'; if (!isset($this->models[$model])) { throw new ProviderCallException( 'Invalid model selected: ' . esc_html($model), ProviderCallException::MODEL_NOT_FOUND, null, '', null, 'openai' ); } $model_config = $this->models[$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 = wp_json_encode($request_body, JSON_UNESCAPED_UNICODE); if ( false === $json_body ) { throw new ProviderCallException( __( 'Failed to encode request body as JSON. The product data may contain invalid characters.', 'ai-product-tools' ), ProviderCallException::BAD_REQUEST, null, '', null, 'openai' ); } $response = wp_remote_post($this->api_url, [ 'headers' => $this->withIdempotencyHeader([ '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) ); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'openai' ); } $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, 'openai' ); } if (isset($body['error'])) { $error_data = $body['error']; $detailed_error = ErrorHandler::format_api_response_error($error_data, 'OpenAI', $response_code); throw self::providerErrorFromResponse( $error_data, (int) $response_code, $detailed_error, $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 OpenAI API: Response structure is not as expected', $this->classifyEmptyContentReason( $finish_reason ), (int) $response_code, $finish_reason, null, 'openai' ); } $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 ); UsageTracker::trackApiCall( 'openai', (string) ( $body['model'] ?? $model_config['name'] ?? $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 ?: 'gpt-5.6-terra'; 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 ?: 'gpt-5.6-terra'; $ai_gate = \AIPT\Core\Services\AiSupportGate::guard(); if ( $ai_gate instanceof \WP_Error ) { 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 ) { $detailed_error = ErrorHandler::format_api_response_error( [ 'code' => 'aipt_vision_fetch_failed', 'message' => esc_html( $e->getMessage() ), 'type' => 'vision_image_fetch_failed', ], 'OpenAI', 0 ); throw new ProviderCallException( $detailed_error, ProviderCallException::IMAGE_UNAVAILABLE, null, 'vision_image_fetch_failed', null, '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 ], ], ], ], ]; if ( ! isset( $this->models[ $resolved_model ] ) ) { throw new ProviderCallException( 'Invalid model selected: ' . esc_html( $resolved_model ), ProviderCallException::MODEL_NOT_FOUND, null, '', null, 'openai' ); } $model_config = $this->models[ $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 = 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, 'openai' ); } $response = wp_remote_post( $this->api_url, [ 'headers' => $this->withIdempotencyHeader( [ '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 ) ); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'openai' ); } $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, 'openai' ); } if ( isset( $body['error'] ) ) { $detailed_error = ErrorHandler::format_api_response_error( $body['error'], 'OpenAI', $response_code ); throw self::providerErrorFromResponse( $body['error'], (int) $response_code, $detailed_error, $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 OpenAI vision API: unexpected structure', $this->classifyEmptyContentReason( $finish_reason ), (int) $response_code, $finish_reason, null, 'openai' ); } $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 ); UsageTracker::trackApiCall( 'openai', (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 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 : 'gpt-5.6-terra'; if ( ! isset( $this->models[ $resolved_model ] ) ) { throw new ProviderCallException( 'Invalid model selected: ' . esc_html( $resolved_model ), ProviderCallException::MODEL_NOT_FOUND, null, '', null, 'openai' ); } $model_config = $this->models[ $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'], '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 = wp_json_encode($request_body, JSON_UNESCAPED_UNICODE); if ( false === $json_body ) { throw new ProviderCallException( __( 'Failed to encode request body as JSON. The product data may contain invalid characters.', 'ai-product-tools' ), ProviderCallException::BAD_REQUEST, null, '', null, 'openai' ); } $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' => $this->withIdempotencyHeader([ '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) ); throw new ProviderCallException( $detailed_error, ProviderCallException::transportReason( $response ), null, '', null, 'openai' ); } $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, 'openai' ); } if (isset($body['error'])) { $detailed_error = ErrorHandler::format_api_response_error($body['error'], 'OpenAI', $response_code); throw self::providerErrorFromResponse( $body['error'], (int) $response_code, $detailed_error, $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 OpenAI API: Response structure is not as expected', $this->classifyEmptyContentReason( $finish_reason ), (int) $response_code, $finish_reason, null, 'openai' ); } $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; } } UsageTracker::trackApiCall( 'openai', (string) ( $body['model'] ?? $model_config['name'] ?? $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, ]; } /** * 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 ) { $detailed_error = ErrorHandler::format_api_response_error( [ 'code' => 'aipt_vision_fetch_failed', 'message' => esc_html( $e->getMessage() ), 'type' => 'vision_image_fetch_failed', ], $provider_label, 0 ); throw new ProviderCallException( $detailed_error, ProviderCallException::IMAGE_UNAVAILABLE, null, 'vision_image_fetch_failed', null, 'openai', $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. * * @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); } private function withIdempotencyHeader( array $headers ): array { if ( null === $this->idempotency_context || ! $this->isIdempotencyAllowed() ) { return $headers; } $key = IdempotencyKeyContext::getIdempotencyKey(); if ( null !== $key ) { $headers['Idempotency-Key'] = $key; } return $headers; } private function isIdempotencyAllowed(): bool { $providers = \apply_filters( 'aipt_chatbot_idempotency_providers', [ 'openai', 'anthropic' ] ); if ( ! is_array( $providers ) ) { return false; } $providers = array_map( '\sanitize_key', $providers ); return in_array( 'openai', $providers, true ); } /** * 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; } /** * 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( __('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, 'openai' ); } /** * A non-empty answer can still be a cutoff or a safety block rather than a * complete success: OpenAI only guarantees `finish_reason` describes how * generation ended, independent of whether any text came back with it. * * @param string $finish_reason OpenAI `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 OpenAI API: the answer was cut off before it finished', ProviderCallException::TRUNCATED_OUTPUT, $response_code, $finish_reason, null, 'openai' ); } 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 OpenAI 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 OpenAI API: the model declined partway through the answer', ProviderCallException::CONTENT_BLOCKED, $response_code, $finish_reason, null, 'openai' ); } } /** * 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. When it * still decodes (the cutoff landed after the closing brace), the answer is * returned as a normal success exactly as today. * * @param string $finish_reason OpenAI `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 OpenAI API: the answer was cut off before it finished', ProviderCallException::TRUNCATED_OUTPUT, $response_code, $finish_reason, null, 'openai' ); } /** * 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 OpenAI API: the model refused the request', ProviderCallException::CONTENT_BLOCKED, $response_code, 'refusal', null, 'openai' ); } /** * 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. * * @param string $finish_reason OpenAI `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; } 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 ); 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); self::throwIfHtmlBody( $content_type, $body_str, $response_code ); $body = json_decode($body_str, true); if (json_last_error() !== JSON_ERROR_NONE || !is_array($body)) { 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' ); } 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 ); throw self::providerErrorFromResponse( $body['error'], $response_code, $detailed_error, null ); } 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' ); } 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_id => &$model_config) { 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; } } else { } } 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; } else { } } 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; } else { } } 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; } else { } } } } } catch (\Exception $e) { } } }