[ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ], 'body' => json_encode([ 'model' => $text_model, 'messages' => [['role' => 'user', 'content' => $full_prompt]], ]), 'timeout' => 1000 ]); if (is_wp_error($response_title)) { error_log('Ошибка при запросе генерации заголовка: ' . $response_title->get_error_message()); return 'No title generated'; } $result_title = json_decode(wp_remote_retrieve_body($response_title), true); // Логируем ответ от API //error_log('Ответ от OpenAI API: ' . print_r($result_title, true)); return $result_title['choices'][0]['message']['content'] ?? 'No title generated'; } } function generate_article_title( $post_topic, $category_name, $selected_language, $keyword, $format, $custom_theme, $additional_requests, $api_key, $text_model, $bing_api_key, $google_api_key, $rss_feed_url, $today_date, $number, $target_audience, $target_region, $writing_style ) { /* // Логируем входные параметры (без API ключей) error_log('Генерация заголовка статьи.'); error_log('Тема поста: ' . $post_topic); error_log('Категория: ' . $category_name); error_log('Выбранный язык: ' . $selected_language); error_log('Ключевое слово: ' . $keyword); error_log('Формат: ' . $format); error_log('Пользовательская тема: ' . $custom_theme); error_log('Дополнительные запросы: ' . $additional_requests); error_log('URL RSS ленты: ' . $rss_feed_url); error_log('Текущая дата: ' . $today_date); error_log('Номер: ' . $number); error_log('Целевая аудитория: ' . $target_audience); error_log('Целевой регион: ' . $target_region); error_log('Стиль написания: ' . $writing_style); */ $language_full_name = get_full_language_name($selected_language); // Проверяем наличие ключей API и URL RSS ленты $keys_or_rss_available = !empty($bing_api_key) || !empty($google_api_key) || !empty($rss_feed_url); // Логика для формата 'news' if ($format == 'news' && $keys_or_rss_available) { if (!empty($rss_feed_url)) { $latest_news_data = ai_content_wizard_fetch_news_from_rss($rss_feed_url); if (!empty($latest_news_data)) { $relevant_news_context = array_filter($latest_news_data, function($news_item) use ($post_topic) { return strpos(strtolower($news_item['title']), strtolower($post_topic)) !== false; }); // Ограничение количества новостей для контекста $relevant_news_context = array_slice($relevant_news_context, 0, 10); $news_context = implode(". ", array_map(function($news) { return "{$news['title']}: {$news['description']}"; }, $relevant_news_context)); $prompt_title = "Create a headline in '$language_full_name' for a news article about '$post_topic' using the following news context: $news_context."; } } } if (empty($prompt_title)) { // Промпты для других форматов или когда ключи и RSS не доступны $prompt_title = "Generate a short, SEO-optimized headline in '$language_full_name' for an '$format' about '$post_topic' in the category of '$category_name', incorporating the primary keyword: '$keyword'. Don't use the category name in the title."; // Контекстные заметки для внутреннего использования $context_notes = "The content is intended for a '$target_audience' audience, relevant to the region '$target_region', and written in a '$writing_style' style. Language: '$language_full_name'. Don't use the category name in the title. The keyword cannot be changed."; if ($format === 'news') { $context_notes .= " The news article should be timely, reflecting the date: {$today_date}."; } if (in_array($format, ['guide', 'review', 'recipe'])) { $context_notes .= " A number like '{$number}' may be used for added engagement."; } if (!empty($custom_theme)) { $context_notes .= " Theme: '$custom_theme'."; } /* if (!empty($additional_requests)) { $context_notes .= " Additional requests: '$additional_requests'."; } */ $full_prompt = $prompt_title . " [Title writing requirements: " . $context_notes . "]"; } else { $full_prompt = $prompt_title; } // Логируем полный промпт для генерации заголовка //error_log('Полный промпт для генерации заголовка: ' . $full_prompt); // Генерация заголовка $article_title = request_title_generation($api_key, $text_model, $full_prompt); // Логируем полученный заголовок //error_log('Полученный заголовок: ' . $article_title); // Проверка и повторная генерация при необходимости $attempts = 0; $max_attempts = 3; // Максимальное количество попыток while (in_array($article_title, ['No title generated', 'Заголовок по умолчанию', 'No title enhanced']) && $attempts < $max_attempts) { //error_log("Попытка $attempts не удалась. Пытаемся снова."); $article_title = request_title_generation($api_key, $text_model, $full_prompt); $attempts++; //error_log('Новая попытка получения заголовка: ' . $article_title); } // Проверяем, включена ли опция улучшенного качества генерации if (ai_content_wizard_get_setting('ai_content_wizard_enhanced_generation_quality', 0) == 1) { $enhancement_prompt_for_title = "The existing headline for a '$format' about '$post_topic' is already engaging and creative. However, it does not directly include the primary keyword phrase '$keyword', which is crucial for SEO optimization and relevance to the target audience '$target_audience'. Please rewrite the headline to incorporate '$keyword' prominently, ensuring it's placed ideally in the first half of the headline. The revised headline should maintain its original appeal, being creative, engaging, and aligned with the '$language_full_name' language context. The ultimate goal is to enhance the headline's SEO effectiveness while keeping it compelling and memorable. Existing headline: '$article_title'."; // Логируем промпт для улучшения заголовка //error_log('Промпт для улучшения заголовка: ' . $enhancement_prompt_for_title); $response_enhancement_for_title = wp_remote_post('https://api.openai.com/v1/chat/completions', [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', ], 'body' => json_encode([ 'model' => $text_model, 'messages' => [['role' => 'system', 'content' => $enhancement_prompt_for_title]], ]), 'timeout' => 1000 ]); if (is_wp_error($response_enhancement_for_title)) { error_log('Ошибка при запросе улучшения заголовка: ' . $response_enhancement_for_title->get_error_message()); } else { $result_enhancement_for_title = json_decode(wp_remote_retrieve_body($response_enhancement_for_title), true); // Логируем ответ от API при улучшении заголовка //error_log('Ответ от OpenAI API (улучшение заголовка): ' . print_r($result_enhancement_for_title, true)); $enhanced_title = $result_enhancement_for_title['choices'][0]['message']['content'] ?? 'No title enhanced'; $article_title = $enhanced_title; //error_log('Улучшенный заголовок: ' . $article_title); } } // Удаление лишних символов и пробелов из заголовка $article_title = preg_replace('/\[[^\]]*\]/', '', $article_title); $article_title = preg_replace('/\([^\)]*\)/', '', $article_title); $article_title = preg_replace('/\|.*$/', '', $article_title); $article_title = trim(str_replace(['"', "'"], '', $article_title)); // Удаление фигурных кавычек, если они обрамляют весь заголовок if (preg_match('/^«(.*)»$/', $article_title, $matches)) { $article_title = $matches[1]; } // Удаление звездочек в начале и конце заголовка (например, из формата **заголовок**) $article_title = preg_replace('/^\*+|\*+$/u', '', $article_title); // Логируем окончательный заголовок после очистки //error_log('Окончательный заголовок после очистки: ' . $article_title); return $article_title; }