prompt_factory = new TitlePromptFactory(); } public function get_products($params) { try { $filterParams = ProductFilterMapper::fromRequest($params); $builder = new ProductFilterBuilder(); ProductFilterMapper::applyToBuilder($builder, $filterParams); return $builder->getProducts(); } catch (\Exception $e) { return [ 'products' => [], 'total' => 0, 'total_pages' => 0, 'error' => 'An error occurred while searching products: ' . $e->getMessage() ]; } } public function get_categories() { return ProductFilterMapper::getCategories(); } public function bulk_generate($product_ids, $options) { $results = []; $language = ( isset( $options['language'] ) && '' !== trim( (string) $options['language'] ) ) ? $options['language'] : get_option('aipt_language', 'English'); $writing_style = isset($options['writing_style']) ? sanitize_text_field($options['writing_style']) : (isset($options['writingStyle']) ? sanitize_text_field($options['writingStyle']) : get_option('aipt_writing_style', 'Professional')); $variant_count = intval($options['variantCount'] ?? 1); $variant_count = max(1, min(5, $variant_count)); $use_blueprint = BlueprintIntegration::usesBlueprint(Generators::TITLE, BlueprintIntegration::jobTrustedFacts()); foreach ($product_ids as $product_id) { $product = wc_get_product($product_id); if (!$product) continue; $refusal = ProductEligibility::refusalMessage($product); if (null !== $refusal) { $results[] = array( 'product_id' => $product_id, 'type' => 'title', 'text' => '', 'api_error' => $refusal, ); continue; } if ($use_blueprint) { $results[] = $this->generateViaBlueprint((int) $product_id, $options, $variant_count); continue; } try { $api_provider = $options['provider'] ?? get_option('aipt_api_provider', 'openai'); $product_data = ProductDataFormatter::getFormattedProductData($product); if (empty($product_data['categories'])) { $product_data['categories'] = ''; } $client = AIClientFactory::create($api_provider, [ 'category' => $product_data['categories'], 'generation_type' => 'title', 'model' => $options['model'] ?? null ]); $title_prompts = $this->prompt_factory->getTitlePrompts($options, $product_data, $language, $writing_style); $system_prompt = $title_prompts['system_prompt']; $user_prompt = $title_prompts['user_prompt']; $variable_map = [ '{SKU}' => $product_data['sku'], '{ATTRIBUTES}' => $product_data['formatted_attributes'], '{CATEGORIES}' => $product_data['categories'], '{TAGS}' => $product_data['tags'], '{PRICE}' => $product_data['price'], '{REGULAR_PRICE}' => $product_data['regular_price'], '{SALE_PRICE}' => $product_data['sale_price'], '{language}' => $language, '{style}' => $writing_style, '{title}' => $product_data['name'], '{short_description}' => $product->get_short_description(), '{long_description}' => $product->get_description(), '{SHORT_DESCRIPTION}' => HtmlToText::convert( (string) $product->get_short_description() ), '{LONG_DESCRIPTION}' => HtmlToText::convert( (string) $product->get_description() ), '{max_length}' => (string) self::resolveMaxLength($options['maxLength'] ?? null), '{keywords}' => $options['keywords'] ?? '', '{tone}' => $options['tone'] ?? 'SEO-Focused' ]; $titles = $this->generateUniqueVariants( $client, $system_prompt, $user_prompt, $variant_count, $variable_map, isset($options['model']) ? (string) $options['model'] : '', $product_id ); $titles = $this->enforceMaxLength($titles, $options['maxLength'] ?? 60); $results[] = array_merge( [ 'product_id' => $product_id, 'type' => 'title', 'variants' => $titles, 'text' => $titles[0] ], BlueprintIntegration::advancedResponseFields() ); } catch (\Exception $e) { $provider = (string) ($options['provider'] ?? get_option('aipt_api_provider', 'openai')); $results[] = array_merge( BlueprintIntegration::advancedResponseFields(), [ 'product_id' => $product_id, 'type' => 'title', 'text' => '', 'api_error' => ProviderCallException::displayMessage($e, $provider), 'provider' => ProviderCallException::providerLabel($provider), 'providerError' => ProviderCallException::providerErrorFor($e, $provider), ] ); } } return $results; } /** * Generate one product's title through the content structure engine. * Returns the EXACT per-product shape * `bulk_generate()`'s legacy branch returns (`variants`, `text`, * `api_error`?), plus the Blueprint response additions, so the * controller's existing review-staging/apply handling needs no changes. * * @since 2.8.0 * * @param int $product_id WooCommerce product id. * @param array $options Request options (generationMode, provider, model, language, blueprintRun, blueprintId, overwrite). * @param int $variant_count Already-clamped 1-5 variant count (the existing Free/Business-neutral clamp; title variants have no entitlement gate today). * @return array */ private function generateViaBlueprint(int $product_id, array $options, int $variant_count): array { $run_options = [ 'language' => (isset($options['language']) && '' !== trim((string) $options['language'])) ? (string) $options['language'] : 'store', 'provider' => isset($options['provider']) ? (string) $options['provider'] : '', 'model' => isset($options['model']) ? (string) $options['model'] : '', 'variants' => $variant_count, 'improveExisting' => ! empty($options['improveExisting']), ]; $result = BlueprintIntegration::run( Generators::TITLE, [ 'type' => 'product', 'id' => $product_id ], $options, $run_options, 'bulk' ); if (is_wp_error($result)) { return [ 'product_id' => $product_id, 'type' => 'title', 'variants' => [], 'text' => '', 'api_error' => $result->get_error_message(), ]; } $variants = array_values(array_filter( (array) ($result['outputs']['titleVariants'] ?? (isset($result['outputs']['title']) ? [ $result['outputs']['title'] ] : [])), 'is_string' )); $title = $variants[0] ?? ''; $generation_mode = is_string($options['generationMode'] ?? null) ? $options['generationMode'] : 'client_preview'; $destination = BlueprintIntegration::destinationForMode($generation_mode); $held_back = BlueprintIntegration::isHeldBack($result, $destination); $blueprint_fields = BlueprintIntegration::responseFields($result); $item = [ 'product_id' => $product_id, 'type' => 'title', 'variants' => $variants, 'text' => $title, ]; if ('' === $title || ProviderErrorMessage::isGenerationFailure($blueprint_fields)) { $item['api_error'] = ProviderErrorMessage::generationFailureMessage($blueprint_fields) ?? ProviderErrorMessage::fromResponseFields($blueprint_fields) ?? __('Title generation failed for this product.', 'ai-product-tools'); } $item = array_merge($item, $blueprint_fields); if ($held_back && '' !== $title) { $item['status'] = 'needs_review'; } return $item; } /** * The request's maxLength as a positive integer, falling back to * DEFAULT_MAX_LENGTH whenever it is missing, null, or - once absint() * turns 0, '' and a non-numeric string into 0 - not a positive number. * A plain `?? 60` only falls back when the option is missing or null, * so a request sending one of those falsy-but-present values reaches * absint() as 0. Shared by enforceMaxLength() below, the variable map's * `{max_length}` substitution, and TitlePromptFactory::getTitlePrompts(), * which interpolates this same request option into the system prompt's * own "hard limit" text - all three must enforce the identical default * instead of drifting apart. * * @param mixed $max_length_raw Request's maxLength option, if any. * @return int */ public static function resolveMaxLength($max_length_raw): int { $max_length = absint($max_length_raw); return $max_length >= 1 ? $max_length : self::DEFAULT_MAX_LENGTH; } /** * Enforce the requested (or default) maxLength on every generated * variant, after the fact: the prompt asks the model for a "hard limit" * but a real provider run has returned titles over it. Cuts at the last * whole word (FormulaText::trimToWordBoundary(), shared with the * content structure engine's own Title/Image-alt generators) instead of * a blind character cut, so a trimmed title never ends mid-word. * * @param string[] $titles Generated title variants. * @param mixed $max_length_raw Request's maxLength option, if any. * @return string[] Same order and count, each within max_length. */ private function enforceMaxLength(array $titles, $max_length_raw): array { $max_length = self::resolveMaxLength($max_length_raw); return array_map( static function ($title) use ($max_length) { return FormulaText::trimToWordBoundary((string) $title, $max_length)['text']; }, $titles ); } /** * Generate unique title variants with retry logic to prevent duplicates */ private function generateUniqueVariants($client, $system_prompt, $user_prompt, $variant_count, $variable_map, $model, $product_id) { $max_retries = 3; $attempt = 0; $all_generated_titles = []; $safe_variables = VariableConverter::convertVariables($variable_map); if ($variant_count <= 1) { $processed_system_prompt = str_replace(array_keys($safe_variables), array_values($safe_variables), $system_prompt); $processed_user_prompt = str_replace(array_keys($safe_variables), array_values($safe_variables), $user_prompt); $processed_system_prompt = PromptFormatter::cleanOutboundPrompt($processed_system_prompt); $processed_user_prompt = PromptFormatter::cleanOutboundPrompt($processed_user_prompt); $generated_text = $client->generate_description($processed_system_prompt, $processed_user_prompt, $model); $generated_text = PromptFormatter::cleanContent($generated_text); $generated_text = trim($generated_text, '"\'`'); $generated_text = wp_strip_all_tags($generated_text); if (empty(trim($generated_text))) { throw new \Exception('No valid title was generated'); } return [$generated_text]; } while ($attempt < $max_retries && count($all_generated_titles) < $variant_count) { $attempt++; $enhanced_user_prompt = $user_prompt; if ($attempt == 1) { $enhanced_user_prompt .= "\n\nIMPORTANT: Generate {$variant_count} COMPLETELY DIFFERENT title variations for this product. Each variant must be unique in wording, style, and approach. Return them separated by '|||'. DO NOT repeat the same title or use very similar words."; } elseif ($attempt == 2) { $enhanced_user_prompt .= "\n\nGenerate {$variant_count} DIVERSE title variations using DIFFERENT approaches:"; $enhanced_user_prompt .= "\n1. Focus on main features"; $enhanced_user_prompt .= "\n2. Emphasize benefits"; $enhanced_user_prompt .= "\n3. Highlight unique selling points"; $enhanced_user_prompt .= "\n4. Use emotional appeal"; $enhanced_user_prompt .= "\n5. SEO-focused approach"; $enhanced_user_prompt .= "\nEach title MUST be completely different. Return them separated by '|||'."; if (!empty($all_generated_titles)) { $enhanced_user_prompt .= "\n\nDO NOT generate these titles again: " . implode(', ', array_map(function($title) { return '"' . $title . '"'; }, $all_generated_titles)); } } else { $enhanced_user_prompt .= "\n\nCREATE {$variant_count} COMPLETELY UNIQUE titles with these requirements:"; $enhanced_user_prompt .= "\n- Use different word choices and sentence structures"; $enhanced_user_prompt .= "\n- Vary the focus (features vs benefits vs emotional appeal)"; $enhanced_user_prompt .= "\n- Different lengths within the character limit"; $enhanced_user_prompt .= "\n- Avoid repeating key phrases from previous attempts"; $enhanced_user_prompt .= "\nReturn them separated by '|||'."; if (!empty($all_generated_titles)) { $enhanced_user_prompt .= "\n\nAVOID these previously generated titles: " . implode(', ', array_map(function($title) { return '"' . $title . '"'; }, $all_generated_titles)); } } $processed_system_prompt = str_replace(array_keys($safe_variables), array_values($safe_variables), $system_prompt); $processed_user_prompt = str_replace(array_keys($safe_variables), array_values($safe_variables), $enhanced_user_prompt); $processed_system_prompt = PromptFormatter::cleanOutboundPrompt($processed_system_prompt); $processed_user_prompt = PromptFormatter::cleanOutboundPrompt($processed_user_prompt); if (defined('WP_DEBUG') && WP_DEBUG) { $log_message = "[AIPT Debug - Title Generator] Attempt {$attempt} for Product ID: {$product_id}\n"; $log_message .= "--- SYSTEM PROMPT ---\n"; $log_message .= $processed_system_prompt . "\n"; $log_message .= "--- USER PROMPT ---\n"; $log_message .= $processed_user_prompt . "\n"; $log_message .= "-----------------------\n"; } try { $generated_text = $client->generate_description($processed_system_prompt, $processed_user_prompt, $model); } catch (\Exception $e) { if (!empty($all_generated_titles)) { return array_slice($all_generated_titles, 0, $variant_count); } throw $e; } $generated_text = PromptFormatter::cleanContent($generated_text); $generated_text = trim($generated_text, '"\'`'); $generated_text = wp_strip_all_tags($generated_text); if (empty(trim($generated_text))) { continue; } $new_titles = []; if (strpos($generated_text, '|||') !== false) { $raw_titles = explode('|||', $generated_text); foreach ($raw_titles as $title) { $title = trim($title); if (!empty($title)) { $new_titles[] = $title; } } } else { $new_titles[] = $generated_text; } foreach ($new_titles as $title) { if (!$this->isDuplicateTitle($title, $all_generated_titles)) { $all_generated_titles[] = $title; if (count($all_generated_titles) >= $variant_count) { break 2; } } } } if (empty($all_generated_titles)) { throw new \Exception('Unable to generate any valid titles'); } return array_slice($all_generated_titles, 0, $variant_count); } /** * Check if a title is duplicate (similar) to existing titles */ private function isDuplicateTitle($new_title, $existing_titles) { $new_title_clean = strtolower(trim($new_title)); foreach ($existing_titles as $existing_title) { $existing_title_clean = strtolower(trim($existing_title)); if ($new_title_clean === $existing_title_clean) { return true; } $new_words = array_filter(explode(' ', $new_title_clean)); $existing_words = array_filter(explode(' ', $existing_title_clean)); if (count($new_words) > 0 && count($existing_words) > 0) { $intersection = array_intersect($new_words, $existing_words); $similarity = count($intersection) / max(count($new_words), count($existing_words)); if ($similarity >= 0.85) { return true; } } } return false; } }