*/ class A1AI_OpenAI { /** * Matches the canned abstention phrasings the prompt instructs the model to use * ("I don't have that information..." / "I don't have that specific information..."). * Keep in sync with the ## RULES / default-prompt wording in prepare_messages() — * quality-event classification depends on this pattern matching those phrases. * * @since 1.6.1 */ const ABSTENTION_PATTERN = "/don'?t have (that|this|the)?\\s*(specific\\s+)?information/i"; /** * The data manager instance. * * @since 1.0.0 * @access private * @var A1AI_Data_Manager $data_manager Handles database operations. */ private $data_manager; /** * Telemetry for the most recent retrieval pass: which tier produced the * WEBSITE CONTENT context, how many results, and whether semantic search * contributed. Read by process_conversation() to build the quality event. * * @since 1.6.1 * @access private * @var array|null $last_retrieval ['tier' => string, 'count' => int, 'semantic' => bool] */ private $last_retrieval = null; /** * The conversation manager instance. * * @since 1.4.0 * @access private * @var A1AI_Conversation_Manager $conversation_manager Handles conversation state and guidance. */ private $conversation_manager; /** * Initialize the class and set its properties. * * @since 1.0.0 * @param A1AI_Data_Manager $data_manager The data manager instance. */ public function __construct($data_manager = null) { // If data manager wasn't passed, create one if (null === $data_manager) { require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-a1ai-data-manager.php'; $this->data_manager = new A1AI_Data_Manager(); } else { $this->data_manager = $data_manager; } // Initialize conversation manager require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-a1ai-conversation-manager.php'; $this->conversation_manager = new A1AI_Conversation_Manager($this->data_manager); } /** * Process a conversation with OpenAI. * * @since 1.0.0 * @param int $conversation_id The conversation ID. * @param string $message The user message. * @param array $settings The chatbot settings. * @return array The response with success status and message or error. */ public function process_conversation($conversation_id, $message, $settings) { // Get chatbot ID from settings $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; // Reset retrieval telemetry so a stale value from a prior call can't leak // into this turn's quality event. $this->last_retrieval = null; // Add conversation ID to settings for conversation manager $settings['conversation_id'] = $conversation_id; // Check for matching adjustments first (3-pass: Exact > Phrase > Broad) if ($chatbot_id > 0) { $adjustments = $this->data_manager->get_adjustments($chatbot_id); if (!empty($adjustments)) { // Normalize helper: strip apostrophes, punctuation, collapse whitespace $normalize = function($str) { $str = trim(strtolower($str)); $str = str_replace("'", '', $str); $str = preg_replace('/[^\w\s]/u', ' ', $str); $str = preg_replace('/\s+/', ' ', $str); return trim($str); }; $current_normalized = $normalize($message); $matched_adjustment = null; // Pass 1: Exact matches (highest priority) foreach ($adjustments as $adjustment) { if ($adjustment['ui_match_type'] !== 'Exact') { continue; } if ($normalize($adjustment['user_input']) === $current_normalized) { $matched_adjustment = $adjustment; break; } } // Pass 2: Phrase matches if (null === $matched_adjustment) { foreach ($adjustments as $adjustment) { if ($adjustment['ui_match_type'] !== 'Phrase') { continue; } if (strpos($current_normalized, $normalize($adjustment['user_input'])) !== false) { $matched_adjustment = $adjustment; break; } } } // Pass 3: Broad and Default matches (lowest priority, best score wins) if (null === $matched_adjustment) { $best_score = -1; foreach ($adjustments as $adjustment) { if ($adjustment['ui_match_type'] === 'Exact' || $adjustment['ui_match_type'] === 'Phrase') { continue; } $raw_input = $adjustment['user_input']; $adj_normalized = $normalize($raw_input); if ($adjustment['ui_match_type'] === 'Broad') { // Parse +word required modifiers from the raw input $required_words = array(); if (preg_match_all('/\+(\w+)/', $raw_input, $req_matches)) { $required_words = array_map('strtolower', $req_matches[1]); } // Check all required words are present in the user message $user_words = explode(' ', $current_normalized); $all_required_present = true; foreach ($required_words as $req) { if (!in_array($req, $user_words, true)) { $all_required_present = false; break; } } if (!$all_required_present) { continue; } // Strip +markers for word-overlap matching $clean_pattern = preg_replace('/\+/', '', $adj_normalized); $clean_pattern = preg_replace('/\s+/', ' ', trim($clean_pattern)); $pattern_words = explode(' ', $clean_pattern); // Word overlap: count how many pattern words appear in user message $matched_words = 0; foreach ($pattern_words as $pw) { if (in_array($pw, $user_words, true)) { $matched_words++; } } $confidence = count($pattern_words) > 0 ? $matched_words / count($pattern_words) : 0; if ($confidence >= 0.5 && $confidence > $best_score) { $best_score = $confidence; $matched_adjustment = $adjustment; } } else { // Default: contains check (either direction) + levenshtein if (strpos($current_normalized, $adj_normalized) !== false || strpos($adj_normalized, $current_normalized) !== false) { $matched_adjustment = $adjustment; break; } if (strlen($current_normalized) <= 255 && strlen($adj_normalized) <= 255) { $max_length = max(strlen($current_normalized), strlen($adj_normalized)); if ($max_length > 0) { $similarity = 1 - (levenshtein($current_normalized, $adj_normalized) / $max_length); if ($similarity > 0.7 && $similarity > $best_score) { $best_score = $similarity; $matched_adjustment = $adjustment; } } } } } } // Return matched adjustment if found if (null !== $matched_adjustment) { // Log match for observability if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log(sprintf( 'A1AI Adjustment Match: type=%s, input="%s", matched="%s"', $matched_adjustment['ui_match_type'], substr($message, 0, 80), substr($matched_adjustment['user_input'], 0, 80) )); } $this->conversation_manager->update_conversation_state($conversation_id, array( 'last_response_type' => 'adjustment', 'last_updated' => current_time('mysql') )); return array( 'success' => true, 'message' => $matched_adjustment['ai_output'], 'tokens_used' => 0, 'from_adjustment' => true, 'quality' => array( 'event_type' => 'adjustment_hit', 'retrieval_tier' => 'adjustment', 'result_count' => 0, 'semantic_used' => 0, ), ); } } } // No adjustment matched, proceed with normal OpenAI request // Get message history for this conversation (capped) $history_limit = isset($settings['message_history_limit']) ? intval($settings['message_history_limit']) : 20; $history_limit = max(4, min($history_limit, 100)); $history = $this->data_manager->get_recent_messages($conversation_id, $history_limit); // Prepare messages for OpenAI $messages = $this->prepare_messages($history, $message, $settings); // Observability: log request details if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { $prompt_length = 0; foreach ($messages as $m) { $prompt_length += mb_strlen($m['content']); } // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log(sprintf( 'A1AI Request: conversation_id=%d, chatbot_id=%d, message_count=%d, estimated_prompt_tokens=%d, model=%s', $conversation_id, $chatbot_id, count($messages), (int) ceil($prompt_length / 4), isset($settings['model']) ? $settings['model'] : 'default' )); } // Send request to OpenAI $response = $this->send_request($messages, $settings); // Process response if ($response['success']) { $response_provider = isset($response['provider']) ? (string) $response['provider'] : 'openai'; $ai_message = $this->extract_message($response['data'], $response_provider); $token_usage = $this->extract_token_usage($response['data'], $response_provider); // Observability: log response details if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log(sprintf( 'A1AI Response: conversation_id=%d, tokens_used=%d, response_length=%d', $conversation_id, $token_usage, mb_strlen($ai_message) )); } // Validate and enhance response if needed $enhanced_response = $this->validate_and_enhance_response($ai_message, $conversation_id, $message, $settings); // Let extensions post-process the answer. This applies the `a1ai_chatbot_response` // filter that the premium A1AI_Upgrade_Phrase_Integration hooks — previously the // filter was registered but NEVER applied, so configured phrase rules silently did // nothing. The callback is a no-op unless the phrase_matching feature is enabled, so // this only changes behavior on sites that explicitly opted in and created rules. $enhanced_response = apply_filters('a1ai_chatbot_response', $enhanced_response, $message, $chatbot_id); // Update conversation state $this->conversation_manager->update_conversation_state($conversation_id, array( 'last_response_type' => 'ai', 'last_user_message' => $message, 'last_updated' => current_time('mysql') )); // Classify the answer for quality telemetry. Abstention wins over // no_context so "couldn't answer even WITH context" stays visible. $retrieval = is_array($this->last_retrieval) ? $this->last_retrieval : array('tier' => 'none', 'count' => 0, 'semantic' => false); if (preg_match(self::ABSTENTION_PATTERN, $enhanced_response)) { $event_type = 'abstention'; } elseif ('none' === $retrieval['tier']) { $event_type = 'no_context'; } else { $event_type = 'answered'; } return array( 'success' => true, 'message' => $enhanced_response, 'tokens_used' => $token_usage, 'quality' => array( 'event_type' => $event_type, 'retrieval_tier' => $retrieval['tier'], 'result_count' => (int) $retrieval['count'], 'semantic_used' => empty($retrieval['semantic']) ? 0 : 1, ), ); } else { // The visitor gets a generic apology (never a config error), but the // failure still has to be recorded — otherwise a chatbot that is // broken for everyone (missing API key, dead model, provider // outage) looks simply idle in the quality reporting. $retrieval = is_array($this->last_retrieval) ? $this->last_retrieval : array('tier' => 'none', 'count' => 0, 'semantic' => false); return array( 'success' => false, 'error' => $response['message'], 'quality' => array( 'event_type' => 'error', 'retrieval_tier' => $retrieval['tier'], 'result_count' => (int) $retrieval['count'], 'semantic_used' => empty($retrieval['semantic']) ? 0 : 1, 'error_message' => (string) $response['message'], ), ); } } /** * Prepare messages for OpenAI API request. * * @since 1.0.0 * @param array $history Previous messages in the conversation. * @param string $message The new user message. * @param array $settings The chatbot settings. * @return array Formatted messages for OpenAI API. */ private function prepare_messages($history, $message, $settings) { $messages = array(); // Get chatbot ID from settings or conversation $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; $conversation_id = isset($settings['conversation_id']) ? intval($settings['conversation_id']) : 0; // Get system prompt from custom instructions table $system_prompt = ''; if ($chatbot_id > 0) { $system_instructions = $this->data_manager->get_custom_instructions($chatbot_id, 'system'); if (!empty($system_instructions) && is_array($system_instructions)) { foreach ($system_instructions as $instruction) { if ($instruction['instruction_name'] === 'System Prompt' && !empty($instruction['instruction_content'])) { $system_prompt = $instruction['instruction_content']; break; } } } } // Get general custom instructions from dedicated table $custom_instructions = ''; if ($chatbot_id > 0) { $instructions_array = $this->data_manager->get_custom_instructions($chatbot_id, 'general'); if (!empty($instructions_array) && is_array($instructions_array)) { $instructions_text = ''; foreach ($instructions_array as $instruction) { if (!empty($instruction['instruction_content'])) { $instructions_text .= $instruction['instruction_content'] . "\n\n"; } } $custom_instructions = trim($instructions_text); } } // Build structured system prompt with clear sections $system_content = ''; // When caller provides system_prompt (e.g. organic contact form), prepend it so it overrides default behavior if ( ! empty( $settings['system_prompt'] ) && is_string( $settings['system_prompt'] ) ) { $system_content .= $settings['system_prompt'] . "\n\n---\n\n"; } // === SECTION 1: ROLE === $system_content .= "## ROLE\n"; if (!empty($system_prompt)) { $system_content .= $system_prompt . "\n\n"; } else { $system_content .= "You are a professional business assistant. Your primary role is to help customers accurately and guide them toward taking action.\n\n"; } if (!empty($custom_instructions)) { $system_content .= $custom_instructions . "\n\n"; } // === SECTION 2: PRIMARY DIRECTIVE === $system_content .= "## PRIMARY DIRECTIVE\n"; $system_content .= "Only use the business information and content provided below; never invent details. Keep responses concise (2-4 sentences) unless the user asks for more detail.\n\n"; // === SECTION 2b: RESPONSE STYLE === $system_content .= "## RESPONSE STYLE\n"; $system_content .= "- Write in short, natural prose. Prefer flowing sentences over lists.\n"; $system_content .= "- Only use a bulleted list when the user is genuinely asking to compare or choose between multiple distinct options, and then use at most 3-4 short bullets. Never bullet a single idea.\n"; $system_content .= "- Keep bullet text to one line each; do not stack bold headers, long descriptions, and emoji together.\n"; $system_content .= "- Use at most one emoji per message, and only when it fits a warm, professional tone. Prefer none.\n"; $system_content .= "- Do not bold whole sentences. Bold is only for a single key term when it truly helps.\n"; $system_content .= "- Lead with the direct answer first, then a brief next step if relevant. Avoid restating the question.\n\n"; // === SECTION 3: BUSINESS INFORMATION === if ($chatbot_id > 0) { $business_info = $this->data_manager->get_business_info($chatbot_id); if (!empty($business_info)) { $system_content .= "## BUSINESS INFORMATION\n"; $system_content .= "You are an AI assistant for " . (!empty($business_info['business_name']) ? $business_info['business_name'] : 'this business') . ".\n\n"; if (!empty($business_info['tagline'])) { $system_content .= "About: " . $business_info['tagline'] . "\n\n"; } else { $system_content .= "No business description was provided. When asked what the business does, do not use placeholder text in square brackets (e.g. [brief description of the business] or [company name]). Never output square brackets with placeholder instructions inside. Say you don't have a description on file and suggest exploring the website or contacting the business directly.\n\n"; } if (!empty($business_info['business_type'])) { $system_content .= "Business Type: " . ucfirst($business_info['business_type']) . "\n\n"; } if (!empty($business_info['services'])) { $services = json_decode($business_info['services'], true); if (!empty($services) && is_array($services)) { $system_content .= "Services Offered:\n"; foreach ($services as $service) { $system_content .= "- " . $service . "\n"; } $system_content .= "\n"; } } if (!empty($business_info['products'])) { $products = json_decode($business_info['products'], true); if (!empty($products) && is_array($products)) { $system_content .= "Products Available:\n"; foreach ($products as $product) { $system_content .= "- " . $product . "\n"; } $system_content .= "\n"; } } if (!empty($business_info['hours'])) { $hours = json_decode($business_info['hours'], true); if (!empty($hours) && is_array($hours)) { $system_content .= "Business Hours:\n"; foreach ($hours as $day => $time) { if (!empty($time)) { $system_content .= ucfirst($day) . ": " . $time . "\n"; } } $system_content .= "\n"; } } $has_contact = false; if (!empty($business_info['address']) || !empty($business_info['phone']) || !empty($business_info['email'])) { $system_content .= "Contact Information:\n"; if (!empty($business_info['address'])) { $system_content .= "Address: " . str_replace("\n", ", ", $business_info['address']) . "\n"; $has_contact = true; } if (!empty($business_info['phone'])) { $system_content .= "Phone: " . $business_info['phone'] . "\n"; $has_contact = true; } if (!empty($business_info['email'])) { $system_content .= "Email: " . $business_info['email'] . "\n"; $has_contact = true; } if (!empty($business_info['website'])) { $system_content .= "Website: " . $business_info['website'] . "\n"; $has_contact = true; } if ($has_contact) { $system_content .= "\n"; } } if (!empty($business_info['policies'])) { $system_content .= "Important Policies & Information:\n"; $system_content .= $business_info['policies'] . "\n\n"; } } } // === SECTION 4: RULES === $system_content .= "## RULES\n"; if ($conversation_id > 0 && !empty($history) && count($history) > 2) { $system_content .= "- This is an ongoing conversation. Maintain context and continuity. Do not restart or repeat greetings.\n"; } $system_content .= "- Respond naturally and directly to the user's question.\n"; $system_content .= "- Only provide information based on the business information above.\n"; $system_content .= "- When SITE KNOWLEDGE or PRICING sections are present below, treat them as authoritative — quote them directly and include the markdown links instead of deflecting.\n"; $system_content .= "- Answer only from the information provided above (business info, SITE KNOWLEDGE, WEBSITE CONTENT, PRICING). When you use a specific page, cite it with its markdown link. If the provided content doesn't actually answer the question, say so plainly and offer to connect them (contact us or request a quote) — do not guess or fill gaps from general knowledge.\n"; $system_content .= "- Prefer the business's main pages (pricing, services, contact, about) when they answer the question; use blog posts only for topics a main page doesn't cover. The links in the sections below are ordered most-important first, so lead with the top ones.\n"; // This phrasing must stay matchable by self::ABSTENTION_PATTERN (quality telemetry). $system_content .= "- Only say 'I don't have that information, please contact us directly' when the question genuinely isn't covered by anything above.\n"; $system_content .= "- Do not repeat links you have already provided in this conversation.\n"; $system_content .= "- If the user is already on a specific page, do not suggest they visit that same page.\n"; $system_content .= "- Never include placeholder text in square brackets (e.g. [brief description of the business] or [company name]) in your replies. Use only real information from the context above or say you don't have that information.\n"; // CTA instruction from chatbot settings (Improvement 4a) $primary_action = isset($settings['primary_action']) ? $settings['primary_action'] : ''; if (!empty($primary_action)) { $system_content .= "- When the user seems interested, naturally guide them toward: " . $primary_action . "\n"; } $system_content .= "\n"; // === SECTION 5: WEBSITE CONTENT === $recent_turns = $this->recent_user_turns($history, 2); $content_awareness_context = $this->get_content_awareness_context($message, $chatbot_id, $recent_turns); if (!empty($content_awareness_context)) { $system_content .= "## WEBSITE CONTENT\n"; $system_content .= $content_awareness_context . "\n\n"; } // === SECTION 6: PAGE CONTEXT === $current_url = isset($settings['_current_url']) ? $settings['_current_url'] : ''; $page_title = isset($settings['_page_title']) ? $settings['_page_title'] : ''; if (!empty($current_url)) { $system_content .= "## PAGE CONTEXT\n"; $system_content .= "The user is currently viewing: " . esc_html($page_title) . " (" . esc_url($current_url) . ")\n"; $system_content .= "Do NOT suggest links to the page the user is already on.\n"; $system_content .= "If the user asks about content on this page, answer directly instead of sending them a link.\n\n"; } // === SECTION 7: ACCURACY === $system_content .= "## ACCURACY\n"; $system_content .= "- Only state facts you are confident are accurate.\n"; $system_content .= "- Never fabricate prices, availability, hours, or policies.\n"; $system_content .= "- When uncertain, say so and suggest contacting the business directly.\n"; $system_content .= "- If you're not sure the provided content actually supports an answer, ask a clarifying question or offer to hand off — never fabricate.\n"; $system_content .= "- Be transparent about your limitations.\n\n"; // Add system message. // NOTE: do NOT run the assembled prompt through sanitize_textarea_field() — this is a // server-built API payload (JSON-encoded downstream), not HTML output. That helper strips // %XX percent-encoding (corrupting the [Title](URL) citation links the grounding design // depends on) and can delete <…>-bearing business text. The user-derived parts are already // sanitized upstream and the content formatters already esc_html()/esc_url() their fields. // We only guard against invalid UTF-8 (strip mode) so the JSON encode can't fail. if (!empty($system_content)) { $messages[] = array( 'role' => 'system', 'content' => wp_check_invalid_utf8($system_content, true), ); } else { // Default system message (business-focused with accuracy emphasis) $default_message = "You are a professional business assistant. Your role is to help customers by:\n\n"; $default_message .= "1. ACCURACY FIRST\n"; $default_message .= " - Only state facts you know to be true\n"; // This phrasing must stay matchable by self::ABSTENTION_PATTERN (quality telemetry). $default_message .= " - If unsure, say 'I don't have that specific information. Please contact us directly.'\n"; $default_message .= " - Never guess prices, availability, hours, or specific business details\n\n"; $default_message .= "2. HELPFUL GUIDANCE\n"; $default_message .= " - Answer general questions professionally\n"; $default_message .= " - Direct customers to contact methods for detailed inquiries\n"; $default_message .= " - Be friendly, concise, and clear\n\n"; $default_message .= "3. LEAD GENERATION\n"; $default_message .= " - When customers show interest, offer to help them connect\n"; $default_message .= " - Suggest contacting the business for quotes or appointments\n"; $default_message .= " - Be proactive but respectful\n\n"; $default_message .= "Remember: It's better to say 'I don't know' than provide incorrect information."; $messages[] = array( 'role' => 'system', 'content' => $default_message, ); } // Add initial messages if provided if (!empty($settings['initial_messages']) && is_array($settings['initial_messages'])) { foreach ($settings['initial_messages'] as $initial_message) { if (!empty($initial_message['role']) && !empty($initial_message['content'])) { $messages[] = array( 'role' => sanitize_text_field($initial_message['role']), 'content' => sanitize_textarea_field($initial_message['content']), ); } } } // Add conversation history with token budget if (!empty($history) && is_array($history)) { $token_budget = 8000; $estimated_tokens_used = 0; $budgeted_history = array(); // Walk from newest to oldest, accumulating until budget is reached $reversed = array_reverse($history); foreach ($reversed as $msg) { $msg_tokens = (int) ceil(mb_strlen($msg['content']) / 4); if ($estimated_tokens_used + $msg_tokens > $token_budget && !empty($budgeted_history)) { break; } $estimated_tokens_used += $msg_tokens; array_unshift($budgeted_history, $msg); } foreach ($budgeted_history as $msg) { $messages[] = array( 'role' => sanitize_text_field($msg['role']), 'content' => $msg['content'], ); } } // Add current user message $messages[] = array( 'role' => 'user', 'content' => $message, ); return $messages; } /** * Send request to the configured LLM provider (OpenAI or Anthropic). * * Resolves the effective provider from the per-chatbot/global settings, * validates the model for that provider, then dispatches to the * provider-specific transport. The return shape is identical regardless * of provider: * success: ['success' => true, 'data' => array, 'provider' => string] * failure: ['success' => false, 'message' => string, 'code' => int?] * * @since 1.0.0 * @param array $messages The formatted messages (OpenAI shape). * @param array $settings The API settings (may carry llm_provider override). * @return array The response with success status and data or error message. */ private function send_request($messages, $settings) { $provider = class_exists('A1AI_LLM_Config') ? A1AI_LLM_Config::get_effective_provider($settings) : 'openai'; $api_key = class_exists('A1AI_LLM_Config') ? A1AI_LLM_Config::get_api_key($provider) : (string) get_option('a1ai_openai_api_key', ''); if (empty($api_key)) { $label = class_exists('A1AI_LLM_Config') ? A1AI_LLM_Config::get_provider_label($provider) : 'OpenAI'; return array( 'success' => false, 'message' => sprintf( /* translators: %s: provider label (OpenAI or Anthropic) */ esc_html__('%s API key is not configured.', 'a1ai-chatbot'), $label ), ); } // Resolve the model: explicit setting wins, otherwise provider default. // Also defensively normalize so a model id valid for the other // provider is not sent across the wire. $default_model = class_exists('A1AI_LLM_Config') ? A1AI_LLM_Config::get_default_model($provider) : (string) get_option('a1ai_default_model', 'gpt-4o'); $requested_model = isset($settings['model']) && '' !== $settings['model'] ? sanitize_text_field($settings['model']) : $default_model; $model = class_exists('A1AI_LLM_Config') ? A1AI_LLM_Config::validate_model_for_provider($requested_model, $provider) : $requested_model; $api_settings = array( 'model' => $model, 'temperature' => isset($settings['temperature']) ? (float) $settings['temperature'] : (float) get_option('a1ai_default_temperature', 0.5), 'max_tokens' => isset($settings['max_tokens']) ? max(1, (int) $settings['max_tokens']) : max(1, (int) get_option('a1ai_default_max_tokens', 1000)), 'api_key' => $api_key, ); if ('anthropic' === $provider) { return $this->send_via_anthropic($messages, $api_settings); } return $this->send_via_openai($messages, $api_settings); } /** * Dispatch a chat-completion request to OpenAI. * * @since 1.4.0 * @param array $messages OpenAI-style messages. * @param array $api_settings Resolved settings: model, temperature, max_tokens, api_key. * @return array Standard response shape (see send_request). */ private function send_via_openai($messages, $api_settings) { $request_data = array( 'model' => $api_settings['model'], 'messages' => $messages, 'temperature' => $api_settings['temperature'], 'max_tokens' => $api_settings['max_tokens'], ); $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_settings['api_key'], 'Content-Type' => 'application/json', ), 'timeout' => 60, 'body' => wp_json_encode($request_data), ); $max_retries = 1; $attempt = 0; $response = null; while ($attempt <= $max_retries) { $attempt++; $response = wp_remote_post('https://api.openai.com/v1/chat/completions', $args); if (is_wp_error($response)) { if ($attempt <= $max_retries) { if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log('A1AI [openai]: API request failed (attempt ' . $attempt . '): ' . $response->get_error_message() . '. Retrying...'); } usleep(500000); continue; } return array( 'success' => false, 'message' => esc_html__('I\'m having trouble connecting right now. Please try again in a moment.', 'a1ai-chatbot'), ); } $response_code = wp_remote_retrieve_response_code($response); if ($response_code >= 500 && $attempt <= $max_retries) { if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log('A1AI [openai]: API returned ' . $response_code . ' (attempt ' . $attempt . '). Retrying...'); } usleep(500000); continue; } break; } $response_code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (200 !== $response_code) { $error_message = class_exists('A1AI_LLM_Config') ? A1AI_LLM_Config::parse_error_body($body, 'openai', $response_code) : (isset($data['error']['message']) ? sanitize_text_field($data['error']['message']) : esc_html__('Unknown error occurred.', 'a1ai-chatbot')); return array( 'success' => false, 'message' => $error_message, 'code' => $response_code, ); } return array( 'success' => true, 'data' => $data, 'provider' => 'openai', ); } /** * Dispatch a chat-completion request to Anthropic's Messages API. * * @since 1.4.0 * @param array $messages OpenAI-style messages (will be adapted). * @param array $api_settings Resolved settings: model, temperature, max_tokens, api_key. * @return array Standard response shape (see send_request). */ private function send_via_anthropic($messages, $api_settings) { $adapted = A1AI_LLM_Config::convert_messages_for_anthropic($messages); $request_data = array( 'model' => $api_settings['model'], 'max_tokens' => max(1, (int) $api_settings['max_tokens']), 'messages' => $adapted['messages'], ); // temperature is optional; pass through if a numeric value was set. if (isset($api_settings['temperature']) && is_numeric($api_settings['temperature'])) { $request_data['temperature'] = (float) $api_settings['temperature']; } // Anthropic accepts an empty system; only include when non-empty. if (isset($adapted['system']) && '' !== $adapted['system']) { $request_data['system'] = $adapted['system']; } $args = array( 'headers' => array( 'x-api-key' => $api_settings['api_key'], 'anthropic-version' => A1AI_LLM_Config::ANTHROPIC_API_VERSION, 'Content-Type' => 'application/json', ), 'timeout' => 60, 'body' => wp_json_encode($request_data), ); $max_retries = 1; $attempt = 0; $response = null; while ($attempt <= $max_retries) { $attempt++; $response = wp_remote_post('https://api.anthropic.com/v1/messages', $args); if (is_wp_error($response)) { if ($attempt <= $max_retries) { if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log('A1AI [anthropic]: API request failed (attempt ' . $attempt . '): ' . $response->get_error_message() . '. Retrying...'); } usleep(500000); continue; } return array( 'success' => false, 'message' => esc_html__('I\'m having trouble connecting right now. Please try again in a moment.', 'a1ai-chatbot'), ); } $response_code = wp_remote_retrieve_response_code($response); if ($response_code >= 500 && $attempt <= $max_retries) { if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log('A1AI [anthropic]: API returned ' . $response_code . ' (attempt ' . $attempt . '). Retrying...'); } usleep(500000); continue; } break; } $response_code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (200 !== $response_code) { return array( 'success' => false, 'message' => A1AI_LLM_Config::parse_error_body($body, 'anthropic', $response_code), 'code' => $response_code, ); } return array( 'success' => true, 'data' => $data, 'provider' => 'anthropic', ); } /** * Extract message text from a provider response. * * @since 1.0.0 * @param array $data The response data. * @param string $provider 'openai' or 'anthropic'. * @return string The extracted message content. */ private function extract_message($data, $provider = 'openai') { if ('anthropic' === $provider) { if (isset($data['content']) && is_array($data['content'])) { // Prefer the first text block; fall back to walking for one. if (isset($data['content'][0]['type']) && 'text' === $data['content'][0]['type'] && isset($data['content'][0]['text'])) { return (string) $data['content'][0]['text']; } foreach ($data['content'] as $block) { if (is_array($block) && isset($block['type'], $block['text']) && 'text' === $block['type']) { return (string) $block['text']; } } } return esc_html__('No response generated.', 'a1ai-chatbot'); } if (isset($data['choices'][0]['message']['content'])) { return $data['choices'][0]['message']['content']; } return esc_html__('No response generated.', 'a1ai-chatbot'); } /** * Extract total token usage from a provider response. * * For Anthropic, returns input+output tokens summed for parity with * OpenAI's `total_tokens`. * * @since 1.0.0 * @param array $data The response data. * @param string $provider 'openai' or 'anthropic'. * @return int The total token usage or 0 if not available. */ private function extract_token_usage($data, $provider = 'openai') { if ('anthropic' === $provider) { $input = isset($data['usage']['input_tokens']) ? (int) $data['usage']['input_tokens'] : 0; $output = isset($data['usage']['output_tokens']) ? (int) $data['usage']['output_tokens'] : 0; return $input + $output; } if (isset($data['usage']['total_tokens'])) { return (int) $data['usage']['total_tokens']; } return 0; } /** * Remove square-bracket placeholder text (e.g. [brief description of the business]) from AI output. * * @since 1.0.0 * @param string $text The message text. * @return string The text with placeholder brackets removed and spaces normalized. */ private function strip_square_bracket_placeholders( $text ) { if ( ! is_string( $text ) || $text === '' ) { return $text; } $cleaned = preg_replace( '/\s*\[[^\]]+\]\s*/u', ' ', $text ); $cleaned = preg_replace( '/\s{2,}/u', ' ', $cleaned ); return trim( $cleaned ); } /** * Validate and enhance AI response based on conversation state. * * @since 1.4.0 * @param string $ai_message The AI response message. * @param int $conversation_id The conversation ID. * @param string $user_message The user message. * @param array $settings The chatbot settings. * @return string The enhanced response. */ private function validate_and_enhance_response($ai_message, $conversation_id, $user_message, $settings) { $ai_message = $this->strip_square_bracket_placeholders( $ai_message ); $enhanced_message = $ai_message; // Organic contact form: do not append "To move our conversation forward" or call-to-action suggestions if ( ! empty( $settings['organic_contact_form'] ) ) { return $ai_message; } // Check for repetitive content - only append suggestions when also short if ($this->conversation_manager->is_repetitive_content($conversation_id, $ai_message)) { $word_count = str_word_count($ai_message); if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging gated behind WP_DEBUG error_log(sprintf( 'A1AI Repetition Detected: conversation_id=%d, word_count=%d', $conversation_id, $word_count )); } // Only append boilerplate suggestions when the reply is repetitive AND short if ($word_count < 80) { $suggested_actions = $this->get_business_aware_suggestions($conversation_id, $settings); if (!empty($suggested_actions)) { $enhanced_message .= "\n\nTo move our conversation forward, I'd be happy to help you with:"; foreach (array_slice($suggested_actions, 0, 3) as $action) { $enhanced_message .= "\n- " . $action; } } } } // Check if response includes action guidance $state = $this->conversation_manager->get_conversation_state($conversation_id); if ($state['conversation_stage'] === 'action' && !$this->contains_action_guidance($ai_message)) { $enhanced_message = $this->add_action_guidance($enhanced_message, $settings); } return $enhanced_message; } /** * Get suggested actions tied to actual business information. * * @since 1.6.0 * @param int $conversation_id The conversation ID. * @param array $settings The chatbot settings. * @return array Array of suggested actions. */ private function get_business_aware_suggestions($conversation_id, $settings) { $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; $suggestions = array(); if ($chatbot_id > 0) { $business_info = $this->data_manager->get_business_info($chatbot_id); if (!empty($business_info)) { if (!empty($business_info['services'])) { $services = json_decode($business_info['services'], true); if (!empty($services) && is_array($services)) { $suggestions[] = 'Learn more about our services: ' . implode(', ', array_slice($services, 0, 3)); } } if (!empty($business_info['phone']) || !empty($business_info['email'])) { $contact_parts = array(); if (!empty($business_info['phone'])) { $contact_parts[] = 'call ' . $business_info['phone']; } if (!empty($business_info['email'])) { $contact_parts[] = 'email ' . $business_info['email']; } $suggestions[] = 'Get in touch: ' . implode(' or ', $contact_parts); } if (!empty($business_info['website'])) { $suggestions[] = 'Visit our website for more details: ' . $business_info['website']; } } } // Fallback to generic suggestions if no business info if (empty($suggestions)) { $suggestions = $this->conversation_manager->get_suggested_actions($conversation_id, $chatbot_id); } return $suggestions; } /** * Check if user message is a pricing-related query * * @since 1.5.6 * @param string $message The user message * @return bool True if pricing-related, false otherwise */ private function is_pricing_query($message) { $pricing_keywords = array( 'price', 'pricing', 'prices', 'cost', 'costs', 'costing', 'fee', 'fees', 'rate', 'rates', 'how much', 'how much does', 'how much do', 'what does it cost', 'what do they cost', 'afford', 'affordable', 'affordability', 'charge', 'charges', 'charging', 'pay', 'payment', 'payments', 'subscription', 'subscriptions', 'plan', 'plans', 'package', 'packages', 'tier', 'tiers', 'pricing tier' ); $message_lower = strtolower($message); foreach ($pricing_keywords as $keyword) { if (strpos($message_lower, $keyword) !== false) { return true; } } return false; } /** * Read workspace-synced knowledge (populated by the desktop app's * "Sync Knowledge" action) and format it as the authoritative system-prompt * context. Returns empty string when no rows exist for this chatbot, so the * caller can fall through to the legacy regex-crawler path. * * @param string $message The user message * @param int $chatbot_id The chatbot ID * @return string Formatted context string or empty */ private function get_workspace_synced_knowledge($message, $chatbot_id) { if (empty($chatbot_id)) { return ''; } global $wpdb; $table = $wpdb->prefix . 'a1ai_workspace_knowledge'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)); if ($table_exists !== $table) { return ''; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $rows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $table is built from $wpdb->prefix + a hardcoded suffix; table names cannot be bound via prepare(). "SELECT page_url, page_title, page_type, summary, key_facts, pricing_items FROM {$table} WHERE chatbot_id = %d ORDER BY id ASC", $chatbot_id ), ARRAY_A ); if (empty($rows)) { return ''; } $is_pricing = $this->is_pricing_query($message); $message_low = strtolower((string) $message); // Score each row for relevance to the user message via keyword overlap on // title + summary. Pricing queries automatically prioritize rows that have // pricing_items so we never miss a price answer when one exists. $scored = array(); foreach ($rows as $idx => $row) { $score = 0; $blob = strtolower($row['page_title'] . ' ' . $row['summary']); $tokens = preg_split('/[^a-z0-9]+/i', $message_low); if (is_array($tokens)) { foreach ($tokens as $tok) { if (strlen($tok) >= 4 && strpos($blob, $tok) !== false) { $score += 1; } } } $has_pricing = !empty($row['pricing_items']) && $row['pricing_items'] !== '[]'; if ($is_pricing && $has_pricing) { $score += 5; } // Importance boost: lift the site's main pages above blog posts so the // chatbot references pricing/services/etc. first. Additive (not absolute) // so a strongly-matching blog can still win a genuinely niche question. if (class_exists('A1AI_Content_Priority')) { $rank = A1AI_Content_Priority::importance_rank( isset($row['page_type']) ? $row['page_type'] : 'page', A1AI_Content_Priority::slug_from_url($row['page_url']), 0, $row['page_title'] ); if ($rank >= 2) { $score += 3; // key page (pricing, services, contact, home...) } elseif ($rank === 1) { $score += 1.5; // any other page } } $scored[] = array('row' => $row, 'score' => $score, 'has_pricing' => $has_pricing, 'idx' => $idx); } // Sort by score desc, keep top 5 (or all rows that have pricing on a pricing query). // Original order breaks ties so ranking stays deterministic. usort($scored, function ($a, $b) { return ($b['score'] <=> $a['score']) ?: ($a['idx'] <=> $b['idx']); }); $top_rows = array_slice($scored, 0, 5); $this->last_retrieval = array('tier' => 'workspace', 'count' => count($top_rows), 'semantic' => false); // Build the SITE KNOWLEDGE block. $context = "## SITE KNOWLEDGE (Workspace-synced — authoritative)\n"; $context .= "These are the canonical, hand-curated summaries of pages on this site. Use them as the source of truth and quote directly when relevant. Always include the markdown links.\n\n"; foreach ($top_rows as $entry) { $r = $entry['row']; // Escaped on the way into the prompt, matching class-a1ai-content-search.php. // These values are synced in from the workspace, so a crafted title or URL must // not be able to break out of the markdown link the model is told to reproduce. $title = esc_html( $r['page_title'] ); $url = esc_url( $r['page_url'] ); $context .= "[" . $title . "](" . $url . ")\n"; $context .= "Summary: " . esc_html( $r['summary'] ) . "\n"; if (!empty($r['key_facts'])) { $facts = json_decode($r['key_facts'], true); if (is_array($facts) && !empty($facts)) { $context .= "Key facts:\n"; foreach (array_slice($facts, 0, 8) as $fact) { $context .= " - " . esc_html( $fact ) . "\n"; } } } $context .= "\n"; } // Always include a complete PRICING block when ANY row has pricing_items — // pricing should never be missed, even on a non-keyword-matching question. $pricing_block = $this->format_workspace_pricing_block($rows); if (!empty($pricing_block)) { $context .= $pricing_block; } return $context; } /** * Format the ## PRICING (Official) block from all rows that have pricing_items. * Returns empty string when no rows have pricing. */ private function format_workspace_pricing_block($rows) { $items = array(); foreach ($rows as $row) { if (empty($row['pricing_items'])) { continue; } $decoded = json_decode($row['pricing_items'], true); if (!is_array($decoded) || empty($decoded)) { continue; } foreach ($decoded as $item) { if (!is_array($item)) { continue; } $items[] = array_merge( array('source_url' => $row['page_url'], 'source_title' => $row['page_title']), $item ); } } if (empty($items)) { return ''; } $block = "## PRICING (Official — Workspace-synced)\n"; $block .= "Use these prices verbatim when the user asks about cost. Always cite the source page link.\n\n"; foreach ($items as $item) { $name = isset($item['item']) ? $item['item'] : (isset($item['name']) ? $item['name'] : 'Item'); $price = isset($item['price']) ? $item['price'] : ''; $unit = isset($item['unit']) ? $item['unit'] : ''; $desc = isset($item['description']) ? $item['description'] : ''; // Escaped for the same reason as the SITE KNOWLEDGE block above: these values // are synced in from the workspace, so a crafted item must not break the prompt. $name = esc_html( $name ); $price = esc_html( $price ); $unit = esc_html( $unit ); $desc = esc_html( $desc ); $src = "[" . esc_html( $item['source_title'] ) . "](" . esc_url( $item['source_url'] ) . ")"; $line = "- **" . $name . "** — " . $price; if (!empty($unit)) { $line .= " " . $unit; } if (!empty($desc)) { $line .= " — " . $desc; } $line .= " (" . $src . ")\n"; $block .= $line; } $block .= "\n"; return $block; } /** * Get Content Awareness context for the user message * * @since 1.5.6 * @param string $message The user message * @param int $chatbot_id The chatbot ID * @return string Formatted context string or empty if not available */ private function get_content_awareness_context($message, $chatbot_id, $recent_turns = '') { // Default until a tier produces context; overwritten below. $this->last_retrieval = array('tier' => 'none', 'count' => 0, 'semantic' => false); // Workspace-synced knowledge takes priority — populated by the desktop // workspace's "Sync Knowledge" action and stored in wp_a1ai_workspace_knowledge. // When present, it's authoritative and replaces the regex-based crawler path. $workspace_context = $this->get_workspace_synced_knowledge($message, $chatbot_id); if (!empty($workspace_context)) { return $workspace_context; } // Check Premium first - if available and enabled, use full Content Awareness if (class_exists('A1AI_Content_Awareness_Manager') && class_exists('A1AI_Upgrade_Settings_Manager')) { $settings_manager = new A1AI_Upgrade_Settings_Manager(); if ($settings_manager->is_feature_enabled('content_awareness')) { // Use full Content Awareness system (Premium) $content_manager = new A1AI_Content_Awareness_Manager(); // Check if this is a pricing query $is_pricing = $this->is_pricing_query($message); // Search for relevant content $search_results = array(); if ($is_pricing) { // Search specifically for pricing content (uses tier2 table when Tier 2 is enabled) $search_results = $content_manager->search_content_with_pricing($message, 5); } else { // General content search (uses appropriate tier table based on settings) $search_results = $content_manager->get_content_suggestions($message, 3); } // Hybrid: blend in semantic (embeddings) results when enabled, so we catch // synonyms/paraphrases the keyword search misses. No-op when disabled. $semantic_contributed = false; if (method_exists($content_manager, 'search_content_semantic')) { $cap = $is_pricing ? 5 : 3; $semantic_results = $content_manager->search_content_semantic($message, $cap, $recent_turns); if (!empty($semantic_results)) { $search_results = $this->fuse_search_results($search_results, $semantic_results, $cap); $semantic_contributed = true; } } // Ensure all results have permalinks for clickable links foreach ($search_results as &$result) { $post_id = isset($result->ID) ? $result->ID : (isset($result->post_id) ? $result->post_id : 0); if ($post_id > 0 && !isset($result->permalink)) { $result->permalink = get_permalink($post_id); } if ($post_id > 0 && !isset($result->post_title) && isset($result->title)) { $result->post_title = $result->title; } } unset($result); // Break reference if (empty($search_results)) { return ''; } $this->last_retrieval = array('tier' => 'premium', 'count' => count($search_results), 'semantic' => $semantic_contributed); // Format the context if ($is_pricing) { return $this->format_pricing_context($search_results, $content_manager); } else { return $this->format_general_content_context($search_results); } } } // Fallback to basic WordPress search (Free version) return $this->get_basic_content_context($message, $chatbot_id); } /** * Fuse lexical + semantic result sets with Reciprocal Rank Fusion, dedupe by * post ID, adopt the richer fields (chunk summary / pricing), re-rank pages * above posts, and truncate. Both inputs are stdClass rows keyed on ->ID. * * @param array $lexical * @param array $semantic * @param int $limit * @return array */ private function fuse_search_results($lexical, $semantic, $limit) { $k = 60; // RRF constant $scores = array(); $by_id = array(); foreach (array($lexical, $semantic) as $list) { if (!is_array($list)) { continue; } $rank = 0; foreach ($list as $item) { if (!is_object($item)) { continue; } $id = isset($item->ID) ? (int) $item->ID : (isset($item->post_id) ? (int) $item->post_id : 0); if ($id <= 0) { continue; } $rank++; $scores[$id] = (isset($scores[$id]) ? $scores[$id] : 0) + (1.0 / ($k + $rank)); if (!isset($by_id[$id])) { $by_id[$id] = $item; } else { // Merge: keep the first object but adopt fields it's missing. $existing = $by_id[$id]; foreach (array('summary', 'pricing_info', 'post_type', 'post_name', 'post_title') as $field) { if (empty($existing->$field) && !empty($item->$field)) { $existing->$field = $item->$field; } } } } } $fused = array(); foreach ($by_id as $id => $obj) { // Fused RRF score drives ordering; keep it >= 0.5 so any later relevance gate passes. $obj->relevance_score = 0.5 + (isset($scores[$id]) ? $scores[$id] : 0); $fused[] = $obj; } usort($fused, function ($a, $b) { return $b->relevance_score <=> $a->relevance_score; }); // Business-rule rerank: important pages ahead of blog posts (stable within tier). if (class_exists('A1AI_Content_Priority')) { A1AI_Content_Priority::sort_objects($fused); } return array_slice($fused, 0, $limit); } /** * Build a short "recent user turns" string from conversation history for * multi-turn query resolution (e.g. "the pro plan" after a plans question). * Excludes the latest turn (that's the current $message, added by the caller). * * @param array $history Rows of ['role'=>..,'content'=>..]. * @param int $max Max prior user turns to include. * @return string */ private function recent_user_turns($history, $max = 2) { if (empty($history) || !is_array($history)) { return ''; } $users = array(); foreach ($history as $h) { if (isset($h['role']) && $h['role'] === 'user' && !empty($h['content'])) { $users[] = (string) $h['content']; } } if (count($users) <= 1) { return ''; } array_pop($users); // drop the current turn return trim(implode(' ', array_slice($users, -$max))); } /** * Get basic content context using WordPress native search (Free version) * * @since 1.5.6 * @param string $message The user message * @param int $chatbot_id The chatbot ID * @return string Formatted context string or empty if not available */ private function get_basic_content_context($message, $chatbot_id) { // Load basic content search class if not already loaded if (!class_exists('A1AI_Content_Search')) { $search_file = plugin_dir_path(dirname(__FILE__)) . 'includes/class-a1ai-content-search.php'; if (file_exists($search_file)) { require_once $search_file; } else { return ''; } } // Initialize basic content search $content_search = new A1AI_Content_Search(); // Check if this is a pricing query $is_pricing = $content_search->is_pricing_query($message); // Search for relevant content $search_results = $content_search->get_content_suggestions($message, $is_pricing ? 5 : 3); if (empty($search_results)) { return ''; } $this->last_retrieval = array('tier' => 'basic', 'count' => count($search_results), 'semantic' => false); // Format the context using basic search formatter return $content_search->format_results_for_prompt($search_results, $is_pricing); } /** * Format pricing context for AI prompt * * @since 1.5.6 * @param array $content_results Search results with pricing information * @param A1AI_Content_Awareness_Manager $content_manager Content Awareness Manager instance * @return string Formatted pricing context */ private function format_pricing_context($content_results, $content_manager = null) { $context = "PRICING INFORMATION FROM WEBSITE:\n\n"; $max_content_length = 3000; $current_length = strlen($context); foreach ($content_results as $result) { $post_id = isset($result->ID) ? $result->ID : (isset($result->post_id) ? $result->post_id : 0); $title = isset($result->post_title) ? $result->post_title : (isset($result->title) ? $result->title : ''); $permalink = $post_id > 0 ? get_permalink($post_id) : ''; if (empty($title) || empty($permalink)) { continue; } $entry = "[" . esc_html($title) . "](" . esc_url($permalink) . ")\n"; // Get pricing information $pricing_info = null; if (isset($result->pricing_info) && !empty($result->pricing_info)) { $pricing_info = json_decode($result->pricing_info, true); } elseif ($post_id > 0 && $content_manager) { $pricing_info = $content_manager->get_pricing_from_content($post_id); } if (!empty($pricing_info) && is_array($pricing_info)) { if (!empty($pricing_info['has_pricing'])) { if (!empty($pricing_info['price_ranges']['min']) && !empty($pricing_info['price_ranges']['max'])) { $min = number_format($pricing_info['price_ranges']['min'], 2); $max = number_format($pricing_info['price_ranges']['max'], 2); if ($min == $max) { $entry .= "Price: $" . $min . "\n"; } else { $entry .= "Price Range: $" . $min . " - $" . $max . "\n"; } } elseif (!empty($pricing_info['price_ranges']['min'])) { $entry .= "Starting at: $" . number_format($pricing_info['price_ranges']['min'], 2) . "\n"; } if (!empty($pricing_info['prices']) && is_array($pricing_info['prices'])) { $entry .= "Pricing Details:\n"; foreach ($pricing_info['prices'] as $price_item) { if (!empty($price_item['amount'])) { $amount = number_format($price_item['amount'], 2); $currency = !empty($price_item['currency']) ? $price_item['currency'] : 'USD'; $context_item = "- $" . $amount . " " . $currency; if (!empty($price_item['context'])) { $context_item .= " (" . $price_item['context'] . ")"; } if (!empty($price_item['pricing_model'])) { $model = ucfirst(str_replace('_', ' ', $price_item['pricing_model'])); $context_item .= " - " . $model; } $entry .= $context_item . "\n"; } } } if (!empty($pricing_info['pricing_note'])) { $entry .= "Pricing Note: " . $pricing_info['pricing_note'] . "\n"; } elseif (!empty($pricing_info['pricing_model'])) { $model = ucfirst(str_replace('_', ' ', $pricing_info['pricing_model'])); $entry .= "Pricing Model: " . $model . "\n"; } if (!empty($pricing_info['has_free_tier'])) { $entry .= "Note: Free tier available\n"; } if (!empty($pricing_info['has_discounts'])) { $entry .= "Note: Discounts may be available\n"; } } } if (!empty($result->summary)) { $summary = wp_trim_words($result->summary, 60); $entry .= "Summary: " . $summary . "\n"; } $entry .= "\n"; // Check length cap before adding this entry if ($current_length + strlen($entry) > $max_content_length) { break; } $context .= $entry; $current_length += strlen($entry); } $context .= "PRICING RESPONSE GUIDELINES:\n"; $context .= "- Always reference the specific pages listed above and include clickable links in markdown format: [Page Title](URL)\n"; $context .= "- Link the dedicated pricing or service page, not a blog post that merely mentions a price in passing.\n"; $context .= "- If specific dollar amounts are shown, state them clearly (e.g., \"Starting at \$199\")\n"; $context .= "- If pricing is listed as custom or requires a quote, tell the user to contact the business and link to the relevant page\n"; $context .= "- If multiple pricing options exist, list them clearly\n"; $context .= "- If the pages above show actual prices, always reference them. If they're clearly related but don't state a price, say pricing isn't published on the site and point the user to the contact/quote page — don't invent a number.\n"; return $context; } /** * Format general content context for AI prompt * * @since 1.5.6 * @param array $content_results Search results * @return string Formatted content context */ private function format_general_content_context($content_results) { $context = "RELEVANT CONTENT FROM WEBSITE:\n"; $context .= "(Ordered by importance — prefer the main pages listed first; use blog posts only for topics the main pages don't cover.)\n\n"; $max_content_length = 2000; $current_length = strlen($context); foreach ($content_results as $result) { $post_id = isset($result->ID) ? $result->ID : (isset($result->post_id) ? $result->post_id : 0); $title = isset($result->post_title) ? $result->post_title : (isset($result->title) ? $result->title : ''); $permalink = $post_id > 0 ? get_permalink($post_id) : ''; $summary = isset($result->summary) ? $result->summary : ''; if (empty($title) || empty($permalink)) { continue; } $entry = "[" . esc_html($title) . "](" . esc_url($permalink) . ")\n"; if (!empty($summary)) { $entry .= wp_trim_words($summary, 60) . "\n"; } $entry .= "\n"; if ($current_length + strlen($entry) > $max_content_length) { break; } $context .= $entry; $current_length += strlen($entry); } return $context; } /** * Check if response contains action guidance. * * @since 1.4.0 * @param string $message The message to check. * @return bool True if contains action guidance. */ private function contains_action_guidance($message) { $action_keywords = array( // Contact-related 'contact', 'call', 'email', 'reach out', 'get in touch', 'phone', 'message us', // Purchase-related 'purchase', 'buy', 'order', 'sign up', 'subscribe', 'enroll', 'register', // Scheduling-related 'schedule', 'book', 'appointment', 'consultation', 'reserve', // Discovery-related 'learn more', 'find out', 'discover', 'explore', 'visit', // CTA indicators 'click here', 'book now', 'get started', 'try now', 'view our', 'check out', 'see our', // URL patterns 'http://', 'https://', ); $message_lower = strtolower($message); foreach ($action_keywords as $keyword) { if (strpos($message_lower, $keyword) !== false) { return true; } } return false; } /** * Add action guidance to response. * * @since 1.4.0 * @param string $message The original message. * @param array $settings The chatbot settings. * @return string The message with action guidance. */ private function add_action_guidance($message, $settings) { // First check primary_action from chatbot settings (most specific) $primary_action = isset($settings['primary_action']) ? trim($settings['primary_action']) : ''; if (!empty($primary_action)) { $message .= "\n\n" . $primary_action; return $message; } // Fallback: scan custom instructions for CTA content $chatbot_id = isset($settings['chatbot_id']) ? intval($settings['chatbot_id']) : 0; $custom_instructions = $this->data_manager->get_custom_instructions($chatbot_id, 'general'); $action_guidance = ''; foreach ($custom_instructions as $instruction) { if (strpos(strtolower($instruction['instruction_content']), 'call to action') !== false || strpos(strtolower($instruction['instruction_content']), 'next step') !== false) { $action_guidance = $instruction['instruction_content']; break; } } if (!empty($action_guidance)) { $message .= "\n\n" . $action_guidance; } else { $message .= "\n\nHow can I help you take the next step? Would you like to learn more about our services or get in touch?"; } return $message; } }