Plugin Directory

Changeset 3833232


Ignore:
Timestamp:
11/29/2026 03:15:43 PM (less than one hour ago)
Author:
ohmevents
Message:

3.1.0: Connect ShareAI, WordPress Connectors, keyword search fallback, new screenshots

Location:
aiohm-knowledge-assistant
Files:
13 added
6 deleted
42 edited
1 copied

Legend:

Unmodified
Added
Removed
  • aiohm-knowledge-assistant/tags/3.1.0/README.md

    r3801412 r3833232  
    1313- PDF, CSV, TXT and JSON document import
    1414- Brand voice settings
    15 - AI providers: OpenAI, Claude, Gemini, Groq and ShareAI
     15- AI providers: ShareAI and Ollama, plus Google Gemini, OpenAI and Anthropic Claude when your site connects them in WordPress 7 Connectors
    1616- Local AI with Ollama, so content can stay on your own server
    17 - MCP endpoint, so MCP clients such as Claude Desktop can query your knowledge base
     17- MCP endpoint, so desktop and mobile MCP clients can query your knowledge base
    1818- White-label mode for agencies
    1919
    … …  
    2222- WordPress 6.2 or later
    2323- PHP 7.4 or later
    24 - An API key for one AI provider, or a reachable Ollama server
     24- A ShareAI connection (Connect ShareAI), a Gemini API key, or a local Ollama server
    2525
    2626## Install
    … …  
    3838composer install --no-dev --optimize-autoloader
    3939```
     40
     41## ShareAI data and deletion
     42
     43"Connect ShareAI" links a ShareAI account to one WordPress site with OAuth (authorization code and PKCE, public client, no shared secret).
     44
     45- **What the site stores:** encrypted access and refresh tokens, their expiry, the approved scopes, the ShareAI account name and identifier, the last billing stop ShareAI reported, and a daily question count. All of it lives in the site's own WordPress database (`aiohm_kb_shareai_connection`, `aiohm_kb_shareai_daily_usage`). Your ShareAI password never reaches the site.
     46- **What the relay sees:** ShareAI returns to `https://www.ohm.events/wp-json/aiohm-kb/v1/shareai/relay` (OHM Events Agency, the maker of this plugin), which shows the destination site and sends the browser back to it with ShareAI's one-time code. The relay stores nothing and never sees a token. The code is useless without the PKCE verifier that stays on the site.
     47- **How to delete it:** in WordPress, open AIOHM, then Settings, and click Disconnect on the ShareAI card. The plugin revokes the tokens at ShareAI and deletes them from the site. Deleting the plugin does the same. You can also remove the app from your ShareAI account at any time.
     48- **Billing:** requests are charged to the connected ShareAI wallet at the model price plus a 10% builder markup for AIOHM, shown by ShareAI before approval.
    4049
    4150## Contributing
  • aiohm-knowledge-assistant/tags/3.1.0/aiohm-knowledge-assistant.php

    r3801412 r3833232  
    44 * Plugin URI:  https://knowledge.aiohm.app/
    55 * Description: WordPress 7.0-ready AI knowledge assistant with intelligent chatbot, brand voice alignment, privacy controls, and multi-provider AI support.
    6  * Version:     3.0.0
     6 * Version:     3.1.0
    77 * Author:      OHM Events Agency
    88 * Author URI:  https://www.ohm.events
    … …  
    2929 */
    3030
    31 define("AIOHM_KB_VERSION", "3.0.0");
     31define("AIOHM_KB_VERSION", "3.1.0");
    3232define("AIOHM_KB_PLUGIN_FILE", __FILE__);
    3333define("AIOHM_KB_PLUGIN_DIR", plugin_dir_path(__FILE__));
    … …  
    278278            "shortcode-private-assistant.php",
    279279            "frontend-widget.php",
     280            "shareai-connect.php",
    280281        ];
    281282
    … …  
    289290                require_once $file_path;
    290291            }
     292        }
     293
     294        if (class_exists("AIOHM_KB_ShareAI_Connect")) {
     295            AIOHM_KB_ShareAI_Connect::init();
    291296        }
    292297
    … …  
    438443            "external_api_consent" => true,
    439444
    440             "openai_api_key" => "",
     445            "shareai_model" => "deepseek/deepseek-v4-flash",
    441446            "gemini_api_key" => "",
    442             "claude_api_key" => "",
    443             "shareai_api_key" => "",
    444             "shareai_model" => "llama4:17b-scout-16e-instruct-fp16",
    445             "groq_api_key" => "",
    446             "groq_model" => "llama-3.3-70b-versatile",
    447447            "private_llm_server_url" => "",
    448448            "private_llm_model" => "llama2",
    449             "default_ai_provider" => "ollama",
     449            "default_ai_provider" => "shareai",
    450450
    451451            "pro_features" => [
    … …  
    467467                "qa_temperature" => "0.8",
    468468                "business_name" => get_bloginfo("name"),
     469                // Muse is the plugin's ambassador: the public assistant's
     470                // default name and face. Site owners can rename her.
     471                "assistant_name" => "Muse",
     472                "ai_avatar" => AIOHM_KB_PLUGIN_URL . "assets/images/muse-avatar.webp",
    469473            ],
    470474
    … …  
    511515        }
    512516
    513         $encrypted_api_keys = [
    514             "openai_api_key",
    515             "gemini_api_key",
    516             "claude_api_key",
    517             "groq_api_key",
    518         ];
     517        $encrypted_api_keys = ["gemini_api_key"];
    519518        foreach ($encrypted_api_keys as $key) {
    520519            if (!empty($settings[$key])) {
    … …  
    528527        }
    529528
    530         if (!empty($settings["shareai_api_key"])) {
    531             if (
    532                 strlen($settings["shareai_api_key"]) > 100 ||
    533                 preg_match("/[+\/=]/", $settings["shareai_api_key"])
    534             ) {
    535                 $current_settings = get_option("aiohm_kb_settings", []);
    536                 // The key is corrupted (looks like base64), clear it from both the current settings and the database option.
    537                 $current_settings["shareai_api_key"] = "";
     529        // ShareAI now runs only through Connect ShareAI. A key pasted in an
     530        // earlier version is no longer used, so it is removed, not kept.
     531        if (array_key_exists("shareai_api_key", $settings)) {
     532            $current_settings = get_option("aiohm_kb_settings", []);
     533            if (is_array($current_settings) && array_key_exists("shareai_api_key", $current_settings)) {
     534                unset($current_settings["shareai_api_key"]);
    538535                update_option("aiohm_kb_settings", $current_settings);
    539                 $settings["shareai_api_key"] = "";
     536            }
     537            unset($settings["shareai_api_key"]);
     538        }
     539
     540        return self::migrate_removed_ai_providers($settings);
     541    }
     542
     543    /**
     544     * Point settings that still name a removed AI provider (OpenAI, Claude,
     545     * Groq) at a supported one. This runs on read only: nothing is written
     546     * back and stored API keys stay in the database untouched.
     547     *
     548     * @param array $settings Merged plugin settings.
     549     * @return array Settings with supported provider and model values.
     550     */
     551    private static function migrate_removed_ai_providers($settings)
     552    {
     553        if (
     554            !function_exists("aiohm_kb_resolve_ai_provider") ||
     555            !function_exists("aiohm_kb_ai_provider_ids")
     556        ) {
     557            return $settings;
     558        }
     559
     560        $stored_provider = (string) ($settings["default_ai_provider"] ?? "");
     561        $provider = null;
     562        if ($stored_provider !== "") {
     563            // An empty value keeps its existing meaning: pick the first
     564            // provider that is set up at request time.
     565            if (in_array($stored_provider, aiohm_kb_ai_provider_ids(), true)) {
     566                $provider = $stored_provider;
     567            } else {
     568                // A removed provider (OpenAI, Claude, Groq) moves to ShareAI,
     569                // or to Gemini when only a Gemini key is set. Ollama is left
     570                // out: it ships enabled at localhost, which a hosted site
     571                // rarely runs.
     572                $provider =
     573                    function_exists("aiohm_kb_gemini_available") &&
     574                    !aiohm_kb_shareai_available($settings) &&
     575                    aiohm_kb_gemini_available($settings)
     576                        ? "gemini"
     577                        : "shareai";
     578            }
     579            $settings["default_ai_provider"] = $provider;
     580        }
     581
     582        foreach (["mirror_mode", "muse_mode"] as $mode) {
     583            if (!isset($settings[$mode]) || !is_array($settings[$mode])) {
     584                continue;
     585            }
     586            $mode_model = (string) ($settings[$mode]["ai_model"] ?? "");
     587            if ($mode_model === "") {
     588                continue;
     589            }
     590            if (0 === strpos($mode_model, "shareai")) {
     591                // ShareAI always follows the shareai_model setting.
     592                $settings[$mode]["ai_model"] = aiohm_kb_default_model_for_provider("shareai", $settings);
     593            } elseif (!aiohm_kb_is_supported_ai_model($mode_model)) {
     594                if (null === $provider) {
     595                    $provider = aiohm_kb_resolve_ai_provider("", $settings);
     596                }
     597                $settings[$mode]["ai_model"] = aiohm_kb_default_model_for_provider($provider, $settings);
    540598            }
    541599        }
    … …  
    9791037                "aiohm_app_email" => "",
    9801038
    981                 "openai_api_key" => "",
     1039                "shareai_model" => "deepseek/deepseek-v4-flash",
    9821040                "gemini_api_key" => "",
    983                 "claude_api_key" => "",
    984                 "shareai_api_key" => "",
    985                 "shareai_model" => "llama4:17b-scout-16e-instruct-fp16",
    9861041                "private_llm_server_url" => "",
    9871042                "private_llm_model" => "llama2",
    988                 "default_ai_provider" => "",
     1043                "default_ai_provider" => "shareai",
    9891044
    9901045                "chat_enabled" => true,
    … …  
    11271182     *
    11281183     * @param string $api_key API key to validate
    1129      * @param string $provider Provider type (openai, claude, gemini, shareai)
     1184     * @param string $provider Provider type (shareai, gemini)
    11301185     * @return string|WP_Error Sanitized API key or WP_Error if invalid
    11311186     */
    … …  
    11481203
    11491204        switch ($provider) {
    1150             case "openai":
    1151                 if (!preg_match('/^sk-[a-zA-Z0-9]{20,}$/', $sanitized)) {
     1205            case "shareai":
     1206                $sanitized = preg_replace("/[^a-zA-Z0-9\-]/", "", $sanitized);
     1207                if (strlen($sanitized) < 10) {
    11521208                    return new WP_Error(
    1153                         "invalid_openai_key",
     1209                        "invalid_shareai_key",
    11541210                        __(
    1155                             "Invalid OpenAI API key format.",
    1156                             "aiohm-knowledge-assistant",
    1157                         ),
    1158                     );
    1159                 }
    1160                 break;
    1161             case "claude":
    1162                 if (!preg_match('/^sk-ant-[a-zA-Z0-9_-]{90,}$/', $sanitized)) {
    1163                     return new WP_Error(
    1164                         "invalid_claude_key",
    1165                         __(
    1166                             "Invalid Claude API key format.",
     1211                            "ShareAI API key too short.",
    11671212                            "aiohm-knowledge-assistant",
    11681213                        ),
    … …  
    11811226                }
    11821227                break;
    1183             case "shareai":
    1184                 $sanitized = preg_replace("/[^a-zA-Z0-9\-]/", "", $sanitized);
    1185                 if (strlen($sanitized) < 10) {
    1186                     return new WP_Error(
    1187                         "invalid_shareai_key",
    1188                         __(
    1189                             "ShareAI API key too short.",
    1190                             "aiohm-knowledge-assistant",
    1191                         ),
    1192                     );
    1193                 }
    1194                 break;
    1195             case "groq":
    1196                 if (!preg_match('/^gsk_[a-zA-Z0-9]{50,}$/', $sanitized)) {
    1197                     return new WP_Error(
    1198                         "invalid_groq_key",
    1199                         __(
    1200                             "Invalid Groq API key format.",
    1201                             "aiohm-knowledge-assistant",
    1202                         ),
    1203                     );
    1204                 }
    1205                 break;
    12061228        }
    12071229
    … …  
    13701392
    13711393        $patterns = [
    1372             "/sk-[a-zA-Z0-9_-]{20,}/" => "OPENAI_API_KEY_HIDDEN",
    1373             "/pk-[a-zA-Z0-9_-]{20,}/" => "OPENAI_PUBLIC_KEY_HIDDEN",
    1374 
    1375             "/sk-ant-[a-zA-Z0-9_-]{90,}/" => "CLAUDE_API_KEY_HIDDEN",
     1394            "/sk-[a-zA-Z0-9_-]{20,}/" => "SECRET_KEY_HIDDEN",
     1395            "/pk-[a-zA-Z0-9_-]{20,}/" => "PUBLIC_KEY_HIDDEN",
     1396
     1397            "/sk-ant-[a-zA-Z0-9_-]{90,}/" => "SECRET_KEY_HIDDEN",
    13761398
    13771399            "/AIza[a-zA-Z0-9_-]{35}/" => "GEMINI_API_KEY_HIDDEN",
  • aiohm-knowledge-assistant/tags/3.1.0/assets/css/aiohm-admin-settings.css

    r3545079 r3833232  
    737737                padding: 8px 16px;
    738738        }
     739
     740/* Run on ShareAI card (2026-11-19) */
     741.aiohm-shareai-connect { margin: 16px 0 24px; }
     742.aiohm-shareai-connect__head { display: flex; align-items: flex-start; gap: 16px; }
     743.aiohm-shareai-connect__head h2 { margin: 0 0 4px; font-size: 18px; color: #193f10; letter-spacing: 0; }
     744.aiohm-shareai-connect__head > div { flex: 1; min-width: 0; }
     745/* Official ShareAI icon: its own corners, never cropped or rounded (shareai.now/brand-guidance). */
     746.aiohm-shareai-connect__icon { display: block; width: 40px; height: 40px; flex-shrink: 0; }
     747.aiohm-shareai-connect__status { flex-shrink: 0; font-size: 12px; font-weight: 700; padding: 4px 10px; border-radius: 999px; background: #ebebeb; color: #444; white-space: nowrap; }
     748.aiohm-shareai-connect__status.is-on { background: #e4efe0; color: #193f10; }
     749.aiohm-shareai-connect__status.is-off { background: #fbe9e7; color: #8a1f11; }
     750.aiohm-shareai-connect__facts { margin: 16px 0; padding-left: 20px; list-style: disc; line-height: 1.6; }
     751.aiohm-shareai-connect__warn { color: #8a1f11; }
     752.aiohm-shareai-connect__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 16px 0; }
     753.aiohm-shareai-connect__stats > div { border: 1px solid #ddd; border-radius: 8px; padding: 10px 12px; }
     754.aiohm-shareai-connect__stats dt { font-size: 11px; font-weight: 700; text-transform: uppercase; color: #666; }
     755.aiohm-shareai-connect__stats dd { margin: 4px 0 0; font-weight: 600; overflow-wrap: anywhere; }
     756.aiohm-shareai-connect__form label { display: block; font-weight: 600; margin-bottom: 4px; }
     757.aiohm-shareai-connect__form select, .aiohm-shareai-connect__form input[type=number] { max-width: 420px; width: 100%; }
     758.aiohm-shareai-connect__form .description { display: block; margin-top: 4px; }
     759.aiohm-shareai-connect__actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
     760/* ShareAI's button pattern, same spec as the AIOHM platform's ShareAI buttons:
     761   white surface, warm border, official 32px icon beside the label, 50px tall, visible focus. */
     762.aiohm-shareai-btn-official { display: inline-flex; align-items: center; justify-content: center; gap: 16px; min-height: 50px; box-sizing: border-box; padding: 9px 20px 9px 16px; border: 1px solid #e2d9cc; border-radius: 9px; background: #fff; color: #24201a; box-shadow: 0 3px 12px rgba(0, 0, 0, .067); font-size: 14px; font-weight: 650; line-height: 1.3; letter-spacing: 0; text-decoration: none; transition: border-color .15s ease, box-shadow .15s ease; }
     763.aiohm-shareai-btn-official:hover { border-color: #ffb07a; color: #24201a; box-shadow: 0 4px 14px rgba(0, 0, 0, .12); }
     764.aiohm-shareai-btn-official:focus-visible { outline: 2px solid #ff9a4c; outline-offset: 2px; color: #24201a; box-shadow: none; }
     765.aiohm-shareai-btn-official img { display: block; flex-shrink: 0; width: 32px; height: 32px; }
     766@media (prefers-reduced-motion: reduce) { .aiohm-shareai-btn-official { transition: none; } }
     767.aiohm-shareai-connect__disconnect { color: #8a1f11 !important; }
  • aiohm-knowledge-assistant/tags/3.1.0/assets/css/aiohm-provider-icons.css

    r3376955 r3833232  
    1212}
    1313
    14 /* 6-Column Grid Layout for all providers */
     14/* 3-column grid layout for all providers */
    1515.aiohm-provider-grid {
    1616        display: grid;
    17         grid-template-columns: repeat(6, 1fr);
     17        /* Tiles share one row and wrap only when the box runs out of room. */
     18        grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
     19        /* Its row is a flex container: take the full width, or the grid shrinks to one tile. */
     20        flex: 1 1 100%;
     21        width: 100%;
    1822        gap: 12px;
    1923        margin: 15px 0;
    20 }
    21 
    22 
    23 @media (max-width: 1400px) {
    24         .aiohm-provider-grid {
    25                 grid-template-columns: repeat(3, 1fr);
    26         }
    27 }
    28 
    29 @media (max-width: 1000px) {
    30         .aiohm-provider-grid {
    31                 grid-template-columns: repeat(2, 1fr);
    32         }
    3324}
    3425
    … …  
    125116
    126117/* Provider-specific icon styling */
    127 .aiohm-provider-option[data-provider="openai"] .aiohm-provider-icon {
    128         border-radius: 8px;
    129         overflow: hidden;
    130 }
    131 
    132118.aiohm-provider-option[data-provider="google"] .aiohm-provider-icon {
    133119        border-radius: 50%;
    134         overflow: hidden;
    135 }
    136 
    137 .aiohm-provider-option[data-provider="anthropic"] .aiohm-provider-icon {
    138         border-radius: 8px;
    139120        overflow: hidden;
    140121}
    … …  
    328309        outline-offset: 2px;
    329310}
     311/* The official ShareAI icon carries its own corners; rounding it would crop them. */
     312.aiohm-provider-icon img[src*="shareai-icon"] {
     313        border-radius: 0;
     314}
  • aiohm-knowledge-assistant/tags/3.1.0/assets/js/aiohm-admin-modes.js

    r3545079 r3833232  
    400400        const apiValue = $('#' + targetInput).val();
    401401       
    402         // Special handling for ShareAI - save both API key and model
    403         if (apiType === 'shareai') {
    404             const selectedModel = $('#shareai_model').val();
    405            
    406             if (!apiValue.trim()) {
    407                 showAdminNotice('Please enter an API key before saving.', 'warning');
    408                 return;
    409             }
    410            
    411             if (!selectedModel) {
    412                 showAdminNotice('Please select a model before saving.', 'warning');
    413                 return;
    414             }
    415            
    416             // Disable button and show loading state
    417             $btn.prop('disabled', true).text('Saving...');
    418            
    419             // Save API key first, then model
    420             let apiSaveCompleted = false;
    421             let modelSaveCompleted = false;
    422             let apiSaveSuccess = false;
    423             let modelSaveSuccess = false;
    424             let apiSaveMessage = '';
    425             let modelSaveMessage = '';
    426            
    427             function checkBothSavesComplete() {
    428                 if (apiSaveCompleted && modelSaveCompleted) {
    429                     // Re-enable button and restore original text
    430                     $btn.prop('disabled', false).text(originalText);
    431                    
    432                     if (apiSaveSuccess && modelSaveSuccess) {
    433                         // Success state
    434                         $btn.addClass('success');
    435                         showAdminNotice('ShareAI settings saved successfully!', 'success');
    436                        
    437                         // Now display the model information
    438                         updateModelInfo(selectedModel);
    439                        
    440                         // Reset button state after 2 seconds
    441                         setTimeout(function() {
    442                             $btn.removeClass('success');
    443                         }, 2000);
    444                     } else {
    445                         const errorMessages = [];
    446                         if (!apiSaveSuccess) errorMessages.push(apiSaveMessage);
    447                         if (!modelSaveSuccess) errorMessages.push(modelSaveMessage);
    448                         showAdminNotice('Error: ' + errorMessages.join(', '), 'error');
    449                     }
    450                 }
    451             }
    452            
    453             // Save API key
    454             $.post(config.ajax_url, {
    455                 action: 'aiohm_save_individual_api_key',
    456                 nonce: config.nonce || $('#aiohm_nonce').val() || $('[name*="nonce"]').val(),
    457                 api_type: 'shareai',
    458                 setting_name: 'shareai_api_key',
    459                 api_value: apiValue
    460             }).done(function(response) {
    461                 apiSaveSuccess = response.success;
    462                 apiSaveMessage = response.data?.message || 'Could not save API key';
    463             }).fail(function() {
    464                 apiSaveSuccess = false;
    465                 apiSaveMessage = 'Server error saving API key';
    466             }).always(function() {
    467                 apiSaveCompleted = true;
    468                 checkBothSavesComplete();
    469             });
    470            
    471             // Save model selection
    472             $.post(config.ajax_url, {
    473                 action: 'aiohm_save_individual_api_key',
    474                 nonce: config.nonce || $('#aiohm_nonce').val() || $('[name*="nonce"]').val(),
    475                 api_type: 'shareai_model',
    476                 setting_name: 'shareai_model',
    477                 api_value: selectedModel
    478             }).done(function(response) {
    479                 modelSaveSuccess = response.success;
    480                 modelSaveMessage = response.data?.message || 'Could not save model';
    481             }).fail(function() {
    482                 modelSaveSuccess = false;
    483                 modelSaveMessage = 'Server error saving model';
    484             }).always(function() {
    485                 modelSaveCompleted = true;
    486                 checkBothSavesComplete();
    487             });
    488            
    489             return; // Exit early for ShareAI
    490         }
    491402       
    492403        // Standard handling for other API providers
    … …  
    502413        let settingName;
    503414        switch(apiType) {
    504             case 'openai':
    505                 settingName = 'openai_api_key';
    506                 break;
    507415            case 'gemini':
    508416                settingName = 'gemini_api_key';
    509                 break;
    510             case 'claude':
    511                 settingName = 'claude_api_key';
    512417                break;
    513418            case 'ollama':
  • aiohm-knowledge-assistant/tags/3.1.0/assets/js/aiohm-admin-settings.js

    r3545079 r3833232  
    116116        // Map key types to setting names
    117117        const settingMap = {
    118             'shareai': 'shareai_api_key',
    119             'openai': 'openai_api_key',
    120118            'gemini': 'gemini_api_key',
    121             'claude': 'claude_api_key',
    122             'groq': 'groq_api_key',
    123119            'ollama': 'private_llm_server_url'
    124120        };
    … …  
    322318       
    323319        // Update breakdown table
    324         const providers = ['openai', 'gemini', 'claude', 'shareai'];
     320        const providers = ['shareai', 'gemini', 'ollama'];
    325321        providers.forEach(provider => {
    326322            const providerData = data.providers?.[provider] || {};
  • aiohm-knowledge-assistant/tags/3.1.0/includes/ai-gpt-client.php

    r3801374 r3833232  
    22/**
    33 * AI client for multi-provider API requests
    4  * Handles OpenAI, Google Gemini, Claude, and ShareAI integrations
     4 * Handles ShareAI, Google Gemini and Ollama integrations
    55 */
    66if ( ! defined( 'ABSPATH' ) ) {
    77        exit;
     8}
     9
     10if ( ! function_exists( 'aiohm_kb_ai_provider_ids' ) ) {
     11        /**
     12         * The supported AI providers, in display and fallback order.
     13         *
     14         * @return array Provider IDs.
     15         */
     16        function aiohm_kb_ai_provider_ids() {
     17                return array( 'shareai', 'gemini', 'ollama', 'openai', 'anthropic' );
     18        }
     19}
     20
     21if ( ! function_exists( 'aiohm_kb_wp_connector_provider_ids' ) ) {
     22        /**
     23         * Providers AIOHM reaches only through WordPress Connectors and the
     24         * WordPress AI Client: their keys live in WordPress, never in AIOHM.
     25         *
     26         * @return array Provider IDs.
     27         */
     28        function aiohm_kb_wp_connector_provider_ids() {
     29                return array( 'openai', 'anthropic' );
     30        }
     31}
     32
     33if ( ! function_exists( 'aiohm_kb_wp_connector_provider_available' ) ) {
     34        /**
     35         * A WordPress Connector provider is usable when WordPress has the AI
     36         * Client and the connector has a key.
     37         *
     38         * @param string $provider openai or anthropic.
     39         * @return bool
     40         */
     41        function aiohm_kb_wp_connector_provider_available( $provider ) {
     42                return function_exists( 'wp_ai_client_prompt' )
     43                        && in_array( $provider, aiohm_kb_wp_connector_provider_ids(), true )
     44                        && function_exists( 'aiohm_kb_is_wp_ai_connector_configured' )
     45                        && aiohm_kb_is_wp_ai_connector_configured( $provider );
     46        }
     47}
     48
     49if ( ! function_exists( 'aiohm_kb_shareai_available' ) ) {
     50        /**
     51         * ShareAI is usable once the site owner has connected a ShareAI account.
     52         *
     53         * @param array $settings Plugin settings.
     54         * @return bool
     55         */
     56        function aiohm_kb_shareai_available( $settings ) {
     57                return class_exists( 'AIOHM_KB_ShareAI_Connect' ) && AIOHM_KB_ShareAI_Connect::is_connected();
     58        }
     59}
     60
     61if ( ! function_exists( 'aiohm_kb_gemini_available' ) ) {
     62        /**
     63         * Gemini is usable with a saved API key or a WordPress Connector key.
     64         *
     65         * @param array $settings Plugin settings.
     66         * @return bool
     67         */
     68        function aiohm_kb_gemini_available( $settings ) {
     69                return ! empty( $settings['gemini_api_key'] )
     70                        || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) );
     71        }
     72}
     73
     74if ( ! function_exists( 'aiohm_kb_ollama_available' ) ) {
     75        /**
     76         * Ollama is usable when it is enabled and has a server URL.
     77         *
     78         * @param array $settings Plugin settings.
     79         * @return bool
     80         */
     81        function aiohm_kb_ollama_available( $settings ) {
     82                $pro_features = isset( $settings['pro_features'] ) && is_array( $settings['pro_features'] ) ? $settings['pro_features'] : array();
     83                $enabled      = ! empty( $pro_features['ollama_enabled'] );
     84                $server_url   = $pro_features['ollama_server_url'] ?? ( $settings['private_llm_server_url'] ?? '' );
     85                return $enabled && ! empty( $server_url );
     86        }
     87}
     88
     89if ( ! function_exists( 'aiohm_kb_ai_provider_available' ) ) {
     90        /**
     91         * Check whether a supported provider is set up.
     92         *
     93         * @param string $provider Provider ID.
     94         * @param array  $settings Plugin settings.
     95         * @return bool
     96         */
     97        function aiohm_kb_ai_provider_available( $provider, $settings ) {
     98                switch ( $provider ) {
     99                        case 'shareai':
     100                                return aiohm_kb_shareai_available( $settings );
     101                        case 'gemini':
     102                                return aiohm_kb_gemini_available( $settings );
     103                        case 'ollama':
     104                                return aiohm_kb_ollama_available( $settings );
     105                        case 'openai':
     106                        case 'anthropic':
     107                                return aiohm_kb_wp_connector_provider_available( $provider );
     108                        default:
     109                                return false;
     110                }
     111        }
     112}
     113
     114if ( ! function_exists( 'aiohm_kb_resolve_ai_provider' ) ) {
     115        /**
     116         * Map a stored provider ID to a supported one.
     117         *
     118         * Supported IDs pass through. Anything else, including the removed
     119         * openai, claude and groq providers, becomes the first set-up provider
     120         * of shareai, gemini and ollama, or shareai when none is set up.
     121         *
     122         * @param string $provider Stored provider ID.
     123         * @param array  $settings Plugin settings.
     124         * @return string Supported provider ID.
     125         */
     126        function aiohm_kb_resolve_ai_provider( $provider, $settings ) {
     127                $provider = is_string( $provider ) ? $provider : '';
     128                if ( '' !== $provider && function_exists( 'aiohm_kb_normalize_wp_ai_provider_id' ) ) {
     129                        $provider = aiohm_kb_normalize_wp_ai_provider_id( $provider );
     130                }
     131                // Connector providers count only while WordPress still has their key.
     132                if ( in_array( $provider, aiohm_kb_ai_provider_ids(), true )
     133                        && ( ! in_array( $provider, aiohm_kb_wp_connector_provider_ids(), true ) || aiohm_kb_ai_provider_available( $provider, $settings ) ) ) {
     134                        return $provider;
     135                }
     136                foreach ( aiohm_kb_ai_provider_ids() as $candidate ) {
     137                        if ( aiohm_kb_ai_provider_available( $candidate, $settings ) ) {
     138                                return $candidate;
     139                        }
     140                }
     141                return 'shareai';
     142        }
     143}
     144
     145if ( ! function_exists( 'aiohm_kb_default_model_for_provider' ) ) {
     146        /**
     147         * The chat model value to send for a provider.
     148         *
     149         * ShareAI uses the shareai_model setting, Gemini the existing Gemini
     150         * model ID, and Ollama the model saved in its own settings.
     151         *
     152         * @param string $provider Provider ID.
     153         * @param array  $settings Plugin settings.
     154         * @return string Model value for AIOHM_KB_AI_GPT_Client::get_chat_completion().
     155         */
     156        function aiohm_kb_default_model_for_provider( $provider, $settings ) {
     157                switch ( $provider ) {
     158                        case 'gemini':
     159                                return 'gemini-pro';
     160                        case 'ollama':
     161                                return 'ollama';
     162                        case 'openai':
     163                        case 'anthropic':
     164                                return 'wp-' . $provider;
     165                        case 'shareai':
     166                        default:
     167                                $shareai_model = (string) ( $settings['shareai_model'] ?? '' );
     168                                if ( '' === $shareai_model ) {
     169                                        $shareai_model = 'deepseek/deepseek-v4-flash';
     170                                }
     171                                return 'shareai-' . $shareai_model;
     172                }
     173        }
     174}
     175
     176if ( ! function_exists( 'aiohm_kb_is_supported_ai_model' ) ) {
     177        /**
     178         * Whether a mode model value belongs to a supported provider.
     179         *
     180         * @param string $model Model value.
     181         * @return bool
     182         */
     183        function aiohm_kb_is_supported_ai_model( $model ) {
     184                $model = (string) $model;
     185                return 0 === strpos( $model, 'gemini' )
     186                        || 0 === strpos( $model, 'shareai' )
     187                        || 0 === strpos( $model, 'ollama' )
     188                        || in_array( $model, array( 'wp-openai', 'wp-anthropic' ), true );
     189        }
    8190}
    9191
    … …  
    34216                        return 'gemini';
    35217                }
    36                 if ( false !== strpos( $haystack, 'anthropic' ) || false !== strpos( $haystack, 'claude' ) ) {
    37                         return 'claude';
    38                 }
    39                 if ( false !== strpos( $haystack, 'openai' ) || false !== strpos( $haystack, 'gpt' ) ) {
    40                         return 'openai';
    41                 }
    42                 if ( false !== strpos( $haystack, 'groq' ) ) {
    43                         return 'groq';
    44                 }
    45218                if ( false !== strpos( $haystack, 'shareai' ) ) {
    46219                        return 'shareai';
    … …  
    49222                        return 'ollama';
    50223                }
     224                if ( false !== strpos( $haystack, 'anthropic' ) || false !== strpos( $haystack, 'claude' ) ) {
     225                        return 'anthropic';
     226                }
     227                if ( false !== strpos( $haystack, 'openai' ) || false !== strpos( $haystack, 'chatgpt' ) ) {
     228                        return 'openai';
     229                }
    51230
    52231                return sanitize_key( $provider_id );
    … …  
    62241         */
    63242        function aiohm_kb_get_wp_connector_api_key( $provider ) {
    64                 $provider       = aiohm_kb_normalize_wp_ai_provider_id( $provider );
     243                $provider = aiohm_kb_normalize_wp_ai_provider_id( $provider );
     244                // AIOHM reads the Google (Gemini), OpenAI and Anthropic connectors.
     245                if ( ! in_array( $provider, array( 'gemini', 'openai', 'anthropic' ), true ) ) {
     246                        return '';
     247                }
     248
    65249                $env_names      = array();
    66250                $constant_names = array();
    … …  
    68252
    69253                $defaults = array(
    70                         'openai' => array(
     254                        'gemini'    => array(
     255                                'env'     => array( 'GOOGLE_API_KEY', 'GEMINI_API_KEY' ),
     256                                'const'   => array( 'GOOGLE_API_KEY', 'GEMINI_API_KEY' ),
     257                                'options' => array( 'connectors_ai_google_api_key', 'connectors_ai_gemini_api_key' ),
     258                        ),
     259                        'openai'    => array(
    71260                                'env'     => array( 'OPENAI_API_KEY' ),
    72261                                'const'   => array( 'OPENAI_API_KEY' ),
    73262                                'options' => array( 'connectors_ai_openai_api_key' ),
    74263                        ),
    75                         'gemini' => array(
    76                                 'env'     => array( 'GOOGLE_API_KEY', 'GEMINI_API_KEY' ),
    77                                 'const'   => array( 'GOOGLE_API_KEY', 'GEMINI_API_KEY' ),
    78                                 'options' => array( 'connectors_ai_google_api_key', 'connectors_ai_gemini_api_key' ),
    79                         ),
    80                         'claude' => array(
    81                                 'env'     => array( 'ANTHROPIC_API_KEY', 'CLAUDE_API_KEY' ),
    82                                 'const'   => array( 'ANTHROPIC_API_KEY', 'CLAUDE_API_KEY' ),
    83                                 'options' => array( 'connectors_ai_anthropic_api_key', 'connectors_ai_claude_api_key' ),
     264                        'anthropic' => array(
     265                                'env'     => array( 'ANTHROPIC_API_KEY' ),
     266                                'const'   => array( 'ANTHROPIC_API_KEY' ),
     267                                'options' => array( 'connectors_ai_anthropic_api_key' ),
    84268                        ),
    85269                );
    … …  
    136320                if ( is_array( $legacy_credentials ) ) {
    137321                        $legacy_ids = array(
    138                                 'openai' => array( 'openai' ),
    139                                 'gemini' => array( 'google', 'gemini' ),
    140                                 'claude' => array( 'anthropic', 'claude' ),
     322                                'gemini'    => array( 'google', 'gemini' ),
     323                                'openai'    => array( 'openai' ),
     324                                'anthropic' => array( 'anthropic' ),
    141325                        );
    142326
    … …  
    167351
    168352        private $settings;
    169         private $openai_api_key;
    170353        private $gemini_api_key;
    171         private $claude_api_key;
    172         private $shareai_api_key;
    173         private $groq_api_key;
    174354        private $ollama_server_url;
    175355        private $ollama_model;
    … …  
    181361                        $this->settings = $settings;
    182362                }
    183                 $this->openai_api_key  = $this->settings['openai_api_key'] ?? '';
    184                 $this->gemini_api_key  = $this->settings['gemini_api_key'] ?? '';
    185                 $this->claude_api_key  = $this->settings['claude_api_key'] ?? '';
    186                 if ( empty( $this->openai_api_key ) ) {
    187                         $this->openai_api_key = aiohm_kb_get_wp_connector_api_key( 'openai' );
    188                 }
     363                $this->gemini_api_key = $this->settings['gemini_api_key'] ?? '';
    189364                if ( empty( $this->gemini_api_key ) ) {
    190365                        $this->gemini_api_key = aiohm_kb_get_wp_connector_api_key( 'gemini' );
    191366                }
    192                 if ( empty( $this->claude_api_key ) ) {
    193                         $this->claude_api_key = aiohm_kb_get_wp_connector_api_key( 'claude' );
    194                 }
    195                 $this->shareai_api_key = $this->settings['shareai_api_key'] ?? '';
    196                 $this->groq_api_key    = $this->settings['groq_api_key'] ?? '';
    197367
    198368                // Ollama settings - check both pro_features and legacy settings
    … …  
    213383         * Check if API key is properly configured for the given provider
    214384         *
    215          * @param string $provider The AI provider (openai, gemini, claude, shareai, groq, ollama)
     385         * @param string $provider The AI provider (shareai, gemini, ollama)
    216386         * @return bool True if API key is configured
    217387         */
    218388        public function is_api_key_configured( $provider ) {
    219389                switch ( $provider ) {
    220                         case 'openai':
    221                                 return ! empty( $this->openai_api_key );
     390                        case 'shareai':
     391                                return aiohm_kb_shareai_available( $this->settings );
    222392                        case 'gemini':
    223393                                return ! empty( $this->gemini_api_key );
    224                         case 'claude':
    225                                 return ! empty( $this->claude_api_key );
    226                         case 'shareai':
    227                                 return ! empty( $this->shareai_api_key );
    228                         case 'groq':
    229                                 return ! empty( $this->groq_api_key );
    230394                        case 'ollama':
    231395                                return ! empty( $this->ollama_server_url );
    … …  
    371535                if ( is_string( $data ) ) {
    372536                        $patterns = array(
    373                                 '/sk-[a-zA-Z0-9_-]{20,}/'                => 'OPENAI_API_KEY_HIDDEN',
    374                                 '/pk-[a-zA-Z0-9_-]{20,}/'                => 'OPENAI_PUBLIC_KEY_HIDDEN',
    375                                 '/sk-ant-[a-zA-Z0-9_-]{90,}/'            => 'CLAUDE_API_KEY_HIDDEN',
     537                                '/sk-[a-zA-Z0-9_-]{20,}/'                => 'SECRET_KEY_HIDDEN',
     538                                '/pk-[a-zA-Z0-9_-]{20,}/'                => 'PUBLIC_KEY_HIDDEN',
     539                                '/sk-ant-[a-zA-Z0-9_-]{90,}/'            => 'SECRET_KEY_HIDDEN',
    376540                                '/AIza[a-zA-Z0-9_-]{35}/'                => 'GEMINI_API_KEY_HIDDEN',
    377541                                '/[a-zA-Z0-9_-]{32,}/'                   => 'POTENTIAL_API_KEY_HIDDEN',
    … …  
    411575                }
    412576
    413                 $provider = $this->settings['default_ai_provider'] ?? 'openai';
     577                $provider = aiohm_kb_resolve_ai_provider( $this->settings['default_ai_provider'] ?? '', $this->settings );
    414578
    415579                switch ( $provider ) {
    416580                        case 'gemini':
    417581                                return $this->generate_gemini_embeddings( $text );
    418                         case 'claude':
    419                                 return $this->generate_claude_embeddings( $text );
    420                         case 'shareai':
    421                                 return $this->generate_shareai_embeddings( $text );
    422582                        case 'ollama':
    423583                                return $this->generate_ollama_embeddings( $text );
    424584                        case 'openai':
     585                        case 'anthropic':
     586                                // Connector providers run chat only; search uses keywords.
     587                                throw new Exception( 'This AI provider is used for chat only. Search uses keywords.' );
     588                        case 'shareai':
    425589                        default:
    426                                 return $this->generate_openai_embeddings( $text );
    427                 }
    428         }
    429 
    430         private function generate_openai_embeddings( $text ) {
    431                 if ( empty( $this->openai_api_key ) ) {
    432                         throw new Exception( 'OpenAI API key is required for embeddings.' );
    433                 }
    434 
    435                 $url  = 'https://api.openai.com/v1/embeddings';
    436                 $data = array(
    437                         'model' => 'text-embedding-ada-002',
    438                         'input' => $this->sanitize_text_for_json( $text ),
    439                 );
    440 
    441                 $body = json_encode( $data );
    442                 if ( $body === false ) {
    443                         throw new Exception( 'Failed to JSON-encode embedding request. Content may contain invalid characters.' );
    444                 }
    445 
    446                 $response = $this->make_http_request( $url, $body, 'openai' );
    447 
    448                 if ( isset( $response['data'][0]['embedding'] ) ) {
    449                         return $response['data'][0]['embedding'];
    450                 } else {
    451                         $error_message = $response['error']['message'] ?? 'Invalid embedding response from OpenAI API.';
    452                         throw new Exception( esc_html( $error_message ) );
     590                                return $this->generate_shareai_embeddings( $text );
    453591                }
    454592        }
    … …  
    483621        }
    484622
    485         private function generate_claude_embeddings( $text ) {
    486                 // Claude API does not currently have a dedicated embedding endpoint.
    487                 // This functionality is not supported.
    488                 throw new Exception( 'Claude does not support embeddings. Please select a different provider for embedding generation.' );
    489         }
    490 
    491623        private function generate_shareai_embeddings( $text ) {
     624                // A connected ShareAI account can embed; a pasted API key cannot.
     625                if ( class_exists( 'AIOHM_KB_ShareAI_Connect' ) && AIOHM_KB_ShareAI_Connect::is_connected() ) {
     626                        if ( ! $this->has_shareai_consent() ) {
     627                                throw new Exception( 'ShareAI service requires user consent. Please enable it in Settings and review our Terms of Service.' );
     628                        }
     629                        $embedding_model = (string) ( $this->settings['shareai_embedding_model'] ?? '' );
     630                        if ( '' !== $embedding_model ) {
     631                                return AIOHM_KB_ShareAI_Connect::embedding( $text, $embedding_model );
     632                        }
     633                        // No ShareAI embedding model chosen: keep searching with the
     634                        // provider that built the existing knowledge base vectors.
     635                        $previous = (string) ( $this->settings['shareai_previous_provider'] ?? '' );
     636                        if ( in_array( $previous, array( 'gemini', 'ollama' ), true ) ) {
     637                                $settings                        = $this->settings;
     638                                $settings['default_ai_provider'] = $previous;
     639                                $client                          = new self( $settings );
     640                                return $client->generate_embeddings( $text );
     641                        }
     642                        throw new Exception( 'Choose a ShareAI embedding model in the AIOHM settings, or switch to a provider that supports embeddings.' );
     643                }
     644
    492645                // ShareAI API does not currently have a dedicated embedding endpoint.
    493646                // This functionality is not supported.
    … …  
    496649
    497650
    498         public function get_chat_completion( $system_message, $user_message, $temperature = 0.7, $model = 'gpt-3.5-turbo' ) {
    499                 $default_provider = $this->settings['default_ai_provider'] ?? 'openai';
    500                 if ( function_exists( 'aiohm_kb_normalize_wp_ai_provider_id' ) ) {
    501                         $default_provider = aiohm_kb_normalize_wp_ai_provider_id( $default_provider );
    502                 }
    503 
    504                 if ( strpos( $model, 'gemini' ) === 0 || ( ( empty( $model ) || 'gpt-3.5-turbo' === $model ) && ( 'gemini' === $default_provider || 'google' === $default_provider ) ) ) {
    505                         return $this->get_gemini_chat_completion( $system_message, $user_message, $temperature, $model );
    506                 }
    507 
    508                 if ( strpos( $model, 'claude' ) === 0 || ( ( empty( $model ) || 'gpt-3.5-turbo' === $model ) && ( 'claude' === $default_provider || 'anthropic' === $default_provider ) ) ) {
    509                         return $this->get_claude_chat_completion( $system_message, $user_message, $temperature, $model );
    510                 }
    511 
    512                 if ( strpos( $model, 'groq' ) === 0 || ( ( empty( $model ) || 'gpt-3.5-turbo' === $model ) && 'groq' === $default_provider ) ) {
    513                         return $this->get_groq_chat_completion( $system_message, $user_message, $temperature, $model );
    514                 }
    515 
    516                 if ( strpos( $model, 'shareai' ) === 0 || $default_provider === 'shareai' ) {
    517                         return $this->get_shareai_chat_completion( $system_message, $user_message, $temperature, $model );
    518                 }
    519 
    520                 if ( $model === 'ollama' || $default_provider === 'ollama' ) {
    521                         return $this->get_ollama_chat_completion( $system_message, $user_message, $temperature, $model );
    522                 }
    523 
    524                 return $this->get_openai_chat_completion( $system_message, $user_message, $temperature, $model );
     651        public function get_chat_completion( $system_message, $user_message, $temperature = 0.7, $model = '' ) {
     652                $model    = (string) $model;
     653                $provider = aiohm_kb_resolve_ai_provider( $this->settings['default_ai_provider'] ?? '', $this->settings );
     654
     655                // An explicit model for a supported provider wins. Any other value,
     656                // including models of removed providers, uses the default provider.
     657                if ( 0 === strpos( $model, 'gemini' ) ) {
     658                        $provider = 'gemini';
     659                } elseif ( 0 === strpos( $model, 'shareai' ) ) {
     660                        $provider = 'shareai';
     661                } elseif ( 0 === strpos( $model, 'ollama' ) ) {
     662                        $provider = 'ollama';
     663                } elseif ( in_array( $model, array( 'wp-openai', 'wp-anthropic' ), true ) ) {
     664                        $provider = substr( $model, 3 );
     665                }
     666
     667                switch ( $provider ) {
     668                        case 'openai':
     669                        case 'anthropic':
     670                                return $this->get_wp_connector_chat_completion( $provider, $system_message, $user_message, $temperature );
     671                        case 'gemini':
     672                                return $this->get_gemini_chat_completion( $system_message, $user_message, $temperature, $model );
     673                        case 'ollama':
     674                                return $this->get_ollama_chat_completion( $system_message, $user_message, $temperature, $model );
     675                        case 'shareai':
     676                        default:
     677                                return $this->get_shareai_chat_completion( $system_message, $user_message, $temperature, $model );
     678                }
     679        }
     680
     681        /**
     682         * Chat through the WordPress AI Client with a provider set up in
     683         * Settings > Connectors. WordPress holds the key and picks the model.
     684         *
     685         * @param string $provider openai or anthropic.
     686         * @throws Exception When the provider is not connected or the request fails.
     687         */
     688        private function get_wp_connector_chat_completion( $provider, $system_message, $user_message, $temperature ) {
     689                if ( empty( $this->settings['external_api_consent'] ) ) {
     690                        throw new Exception( esc_html__( 'External API calls require user consent. Please enable this option in settings.', 'aiohm-knowledge-assistant' ) );
     691                }
     692                if ( ! aiohm_kb_wp_connector_provider_available( $provider ) ) {
     693                        throw new Exception( esc_html__( 'Add this provider in Settings > Connectors in WordPress, or choose another AI provider in the AIOHM settings.', 'aiohm-knowledge-assistant' ) );
     694                }
     695                if ( ! $this->check_rate_limit( $provider ) ) {
     696                        throw new Exception( esc_html__( 'AI rate limit exceeded. Please try again later.', 'aiohm-knowledge-assistant' ) );
     697                }
     698
     699                $text = wp_ai_client_prompt( (string) $user_message )
     700                        ->using_provider( $provider )
     701                        ->using_system_instruction( (string) $system_message )
     702                        ->using_temperature( (float) $temperature )
     703                        ->generate_text();
     704
     705                if ( is_wp_error( $text ) ) {
     706                        throw new Exception( esc_html( $this->get_safe_error_message( $text->get_error_message(), 'openai' === $provider ? 'OpenAI' : 'Anthropic' ) ) );
     707                }
     708                $text = (string) $text;
     709                if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
     710                        AIOHM_KB_Core_Init::log_ai_usage( $provider, intval( ( strlen( $system_message ) + strlen( $user_message ) + strlen( $text ) ) / 4 ), 0 );
     711                }
     712                return $text;
    525713        }
    526714
    … …  
    578766        }
    579767
    580         private function get_claude_chat_completion( $system_message, $user_message, $temperature, $model ) {
    581                 if ( empty( $this->claude_api_key ) ) {
    582                         throw new Exception( 'Claude API key is required for chat completions.' );
    583                 }
    584 
    585                 $claude_model_map = array(
    586                         'claude-3-sonnet' => 'claude-3-sonnet-20240229',
    587                         'claude-3-haiku'  => 'claude-3-haiku-20240307',
    588                         'claude-3-opus'   => 'claude-3-opus-20240229',
    589                 );
    590 
    591                 $actual_model = $claude_model_map[ $model ] ?? 'claude-3-sonnet-20240229';
    592                 $url          = 'https://api.anthropic.com/v1/messages';
    593 
    594                 $data = array(
    595                         'model'       => $actual_model,
    596                         'max_tokens'  => 4000,
    597                         'temperature' => floatval( $temperature ),
    598                         'system'      => $this->sanitize_text_for_json( $system_message ),
    599                         'messages'    => array(
    600                                 array(
    601                                         'role'    => 'user',
    602                                         'content' => $this->sanitize_text_for_json( $user_message ),
    603                                 ),
    604                         ),
    605                 );
    606 
    607                 $body = json_encode( $data );
    608                 if ( $body === false ) {
    609                         throw new Exception( 'Failed to JSON-encode chat request.' );
    610                 }
    611 
    612                 $response = $this->make_http_request( $url, $body, 'claude' );
    613 
    614                 if ( isset( $response['content'][0]['text'] ) ) {
    615                         $content          = $response['content'][0]['text'];
    616                         $estimated_tokens = ( strlen( $system_message ) + strlen( $user_message ) + strlen( $content ) ) / 4;
    617                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    618                                 AIOHM_KB_Core_Init::log_ai_usage( 'claude', intval( $estimated_tokens ), 0 );
    619                         }
    620                         return $content;
    621                 } else {
    622                         $error_message = $response['error']['message'] ?? 'Invalid chat response from Claude API.';
    623                         throw new Exception( esc_html( $this->get_safe_error_message( $error_message, 'Claude' ) ) );
    624                 }
    625         }
    626 
    627768        private function get_shareai_chat_completion( $system_message, $user_message, $temperature, $model ) {
    628769                // WordPress.org compliance: Check for ShareAI consent
    … …  
    631772                }
    632773
    633                 if ( empty( $this->shareai_api_key ) ) {
    634                         throw new Exception( 'ShareAI API key is required for chat completions.' );
    635                 }
    636 
    637                 if ( ! $this->check_rate_limit( 'shareai' ) ) {
    638                         throw new Exception( 'ShareAI API rate limit exceeded. Please try again later.' );
    639                 }
    640 
    641                 $shareai_model = $this->settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    642                 if ( strpos( $model, 'shareai-' ) === 0 ) {
    643                         $shareai_model = str_replace( 'shareai-', '', $model );
    644                 }
    645 
    646                 $url = 'https://api.shareai.now/api/v1/chat/completions';
    647 
    648                 $combined_message = $system_message . "\n\n" . 'User question: ' . $user_message;
    649 
    650                 $data = array(
    651                         'model'       => $shareai_model,
    652                         'messages'    => array(
    653                                 array(
    654                                         'role'    => 'user',
    655                                         'content' => $this->sanitize_text_for_json( $combined_message ),
    656                                 ),
    657                         ),
    658                         'temperature' => floatval( $temperature ),
    659                         'max_tokens'  => 4000,
    660                 );
    661 
    662                 $body = json_encode( $data );
    663                 if ( $body === false ) {
    664                         throw new Exception( 'Failed to JSON-encode chat request.' );
    665                 }
    666 
    667                 try {
    668                         $response = $this->make_http_request( $url, $body, 'shareai' );
    669                 } catch ( Exception $e ) {
    670                         throw new Exception( esc_html( $this->get_safe_error_message( $e->getMessage(), 'ShareAI' ) ) );
    671                 }
    672 
    673                 if ( isset( $response['choices'][0]['message']['content'] ) ) {
    674                         $content          = $response['choices'][0]['message']['content'];
    675                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    676                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    677                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    678                         }
    679                         return $content;
    680                 } elseif ( isset( $response['message'] ) ) {
    681                         $message = $response['message'];
    682 
    683                         $final_content = '';
    684                         if ( is_string( $message ) ) {
    685                                 $decoded = json_decode( $message, true );
    686                                 if ( $decoded !== null && isset( $decoded['content'] ) ) {
    687                                         $final_content = $decoded['content'];
    688                                 } else {
    689                                         $final_content = $message;
    690                                 }
    691                         } elseif ( is_array( $message ) && isset( $message['content'] ) ) {
    692                                 $final_content = $message['content'];
    693                         } else {
    694                                 $final_content = is_string( $message ) ? $message : json_encode( $message );
    695                         }
    696 
    697                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $final_content ) ) / 4;
    698                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    699                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    700                         }
    701                         return $final_content;
    702                 } elseif ( isset( $response['response'] ) ) {
    703                         $content          = $response['response'];
    704                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    705                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    706                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    707                         }
    708                         return $content;
    709                 } elseif ( isset( $response['content'] ) ) {
    710                         $content          = $response['content'];
    711                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    712                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    713                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    714                         }
    715                         return $content;
    716                 } elseif ( isset( $response['text'] ) ) {
    717                         $content          = $response['text'];
    718                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    719                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    720                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    721                         }
    722                         return $content;
    723                 } elseif ( isset( $response['data']['text'] ) ) {
    724                         $content          = $response['data']['text'];
    725                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    726                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    727                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    728                         }
    729                         return $content;
    730                 } else {
    731                         $error_message = $response['error']['message'] ?? 'Invalid chat response from ShareAI API.';
    732                         throw new Exception( esc_html( $error_message ) );
    733                 }
    734         }
    735 
    736         private function get_groq_chat_completion( $system_message, $user_message, $temperature, $model ) {
    737                 if ( empty( $this->groq_api_key ) ) {
    738                         throw new Exception( 'Groq API key is required for chat completions.' );
    739                 }
    740 
    741                 // Map UI model names to actual Groq API model names
    742                 $groq_model_map = array(
    743                         'groq-llama-3.3-70b-versatile' => 'llama-3.3-70b-versatile',
    744                         'groq-llama-3.1-70b-versatile' => 'llama-3.3-70b-versatile', // Fallback for deprecated model
    745                 );
    746                 $actual_model = $groq_model_map[ $model ] ?? 'llama-3.3-70b-versatile';
    747 
    748                 $url  = 'https://api.groq.com/openai/v1/chat/completions';
    749                 $data = array(
    750                         'model'       => $actual_model,
    751                         'messages'    => array(
    752                                 array(
    753                                         'role'    => 'system',
    754                                         'content' => $this->sanitize_text_for_json( $system_message ),
    755                                 ),
    756                                 array(
    757                                         'role'    => 'user',
    758                                         'content' => $this->sanitize_text_for_json( $user_message ),
    759                                 ),
    760                         ),
    761                         'temperature' => floatval( $temperature ),
    762                 );
    763 
    764                 $body = json_encode( $data );
    765                 if ( $body === false ) {
    766                         throw new Exception( 'Failed to JSON-encode chat request.' );
    767                 }
    768 
    769                 $response = $this->make_http_request( $url, $body, 'groq' );
    770 
    771                 if ( isset( $response['choices'][0]['message']['content'] ) ) {
    772                         $content       = $response['choices'][0]['message']['content'];
    773                         $total_tokens  = $response['usage']['total_tokens'] ?? 0;
    774 
    775                         // Log usage for Groq
    776                         if ( $total_tokens > 0 ) {
    777                                 AIOHM_KB_Core_Init::log_ai_usage( 'groq', intval( $total_tokens ), 0 );
    778                         }
    779                         return $content;
    780                 } else {
    781                         $error_message = $response['error']['message'] ?? 'Invalid chat response from Groq API.';
    782                         throw new Exception( esc_html( $error_message ) );
    783                 }
    784         }
    785 
    786         private function get_openai_chat_completion( $system_message, $user_message, $temperature, $model ) {
    787                 if ( empty( $this->openai_api_key ) ) {
    788                         throw new Exception( 'OpenAI API key is required for chat completions.' );
    789                 }
    790 
    791                 $url  = 'https://api.openai.com/v1/chat/completions';
    792                 $data = array(
    793                         'model'       => $model,
    794                         'messages'    => array(
    795                                 array(
    796                                         'role'    => 'system',
    797                                         'content' => $this->sanitize_text_for_json( $system_message ),
    798                                 ),
    799                                 array(
    800                                         'role'    => 'user',
    801                                         'content' => $this->sanitize_text_for_json( $user_message ),
    802                                 ),
    803                         ),
    804                         'temperature' => floatval( $temperature ),
    805                 );
    806 
    807                 $body = json_encode( $data );
    808                 if ( $body === false ) {
    809                         throw new Exception( 'Failed to JSON-encode chat request.' );
    810                 }
    811 
    812                 $response = $this->make_http_request( $url, $body, 'openai' );
    813 
    814                 if ( isset( $response['choices'][0]['message']['content'] ) ) {
    815                         $content       = $response['choices'][0]['message']['content'];
    816                         $tokens_used   = $response['usage']['total_tokens'] ?? intval( ( strlen( $system_message ) + strlen( $user_message ) + strlen( $content ) ) / 4 );
    817                         $cost_estimate = $this->estimate_openai_cost( $model, $tokens_used );
    818                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    819                                 AIOHM_KB_Core_Init::log_ai_usage( 'openai', $tokens_used, $cost_estimate );
    820                         }
    821                         return $content;
    822                 } else {
    823                         $error_message = $response['error']['message'] ?? 'Invalid chat response from OpenAI API.';
    824                         throw new Exception( esc_html( $error_message ) );
    825                 }
    826         }
    827 
    828         private function estimate_openai_cost( $model, $tokens ) {
    829                 $pricing = array(
    830                         'gpt-4'             => 0.03,
    831                         'gpt-4-turbo'       => 0.01,
    832                         'gpt-3.5-turbo'     => 0.002,
    833                         'gpt-3.5-turbo-16k' => 0.004,
    834                 );
    835 
    836                 $rate = $pricing[ $model ] ?? 0.002;
    837                 return ( $tokens / 1000000 ) * $rate;
     774                // ShareAI runs on the owner's connected account and wallet (AIOHM's
     775                // builder plan). There is no pasted API key route.
     776                if ( class_exists( 'AIOHM_KB_ShareAI_Connect' ) && AIOHM_KB_ShareAI_Connect::is_connected() ) {
     777                        if ( ! $this->check_rate_limit( 'shareai' ) ) {
     778                                throw new Exception( 'ShareAI API rate limit exceeded. Please try again later.' );
     779                        }
     780                        $connected_model = (string) ( $this->settings['shareai_model'] ?? '' );
     781                        if ( strpos( $model, 'shareai-' ) === 0 ) {
     782                                $connected_model = str_replace( 'shareai-', '', $model );
     783                        }
     784                        return AIOHM_KB_ShareAI_Connect::chat( $system_message, $user_message, $temperature, $connected_model );
     785                }
     786
     787                throw new Exception( 'Connect ShareAI in the AIOHM settings to use ShareAI.' );
    838788        }
    839789
    … …  
    844794
    845795                $headers = array( 'Content-Type' => 'application/json' );
    846                 if ( $api_type === 'openai' ) {
    847                         $headers['Authorization'] = 'Bearer ' . $this->openai_api_key;
    848                 } elseif ( $api_type === 'gemini' ) {
     796                if ( $api_type === 'gemini' ) {
    849797                        $headers['x-goog-api-key'] = $this->gemini_api_key;
    850                 } elseif ( $api_type === 'claude' ) {
    851                         $headers['Authorization']     = 'Bearer ' . $this->claude_api_key;
    852                         $headers['anthropic-version'] = '2023-06-01';
    853                 } elseif ( $api_type === 'groq' ) {
    854                         $headers['Authorization'] = 'Bearer ' . $this->groq_api_key;
    855                 } elseif ( $api_type === 'shareai' ) {
    856                         $headers['Authorization'] = 'Bearer ' . $this->shareai_api_key;
    857798                }
    858799
    … …  
    955896        }
    956897
    957         public function test_claude_api_connection() {
    958                 if ( empty( $this->claude_api_key ) ) {
     898        /**
     899         * Check the connected ShareAI account: a valid access token (refreshed when
     900         * needed) means the connection works.
     901         *
     902         * @return array{success: bool, error?: string}
     903         */
     904        public function test_shareai_api_connection() {
     905                if ( ! class_exists( 'AIOHM_KB_ShareAI_Connect' ) || ! AIOHM_KB_ShareAI_Connect::is_connected() ) {
    959906                        return array(
    960907                                'success' => false,
    961                                 'error'   => 'Claude API key is missing.',
     908                                'error'   => 'ShareAI is not connected. Click Connect ShareAI in the AIOHM settings.',
    962909                        );
    963910                }
    964911                try {
    965                         $this->get_chat_completion( 'Test prompt', "Say 'hello'.", 0.5, 'claude-3-sonnet' );
     912                        AIOHM_KB_ShareAI_Connect::access_token();
    966913                        return array( 'success' => true );
    967914                } catch ( Exception $e ) {
    … …  
    973920        }
    974921
    975         public function test_shareai_api_connection() {
    976                 // WordPress.org compliance: Check for ShareAI consent
    977                 if ( ! $this->has_shareai_consent() ) {
    978                         return array(
    979                                 'success' => false,
    980                                 'error'   => 'ShareAI service requires user consent. Please enable it in Settings.',
    981                         );
    982                 }
    983 
    984                 if ( empty( $this->shareai_api_key ) ) {
    985                         return array(
    986                                 'success' => false,
    987                                 'error'   => 'ShareAI API key is missing.',
    988                         );
    989                 }
    990 
    991                 // Check if this looks like a base64 encoded string (which would be wrong)
    992                 if ( strlen( $this->shareai_api_key ) > 200 && preg_match( '/^[A-Za-z0-9+\/=]+$/', $this->shareai_api_key ) ) {
    993                 }
    994 
    995                 // Check if key has any unusual characters that might indicate corruption
    996                 if ( preg_match( '/[^A-Za-z0-9\-_.]/', $this->shareai_api_key ) ) {
    997                 }
    998 
    999                 // First test basic connectivity without auth
    1000                 $basic_test = wp_remote_get( 'https://api.shareai.now/api/v1/', array( 'timeout' => 10 ) );
    1001                 if ( is_wp_error( $basic_test ) ) {
    1002                 } else {
    1003                 }
    1004 
    1005                 // Use the key info endpoint to test connection without consuming tokens
    1006                 $key_info_url = 'https://api.shareai.now/api/v1/iam/key/info';
    1007 
    1008                 try {
    1009                         $response = wp_remote_get(
    1010                                 $key_info_url,
    1011                                 array(
    1012                                         'headers' => array(
    1013                                                 'Content-Type'  => 'application/json',
    1014                                                 'Authorization' => 'Bearer ' . $this->shareai_api_key,
    1015                                         ),
    1016                                         'timeout' => 30,
    1017                                 )
    1018                         );
    1019 
    1020                         if ( is_wp_error( $response ) ) {
    1021                                 return array(
    1022                                         'success' => false,
    1023                                         'error'   => 'Connection error: ' . $response->get_error_message(),
    1024                                 );
    1025                         }
    1026 
    1027                         $response_code = wp_remote_retrieve_response_code( $response );
    1028                         $response_body = wp_remote_retrieve_body( $response );
    1029 
    1030                         if ( $response_code !== 200 ) {
    1031                                 // If key info endpoint fails, fall back to minimal chat test
    1032                                 return $this->test_shareai_fallback_connection();
    1033                         }
    1034 
    1035                         $decoded = json_decode( $response_body, true );
    1036                         if ( $decoded === null ) {
    1037                                 return $this->test_shareai_fallback_connection();
    1038                         }
    1039 
    1040                         // Check for valid key info response and extract usage information
    1041                         $usage_info = $this->extract_shareai_usage_from_response( $decoded );
    1042 
    1043                         if ( isset( $decoded['valid'] ) && $decoded['valid'] === true ) {
    1044                                 $message = 'ShareAI connection successful - API key is valid';
    1045                                 if ( $usage_info['has_usage'] ) {
    1046                                         $message .= sprintf(
    1047                                                 ' | Tokens used: %d | Requests: %d',
    1048                                                 $usage_info['tokens_used'],
    1049                                                 $usage_info['requests_made']
    1050                                         );
    1051                                         if ( $usage_info['quota_remaining'] !== null ) {
    1052                                                 $message .= sprintf( ' | Quota remaining: %s', $usage_info['quota_remaining'] );
    1053                                         }
    1054                                 }
    1055                                 return array(
    1056                                         'success'  => true,
    1057                                         'message'  => $message,
    1058                                         'key_info' => $decoded,
    1059                                         'usage'    => $usage_info,
    1060                                 );
    1061                         } elseif ( isset( $decoded['status'] ) && $decoded['status'] === 'active' ) {
    1062                                 $message = 'ShareAI connection successful - API key is active';
    1063                                 if ( $usage_info['has_usage'] ) {
    1064                                         $message .= sprintf(
    1065                                                 ' | Tokens used: %d | Requests: %d',
    1066                                                 $usage_info['tokens_used'],
    1067                                                 $usage_info['requests_made']
    1068                                         );
    1069                                 }
    1070                                 return array(
    1071                                         'success'  => true,
    1072                                         'message'  => $message,
    1073                                         'key_info' => $decoded,
    1074                                         'usage'    => $usage_info,
    1075                                 );
    1076                         } elseif ( isset( $decoded['keyId'] ) || isset( $decoded['key_id'] ) || isset( $decoded['id'] ) ) {
    1077                                 // Key info returned some identifier, consider it successful
    1078                                 $message = 'ShareAI connection successful - Key info retrieved';
    1079                                 if ( $usage_info['has_usage'] ) {
    1080                                         $message .= sprintf(
    1081                                                 ' | Tokens used: %d | Requests: %d',
    1082                                                 $usage_info['tokens_used'],
    1083                                                 $usage_info['requests_made']
    1084                                         );
    1085                                 }
    1086                                 return array(
    1087                                         'success'  => true,
    1088                                         'message'  => $message,
    1089                                         'key_info' => $decoded,
    1090                                         'usage'    => $usage_info,
    1091                                 );
    1092                         } elseif ( isset( $decoded['error'] ) ) {
    1093                                 return array(
    1094                                         'success' => false,
    1095                                         'error'   => 'ShareAI API Error: ' . $decoded['error'],
    1096                                 );
    1097                         } else {
    1098                                 // If key info doesn't work as expected, fall back to minimal chat test
    1099                                 return $this->test_shareai_fallback_connection();
    1100                         }
    1101                 } catch ( Exception $e ) {
    1102                         return array(
    1103                                 'success' => false,
    1104                                 'error'   => 'Connection test failed: ' . $e->getMessage(),
    1105                         );
    1106                 }
    1107         }
    1108 
    1109         /**
    1110          * Extract usage information from ShareAI API response
    1111          *
    1112          * @param array $decoded The decoded API response
    1113          * @return array Usage information
    1114          */
    1115         private function extract_shareai_usage_from_response( $decoded ) {
    1116                 $usage_info = array(
    1117                         'has_usage'       => false,
    1118                         'tokens_used'     => 0,
    1119                         'requests_made'   => 0,
    1120                         'quota_remaining' => null,
    1121                         'quota_limit'     => null,
    1122                         'reset_date'      => null,
    1123                 );
    1124 
    1125                 // Parse different possible response formats for usage data
    1126                 if ( isset( $decoded['usage'] ) ) {
    1127                         $usage                         = $decoded['usage'];
    1128                         $usage_info['has_usage']       = true;
    1129                         $usage_info['tokens_used']     = $usage['tokens'] ?? $usage['total_tokens'] ?? 0;
    1130                         $usage_info['requests_made']   = $usage['requests'] ?? $usage['total_requests'] ?? 0;
    1131                         $usage_info['quota_remaining'] = $usage['remaining'] ?? $usage['quota_remaining'] ?? null;
    1132                         $usage_info['quota_limit']     = $usage['limit'] ?? $usage['quota_limit'] ?? null;
    1133                         $usage_info['reset_date']      = $usage['reset_date'] ?? $usage['quota_reset'] ?? null;
    1134                 } elseif ( isset( $decoded['tokens'] ) || isset( $decoded['requests'] ) ) {
    1135                         // Direct usage fields in root
    1136                         $usage_info['has_usage']       = true;
    1137                         $usage_info['tokens_used']     = $decoded['tokens'] ?? $decoded['total_tokens'] ?? 0;
    1138                         $usage_info['requests_made']   = $decoded['requests'] ?? $decoded['total_requests'] ?? 0;
    1139                         $usage_info['quota_remaining'] = $decoded['remaining'] ?? $decoded['quota_remaining'] ?? null;
    1140                         $usage_info['quota_limit']     = $decoded['limit'] ?? $decoded['quota_limit'] ?? null;
    1141                 }
    1142 
    1143                 return $usage_info;
    1144         }
    1145 
    1146         private function test_shareai_fallback_connection() {
    1147 
    1148                 // Fallback to minimal chat test if key info endpoint doesn't work
    1149                 $test_url       = 'https://api.shareai.now/api/v1/chat/completions';
    1150                 $selected_model = $this->settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    1151 
    1152                 $test_data = array(
    1153                         'model'      => $selected_model,
    1154                         'messages'   => array(
    1155                                 array(
    1156                                         'role'    => 'user',
    1157                                         'content' => 'Hi',
    1158                                 ),
    1159                         ),
    1160                         'max_tokens' => 10, // Minimal tokens to reduce consumption
    1161                 );
    1162 
    1163                 try {
    1164                         $response = wp_remote_post(
    1165                                 $test_url,
    1166                                 array(
    1167                                         'headers' => array(
    1168                                                 'Content-Type'  => 'application/json',
    1169                                                 'Authorization' => 'Bearer ' . $this->shareai_api_key,
    1170                                         ),
    1171                                         'body'    => json_encode( $test_data ),
    1172                                         'timeout' => 30,
    1173                                 )
    1174                         );
    1175 
    1176                         if ( is_wp_error( $response ) ) {
    1177                                 return array(
    1178                                         'success' => false,
    1179                                         'error'   => 'Connection error: ' . $response->get_error_message(),
    1180                                 );
    1181                         }
    1182 
    1183                         $response_code = wp_remote_retrieve_response_code( $response );
    1184                         $response_body = wp_remote_retrieve_body( $response );
    1185 
    1186                         if ( $response_code !== 200 ) {
    1187                                 return array(
    1188                                         'success' => false,
    1189                                         'error'   => 'HTTP ' . $response_code . ': ' . $response_body,
    1190                                 );
    1191                         }
    1192 
    1193                         $decoded = json_decode( $response_body, true );
    1194                         if ( $decoded === null ) {
    1195                                 return array(
    1196                                         'success' => false,
    1197                                         'error'   => 'Invalid JSON response: ' . json_last_error_msg(),
    1198                                 );
    1199                         }
    1200 
    1201                         // Check for any valid response format
    1202                         if ( isset( $decoded['choices'][0]['message']['content'] ) ||
    1203                                 isset( $decoded['message'] ) ||
    1204                                 isset( $decoded['response'] ) ||
    1205                                 isset( $decoded['content'] ) ||
    1206                                 isset( $decoded['text'] ) ) {
    1207                                 return array(
    1208                                         'success' => true,
    1209                                         'message' => 'ShareAI connection successful (fallback test)',
    1210                                 );
    1211                         } else {
    1212                                 return array(
    1213                                         'success' => true,
    1214                                         'message' => 'ShareAI connection successful (unknown format)',
    1215                                 );
    1216                         }
    1217                 } catch ( Exception $e ) {
    1218                         return array(
    1219                                 'success' => false,
    1220                                 'error'   => 'Fallback connection test failed: ' . $e->getMessage(),
    1221                         );
    1222                 }
    1223         }
    1224 
    1225         /**
    1226          * Get ShareAI usage information without consuming tokens
    1227          *
    1228          * @return array Usage information or error
    1229          */
    1230         public function get_shareai_usage_info() {
    1231                 if ( empty( $this->shareai_api_key ) ) {
    1232                         return array(
    1233                                 'success' => false,
    1234                                 'error'   => 'ShareAI API key is missing.',
    1235                         );
    1236                 }
    1237 
    1238                 $key_info_url = 'https://api.shareai.now/api/v1/iam/key/info';
    1239 
    1240                 try {
    1241                         $response = wp_remote_get(
    1242                                 $key_info_url,
    1243                                 array(
    1244                                         'headers' => array(
    1245                                                 'Content-Type'  => 'application/json',
    1246                                                 'Authorization' => 'Bearer ' . $this->shareai_api_key,
    1247                                         ),
    1248                                         'timeout' => 30,
    1249                                 )
    1250                         );
    1251 
    1252                         if ( is_wp_error( $response ) ) {
    1253                                 return array(
    1254                                         'success' => false,
    1255                                         'error'   => 'Connection error: ' . $response->get_error_message(),
    1256                                 );
    1257                         }
    1258 
    1259                         $response_code = wp_remote_retrieve_response_code( $response );
    1260                         $response_body = wp_remote_retrieve_body( $response );
    1261 
    1262                         if ( $response_code !== 200 ) {
    1263                                 return array(
    1264                                         'success' => false,
    1265                                         'error'   => 'HTTP ' . $response_code . ': ' . $response_body,
    1266                                 );
    1267                         }
    1268 
    1269                         $decoded = json_decode( $response_body, true );
    1270                         if ( $decoded === null ) {
    1271                                 return array(
    1272                                         'success' => false,
    1273                                         'error'   => 'Invalid JSON response: ' . json_last_error_msg(),
    1274                                 );
    1275                         }
    1276 
    1277                         // Extract usage information from the response
    1278                         $usage_info = array(
    1279                                 'success'         => true,
    1280                                 'tokens_used'     => 0,
    1281                                 'requests_made'   => 0,
    1282                                 'quota_remaining' => null,
    1283                                 'quota_limit'     => null,
    1284                                 'reset_date'      => null,
    1285                         );
    1286 
    1287                         // Parse different possible response formats for usage data
    1288                         if ( isset( $decoded['usage'] ) ) {
    1289                                 $usage                         = $decoded['usage'];
    1290                                 $usage_info['tokens_used']     = $usage['tokens'] ?? $usage['total_tokens'] ?? 0;
    1291                                 $usage_info['requests_made']   = $usage['requests'] ?? $usage['total_requests'] ?? 0;
    1292                                 $usage_info['quota_remaining'] = $usage['remaining'] ?? $usage['quota_remaining'] ?? null;
    1293                                 $usage_info['quota_limit']     = $usage['limit'] ?? $usage['quota_limit'] ?? null;
    1294                                 $usage_info['reset_date']      = $usage['reset_date'] ?? $usage['quota_reset'] ?? null;
    1295                         } elseif ( isset( $decoded['tokens'] ) || isset( $decoded['requests'] ) ) {
    1296                                 // Direct usage fields in root
    1297                                 $usage_info['tokens_used']     = $decoded['tokens'] ?? $decoded['total_tokens'] ?? 0;
    1298                                 $usage_info['requests_made']   = $decoded['requests'] ?? $decoded['total_requests'] ?? 0;
    1299                                 $usage_info['quota_remaining'] = $decoded['remaining'] ?? $decoded['quota_remaining'] ?? null;
    1300                                 $usage_info['quota_limit']     = $decoded['limit'] ?? $decoded['quota_limit'] ?? null;
    1301                         }
    1302 
    1303                         $usage_info['raw_response'] = $decoded;
    1304 
    1305                         return $usage_info;
    1306 
    1307                 } catch ( Exception $e ) {
    1308                         return array(
    1309                                 'success' => false,
    1310                                 'error'   => 'Failed to get usage info: ' . $e->getMessage(),
    1311                         );
    1312                 }
    1313         }
    1314 
    1315 
    1316922        /**
    1317923         * Get the current AI provider based on settings
    … …  
    1320926         */
    1321927        public function get_current_provider() {
    1322                 $provider = $this->settings['default_ai_provider'] ?? ($this->settings['ai_provider'] ?? 'openai');
    1323                 if ( function_exists( 'aiohm_kb_normalize_wp_ai_provider_id' ) ) {
    1324                         $provider = aiohm_kb_normalize_wp_ai_provider_id( $provider );
    1325                 }
    1326 
    1327                 // Map old provider names to current ones
    1328                 $provider_mapping = array(
    1329                         'gpt'       => 'openai',
    1330                         'openai'    => 'openai',
    1331                         'gemini'    => 'google',
    1332                         'google'    => 'google',
    1333                         'claude'    => 'anthropic',
    1334                         'anthropic' => 'anthropic',
    1335                         'shareai'   => 'shareai',
    1336                 );
    1337 
    1338                 return $provider_mapping[ $provider ] ?? 'openai';
     928                return aiohm_kb_resolve_ai_provider( $this->settings['default_ai_provider'] ?? ( $this->settings['ai_provider'] ?? '' ), $this->settings );
    1339929        }
    1340930
    … …  
    1354944                if ( ! $model ) {
    1355945                        $provider = $this->get_current_provider();
    1356                         switch ( $provider ) {
    1357                                 case 'openai':
    1358                                         $model = 'gpt-4';
    1359                                         break;
    1360                                 case 'gemini':
    1361                                 case 'google':
    1362                                         $model = 'gemini-2.5-flash';
    1363                                         break;
    1364                                 case 'anthropic':
    1365                                         $model = 'claude-3-sonnet-20240229';
    1366                                         break;
    1367                                 default:
    1368                                         $model = 'gemini-2.5-flash';
     946                        if ( 'gemini' === $provider ) {
     947                                $model = 'gemini-2.5-flash';
     948                        } else {
     949                                $model = aiohm_kb_default_model_for_provider( $provider, $this->settings );
    1369950                        }
    1370951                }
    1371952
    1372953                return $this->get_chat_completion( '', $prompt, $temperature, $model );
    1373         }
    1374 
    1375         /**
    1376          * Test Groq API connection
    1377          *
    1378          * @return array Result with success status and message
    1379          */
    1380         public function test_groq_api_connection() {
    1381                 if ( empty( $this->groq_api_key ) ) {
    1382                         return array(
    1383                                 'success' => false,
    1384                                 'error'   => 'Groq API key is missing.',
    1385                         );
    1386                 }
    1387 
    1388                 try {
    1389                         // Use a simple direct API call for testing
    1390                         $url = 'https://api.groq.com/openai/v1/chat/completions';
    1391 
    1392                         $data = array(
    1393                                 'model' => 'llama-3.3-70b-versatile',
    1394                                 'messages' => array(
    1395                                         array( 'role' => 'user', 'content' => 'Say hello in one word' ),
    1396                                 ),
    1397                                 'max_tokens' => 5,
    1398                         );
    1399 
    1400                         $response = wp_remote_post(
    1401                                 $url,
    1402                                 array(
    1403                                         'headers' => array(
    1404                                                 'Content-Type'  => 'application/json',
    1405                                                 'Authorization' => 'Bearer ' . $this->groq_api_key,
    1406                                         ),
    1407                                         'body'    => json_encode( $data ),
    1408                                         'timeout' => 30,
    1409                                 )
    1410                         );
    1411 
    1412                         if ( is_wp_error( $response ) ) {
    1413                                 return array(
    1414                                         'success' => false,
    1415                                         'error'   => 'Connection error: ' . $response->get_error_message(),
    1416                                 );
    1417                         }
    1418 
    1419                         $status_code = wp_remote_retrieve_response_code( $response );
    1420                         $body        = wp_remote_retrieve_body( $response );
    1421 
    1422                         if ( $status_code === 200 ) {
    1423                                 $decoded = json_decode( $body, true );
    1424                                 if ( isset( $decoded['choices'] ) && ! empty( $decoded['choices'] ) ) {
    1425                                         return array(
    1426                                                 'success' => true,
    1427                                                 'message' => 'Groq connection successful!',
    1428                                         );
    1429                                 }
    1430                         }
    1431 
    1432                         $decoded = json_decode( $body, true );
    1433                         $error_message = $decoded['error']['message'] ?? 'Unknown API error';
    1434 
    1435                         return array(
    1436                                 'success' => false,
    1437                                 'error'   => $error_message,
    1438                         );
    1439 
    1440                 } catch ( Exception $e ) {
    1441                         return array(
    1442                                 'success' => false,
    1443                                 'error'   => 'Connection test failed: ' . $e->getMessage(),
    1444                         );
    1445                 }
    1446954        }
    1447955
    … …  
    1460968
    1461969                // Future implementation would handle direct file uploads to:
    1462                 // - OpenAI's file upload API
     970                // - ShareAI document models
    1463971                // - Gemini's document processing
    1464                 // - Claude's document analysis
     972                // - Local Ollama vision models
    1465973
    1466974                throw new Exception( 'Direct file processing not yet implemented. Use text extraction approach.' );
    … …  
    15751083        }
    15761084}
     1085
     1086if ( ! function_exists( 'aiohm_kb_no_provider_notice' ) ) {
     1087        /**
     1088         * Tell administrators when no AI provider is usable, so a site that relied
     1089         * on a removed key (OpenAI, Claude, Groq or a pasted ShareAI key) does not
     1090         * go quiet without a word. Shown on the AIOHM screens, the Dashboard and
     1091         * the Plugins screen, and only while nothing is set up.
     1092         */
     1093        function aiohm_kb_no_provider_notice() {
     1094                if ( ! current_user_can( 'manage_options' ) || ! function_exists( 'get_current_screen' ) ) {
     1095                        return;
     1096                }
     1097                $screen = get_current_screen();
     1098                $id     = $screen ? (string) $screen->id : '';
     1099                if ( false === strpos( $id, 'aiohm' ) && ! in_array( $id, array( 'dashboard', 'plugins' ), true ) ) {
     1100                        return;
     1101                }
     1102                $settings = class_exists( 'AIOHM_KB_Assistant' ) ? AIOHM_KB_Assistant::get_settings() : array();
     1103                foreach ( aiohm_kb_ai_provider_ids() as $provider ) {
     1104                        if ( aiohm_kb_ai_provider_available( $provider, $settings ) ) {
     1105                                return;
     1106                        }
     1107                }
     1108                $settings_url = admin_url( 'admin.php?page=aiohm-settings#aiohm-shareai-connect' );
     1109                echo '<div class="notice notice-warning"><p><strong>' . esc_html__( 'AIOHM Knowledge Assistant has no AI provider yet, so the assistant cannot answer.', 'aiohm-knowledge-assistant' ) . '</strong> ';
     1110                echo esc_html__( 'Connect ShareAI, set up a local Ollama server, or add OpenAI, Anthropic or Google in Settings > Connectors.', 'aiohm-knowledge-assistant' );
     1111                echo ' <a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Open AIOHM settings', 'aiohm-knowledge-assistant' ) . '</a></p></div>';
     1112        }
     1113        add_action( 'admin_notices', 'aiohm_kb_no_provider_notice' );
     1114}
  • aiohm-knowledge-assistant/tags/3.1.0/includes/core-init.php

    r3545079 r3833232  
    517517     */
    518518    private static function is_provider_configured($settings, $provider) {
    519         switch ($provider) {
    520             case 'shareai':
    521                 return !empty($settings['shareai_api_key']);
    522             case 'openai':
    523                 return !empty($settings['openai_api_key'])
    524                     || (function_exists('aiohm_kb_is_wp_ai_connector_configured') && aiohm_kb_is_wp_ai_connector_configured('openai'));
    525             case 'gemini':
    526                 return !empty($settings['gemini_api_key'])
    527                     || (function_exists('aiohm_kb_is_wp_ai_connector_configured') && aiohm_kb_is_wp_ai_connector_configured('gemini'));
    528             case 'claude':
    529                 return !empty($settings['claude_api_key'])
    530                     || (function_exists('aiohm_kb_is_wp_ai_connector_configured') && aiohm_kb_is_wp_ai_connector_configured('claude'));
    531             default:
    532                 return false;
    533         }
     519        return aiohm_kb_ai_provider_available((string) $provider, $settings);
    534520    }
    535521
    … …  
    1003989                $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    1004990            }
    1005             $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];
     991            $provider_priority = aiohm_kb_ai_provider_ids();
    1006992           
    1007993            // If no default set, find first available provider
    … …  
    10261012           
    10271013            // Set appropriate model based on provider
    1028             switch ($default_provider) {
    1029                 case 'shareai':
    1030                     $model = $settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    1031                     break;
    1032                 case 'gemini':
    1033                     $model = 'gemini-pro';
    1034                     break;
    1035                 case 'claude':
    1036                     $model = 'claude-3-sonnet-20240229';
    1037                     break;
    1038                 case 'openai':
    1039                     $model = 'gpt-4';
    1040                     break;
    1041                 default:
    1042                     $model = 'gpt-4'; // Final fallback
    1043                     break;
    1044             }
     1014            $model = aiohm_kb_default_model_for_provider($default_provider, $settings);
    10451015           
    10461016            // Enhanced formatting instructions for better readability
    … …  
    11021072
    11031073    public static function handle_frontend_chat_ajax() {
    1104         // Enhanced rate limiting for chat requests - stricter for public endpoints
    1105         $user_id = get_current_user_id() ?: 0;
    1106         $rate_limit = $user_id > 0 ? 50 : 20; // Lower limit for non-authenticated users
    1107        
    1108         if (!AIOHM_KB_Assistant::check_enhanced_rate_limit('frontend_chat', $user_id, $rate_limit)) {
    1109             wp_send_json_error(['reply' => __('Chat rate limit exceeded. Please wait before sending more messages.', 'aiohm-knowledge-assistant')]);
    1110         }
    1111 
    11121074        if (!check_ajax_referer('aiohm_chat_nonce', 'nonce', false)) {
    11131075            wp_send_json_error(['reply' => __('Security check failed.', 'aiohm-knowledge-assistant')]);
    11141076        }
    1115        
    1116         // Additional validation for public endpoints
    11171077        if (!isset($_POST['message']) || !is_string($_POST['message'])) {
    11181078            wp_send_json_error(['reply' => __('Invalid message format.', 'aiohm-knowledge-assistant')]);
    … …  
    11201080
    11211081        try {
    1122             $user_message = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : '';
    1123            
    1124             // Enhanced message validation
    1125             if (empty(trim($user_message))) {
    1126                 wp_send_json_error(['reply' => __('Message cannot be empty.', 'aiohm-knowledge-assistant')]);
    1127             }
    1128            
    1129             if (strlen($user_message) > 2000) {
    1130                 wp_send_json_error(['reply' => __('Message is too long. Please limit to 2000 characters.', 'aiohm-knowledge-assistant')]);
    1131             }
    1132            
    1133             // Check for potentially malicious content
    1134             if (preg_match('/<script|<iframe|javascript:|vbscript:|onload=|onerror=/i', $user_message)) {
    1135                 wp_send_json_error(['reply' => __('Message contains invalid content.', 'aiohm-knowledge-assistant')]);
    1136             }
    1137            
    1138             $settings = AIOHM_KB_Assistant::get_settings();
    1139             $mirror_settings = $settings['mirror_mode'] ?? [];
    1140 
    1141             $ai_client = new AIOHM_KB_AI_GPT_Client();
    1142             $rag_engine = new AIOHM_KB_RAG_Engine();
    1143            
     1082            $answer = self::answer_public_question(sanitize_textarea_field(wp_unslash($_POST['message'])));
     1083            wp_send_json_success(['reply' => $answer['reply'], 'sources' => $answer['sources'], 'assistant_name' => $answer['assistant_name']]);
     1084        } catch (Exception $e) {
     1085            wp_send_json_error(['reply' => $e->getMessage()]);
     1086        }
     1087    }
     1088
     1089    /**
     1090     * Muse's public answer to one visitor question, from this site's public
     1091     * knowledge base. Used by the plugin's own chat and by any site widget
     1092     * that wants Muse (for example a theme's floating assistant).
     1093     *
     1094     * @param string $user_message The visitor's question.
     1095     * @return array{reply: string, sources: array<int, array{title: string, url: string}>, assistant_name: string}
     1096     * @throws Exception With a message that is safe to show the visitor.
     1097     */
     1098    public static function answer_public_question($user_message) {
     1099        $user_message = trim((string) $user_message);
     1100        $user_id = get_current_user_id() ?: 0;
     1101        if (!AIOHM_KB_Assistant::check_enhanced_rate_limit('frontend_chat', $user_id, $user_id > 0 ? 50 : 20)) {
     1102            throw new Exception(esc_html__('Chat rate limit exceeded. Please wait before sending more messages.', 'aiohm-knowledge-assistant'));
     1103        }
     1104        if ($user_message === '') {
     1105            throw new Exception(esc_html__('Message cannot be empty.', 'aiohm-knowledge-assistant'));
     1106        }
     1107        if (strlen($user_message) > 2000) {
     1108            throw new Exception(esc_html__('Message is too long. Please limit to 2000 characters.', 'aiohm-knowledge-assistant'));
     1109        }
     1110        if (preg_match('/<script|<iframe|javascript:|vbscript:|onload=|onerror=/i', $user_message)) {
     1111            throw new Exception(esc_html__('Message contains invalid content.', 'aiohm-knowledge-assistant'));
     1112        }
     1113
     1114        $settings = AIOHM_KB_Assistant::get_settings();
     1115        $mirror_settings = $settings['mirror_mode'] ?? [];
     1116        $assistant_name = trim((string) ($mirror_settings['assistant_name'] ?? '')) ?: 'Muse';
     1117
     1118        $ai_client = new AIOHM_KB_AI_GPT_Client();
     1119        $rag_engine = new AIOHM_KB_RAG_Engine();
     1120
     1121        $context_data = [];
     1122        try {
    11441123            $context_data = $rag_engine->find_relevant_context($user_message, 5);
    1145             $context_string = "";
    1146             $has_context = false;
    1147            
    1148             if (!empty($context_data)) {
    1149                 foreach ($context_data as $data) {
    1150                     $context_string .= "Source: " . $data['entry']['title'] . "\nContent: " . $data['entry']['content'] . "\n\n";
    1151                 }
    1152                 $has_context = true;
    1153             }
    1154            
    1155             // Check if this is a greeting or basic interaction that doesn't need knowledge base context
    1156             $greeting_patterns = ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening', 'greetings', 'how are you', 'what\'s up', 'sup', 'heloo', 'helo', 'hllo'];
    1157             $is_greeting = false;
    1158            
    1159             // Also check for very short messages (likely greetings)
    1160             $is_short_message = strlen(trim($user_message)) <= 10;
    1161            
    1162             foreach ($greeting_patterns as $pattern) {
    1163                 if (stripos($user_message, $pattern) !== false) {
    1164                     $is_greeting = true;
     1124        } catch (Exception $e) {
     1125            $context_data = [];
     1126        }
     1127
     1128        $context_string = '';
     1129        $sources = [];
     1130        foreach ((array) $context_data as $data) {
     1131            $entry = $data['entry'] ?? [];
     1132            $context_string .= 'Source: ' . ($entry['title'] ?? '') . "\nContent: " . ($entry['content'] ?? '') . "\n\n";
     1133            $meta = json_decode((string) ($entry['metadata'] ?? ''), true);
     1134            $post_id = is_array($meta) ? (int) ($meta['post_id'] ?? 0) : 0;
     1135            $url = $post_id > 0 ? get_permalink($post_id) : '';
     1136            if ($url && !isset($sources[$url])) {
     1137                $sources[$url] = ['title' => wp_strip_all_tags((string) ($entry['title'] ?? get_the_title($post_id))), 'url' => $url];
     1138            }
     1139        }
     1140        $has_context = $context_string !== '';
     1141
     1142        $greeting_patterns = ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening', 'greetings', 'how are you', 'what\'s up', 'sup', 'heloo', 'helo', 'hllo'];
     1143        $is_greeting = strlen($user_message) <= 10;
     1144        foreach ($greeting_patterns as $pattern) {
     1145            if (stripos($user_message, $pattern) !== false) {
     1146                $is_greeting = true;
     1147                break;
     1148            }
     1149        }
     1150        if (!$has_context && !$is_greeting) {
     1151            $context_string = 'No relevant context found in the knowledge base.';
     1152        } elseif (!$has_context) {
     1153            $context_string = 'GREETING DETECTED: respond warmly, introduce yourself by name, and offer to help. No knowledge base context is needed for a greeting.';
     1154        }
     1155
     1156        // Muse's identity comes first, whatever prompt the site owner wrote.
     1157        $identity = "Your name is %assistant_name%. You are the AI guide of %site_name%, built on the AIOHM Knowledge Assistant. "
     1158            . "When you introduce yourself, use your name. Answer from the knowledge base below. Never invent prices, results, testimonials, clients or integrations; "
     1159            . "when the knowledge base does not cover a question, say so plainly and suggest contacting the team.\n\n";
     1160        $system_message = $identity . ($mirror_settings['qa_system_message'] ?? 'You are a helpful assistant.');
     1161        $temperature = floatval($mirror_settings['qa_temperature'] ?? 0.8);
     1162
     1163        $default_provider = $settings['default_ai_provider'] ?? null;
     1164        if (function_exists('aiohm_kb_normalize_wp_ai_provider_id')) {
     1165            $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
     1166        }
     1167        if (!$default_provider || !self::is_provider_configured($settings, $default_provider)) {
     1168            foreach (aiohm_kb_ai_provider_ids() as $provider) {
     1169                if (self::is_provider_configured($settings, $provider)) {
     1170                    $default_provider = $provider;
    11651171                    break;
    11661172                }
    11671173            }
    1168            
    1169             // Consider it a greeting if it's a short message or matches greeting patterns
    1170             $is_greeting = $is_greeting || $is_short_message;
    1171            
    1172             if (!$has_context && !$is_greeting) {
    1173                 $context_string = "No relevant context found in the knowledge base.";
    1174             } elseif (!$has_context && $is_greeting) {
    1175                 $context_string = "GREETING DETECTED: This is a friendly greeting or casual message. You should respond warmly and naturally as the brand representative. Introduce yourself, welcome them, and offer to help. You DO NOT need knowledge base context for basic greetings and social interactions. Be conversational and friendly.";
    1176             }
    1177 
    1178             $system_message = $mirror_settings['qa_system_message'] ?? 'You are a helpful assistant.';
    1179             $temperature = floatval($mirror_settings['qa_temperature'] ?? 0.8);
    1180            
    1181             // Use the user's selected default AI provider with smart fallback
    1182             $default_provider = $settings['default_ai_provider'] ?? null;
    1183             if (function_exists('aiohm_kb_normalize_wp_ai_provider_id')) {
    1184                 $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    1185             }
    1186             $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];
    1187            
    1188             // If no default set, find first available provider
    1189             if (!$default_provider) {
    1190                 foreach ($provider_priority as $provider) {
    1191                     if (self::is_provider_configured($settings, $provider)) {
    1192                         $default_provider = $provider;
    1193                         break;
    1194                     }
    1195                 }
    1196             }
    1197            
    1198             // If default provider not configured, fallback to next available
    1199             if (!self::is_provider_configured($settings, $default_provider)) {
    1200                 foreach ($provider_priority as $provider) {
    1201                     if (self::is_provider_configured($settings, $provider)) {
    1202                         $default_provider = $provider;
    1203                         break;
    1204                     }
    1205                 }
    1206             }
    1207            
    1208             // Set appropriate model based on provider (Mirror Mode)
    1209             switch ($default_provider) {
    1210                 case 'shareai':
    1211                     $model = $settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    1212                     break;
    1213                 case 'gemini':
    1214                     $model = 'gemini-pro';
    1215                     break;
    1216                 case 'claude':
    1217                     $model = 'claude-3-sonnet-20240229';
    1218                     break;
    1219                 case 'openai':
    1220                     $model = 'gpt-3.5-turbo';
    1221                     break;
    1222                 default:
    1223                     $model = 'gpt-3.5-turbo'; // Final fallback
    1224                     break;
    1225             }
    1226            
    1227             // Apply variable replacements to system message
    1228             $replacements = [
    1229                 '{context}'        => $context_string,
    1230                 '%site_name%'      => get_bloginfo('name'),
    1231                 '%site_tagline%'   => get_bloginfo('description'),
    1232                 '%business_name%'  => $mirror_settings['business_name'] ?? get_bloginfo('name'),
    1233                 '%day_of_week%'    => wp_date('l'),
    1234                 '%current_date%'   => wp_date(get_option('date_format')),
    1235                 '%current_time%'   => wp_date(get_option('time_format')),
    1236             ];
    1237             $final_system_message = str_replace(array_keys($replacements), array_values($replacements), $system_message);
    1238 
     1174        }
     1175        $model = aiohm_kb_default_model_for_provider($default_provider, $settings);
     1176
     1177        $replacements = [
     1178            '{context}'         => $context_string,
     1179            '%assistant_name%'  => $assistant_name,
     1180            '%site_name%'       => get_bloginfo('name'),
     1181            '%site_tagline%'    => get_bloginfo('description'),
     1182            '%business_name%'   => $mirror_settings['business_name'] ?? get_bloginfo('name'),
     1183            '%day_of_week%'     => wp_date('l'),
     1184            '%current_date%'    => wp_date(get_option('date_format')),
     1185            '%current_time%'    => wp_date(get_option('time_format')),
     1186        ];
     1187        $final_system_message = str_replace(array_keys($replacements), array_values($replacements), $system_message);
     1188
     1189        try {
    12391190            $answer = $ai_client->get_chat_completion($final_system_message, $user_message, $temperature, $model);
    1240            
    1241             // Apply variable replacements to the AI response as well in case it contains placeholders
    1242             // Use strtr instead of str_replace to avoid partial matches and conflicts
    1243             $final_answer = strtr($answer, $replacements);
    1244 
    1245             wp_send_json_success(['reply' => $final_answer]);
    1246 
    12471191        } catch (Exception $e) {
    1248             wp_send_json_error(['reply' => __('An error occurred while processing your request. Please try again.', 'aiohm-knowledge-assistant')]);
    1249         }
     1192            // Keep provider internals private; ShareAI's own wording and
     1193            // messages written for visitors (the daily limit) are already safe.
     1194            $text = $e->getMessage();
     1195            $visitor_safe = (class_exists('AIOHM_KB_Visitor_Message_Exception') && $e instanceof AIOHM_KB_Visitor_Message_Exception)
     1196                || (stripos($text, 'ShareAI') !== false && strpos($text, 'API Error') === false);
     1197            throw new Exception(esc_html($visitor_safe
     1198                ? $text
     1199                : __('An error occurred while processing your request. Please try again.', 'aiohm-knowledge-assistant')));
     1200        }
     1201
     1202        return [
     1203            'reply' => strtr($answer, $replacements),
     1204            'sources' => array_values(array_slice($sources, 0, 5)),
     1205            'assistant_name' => $assistant_name,
     1206        ];
    12501207    }
    12511208   
    … …  
    14351392                $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    14361393            }
    1437             $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];
     1394            $provider_priority = aiohm_kb_ai_provider_ids();
    14381395           
    14391396            // If no default set, find first available provider
    … …  
    14581415           
    14591416            // Set appropriate model based on provider (Mirror Mode Test)
    1460             switch ($default_provider) {
    1461                 case 'shareai':
    1462                     $model = $current_settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    1463                     break;
    1464                 case 'gemini':
    1465                     $model = 'gemini-pro';
    1466                     break;
    1467                 case 'claude':
    1468                     $model = 'claude-3-sonnet-20240229';
    1469                     break;
    1470                 case 'openai':
    1471                     $model = 'gpt-3.5-turbo';
    1472                     break;
    1473                 default:
    1474                     $model = 'gpt-3.5-turbo'; // Final fallback
    1475                     break;
    1476             }
     1417            $model = aiohm_kb_default_model_for_provider($default_provider, $current_settings);
    14771418           
    14781419            $answer = $ai_client->get_chat_completion($final_system_message, $user_message, $temperature, $model);
    … …  
    15031444            $system_prompt = wp_kses_post($posted_settings['system_prompt'] ?? 'You are a helpful brand assistant.');
    15041445            $temperature = floatval($posted_settings['temperature'] ?? 0.7);
    1505             $model = sanitize_text_field($posted_settings['ai_model'] ?? 'gpt-4');
     1446            $model = sanitize_text_field($posted_settings['ai_model'] ?? '');
    15061447   
    15071448            // Initialize AI client with current settings
    … …  
    15541495                    // Check prerequisites - validate API key for selected provider
    15551496                    $settings = AIOHM_KB_Assistant::get_settings();
    1556                     $default_provider = $settings['default_ai_provider'] ?? 'openai';
    1557                     if (function_exists('aiohm_kb_normalize_wp_ai_provider_id')) {
    1558                         $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    1559                     }
     1497                    $default_provider = aiohm_kb_resolve_ai_provider($settings['default_ai_provider'] ?? '', $settings);
    15601498                   
    15611499                    // Check if the selected default provider has proper configuration
    15621500                    $api_key_exists = false;
    15631501                    $provider_names = [
     1502                        'shareai' => 'ShareAI',
     1503                        'gemini' => 'Gemini',
     1504                        'ollama' => 'Ollama',
    15641505                        'openai' => 'OpenAI',
    1565                         'gemini' => 'Gemini',
    1566                         'claude' => 'Claude',
    1567                         'shareai' => 'ShareAI',
    1568                         'groq' => 'Groq',
    1569                         'ollama' => 'Ollama'
     1506                        'anthropic' => 'Anthropic'
    15701507                    ];
    15711508                   
    1572                     switch ($default_provider) {
    1573                         case 'openai':
    1574                             $api_key_exists = !empty($settings['openai_api_key']);
    1575                             break;
    1576                         case 'gemini':
    1577                             $api_key_exists = !empty($settings['gemini_api_key']);
    1578                             break;
    1579                         case 'claude':
    1580                             $api_key_exists = !empty($settings['claude_api_key']);
    1581                             break;
    1582                         case 'shareai':
    1583                             $api_key_exists = !empty($settings['shareai_api_key']);
    1584                             break;
    1585                         case 'groq':
    1586                             $api_key_exists = !empty($settings['groq_api_key']);
    1587                             break;
    1588                         case 'ollama':
    1589                             $ollama_enabled = $settings['pro_features']['ollama_enabled'] ?? false;
    1590                             $ollama_url = $settings['pro_features']['ollama_server_url'] ?? ($settings['private_llm_server_url'] ?? '');
    1591                             $api_key_exists = $ollama_enabled && !empty($ollama_url);
    1592                             break;
    1593                         default:
    1594                             $api_key_exists = false;
    1595                     }
     1509                    $api_key_exists = aiohm_kb_ai_provider_available($default_provider, $settings);
    15961510                   
    15971511                    if (!$api_key_exists) {
    … …  
    17271641        $api_key = '';
    17281642        switch ($key_type) {
    1729             case 'openai':
    1730                 $api_key = $settings['openai_api_key'] ?? '';
    1731                 if ( empty( $api_key ) && function_exists( 'aiohm_kb_get_wp_connector_api_key' ) ) {
    1732                     $api_key = aiohm_kb_get_wp_connector_api_key( 'openai' );
    1733                 }
     1643            case 'shareai':
     1644                // ShareAI has no key: the test checks the connected account.
     1645                $api_key = aiohm_kb_shareai_available($settings) ? 'connected' : '';
    17341646                break;
    17351647            case 'gemini':
    … …  
    17391651                }
    17401652                break;
    1741             case 'claude':
    1742                 $api_key = $settings['claude_api_key'] ?? '';
    1743                 if ( empty( $api_key ) && function_exists( 'aiohm_kb_get_wp_connector_api_key' ) ) {
    1744                     $api_key = aiohm_kb_get_wp_connector_api_key( 'claude' );
    1745                 }
    1746                 break;
    1747             case 'shareai':
    1748                 $api_key = $settings['shareai_api_key'] ?? '';
    1749                 break;
    1750             case 'groq':
    1751                 $api_key = $settings['groq_api_key'] ?? '';
    1752                 break;
    17531653        }
    17541654       
    … …  
    17581658        try {
    17591659            switch ($key_type) {
    1760                 case 'openai':
     1660                case 'shareai':
    17611661                    $ai_client = new AIOHM_KB_AI_GPT_Client($settings);
    1762                     $result = $ai_client->test_api_connection();
     1662                    $result = $ai_client->test_shareai_api_connection();
    17631663                    if ($result['success']) {
    1764                         wp_send_json_success(['message' => __('OpenAI connection successful!', 'aiohm-knowledge-assistant')]);
     1664                        wp_send_json_success(['message' => __('ShareAI connection successful!', 'aiohm-knowledge-assistant')]);
    17651665                    } else {
    1766                         // translators: %s is the OpenAI API error message
    1767                         wp_send_json_error(['message' => sprintf(__('OpenAI connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
     1666                        // translators: %s is the ShareAI API error message
     1667                        wp_send_json_error(['message' => sprintf(__('ShareAI connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
    17681668                    }
    17691669                    break;
    … …  
    17781678                    }
    17791679                    break;
    1780                 case 'claude':
    1781                     $ai_client = new AIOHM_KB_AI_GPT_Client($settings);
    1782                     $result = $ai_client->test_claude_api_connection();
    1783                     if ($result['success']) {
    1784                         wp_send_json_success(['message' => __('Claude connection successful!', 'aiohm-knowledge-assistant')]);
    1785                     } else {
    1786                         // translators: %s is the Claude API error message
    1787                         wp_send_json_error(['message' => sprintf(__('Claude connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
    1788                     }
    1789                     break;
    1790                 case 'shareai':
    1791                     $ai_client = new AIOHM_KB_AI_GPT_Client($settings);
    1792                     $result = $ai_client->test_shareai_api_connection();
    1793                     if ($result['success']) {
    1794                         wp_send_json_success(['message' => __('ShareAI connection successful!', 'aiohm-knowledge-assistant')]);
    1795                     } else {
    1796                         // translators: %s is the ShareAI API error message
    1797                         wp_send_json_error(['message' => sprintf(__('ShareAI connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
    1798                     }
    1799                     break;
    1800                 case 'groq':
    1801                     $ai_client = new AIOHM_KB_AI_GPT_Client($settings);
    1802                     $result = $ai_client->test_groq_api_connection();
    1803                     if ($result['success']) {
    1804                         wp_send_json_success(['message' => __('Groq connection successful!', 'aiohm-knowledge-assistant')]);
    1805                     } else {
    1806                         // translators: %s is the Groq API error message
    1807                         wp_send_json_error(['message' => sprintf(__('Groq connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
    1808                     }
    1809                     break;
    18101680                default:
    18111681                    wp_send_json_error(['message' => __('Invalid key type specified.', 'aiohm-knowledge-assistant')]);
    … …  
    18551725           
    18561726            // Enhanced API key validation and encryption
    1857             if (in_array($setting_name, ['openai_api_key', 'gemini_api_key', 'claude_api_key', 'groq_api_key'])) {
     1727            $supported_key_settings = ['gemini_api_key'];
     1728            if (substr($setting_name, -8) === '_api_key' && !in_array($setting_name, $supported_key_settings, true)) {
     1729                // Keys for providers AIOHM no longer supports are not accepted.
     1730                wp_send_json_error(['message' => __('This AI provider is no longer supported.', 'aiohm-knowledge-assistant')]);
     1731            }
     1732
     1733            if ($setting_name === 'gemini_api_key') {
    18581734                // Validate API key format using new validation function
    18591735                $provider = str_replace('_api_key', '', $setting_name);
    … …  
    18661742                // Encrypt the validated API key
    18671743                $current_settings[$setting_name] = AIOHM_KB_Assistant::encrypt_api_key($validated_key);
    1868             } elseif ($setting_name === 'shareai_api_key') {
    1869                 // Validate ShareAI key
    1870                 $validated_key = AIOHM_KB_Assistant::validate_and_sanitize_api_key($api_value, 'shareai');
    1871                
    1872                 if (is_wp_error($validated_key)) {
    1873                     wp_send_json_error(['message' => $validated_key->get_error_message()]);
    1874                 }
    1875                
    1876                 $current_settings[$setting_name] = $validated_key;
    18771744            } else {
    18781745                // For non-API keys (like models), save as plain text with additional validation
    … …  
    19361803                    wp_send_json_success(['message' => __('ShareAI model saved successfully!', 'aiohm-knowledge-assistant')]);
    19371804                } else {
    1938                     // translators: %s is the API provider name (e.g., OpenAI, Claude)
     1805                    // translators: %s is the API provider name (e.g., Gemini, ShareAI)
    19391806                    wp_send_json_success(['message' => sprintf(__('%s API key saved successfully!', 'aiohm-knowledge-assistant'), ucfirst($api_type))]);
    19401807                }
    … …  
    24062273        $settings['mirror_mode']['ai_avatar'] = esc_url_raw($settings_input['ai_avatar'] ?? '');
    24072274        $settings['mirror_mode']['welcome_message'] = wp_kses_post(trim($settings_input['welcome_message'] ?? ''));
    2408         $settings['mirror_mode']['ai_model'] = sanitize_text_field($settings_input['ai_model'] ?? 'gpt-3.5-turbo');
     2275        $settings['mirror_mode']['ai_model'] = sanitize_text_field($settings_input['ai_model'] ?? '');
    24092276       
    24102277        // Handle URL sanitization with proper validation
    … …  
    25012368        }
    25022369       
    2503         $settings['muse_mode']['ai_model'] = sanitize_text_field($muse_input['ai_model'] ?? 'gpt-4');
     2370        $settings['muse_mode']['ai_model'] = sanitize_text_field($muse_input['ai_model'] ?? '');
    25042371        $settings['muse_mode']['temperature'] = floatval($muse_input['temperature'] ?? 0.7);
    25052372        $settings['muse_mode']['start_fullscreen'] = isset($muse_input['start_fullscreen']) ? 1 : 0;
    … …  
    25552422            } else {
    25562423                // Fallback to default provider if no Mirror Mode model is set
    2557                 $default_provider = $settings['default_ai_provider'] ?? 'openai';
    2558                 if (function_exists('aiohm_kb_normalize_wp_ai_provider_id')) {
    2559                     $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    2560                 }
    2561                 switch ($default_provider) {
    2562                     case 'gemini':
    2563                         $model = 'gemini-pro';
    2564                         break;
    2565                     case 'claude':
    2566                         $model = 'claude-3-sonnet';
    2567                         break;
    2568                     case 'shareai':
    2569                         $model = 'shareai-llama4:17b-scout-16e-instruct-fp16';
    2570                         break;
    2571                     case 'openai':
    2572                     default:
    2573                         $model = 'gpt-3.5-turbo';
    2574                         break;
    2575                 }
     2424                $default_provider = aiohm_kb_resolve_ai_provider($settings['default_ai_provider'] ?? '', $settings);
     2425                $model = aiohm_kb_default_model_for_provider($default_provider, $settings);
    25762426            }
    25772427           
    … …  
    40243874            // Format provider data
    40253875            $providers = [
    4026                 'openai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],
     3876                'shareai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],
    40273877                'gemini' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],
    4028                 'claude' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],
    4029                 'shareai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00']
     3878                'ollama' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00']
    40303879            ];
    40313880
    … …  
    43694218                $research_prompt,
    43704219                0.3,
    4371                 $settings['muse_mode']['ai_model'] ?? 'gpt-3.5-turbo'
     4220                $settings['muse_mode']['ai_model'] ?? ''
    43724221            );
    43734222           
    … …  
    55665415            // Test each configured API
    55675416            $apis_to_test = [
    5568                 'openai' => $settings['openai_api_key'] ?? '',
     5417                'shareai' => aiohm_kb_shareai_available($settings) ? 'connected' : '',
    55695418                'gemini' => $settings['gemini_api_key'] ?? '',
    5570                 'claude' => $settings['claude_api_key'] ?? '',
    5571                 'shareai' => $settings['shareai_api_key'] ?? ''
     5419                'ollama' => aiohm_kb_ollama_available($settings) ? ($settings['pro_features']['ollama_server_url'] ?? ($settings['private_llm_server_url'] ?? '')) : ''
    55725420            ];
    55735421           
    … …  
    55895437                   
    55905438                    switch ($provider) {
    5591                         case 'openai':
    5592                             $test_result = $ai_client->test_api_connection();
     5439                        case 'shareai':
     5440                            $test_result = $ai_client->test_shareai_api_connection();
    55935441                            break;
    55945442                        case 'gemini':
    55955443                            $test_result = $ai_client->test_gemini_api_connection();
    55965444                            break;
    5597                         case 'claude':
    5598                             $test_result = $ai_client->test_claude_api_connection();
    5599                             break;
    5600                         case 'shareai':
    5601                             $test_result = $ai_client->test_shareai_api_connection();
     5445                        case 'ollama':
     5446                            $test_result = $ai_client->test_ollama_api_connection();
    56025447                            break;
    56035448                    }
  • aiohm-knowledge-assistant/tags/3.1.0/includes/parsers/ai-fallback-parser.php

    r3545079 r3833232  
    6464                $settings = AIOHM_KB_Assistant::get_settings();
    6565
    66                 // Check if any AI provider is configured
    67                 $providers = array( 'openai_api_key', 'gemini_api_key', 'claude_api_key' );
    68                 foreach ( $providers as $provider ) {
    69                         if ( ! empty( $settings[ $provider ] ) ) {
     66                // Check if any supported AI provider (ShareAI, Gemini, Ollama) is set up.
     67                foreach ( aiohm_kb_ai_provider_ids() as $provider ) {
     68                        if ( aiohm_kb_ai_provider_available( $provider, $settings ) ) {
    7069                                return true;
    7170                        }
    72                 }
    73 
    74                 if ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) ) {
    75                         if ( aiohm_kb_is_wp_ai_connector_configured( 'openai' ) ||
    76                                  aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) ||
    77                                  aiohm_kb_is_wp_ai_connector_configured( 'claude' ) ) {
    78                                 return true;
    79                         }
    80                 }
    81 
    82                 if ( ! empty( get_option( 'connectors_ai_openai_api_key' ) ) ||
    83                          ! empty( get_option( 'connectors_ai_google_api_key' ) ) ||
    84                          ! empty( get_option( 'connectors_ai_gemini_api_key' ) ) ||
    85                          ! empty( get_option( 'connectors_ai_anthropic_api_key' ) ) ||
    86                          ! empty( get_option( 'connectors_ai_claude_api_key' ) ) ||
    87                          ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY ) ||
    88                          ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY ) ||
    89                          ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY ) ||
    90                          ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY ) ||
    91                          ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY ) ||
    92                          getenv( 'OPENAI_API_KEY' ) ||
    93                          getenv( 'GOOGLE_API_KEY' ) ||
    94                          getenv( 'GEMINI_API_KEY' ) ||
    95                          getenv( 'ANTHROPIC_API_KEY' ) ||
    96                          getenv( 'CLAUDE_API_KEY' ) ) {
    97                         return true;
    9871                }
    9972
    … …  
    469442                        $system_message = 'You are an expert document parser. Extract clean, readable text content from the provided document data. Remove any metadata, formatting artifacts, or technical gibberish. Return only the meaningful text content.';
    470443
    471                         $response = $this->ai_client->get_chat_completion( $system_message, $prompt, 0.3 );
     444                        $settings = AIOHM_KB_Assistant::get_settings();
     445                        $provider = $this->get_active_provider( $settings );
     446                        $model    = '' !== $provider ? aiohm_kb_default_model_for_provider( $provider, $settings ) : '';
     447
     448                        $response = $this->ai_client->get_chat_completion( $system_message, $prompt, 0.3, $model );
    472449
    473450                        if ( empty( $response ) ) {
    … …  
    545522
    546523        /**
     524         * The provider the parser sends requests to: the default provider when
     525         * it is set up, else the first set-up one of ShareAI, Gemini and Ollama.
     526         *
     527         * @param array $settings Plugin settings.
     528         * @return string Provider ID, or an empty string when none is set up.
     529         */
     530        private function get_active_provider( $settings ) {
     531                $provider = aiohm_kb_resolve_ai_provider( $settings['default_ai_provider'] ?? '', $settings );
     532                if ( aiohm_kb_ai_provider_available( $provider, $settings ) ) {
     533                        return $provider;
     534                }
     535                foreach ( aiohm_kb_ai_provider_ids() as $candidate ) {
     536                        if ( aiohm_kb_ai_provider_available( $candidate, $settings ) ) {
     537                                return $candidate;
     538                        }
     539                }
     540                return '';
     541        }
     542
     543        /**
    547544         * Get AI model information
    548545         *
    … …  
    552549                $settings = AIOHM_KB_Assistant::get_settings();
    553550
    554                 $aiohm_has_openai = ! empty( $settings['openai_api_key'] )
    555                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    556                         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    557                         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    558                         || getenv( 'OPENAI_API_KEY' );
    559 
    560                 $aiohm_has_gemini = ! empty( $settings['gemini_api_key'] )
    561                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    562                         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    563                         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    564                         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    565                         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    566                         || getenv( 'GOOGLE_API_KEY' )
    567                         || getenv( 'GEMINI_API_KEY' );
    568 
    569                 $aiohm_has_claude = ! empty( $settings['claude_api_key'] )
    570                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    571                         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    572                         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    573                         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    574                         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    575                         || getenv( 'ANTHROPIC_API_KEY' )
    576                         || getenv( 'CLAUDE_API_KEY' );
    577 
    578                 // Determine which AI provider was used
    579                 if ( $aiohm_has_openai ) {
    580                         return array(
    581                                 'provider' => 'openai',
    582                                 'model'    => $settings['openai_model'] ?? 'gpt-3.5-turbo',
    583                         );
    584                 } elseif ( $aiohm_has_gemini ) {
    585                         return array(
    586                                 'provider' => 'gemini',
    587                                 'model'    => 'gemini-pro',
    588                         );
    589                 } elseif ( $aiohm_has_claude ) {
    590                         return array(
    591                                 'provider' => 'claude',
    592                                 'model'    => 'claude-3',
    593                         );
     551                switch ( $this->get_active_provider( $settings ) ) {
     552                        case 'shareai':
     553                                $model = (string) ( $settings['shareai_model'] ?? '' );
     554                                return array(
     555                                        'provider' => 'shareai',
     556                                        'model'    => '' !== $model ? $model : 'deepseek/deepseek-v4-flash',
     557                                );
     558                        case 'gemini':
     559                                return array(
     560                                        'provider' => 'gemini',
     561                                        'model'    => 'gemini-pro',
     562                                );
     563                        case 'ollama':
     564                                return array(
     565                                        'provider' => 'ollama',
     566                                        'model'    => $settings['pro_features']['ollama_model'] ?? ( $settings['private_llm_model'] ?? 'llama3.2:latest' ),
     567                                );
    594568                }
    595569
  • aiohm-knowledge-assistant/tags/3.1.0/includes/rag-engine.php

    r3801374 r3833232  
    5151                }
    5252                return $table_name;
     53        }
     54
     55        /**
     56         * An embedding for the text, or null when no provider can embed right now
     57         * (for example ShareAI without an embedding model and no Gemini or Ollama).
     58         * Entries without a vector are still stored and found by full-text search.
     59         *
     60         * @param AIOHM_KB_AI_GPT_Client $ai_client Client to ask.
     61         * @param string                 $text      Text to embed.
     62         * @return array|null
     63         */
     64        private function try_embedding( $ai_client, $text ) {
     65                try {
     66                        $vector = $ai_client->generate_embeddings( $text );
     67                } catch ( Exception $e ) {
     68                        return null;
     69                }
     70                return ( is_array( $vector ) && ! empty( $vector ) ) ? $vector : null;
     71        }
     72
     73        /**
     74         * Cosine similarity, or null when the vectors cannot be compared (missing,
     75         * or built by a different embedding model with another dimension).
     76         *
     77         * @param array      $query_vector Query embedding.
     78         * @param array|null $vector       Stored embedding.
     79         * @return float|null
     80         */
     81        private function cosine_similarity( $query_vector, $vector ) {
     82                if ( ! is_array( $vector ) || count( $vector ) !== count( $query_vector ) ) {
     83                        return null;
     84                }
     85                $dot_product = array_sum( array_map( fn( $a, $b ) => $a * $b, $query_vector, $vector ) );
     86                $mag_a       = sqrt( array_sum( array_map( fn( $a ) => $a * $a, $query_vector ) ) );
     87                $mag_b       = sqrt( array_sum( array_map( fn( $b ) => $b * $b, $vector ) ) );
     88                if ( $mag_a <= 0 || $mag_b <= 0 ) {
     89                        return null;
     90                }
     91                return $dot_product / ( $mag_a * $mag_b );
    5392        }
    5493
    … …  
    104143                $successful_inserts = 0;
    105144                foreach ( $chunks as $chunk_index => $chunk ) {
    106                         $embedding = $ai_client->generate_embeddings( $chunk );
    107 
    108                         if ( ! $embedding || empty( $embedding ) ) {
    109                                 continue; // Skip chunks that fail embedding generation
    110                         }
     145                        // No embedding provider: keep the chunk, full-text search finds it.
     146                        $embedding = $this->try_embedding( $ai_client, $chunk );
    111147
    112148                        $chunk_metadata = array_merge( $metadata, array(
    … …  
    121157                                'title'        => $title,
    122158                                'content'      => $chunk,
    123                                 'vector_data'  => json_encode( $embedding ),
     159                                'vector_data'  => null === $embedding ? null : json_encode( $embedding ),
    124160                                'metadata'     => json_encode( $chunk_metadata ),
    125161                                'is_public'    => $is_public,
    … …  
    197233
    198234                $ai_client = new AIOHM_KB_AI_GPT_Client();
    199                 $embedding = $ai_client->generate_embeddings( $chunk );
    200 
    201                 if ( ! $embedding || empty( $embedding ) ) {
    202                         throw new Exception( 'Failed to generate embeddings.' );
    203                 }
     235                // No embedding provider: keep the chunk, full-text search finds it.
     236                $embedding = $this->try_embedding( $ai_client, $chunk );
    204237
    205238                $metadata = array(
    … …  
    216249                        'title'        => $title,
    217250                        'content'      => $chunk,
    218                         'vector_data'  => json_encode( $embedding ),
     251                        'vector_data'  => null === $embedding ? null : json_encode( $embedding ),
    219252                        'metadata'     => json_encode( $metadata ),
    220253                        'is_public'    => 0,
    … …  
    282315                        $system_message_key = ( $scope === 'private' ) ? 'system_prompt' : 'qa_system_message';
    283316                        $system_message     = $ai_settings[ $system_message_key ] ?? 'You are a helpful assistant.';
    284                         $model_name         = $ai_settings['ai_model'] ?? 'gpt-3.5-turbo';
     317                        $model_name         = $ai_settings['ai_model'] ?? '';
    285318                        $temperature        = $ai_settings['temperature'] ?? 0.7;
    286319
    … …  
    465498                }
    466499
    467                 $ai_client       = new AIOHM_KB_AI_GPT_Client();
    468                 $query_embedding = $ai_client->generate_embeddings( $query_text );
     500                // No embedding provider right now (for example ShareAI without
     501                // embeddings and no Gemini key): rank by full-text relevance below.
     502                $query_embedding = $this->try_embedding( new AIOHM_KB_AI_GPT_Client(), $query_text );
    469503
    470504                $keywords = preg_replace( '/[^a-z0-9\s]/i', '', strtolower( $query_text ) );
    … …  
    472506                $table_name = $this->table_name;
    473507                $safe_table = $this->get_safe_table_name( $wpdb->prefix . 'aiohm_vector_entries' );
     508
     509                // Without an embedding, full-text relevance is the ranking.
     510                if ( null === $query_embedding ) {
     511                        if ( '' === trim( $keywords ) ) {
     512                                return array();
     513                        }
     514                        $keyword_rows = $wpdb->get_results(
     515                                $wpdb->prepare(
     516                                        'SELECT id, title, content, content_type, metadata, vector_data FROM `' . esc_sql( $safe_table ) . '` WHERE user_id = 0 AND is_public = 1 AND MATCH(content) AGAINST(%s IN NATURAL LANGUAGE MODE) LIMIT %d',
     517                                        trim( $keywords ),
     518                                        (int) $limit
     519                                ),
     520                                ARRAY_A
     521                        ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
     522                        $keyword_hits = array();
     523                        foreach ( $this->filter_public_context_entries( (array) $keyword_rows ) as $entry ) {
     524                                $keyword_hits[] = array(
     525                                        'score' => null,
     526                                        'entry' => $entry,
     527                                );
     528                        }
     529                        return $keyword_hits;
     530                }
    474531
    475532                if ( ! empty( trim( $keywords ) ) ) {
    … …  
    571628                }
    572629
     630                if ( null === $query_embedding ) {
     631                        return array();
     632                }
     633
    573634                // Recheck persisted visibility even for cached candidates, so revocation is immediate.
    574635                $pre_filtered_entries = $this->filter_public_context_entries( $pre_filtered_entries );
    575636                $similarities = array();
    576637                foreach ( $pre_filtered_entries as $entry ) {
    577                         $vector = json_decode( $entry['vector_data'], true );
    578                         if ( is_array( $vector ) ) {
    579                                 $dot_product = array_sum( array_map( fn( $a, $b ) => $a * $b, $query_embedding, $vector ) );
    580                                 $mag_a       = sqrt( array_sum( array_map( fn( $a ) => $a * $a, $query_embedding ) ) );
    581                                 $mag_b       = sqrt( array_sum( array_map( fn( $b ) => $b * $b, $vector ) ) );
    582                                 if ( $mag_a > 0 && $mag_b > 0 ) {
    583                                         $similarities[] = array(
    584                                                 'score' => $dot_product / ( $mag_a * $mag_b ),
    585                                                 'entry' => $entry,
    586                                         );
    587                                 }
     638                        $vector = ! empty( $entry['vector_data'] ) ? json_decode( $entry['vector_data'], true ) : null;
     639                        $score  = $this->cosine_similarity( $query_embedding, $vector );
     640                        if ( null !== $score ) {
     641                                $similarities[] = array(
     642                                        'score' => $score,
     643                                        'entry' => $entry,
     644                                );
    588645                        }
    589646                }
    … …  
    11221179        public function find_context_for_user( $query_text, $user_id, $limit = 5 ) {
    11231180                global $wpdb;
    1124                 $ai_client       = new AIOHM_KB_AI_GPT_Client();
    1125                 $query_embedding = $ai_client->generate_embeddings( $query_text );
     1181                $query_embedding = $this->try_embedding( new AIOHM_KB_AI_GPT_Client(), $query_text );
    11261182        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
    11271183                // User context search query requires direct database access for vector similarity operations
    … …  
    11291185                // Validate table name for security
    11301186                $safe_table = $this->get_safe_table_name( $wpdb->prefix . 'aiohm_vector_entries' );
     1187
     1188                // Without an embedding, full-text relevance is the ranking.
     1189                if ( null === $query_embedding ) {
     1190                        $keywords = trim( preg_replace( '/[^\p{L}\p{N}\s]/u', ' ', (string) $query_text ) );
     1191                        if ( '' === $keywords ) {
     1192                                return array();
     1193                        }
     1194                        $keyword_rows = $wpdb->get_results(
     1195                                $wpdb->prepare(
     1196                                        'SELECT id, title, content, content_type, metadata, vector_data FROM `' . esc_sql( $safe_table ) . '` WHERE ( user_id = 0 OR user_id = %d ) AND MATCH(content) AGAINST(%s IN NATURAL LANGUAGE MODE) LIMIT %d',
     1197                                        $user_id,
     1198                                        $keywords,
     1199                                        (int) $limit
     1200                                ),
     1201                                ARRAY_A
     1202                        );
     1203                        $keyword_hits = array();
     1204                        foreach ( (array) $keyword_rows as $entry ) {
     1205                                $keyword_hits[] = array(
     1206                                        'score' => null,
     1207                                        'entry' => $entry,
     1208                                );
     1209                        }
     1210                        return $keyword_hits;
     1211                }
    11311212
    11321213                $all_entries = $wpdb->get_results(
    … …  
    11411222                foreach ( $all_entries as $entry ) {
    11421223                        $vector = ! empty( $entry['vector_data'] ) ? json_decode( $entry['vector_data'], true ) : null;
    1143                         if ( is_array( $vector ) ) {
    1144                                 $dot_product = array_sum( array_map( fn( $a, $b ) => $a * $b, $query_embedding, $vector ) );
    1145                                 $mag_a       = sqrt( array_sum( array_map( fn( $a ) => $a * $a, $query_embedding ) ) );
    1146                                 $mag_b       = sqrt( array_sum( array_map( fn( $b ) => $b * $b, $vector ) ) );
    1147                                 if ( $mag_a > 0 && $mag_b > 0 ) {
    1148                                         $similarities[] = array(
    1149                                                 'score' => $dot_product / ( $mag_a * $mag_b ),
    1150                                                 'entry' => $entry,
    1151                                         );
    1152                                 }
     1224                        $score  = $this->cosine_similarity( $query_embedding, $vector );
     1225                        if ( null !== $score ) {
     1226                                $similarities[] = array(
     1227                                        'score' => $score,
     1228                                        'entry' => $entry,
     1229                                );
    11531230                        }
    11541231                }
  • aiohm-knowledge-assistant/tags/3.1.0/includes/settings-page.php

    r3801374 r3833232  
    160160
    161161                // Pro Features tab (shows upgrade notice in FREE, full features in PRO)
    162                 add_submenu_page( 'aiohm-knowledge-assistant', 'Pro Features', 'Pro Features', 'manage_options', 'aiohm-pro-features', array( $this, 'render_pro_features_page' ) );
     162                add_submenu_page( 'aiohm-knowledge-assistant', __( 'Advanced', 'aiohm-knowledge-assistant' ), __( 'Advanced', 'aiohm-knowledge-assistant' ), 'manage_options', 'aiohm-pro-features', array( $this, 'render_pro_features_page' ) );
    163163
    164164                // Get Help page
    … …  
    989989                                : sanitize_key( $setting_value );
    990990
    991                         if ( ! in_array( $setting_value, array( 'shareai', 'openai', 'claude', 'gemini', 'groq', 'ollama' ), true ) ) {
     991                        if ( ! in_array( $setting_value, aiohm_kb_ai_provider_ids(), true ) ) {
    992992                                wp_send_json_error( 'Invalid AI provider selected' );
    993993                                return;
    … …  
    10931093
    10941094                // Sanitize API keys and encrypt them for storage
    1095                 $api_keys = array( 'openai_api_key', 'gemini_api_key', 'claude_api_key' );
     1095                $api_keys = array( 'gemini_api_key' );
    10961096                foreach ( $api_keys as $field ) {
    10971097                        if ( isset( $input[ $field ] ) ) {
    … …  
    11101110                }
    11111111
    1112                 // ShareAI API key and model are handled via AJAX, but sanitize if submitted with main form
    1113                 if ( isset( $input['shareai_api_key'] ) ) {
    1114                         $sanitized['shareai_api_key'] = sanitize_text_field( trim( $input['shareai_api_key'] ) );
     1112                // Connect ShareAI choices (saved from the ShareAI card).
     1113                foreach ( array( 'shareai_model', 'shareai_embedding_model', 'shareai_previous_provider' ) as $field ) {
     1114                        if ( isset( $input[ $field ] ) ) {
     1115                                $sanitized[ $field ] = sanitize_text_field( trim( (string) $input[ $field ] ) );
     1116                        }
     1117                }
     1118                if ( isset( $input['shareai_daily_cap'] ) ) {
     1119                        $sanitized['shareai_daily_cap'] = absint( $input['shareai_daily_cap'] );
    11151120                }
    11161121
    … …  
    11281133                                ? aiohm_kb_normalize_wp_ai_provider_id( $input['default_ai_provider'] )
    11291134                                : sanitize_key( $input['default_ai_provider'] );
    1130                         if ( in_array( $provider, array( 'shareai', 'openai', 'claude', 'gemini', 'groq', 'ollama' ), true ) ) {
     1135                        if ( in_array( $provider, aiohm_kb_ai_provider_ids(), true ) ) {
    11311136                                $sanitized['default_ai_provider'] = $provider;
    11321137                        }
    … …  
    12021207                        $temperature = floatval( $muse_settings['temperature'] ?? 0.7 );
    12031208                        $assistant_name = $muse_settings['assistant_name'] ?? 'Muse';
    1204                         $ai_model = $muse_settings['ai_model'] ?? 'gpt-3.5-turbo';
     1209                        $ai_model = $muse_settings['ai_model'] ?? '';
    12051210                       
    12061211                        // Initialize AI client
    … …  
    12081213                       
    12091214                        // Check if any AI provider is configured
    1210                         $providers = array( 'openai', 'gemini', 'claude', 'groq', 'shareai' );
     1215                        $providers = aiohm_kb_ai_provider_ids();
    12111216                        $has_api_key = false;
    12121217                        foreach ( $providers as $provider ) {
  • aiohm-knowledge-assistant/tags/3.1.0/includes/shortcode-qa.php

    r3545079 r3833232  
    9999
    100100                        // Check if any AI provider is configured
    101                         $has_api_key = ! empty( $settings['openai_api_key'] ) ||
    102                                                         ! empty( $settings['gemini_api_key'] ) ||
    103                                                         ! empty( $settings['claude_api_key'] ) ||
    104                                                         ! empty( $settings['shareai_api_key'] ) ||
    105                                                         ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) &&
    106                                                                 ( aiohm_kb_is_wp_ai_connector_configured( 'openai' ) ||
    107                                                                   aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) ||
    108                                                                   aiohm_kb_is_wp_ai_connector_configured( 'claude' ) ) ) ||
    109                                                         ! empty( get_option( 'connectors_ai_openai_api_key' ) ) ||
    110                                                         ! empty( get_option( 'connectors_ai_google_api_key' ) ) ||
    111                                                         ! empty( get_option( 'connectors_ai_gemini_api_key' ) ) ||
    112                                                         ! empty( get_option( 'connectors_ai_anthropic_api_key' ) ) ||
    113                                                         ! empty( get_option( 'connectors_ai_claude_api_key' ) ) ||
    114                                                         ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY ) ||
    115                                                         ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY ) ||
    116                                                         ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY ) ||
    117                                                         ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY ) ||
    118                                                         ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY ) ||
    119                                                         getenv( 'OPENAI_API_KEY' ) ||
    120                                                         getenv( 'GOOGLE_API_KEY' ) ||
    121                                                         getenv( 'GEMINI_API_KEY' ) ||
    122                                                         getenv( 'ANTHROPIC_API_KEY' ) ||
    123                                                         getenv( 'CLAUDE_API_KEY' );
     101                        $has_api_key = false;
     102                        foreach ( aiohm_kb_ai_provider_ids() as $aiohm_provider ) {
     103                                if ( aiohm_kb_ai_provider_available( $aiohm_provider, $settings ) ) {
     104                                        $has_api_key = true;
     105                                        break;
     106                                }
     107                        }
    124108
    125109                        if ( ! $has_api_key ) {
    … …  
    138122                        } else {
    139123                                // Fallback to default provider if no Mirror Mode model is set
    140                                 $default_provider = $settings['default_ai_provider'] ?? 'openai';
    141                                 switch ( $default_provider ) {
    142                                         case 'gemini':
    143                                                 $model = 'gemini-pro';
    144                                                 break;
    145                                         case 'claude':
    146                                                 $model = 'claude-3-sonnet';
    147                                                 break;
    148                                         case 'shareai':
    149                                                 $model = 'shareai-llama4:17b-scout-16e-instruct-fp16';
    150                                                 break;
    151                                         case 'openai':
    152                                         default:
    153                                                 $model = 'gpt-3.5-turbo';
    154                                                 break;
    155                                 }
     124                                $default_provider = aiohm_kb_resolve_ai_provider( $settings['default_ai_provider'] ?? '', $settings );
     125                                $model            = aiohm_kb_default_model_for_provider( $default_provider, $settings );
    156126                        }
    157127
  • aiohm-knowledge-assistant/tags/3.1.0/includes/uninstall-cleanup.php

    r3801374 r3833232  
    1313function aiohm_kb_uninstall_cleanup()
    1414{
     15    // ShareAI tokens never outlive the plugin, whatever the data setting.
     16    aiohm_kb_uninstall_shareai();
     17
    1518    // Check if user wants to delete data on uninstall
    1619    $settings = get_option("aiohm_kb_settings", []);
    … …  
    9396    wp_cache_flush();
    9497}
     98
     99/**
     100 * Revoke the ShareAI grant and delete its tokens. The plugin's classes are
     101 * not loaded during uninstall, so the token is decrypted here with the same
     102 * key the plugin used to encrypt it.
     103 */
     104function aiohm_kb_uninstall_shareai()
     105{
     106    $data = get_option("aiohm_kb_shareai_connection", []);
     107    if (is_array($data) && function_exists("openssl_decrypt")) {
     108        $key = wp_hash(SECURE_AUTH_KEY . LOGGED_IN_KEY);
     109        foreach (["refresh_token", "access_token"] as $type) {
     110            $raw = base64_decode((string) ($data[$type] ?? ""), true);
     111            if ($raw === false || strlen($raw) < 17) {
     112                continue;
     113            }
     114            $token = openssl_decrypt(substr($raw, 16), "AES-256-CBC", $key, 0, substr($raw, 0, 16));
     115            if (is_string($token) && $token !== "") {
     116                wp_remote_post("https://auth.shareai.now/oauth/revoke", [
     117                    "timeout" => 10,
     118                    "body" => [
     119                        "token" => $token,
     120                        "token_type_hint" => $type,
     121                        "client_id" => defined("AIOHM_KB_SHAREAI_CLIENT_ID") ? AIOHM_KB_SHAREAI_CLIENT_ID : "90bd7595f6bb64f73a28dc18e96b7a6d",
     122                    ],
     123                ]);
     124            }
     125        }
     126    }
     127    delete_option("aiohm_kb_shareai_connection");
     128    delete_option("aiohm_kb_shareai_refresh_lock");
     129    delete_option("aiohm_kb_shareai_daily_usage");
     130}
  • aiohm-knowledge-assistant/tags/3.1.0/readme.txt

    r3801412 r3833232  
    1 === AIOHM Knowledge Assistant PRO ===
     1=== AIOHM Knowledge Assistant ===
    22Contributors: ohmevents
    33Tags: ai assistant, knowledge base, chatbot, brand voice, personalized ai
    44Requires at least: 6.2
    55Tested up to: 7.1
    6 Stable tag: 3.0.0
     6Stable tag: 3.1.0
    77Requires PHP: 7.4
    88License: GPLv2 or later
    … …  
    2121* **Public Chatbot**: Add an intelligent chatbot to your website that answers visitor questions based on your content
    2222* **Knowledge Base Management**: Scan and index your WordPress posts, pages, and uploaded documents
    23 * **Multi-Provider AI Support**: Choose from OpenAI, Google Gemini, Anthropic Claude, Groq, and ShareAI
     23* **Multi-Provider AI Support**: Choose from ShareAI, Google Gemini or a local Ollama server
    2424* **Brand Voice Configuration**: Set up your chatbot's personality and communication style
    2525* **Content Processing**: Support for PDF, CSV, TXT, and JSON document formats
    … …  
    3434* Automatic indexing of WordPress posts, pages, and uploaded files
    3535* Support for PDF, CSV, TXT, and JSON document formats
    36 * Advanced semantic search with vector embeddings
     36* Full-text search on every setup, plus semantic search when Gemini or Ollama provides embeddings
    3737* Smart content chunking for optimal AI processing
    3838
    3939**Multi-Provider AI Integration**
    40 * OpenAI GPT models (GPT-5)
    41 * Google Gemini Pro with advanced embeddings
    42 * Anthropic Claude for sophisticated reasoning
    43 * Groq for ultra-fast inference with Llama and Mistral models
    44 * ShareAI for specialized model access
     40* ShareAI, connected with your ShareAI account (Connect ShareAI)
     41* Google Gemini with embeddings
     42* OpenAI and Anthropic Claude for chat, when your site connects them in Settings > Connectors (WordPress 7)
    4543* **Ollama Local AI for completely private, on-premise processing**
    4644* ServBay Ollama server integration for development environments
    … …  
    9290* WordPress 6.2 or higher
    9391* PHP 7.4 or higher
    94 * API key from at least one supported provider (OpenAI, Claude, Gemini, Groq, or ShareAI)
     92* A ShareAI connection (Connect ShareAI), a Gemini API key, or a local Ollama server
    9593* Optional: Paid Memberships Pro for advanced access control
    9694
    9795## Privacy & External Services
    9896
    99 This plugin connects to external AI services only when configured with user-provided API keys. All communications use secure HTTPS connections, and no conversation data is stored on external servers beyond temporary processing requirements.
     97This plugin connects to external AI services only after you connect ShareAI, add a Gemini API key, or point it at your own Ollama server. All communications use secure HTTPS connections, and no conversation data is stored on external servers beyond temporary processing requirements.
    10098
    10199**Supported AI Services:**
    102100* ShareAI API (shareai.now) - [Terms](https://shareai.now/terms) | [Docs](https://shareai.now/documentation/)
    103 * OpenAI API (api.openai.com) - [Terms](https://openai.com/terms/) | [Privacy](https://openai.com/privacy/)
    104101* Google Gemini API (generativelanguage.googleapis.com) - [Terms](https://ai.google.dev/terms) | [Privacy](https://policies.google.com/privacy)
    105 * Anthropic Claude API (api.anthropic.com) - [Terms](https://www.anthropic.com/terms) | [Privacy](https://www.anthropic.com/privacy)
    106 * Groq API (api.groq.com) - [Terms](https://groq.com/terms-of-service/) | [Privacy](https://groq.com/privacy-policy/)
     102* OpenAI (api.openai.com) and Anthropic (api.anthropic.com), only when you connect them in WordPress Settings > Connectors. WordPress keeps those keys and sends the requests through its own AI Client. - OpenAI [Terms](https://openai.com/policies/terms-of-use/) | [Privacy](https://openai.com/policies/privacy-policy/) - Anthropic [Terms](https://www.anthropic.com/legal/commercial-terms) | [Privacy](https://www.anthropic.com/legal/privacy)
     103* Ollama (optional): requests go only to the Ollama server URL you enter, for example http://localhost:11434 on your own machine.
    107104
    108105User consent is required before making any external API calls. All API keys are encrypted and stored securely in your WordPress database.
     106
     107**Connect ShareAI (optional):**
     108ShareAI is connected with "Connect ShareAI" on the settings page. When you do:
     109
     110* Your browser goes to ShareAI (auth.shareai.now and console.shareai.now) to sign in and approve the AIOHM Knowledge Assistant plan.
     111* ShareAI returns you to AIOHM's relay page on www.ohm.events (OHM Events Agency). The relay receives only ShareAI's one-time code and your site's admin address, shows you which site you are connecting, and sends you back there. It stores nothing and never receives a token.
     112* Your site exchanges the code for tokens itself. The tokens are encrypted and stored in your WordPress database, and are revoked and removed when you click Disconnect or delete the plugin.
     113* Chat requests go to api.shareai.now and are paid from your ShareAI wallet at the model price plus a 10% builder markup that goes to AIOHM, the maker of this plugin. ShareAI shows this markup before you approve.
     114* ShareAI: [Terms](https://shareai.now/terms) | [Privacy](https://shareai.now/privacy). AIOHM (OHM Events Agency): [Terms](https://www.ohm.events/terms-and-conditions/) | [Privacy](https://www.ohm.events/privacy-policy/).
    109115
    110116== Installation ==
    … …  
    1121181. Upload the plugin files to `/wp-content/plugins/aiohm-knowledge-assistant/`
    1131192. Activate the plugin through the WordPress Plugins menu
    114 3. Navigate to AIOHM > Settings and configure your AI provider API key
     1203. Navigate to AIOHM > Settings and click Connect ShareAI, or add a Gemini API key, or point AIOHM at your Ollama server
    1151214. Run the content scan to build your knowledge base
    1161225. Configure your brand voice settings
    … …  
    121127= What AI providers are supported? =
    122128
    123 AIOHM supports OpenAI (GPT-3.5, GPT-4), Google Gemini Pro, Anthropic Claude, Groq (ultra-fast inference), and ShareAI. You need only one API key to get started.
     129AIOHM supports ShareAI and a local Ollama server, and also Google Gemini, OpenAI and Anthropic Claude when your site connects them in WordPress 7 Settings > Connectors. You need only one to get started: connect your ShareAI account, point AIOHM at your Ollama server, or add a provider in Connectors. OpenAI and Claude run chat; search then uses keywords.
     130
     131= Does AIOHM earn anything when I use ShareAI? =
     132
     133Yes, when your assistant runs on ShareAI. ShareAI adds a 10% builder markup to your AI usage and pays it to AIOHM. That is how this free plugin is funded. ShareAI shows the markup before you approve. Google Gemini and a local Ollama server carry no markup.
    124134
    125135= How does this differ from other AI chatbot plugins? =
    … …  
    169179
    170180== Changelog ==
     181
     182= 3.1.0 =
     183* ADDED: Connect ShareAI. Sign in to ShareAI once, with no API key to copy. Chat runs on your ShareAI wallet, with a 10% builder markup for AIOHM shown by ShareAI before you approve.
     184* ADDED: OpenAI and Anthropic Claude through WordPress 7 Connectors. They appear as AI providers only after your site connects them, and WordPress keeps their keys.
     185* CHANGED: The AI provider list always shows ShareAI and Ollama. Gemini, OpenAI and Claude appear once your site connects them.
     186* CHANGED: ShareAI now runs only through Connect ShareAI. The ShareAI API key field is gone, and a key saved by an earlier version is deleted. Sites that used a key click Connect ShareAI once.
     187* ADDED: Daily question limit for visitors, so a busy chat cannot drain your ShareAI wallet.
     188* ADDED: ShareAI chat and embedding models are read from your account instead of a fixed list.
     189* FIXED: The knowledge base no longer fails to index when no embedding provider is available. Entries are stored and found by full-text search, so a ShareAI-only site works.
     190* CHANGED: AIOHM no longer stores OpenAI, Anthropic or Groq API keys. OpenAI and Claude work through WordPress Connectors instead; Groq is removed. A site that relied on a removed key switches to the first provider that is set up.
     191* ADDED: An admin notice on the AIOHM screens, the Dashboard and the Plugins screen while no AI provider is set up, with a link to the settings.
     192* ADDED: Default ShareAI embedding model (text-embedding-3-small). While ShareAI does not offer embeddings for an account, AIOHM pauses those calls and search uses keywords.
     193* CHANGED: ShareAI buttons follow ShareAI's application guidance, with the official ShareAI icon.
     194* CHANGED: The plugin is listed as AIOHM Knowledge Assistant, and its "Pro Features" page is now called "Advanced".
     195* FIXED: Visitors now see the daily question limit message instead of a general error.
     196* FIXED: Plugin Check errors for unescaped exception messages.
    171197
    172198= 3.0.0 =
    … …  
    308334== Upgrade Notice ==
    309335
     336= 3.1.0 =
     337ShareAI now connects with your ShareAI account (Connect ShareAI) instead of an API key. OpenAI and Claude work through WordPress 7 Connectors. If your site used an OpenAI, Claude, Groq or ShareAI key, set up a provider after updating.
     338
    310339= 1.4.1 =
    311340CRITICAL FIX: Resolves knowledge base content not appearing after scanning. Essential update for users experiencing empty manage knowledge base tables after content scanning operations.
    … …  
    322351== Screenshots ==
    323352
    324 1. **Dashboard Overview** - Complete control center for AI assistant setup and management
    325 2. **Mirror Mode Configuration** - Set up your public chatbot with brand voice and personality
    326 3. **Muse Mode Settings** - Configure your private AI assistant for creative workflows
    327 4. **Knowledge Base Manager** - View, organize, and manage all indexed content
    328 5. **Brand Soul Questionnaire** - Define your unique voice and communication style
    329 6. **Public Chat Interface** - Clean, responsive chatbot for website visitors
    330 7. **Private Assistant Interface** - Full-featured AI assistant for authenticated users
    331 8. **Content Scanning** - Automatic indexing of posts, pages, and uploaded documents
     3531. **Answers from your content** - The live preview answers a visitor question from the site's own pages
     3542. **Connect ShareAI** - Connect your ShareAI account once, with the 10% builder markup shown up front
     3553. **Scan your site** - Posts, pages, products and media files ready to index
     3564. **Knowledge base manager** - Choose what is public and what stays private
     3575. **Four-step setup** - From choosing an AI provider to adding the chat to your site
  • aiohm-knowledge-assistant/tags/3.1.0/templates/admin-dashboard.php

    r3801374 r3833232  
    4747                                                <div class="benefit">
    4848                                                        <h3><?php esc_html_e( '1. Configure AI Provider', 'aiohm-knowledge-assistant' ); ?></h3>
    49                                                         <p><?php esc_html_e( 'Add your OpenAI, Claude, Gemini, or ShareAI API key to get started.', 'aiohm-knowledge-assistant' ); ?></p>
     49                                                        <p><?php esc_html_e( 'Connect ShareAI, add a Gemini API key, or point AIOHM at a local Ollama server to get started.', 'aiohm-knowledge-assistant' ); ?></p>
    5050                                                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=aiohm-settings' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Configure AI', 'aiohm-knowledge-assistant' ); ?></a>
    5151                                                </div>
    … …  
    7777                                                <div class="benefit">
    7878                                                        <h3><?php esc_html_e( 'Multi-Provider AI Support', 'aiohm-knowledge-assistant' ); ?></h3>
    79                                                         <p><?php esc_html_e( 'OpenAI GPT, Claude, Gemini, and ShareAI integration. Use your own API keys.', 'aiohm-knowledge-assistant' ); ?></p>
     79                                                        <p><?php esc_html_e( 'ShareAI, Google Gemini and local Ollama. Use your own account or API key.', 'aiohm-knowledge-assistant' ); ?></p>
    8080                                                </div>
    8181                                                <div class="benefit">
    … …  
    110110                                                <div class="benefit">
    111111                                                        <h3><?php esc_html_e( 'Step 1: AI Configuration', 'aiohm-knowledge-assistant' ); ?></h3>
    112                                                         <p><?php esc_html_e( 'Go to Settings and add your AI provider API key (OpenAI, Claude, Gemini, or ShareAI).', 'aiohm-knowledge-assistant' ); ?></p>
     112                                                        <p><?php esc_html_e( 'Go to Settings and set up an AI provider: ShareAI, Gemini or Ollama.', 'aiohm-knowledge-assistant' ); ?></p>
    113113                                                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=aiohm-settings' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Configure AI', 'aiohm-knowledge-assistant' ); ?></a>
    114114                                                </div>
  • aiohm-knowledge-assistant/tags/3.1.0/templates/admin-mirror-mode.php

    r3545079 r3833232  
    107107                                                </div>
    108108                                                <?php
    109                                                 $aiohm_has_openai = ! empty( $aiohm_global_settings['openai_api_key'] )
    110                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    111                                                         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    112                                                         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    113                                                         || getenv( 'OPENAI_API_KEY' );
    114 
    115                                                 $aiohm_has_gemini = ! empty( $aiohm_global_settings['gemini_api_key'] )
    116                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    117                                                         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    118                                                         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    119                                                         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    120                                                         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    121                                                         || getenv( 'GOOGLE_API_KEY' )
    122                                                         || getenv( 'GEMINI_API_KEY' );
    123 
    124                                                 $aiohm_has_claude = ! empty( $aiohm_global_settings['claude_api_key'] )
    125                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    126                                                         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    127                                                         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    128                                                         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    129                                                         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    130                                                         || getenv( 'ANTHROPIC_API_KEY' )
    131                                                         || getenv( 'CLAUDE_API_KEY' );
    132 
    133                                                 $aiohm_has_groq = ! empty( $aiohm_global_settings['groq_api_key'] );
    134                                                 $aiohm_has_shareai = ! empty( $aiohm_global_settings['shareai_api_key'] );
     109                                                $aiohm_has_shareai         = aiohm_kb_shareai_available( $aiohm_global_settings );
     110                                                $aiohm_has_gemini          = aiohm_kb_gemini_available( $aiohm_global_settings );
     111                                                $aiohm_has_ollama          = aiohm_kb_ollama_available( $aiohm_global_settings );
     112                                                $aiohm_shareai_model_value = aiohm_kb_default_model_for_provider( 'shareai', $aiohm_global_settings );
     113                                                $aiohm_ollama_model_name   = $aiohm_global_settings['pro_features']['ollama_model'] ?? ( $aiohm_global_settings['private_llm_model'] ?? 'llama3.2:latest' );
     114                                                $aiohm_selected_model      = (string) ( $aiohm_settings['ai_model'] ?? '' );
     115                                                if ( '' === $aiohm_selected_model ) {
     116                                                        $aiohm_selected_model = aiohm_kb_default_model_for_provider(
     117                                                                aiohm_kb_resolve_ai_provider( $aiohm_global_settings['default_ai_provider'] ?? '', $aiohm_global_settings ),
     118                                                                $aiohm_global_settings
     119                                                        );
     120                                                }
    135121                                                ?>
    136122                                                <select id="ai_model_selector" name="aiohm_kb_settings[mirror_mode][ai_model]">
    137                                                         <?php if ($aiohm_has_openai): ?>
    138                                                                 <option value="gpt-3.5-turbo" <?php selected(
    139             $aiohm_settings["ai_model"] ?? "gpt-3.5-turbo",
    140             "gpt-3.5-turbo",
    141         ); ?>>OpenAI: GPT-3.5 Turbo (Fast & Reliable)</option>
    142                                                                 <option value="gpt-4" <?php selected(
    143             $aiohm_settings["ai_model"] ?? "",
    144             "gpt-4",
    145         ); ?>>OpenAI: GPT-4 (Advanced)</option>
     123                                                        <?php if ( $aiohm_has_shareai ) : ?>
     124                                                                <option value="<?php echo esc_attr( $aiohm_shareai_model_value ); ?>" <?php selected( $aiohm_selected_model, $aiohm_shareai_model_value ); ?>>
     125                                                                        <?php
     126                                                                        /* translators: %s: ShareAI model ID */
     127                                                                        echo esc_html( sprintf( __( 'ShareAI: %s', 'aiohm-knowledge-assistant' ), substr( $aiohm_shareai_model_value, strlen( 'shareai-' ) ) ) );
     128                                                                        ?>
     129                                                                </option>
    146130                                                        <?php endif; ?>
    147                                                         <?php if ($aiohm_has_gemini): ?>
    148                                                                 <option value="gemini-pro" <?php selected(
    149             $aiohm_settings["ai_model"] ?? "",
    150             "gemini-pro",
    151         ); ?>>Google: Gemini Pro</option>
     131                                                        <?php if ( $aiohm_has_gemini ) : ?>
     132                                                                <option value="gemini-pro" <?php selected( $aiohm_selected_model, 'gemini-pro' ); ?>><?php esc_html_e( 'Google: Gemini Pro', 'aiohm-knowledge-assistant' ); ?></option>
    152133                                                        <?php endif; ?>
    153                                                         <?php if ($aiohm_has_claude): ?>
    154                                                                 <option value="claude-3-sonnet" <?php selected(
    155             $aiohm_settings["ai_model"] ?? "",
    156             "claude-3-sonnet",
    157         ); ?>>Anthropic: Claude 3 Sonnet</option>
     134                                                        <?php if ( $aiohm_has_ollama ) : ?>
     135                                                                <option value="ollama" <?php selected( $aiohm_selected_model, 'ollama' ); ?>>
     136                                                                        <?php
     137                                                                        /* translators: %s: Ollama model name */
     138                                                                        echo esc_html( sprintf( __( 'Ollama: %s', 'aiohm-knowledge-assistant' ), $aiohm_ollama_model_name ) );
     139                                                                        ?>
     140                                                                </option>
    158141                                                        <?php endif; ?>
    159                                                         <?php if ($aiohm_has_groq): ?>
    160                                                                 <option value="groq-llama-3.3-70b-versatile" <?php selected(
    161             $aiohm_settings["ai_model"] ?? "",
    162             "groq-llama-3.3-70b-versatile",
    163         ); ?>>Groq: Llama 3.3 70B (Ultra-Fast)</option>
     142                                                        <?php if ( aiohm_kb_wp_connector_provider_available( 'openai' ) ) : ?>
     143                                                                <option value="wp-openai" <?php selected( $aiohm_selected_model, 'wp-openai' ); ?>><?php esc_html_e( 'OpenAI (WordPress Connectors)', 'aiohm-knowledge-assistant' ); ?></option>
    164144                                                        <?php endif; ?>
    165                                                         <?php if ($aiohm_has_shareai): ?>
    166                                                                 <option value="shareai-llama4:17b-scout-16e-instruct-fp16" <?php selected(
    167             $aiohm_settings["ai_model"] ?? "",
    168             "shareai-llama4:17b-scout-16e-instruct-fp16",
    169         ); ?>>ShareAI</option>
     145                                                        <?php if ( aiohm_kb_wp_connector_provider_available( 'anthropic' ) ) : ?>
     146                                                                <option value="wp-anthropic" <?php selected( $aiohm_selected_model, 'wp-anthropic' ); ?>><?php esc_html_e( 'Anthropic Claude (WordPress Connectors)', 'aiohm-knowledge-assistant' ); ?></option>
    170147                                                        <?php endif; ?>
    171148                                                </select>
  • aiohm-knowledge-assistant/tags/3.1.0/templates/admin-muse-mode.php

    r3545079 r3833232  
    175175                                                </div>
    176176                                                <?php
    177                                                 $aiohm_has_openai = ! empty( $aiohm_global_settings['openai_api_key'] )
    178                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    179                                                         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    180                                                         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    181                                                         || getenv( 'OPENAI_API_KEY' );
    182 
    183                                                 $aiohm_has_gemini = ! empty( $aiohm_global_settings['gemini_api_key'] )
    184                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    185                                                         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    186                                                         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    187                                                         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    188                                                         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    189                                                         || getenv( 'GOOGLE_API_KEY' )
    190                                                         || getenv( 'GEMINI_API_KEY' );
    191 
    192                                                 $aiohm_has_claude = ! empty( $aiohm_global_settings['claude_api_key'] )
    193                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    194                                                         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    195                                                         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    196                                                         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    197                                                         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    198                                                         || getenv( 'ANTHROPIC_API_KEY' )
    199                                                         || getenv( 'CLAUDE_API_KEY' );
    200 
    201                                                 $aiohm_has_groq = ! empty( $aiohm_global_settings['groq_api_key'] );
    202                                                 $aiohm_has_shareai = ! empty( $aiohm_global_settings['shareai_api_key'] );
     177                                                $aiohm_has_shareai         = aiohm_kb_shareai_available( $aiohm_global_settings );
     178                                                $aiohm_has_gemini          = aiohm_kb_gemini_available( $aiohm_global_settings );
     179                                                $aiohm_has_ollama          = aiohm_kb_ollama_available( $aiohm_global_settings );
     180                                                $aiohm_shareai_model_value = aiohm_kb_default_model_for_provider( 'shareai', $aiohm_global_settings );
     181                                                $aiohm_ollama_model_name   = $aiohm_global_settings['pro_features']['ollama_model'] ?? ( $aiohm_global_settings['private_llm_model'] ?? 'llama3.2:latest' );
     182                                                $aiohm_selected_model      = (string) ( $aiohm_settings['ai_model'] ?? '' );
     183                                                if ( '' === $aiohm_selected_model ) {
     184                                                        $aiohm_selected_model = aiohm_kb_default_model_for_provider(
     185                                                                aiohm_kb_resolve_ai_provider( $aiohm_global_settings['default_ai_provider'] ?? '', $aiohm_global_settings ),
     186                                                                $aiohm_global_settings
     187                                                        );
     188                                                }
    203189                                                ?>
    204190                                                <select id="ai_model_selector" name="aiohm_kb_settings[muse_mode][ai_model]">
    205                                                         <?php if ($aiohm_has_openai): ?>
    206                                                                 <option value="gpt-3.5-turbo" <?php selected(
    207             $aiohm_settings["ai_model"] ?? "gpt-3.5-turbo",
    208             "gpt-3.5-turbo",
    209         ); ?>>OpenAI: GPT-3.5 Turbo</option>
    210                                                                 <option value="gpt-4" <?php selected(
    211             $aiohm_settings["ai_model"] ?? "",
    212             "gpt-4",
    213         ); ?>>OpenAI: GPT-4</option>
     191                                                        <?php if ( $aiohm_has_shareai ) : ?>
     192                                                                <option value="<?php echo esc_attr( $aiohm_shareai_model_value ); ?>" <?php selected( $aiohm_selected_model, $aiohm_shareai_model_value ); ?>>
     193                                                                        <?php
     194                                                                        /* translators: %s: ShareAI model ID */
     195                                                                        echo esc_html( sprintf( __( 'ShareAI: %s', 'aiohm-knowledge-assistant' ), substr( $aiohm_shareai_model_value, strlen( 'shareai-' ) ) ) );
     196                                                                        ?>
     197                                                                </option>
    214198                                                        <?php endif; ?>
    215                                                         <?php if ($aiohm_has_gemini): ?>
    216                                                                 <option value="gemini-pro" <?php selected(
    217             $aiohm_settings["ai_model"] ?? "",
    218             "gemini-pro",
    219         ); ?>>Google: Gemini Pro</option>
     199                                                        <?php if ( $aiohm_has_gemini ) : ?>
     200                                                                <option value="gemini-pro" <?php selected( $aiohm_selected_model, 'gemini-pro' ); ?>><?php esc_html_e( 'Google: Gemini Pro', 'aiohm-knowledge-assistant' ); ?></option>
    220201                                                        <?php endif; ?>
    221                                                         <?php if ($aiohm_has_claude): ?>
    222                                                                 <option value="claude-3-sonnet" <?php selected(
    223             $aiohm_settings["ai_model"] ?? "",
    224             "claude-3-sonnet",
    225         ); ?>>Anthropic: Claude 3 Sonnet</option>
     202                                                        <?php if ( $aiohm_has_ollama ) : ?>
     203                                                                <option value="ollama" <?php selected( $aiohm_selected_model, 'ollama' ); ?>>
     204                                                                        <?php
     205                                                                        /* translators: %s: Ollama model name */
     206                                                                        echo esc_html( sprintf( __( 'Ollama: %s', 'aiohm-knowledge-assistant' ), $aiohm_ollama_model_name ) );
     207                                                                        ?>
     208                                                                </option>
    226209                                                        <?php endif; ?>
    227                                                         <?php if ($aiohm_has_groq): ?>
    228                                                                 <option value="groq-llama-3.3-70b-versatile" <?php selected(
    229             $aiohm_settings["ai_model"] ?? "",
    230             "groq-llama-3.3-70b-versatile",
    231         ); ?>>Groq: Llama 3.3 70B (Ultra-Fast)</option>
     210                                                        <?php if ( aiohm_kb_wp_connector_provider_available( 'openai' ) ) : ?>
     211                                                                <option value="wp-openai" <?php selected( $aiohm_selected_model, 'wp-openai' ); ?>><?php esc_html_e( 'OpenAI (WordPress Connectors)', 'aiohm-knowledge-assistant' ); ?></option>
    232212                                                        <?php endif; ?>
    233                                                         <?php if ($aiohm_has_shareai): ?>
    234                                                                 <option value="shareai-llama4:17b-scout-16e-instruct-fp16" <?php selected(
    235             $aiohm_settings["ai_model"] ?? "",
    236             "shareai-llama4:17b-scout-16e-instruct-fp16",
    237         ); ?>>ShareAI</option>
     213                                                        <?php if ( aiohm_kb_wp_connector_provider_available( 'anthropic' ) ) : ?>
     214                                                                <option value="wp-anthropic" <?php selected( $aiohm_selected_model, 'wp-anthropic' ); ?>><?php esc_html_e( 'Anthropic Claude (WordPress Connectors)', 'aiohm-knowledge-assistant' ); ?></option>
    238215                                                        <?php endif; ?>
    239216                                                </select>
  • aiohm-knowledge-assistant/tags/3.1.0/templates/admin-pro-features.php

    r3801374 r3833232  
    4040
    4141<div class="wrap aiohm-settings-page">
    42         <h1><?php esc_html_e( 'Pro Features - Private Knowledge Hub', 'aiohm-knowledge-assistant' ); ?></h1>
     42        <h1><?php esc_html_e( 'Advanced: Private Knowledge Hub', 'aiohm-knowledge-assistant' ); ?></h1>
    4343        <p class="page-description"><?php esc_html_e( 'Advanced settings for local AI processing, MCP integration, and private knowledge hub functionality.', 'aiohm-knowledge-assistant' ); ?></p>
    4444
    … …  
    281281                                                                        <th scope="row"><?php esc_html_e('Token Name', 'aiohm-knowledge-assistant'); ?></th>
    282282                                                                        <td>
    283                                                                                 <input type="text" name="token_name" placeholder="<?php esc_attr_e('e.g., Mobile App, Claude Desktop', 'aiohm-knowledge-assistant'); ?>" required maxlength="255" class="regular-text">
     283                                                                                <input type="text" name="token_name" placeholder="<?php esc_attr_e('e.g., Mobile app, desktop MCP client', 'aiohm-knowledge-assistant'); ?>" required maxlength="255" class="regular-text">
    284284                                                                                <p class="description"><?php esc_html_e('A descriptive name to identify this token', 'aiohm-knowledge-assistant'); ?></p>
    285285                                                                        </td>
    … …  
    339339                <div class="aiohm-save-section">
    340340                        <p class="submit">
    341                                 <input type="submit" name="submit" id="submit" class="button button-primary button-large" value="<?php esc_attr_e( 'Save All Pro Features Settings', 'aiohm-knowledge-assistant' ); ?>">
     341                                <input type="submit" name="submit" id="submit" class="button button-primary button-large" value="<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>">
    342342                        </p>
    343343                </div>
    … …  
    548548                        success: function(response) {
    549549                                console.log('AJAX response:', response);
    550                                 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Pro Features Settings', 'aiohm-knowledge-assistant' ); ?>');
     550                                $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>');
    551551                               
    552552                                if (response.success) {
    … …  
    573573                        error: function(xhr, status, error) {
    574574                                console.error('AJAX error:', xhr, status, error);
    575                                 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Pro Features Settings', 'aiohm-knowledge-assistant' ); ?>');
     575                                $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>');
    576576                                $('#aiohm-admin-notice').removeClass('notice-success notice-info').addClass('notice-error').find('p').text('Save failed: ' + error);
    577577                        }
  • aiohm-knowledge-assistant/tags/3.1.0/templates/admin-scan-website.php

    r3545079 r3833232  
    99// The controller (settings-page.php) prepares these variables before including this template.
    1010$aiohm_settings         = class_exists( 'AIOHM_KB_Assistant' ) ? AIOHM_KB_Assistant::get_settings() : array();
    11 $aiohm_default_provider = $aiohm_settings['default_ai_provider'] ?? 'openai';
    12 
    13 // Check if the selected default provider has an API key configured
    14 $aiohm_has_openai = ! empty( $aiohm_settings['openai_api_key'] )
    15         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    16         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    17         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    18         || getenv( 'OPENAI_API_KEY' );
    19 
    20 $aiohm_has_gemini = ! empty( $aiohm_settings['gemini_api_key'] )
    21         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    22         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    23         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    24         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    25         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    26         || getenv( 'GOOGLE_API_KEY' )
    27         || getenv( 'GEMINI_API_KEY' );
    28 
    29 $aiohm_has_claude = ! empty( $aiohm_settings['claude_api_key'] )
    30         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    31         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    32         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    33         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    34         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    35         || getenv( 'ANTHROPIC_API_KEY' )
    36         || getenv( 'CLAUDE_API_KEY' );
    37 
    38 $aiohm_has_shareai = ! empty( $aiohm_settings['shareai_api_key'] );
    39 
    40 $aiohm_api_key_exists = false;
    41 switch ( $aiohm_default_provider ) {
    42         case 'openai':
    43                 $aiohm_api_key_exists = $aiohm_has_openai;
    44                 break;
    45         case 'gemini':
    46                 $aiohm_api_key_exists = $aiohm_has_gemini;
    47                 break;
    48         case 'claude':
    49                 $aiohm_api_key_exists = $aiohm_has_claude;
    50                 break;
    51         case 'shareai':
    52                 $aiohm_api_key_exists = $aiohm_has_shareai;
    53                 break;
    54         default:
    55                 // For unknown providers, don't assume OpenAI - require proper configuration
    56                 $aiohm_api_key_exists = false;
    57 }
     11$aiohm_default_provider = aiohm_kb_resolve_ai_provider( $aiohm_settings['default_ai_provider'] ?? '', $aiohm_settings );
     12
     13// Check if the selected default provider is set up.
     14$aiohm_api_key_exists = aiohm_kb_ai_provider_available( $aiohm_default_provider, $aiohm_settings );
    5815
    5916// Also get provider display name for better error messaging
    6017$aiohm_provider_names        = array(
    61         'openai'  => 'OpenAI',
     18        'shareai' => 'ShareAI',
    6219        'gemini'  => 'Gemini',
    63         'claude'  => 'Claude',
    64         'shareai' => 'ShareAI',
     20        'ollama'  => 'Ollama',
    6521);
    6622$aiohm_current_provider_name = $aiohm_provider_names[ $aiohm_default_provider ] ?? 'Unknown Provider';
    … …  
    8137                        <?php
    8238                                printf(
    83                                         /* translators: %s is the name of the AI provider (e.g., OpenAI, Gemini, Claude) */
     39                                        /* translators: %s is the name of the AI provider (e.g., ShareAI, Gemini, Ollama) */
    8440                                        esc_html__( 'Content scanning is disabled because your %s API key has not been configured. Please add your key to enable this feature.', 'aiohm-knowledge-assistant' ),
    8541                                        esc_html( $aiohm_current_provider_name )
  • aiohm-knowledge-assistant/tags/3.1.0/templates/admin-settings.php

    r3801374 r3833232  
    2424        </div>
    2525
     26        <?php include AIOHM_KB_PLUGIN_DIR . 'templates/admin-shareai-connect.php'; ?>
    2627
    2728        <form id="aiohm-settings-form" method="post" action="options.php">
    … …  
    3637                                        <div class="aiohm-shareai-settings-box">
    3738                                                <?php
    38                                                 $aiohm_has_openai  = ! empty( $aiohm_settings['openai_api_key'] )
    39                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    40                                                         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    41                                                         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    42                                                         || getenv( 'OPENAI_API_KEY' );
    43                                                 $aiohm_has_gemini  = ! empty( $aiohm_settings['gemini_api_key'] )
    44                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    45                                                         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    46                                                         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    47                                                         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    48                                                         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    49                                                         || getenv( 'GOOGLE_API_KEY' )
    50                                                         || getenv( 'GEMINI_API_KEY' );
    51                                                 $aiohm_has_claude  = ! empty( $aiohm_settings['claude_api_key'] )
    52                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    53                                                         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    54                                                         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    55                                                         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    56                                                         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    57                                                         || getenv( 'ANTHROPIC_API_KEY' )
    58                                                         || getenv( 'CLAUDE_API_KEY' );
    59                                                 $aiohm_has_shareai = ! empty( $aiohm_settings['shareai_api_key'] );
    60                                                 $aiohm_has_groq    = ! empty( $aiohm_settings['groq_api_key'] );
     39                                                $aiohm_has_shareai   = aiohm_kb_shareai_available( $aiohm_settings );
     40                                                $aiohm_has_gemini    = aiohm_kb_gemini_available( $aiohm_settings );
     41                                                $aiohm_has_openai    = aiohm_kb_wp_connector_provider_available( 'openai' );
     42                                                $aiohm_has_anthropic = aiohm_kb_wp_connector_provider_available( 'anthropic' );
    6143
    6244                                                // Check for Ollama
    … …  
    6446                                                $aiohm_has_ollama   = ! empty( $aiohm_pro_features['ollama_enabled'] );
    6547
    66                                                 $aiohm_has_any_api = $aiohm_has_openai || $aiohm_has_gemini || $aiohm_has_claude || $aiohm_has_shareai || $aiohm_has_groq || $aiohm_has_ollama;
     48                                                // ShareAI and Ollama are always offered. Other providers appear
     49                                                // only once the site connects them (WordPress Connectors or a key).
     50                                                $aiohm_has_any_api = true;
    6751                                                $aiohm_enabled_provider_values = array();
    6852                                                foreach (
    6953                                                        array(
    7054                                                                'shareai' => $aiohm_has_shareai,
    71                                                                 'openai'  => $aiohm_has_openai,
    72                                                                 'claude'  => $aiohm_has_claude,
    7355                                                                'gemini'  => $aiohm_has_gemini,
    74                                                                 'groq'    => $aiohm_has_groq,
    7556                                                                'ollama'  => $aiohm_has_ollama,
     57                                                                'openai'    => $aiohm_has_openai,
     58                                                                'anthropic' => $aiohm_has_anthropic,
    7659                                                        ) as $aiohm_provider_value => $aiohm_provider_enabled
    7760                                                ) {
    … …  
    9679                                                <div class="shareai-setting-row">
    9780                                                       
    98                                                         <!-- All AI Providers (6-column grid) -->
     81                                                        <!-- All AI Providers (3-column grid) -->
    9982                                                        <div class="aiohm-provider-selection aiohm-provider-grid">
    10083                                                                <label class="aiohm-provider-option <?php echo ! $aiohm_has_shareai ? 'disabled' : ''; ?>" data-provider="shareai">
    10184                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="shareai" <?php checked( $aiohm_default_ai_provider, 'shareai' ); ?> <?php echo ! $aiohm_has_shareai ? 'disabled' : ''; ?>>
    10285                                                                        <div class="aiohm-provider-icon">
    103                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/shareai-icon.jpeg' ); ?>" alt="ShareAI">
     86                                                                                <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/shareai-icon-64.png' ); ?>" alt="ShareAI">
    10487                                                                        </div>
    10588                                                                        <div class="aiohm-provider-info">
    10689                                                                                <div class="aiohm-provider-name">ShareAI</div>
    107                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_shareai ? 'Affordable AI' : 'API Key Required'; ?></div>
     90                                                                                <div class="aiohm-provider-description"><?php echo $aiohm_has_shareai ? esc_html__( 'Affordable AI', 'aiohm-knowledge-assistant' ) : esc_html__( 'Connect ShareAI above', 'aiohm-knowledge-assistant' ); ?></div>
    10891                                                                        </div>
    10992                                                                        <?php if ( ! $aiohm_has_shareai ) : ?>
    … …  
    11295                                                                </label>
    11396                                                               
    114                                                                 <label class="aiohm-provider-option <?php echo ! $aiohm_has_openai ? 'disabled' : ''; ?>" data-provider="openai">
    115                                                                         <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="openai" <?php checked( $aiohm_default_ai_provider, 'openai' ); ?> <?php echo ! $aiohm_has_openai ? 'disabled' : ''; ?>>
    116                                                                         <div class="aiohm-provider-icon">
    117                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/openai-icon.svg' ); ?>" alt="OpenAI">
    118                                                                         </div>
    119                                                                         <div class="aiohm-provider-info">
    120                                                                                 <div class="aiohm-provider-name">OpenAI</div>
    121                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_openai ? 'GPT-4, GPT-3.5' : 'API Key Required'; ?></div>
    122                                                                         </div>
    123                                                                         <?php if ( ! $aiohm_has_openai ) : ?>
    124                                                                         <div class="aiohm-provider-overlay">🔒</div>
    125                                                                         <?php endif; ?>
    126                                                                 </label>
    127                                                                
    128                                                                 <label class="aiohm-provider-option <?php echo ! $aiohm_has_claude ? 'disabled' : ''; ?>" data-provider="anthropic">
    129                                                                         <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="claude" <?php checked( $aiohm_default_ai_provider, 'claude' ); ?> <?php echo ! $aiohm_has_claude ? 'disabled' : ''; ?>>
    130                                                                         <div class="aiohm-provider-icon">
    131                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/claude-icon.svg' ); ?>" alt="Anthropic Claude">
    132                                                                         </div>
    133                                                                         <div class="aiohm-provider-info">
    134                                                                                 <div class="aiohm-provider-name">Claude</div>
    135                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_claude ? 'Anthropic AI' : 'API Key Required'; ?></div>
    136                                                                         </div>
    137                                                                         <?php if ( ! $aiohm_has_claude ) : ?>
    138                                                                         <div class="aiohm-provider-overlay">🔒</div>
    139                                                                         <?php endif; ?>
    140                                                                 </label>
    141                                                                
    142                                                                 <label class="aiohm-provider-option <?php echo ! $aiohm_has_gemini ? 'disabled' : ''; ?>" data-provider="google">
    143                                                                         <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="gemini" <?php checked( $aiohm_default_ai_provider, 'gemini' ); ?> <?php echo ! $aiohm_has_gemini ? 'disabled' : ''; ?>>
    144                                                                         <div class="aiohm-provider-icon">
    145                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/gemini-icon.svg' ); ?>" alt="Google Gemini">
    146                                                                         </div>
    147                                                                         <div class="aiohm-provider-info">
    148                                                                                 <div class="aiohm-provider-name">Gemini</div>
    149                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_gemini ? 'Google AI' : 'API Key Required'; ?></div>
    150                                                                         </div>
    151                                                                         <?php if ( ! $aiohm_has_gemini ) : ?>
    152                                                                         <div class="aiohm-provider-overlay">🔒</div>
    153                                                                         <?php endif; ?>
    154                                                                 </label>
    155 
    156                                                                 <label class="aiohm-provider-option <?php echo ! $aiohm_has_groq ? 'disabled' : ''; ?>" data-provider="groq">
    157                                                                         <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="groq" <?php checked( $aiohm_default_ai_provider, 'groq' ); ?> <?php echo ! $aiohm_has_groq ? 'disabled' : ''; ?>>
    158                                                                         <div class="aiohm-provider-icon">
    159                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/groq-icon.svg' ); ?>" alt="Groq">
    160                                                                         </div>
    161                                                                         <div class="aiohm-provider-info">
    162                                                                                 <div class="aiohm-provider-name">Groq</div>
    163                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_groq ? 'Ultra-Fast AI' : 'API Key Required'; ?></div>
    164                                                                         </div>
    165                                                                         <?php if ( ! $aiohm_has_groq ) : ?>
    166                                                                         <div class="aiohm-provider-overlay">🔒</div>
    167                                                                         <?php endif; ?>
    168                                                                 </label>
    169 
    17097                                                                <label class="aiohm-provider-option <?php echo ! $aiohm_has_ollama ? 'disabled' : ''; ?>" data-provider="ollama">
    17198                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="ollama" <?php checked( $aiohm_default_ai_provider, 'ollama' ); ?> <?php echo ! $aiohm_has_ollama ? 'disabled' : ''; ?>>
    … …  
    175102                                                                        <div class="aiohm-provider-info">
    176103                                                                                <div class="aiohm-provider-name">Ollama</div>
    177                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_ollama ? 'Local AI' : 'Pro Feature'; ?></div>
     104                                                                                <div class="aiohm-provider-description"><?php echo $aiohm_has_ollama ? esc_html__( 'Local AI', 'aiohm-knowledge-assistant' ) : esc_html__( 'Set up in Advanced', 'aiohm-knowledge-assistant' ); ?></div>
    178105                                                                        </div>
    179106                                                                        <?php if ( ! $aiohm_has_ollama ) : ?>
    … …  
    181108                                                                        <?php endif; ?>
    182109                                                                </label>
     110
     111                                                                <?php if ( $aiohm_has_gemini ) : ?>
     112                                                                <label class="aiohm-provider-option" data-provider="google">
     113                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="gemini" <?php checked( $aiohm_default_ai_provider, 'gemini' ); ?>>
     114                                                                        <div class="aiohm-provider-icon">
     115                                                                                <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/gemini-icon.svg' ); ?>" alt="Google Gemini">
     116                                                                        </div>
     117                                                                        <div class="aiohm-provider-info">
     118                                                                                <div class="aiohm-provider-name">Gemini</div>
     119                                                                                <div class="aiohm-provider-description"><?php esc_html_e( 'Google AI', 'aiohm-knowledge-assistant' ); ?></div>
     120                                                                        </div>
     121                                                                </label>
     122                                                                <?php endif; ?>
     123
     124                                                                <?php if ( $aiohm_has_openai ) : ?>
     125                                                                <label class="aiohm-provider-option" data-provider="openai">
     126                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="openai" <?php checked( $aiohm_default_ai_provider, 'openai' ); ?>>
     127                                                                        <div class="aiohm-provider-icon">
     128                                                                                <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/openai-icon.svg' ); ?>" alt="OpenAI">
     129                                                                        </div>
     130                                                                        <div class="aiohm-provider-info">
     131                                                                                <div class="aiohm-provider-name">OpenAI</div>
     132                                                                                <div class="aiohm-provider-description"><?php esc_html_e( 'WordPress Connectors', 'aiohm-knowledge-assistant' ); ?></div>
     133                                                                        </div>
     134                                                                </label>
     135                                                                <?php endif; ?>
     136
     137                                                                <?php if ( $aiohm_has_anthropic ) : ?>
     138                                                                <label class="aiohm-provider-option" data-provider="anthropic">
     139                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="anthropic" <?php checked( $aiohm_default_ai_provider, 'anthropic' ); ?>>
     140                                                                        <div class="aiohm-provider-icon">
     141                                                                                <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/claude-icon.svg' ); ?>" alt="Anthropic Claude">
     142                                                                        </div>
     143                                                                        <div class="aiohm-provider-info">
     144                                                                                <div class="aiohm-provider-name">Claude</div>
     145                                                                                <div class="aiohm-provider-description"><?php esc_html_e( 'WordPress Connectors', 'aiohm-knowledge-assistant' ); ?></div>
     146                                                                        </div>
     147                                                                </label>
     148                                                                <?php endif; ?>
    183149
    184150                                                        </div>
    … …  
    225191                                                <div class="aiohm-privacy-notice">
    226192                                                        <p><strong><?php esc_html_e( 'Data Processing Notice:', 'aiohm-knowledge-assistant' ); ?></strong></p>
    227                                                         <p><?php esc_html_e( 'This plugin makes API calls to external AI services (OpenAI, Google Gemini, Claude, ShareAI, etc.) to process your content and provide AI responses.', 'aiohm-knowledge-assistant' ); ?></p>
     193                                                        <p><?php esc_html_e( 'This plugin sends requests to the AI service you choose (ShareAI, or Google Gemini, OpenAI or Anthropic when your site connects them) to process your content and write AI responses. A local Ollama server keeps requests on your own server.', 'aiohm-knowledge-assistant' ); ?></p>
    228194                                                </div>
    229195                                        </div>
    … …  
    232198                </div>
    233199
    234                 <!-- Free AI Services Section -->
    235                 <div class="aiohm-card">
    236                         <h2><?php esc_html_e( 'Free AI Services & Connectors', 'aiohm-knowledge-assistant' ); ?></h2>
    237                         <p class="aiohm-section-description"><?php esc_html_e( 'Get started with AI for free using these services and connectors. Perfect for testing and development.', 'aiohm-knowledge-assistant' ); ?></p>
    238                        
    239                         <!-- ShareAI Configuration -->
    240                         <h3 class="aiohm-service-title">
    241                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/shareai-icon.jpeg' ); ?>" alt="ShareAI" class="aiohm-service-icon" />
    242                                 <?php esc_html_e( 'ShareAI', 'aiohm-knowledge-assistant' ); ?>
    243                         </h3>
    244                         <div class="aiohm-shareai-two-column-layout">
    245                                                         <!-- Left Column: Settings -->
    246                                                         <div class="aiohm-shareai-settings-column">
    247                                                                 <div class="aiohm-shareai-settings-box">
    248                                                                         <div class="shareai-setting-row">
    249                                                                                 <label for="shareai_api_key" class="shareai-inline-label"><?php esc_html_e( 'API Key:', 'aiohm-knowledge-assistant' ); ?></label>
    250                                                                                 <div class="aiohm-api-key-wrapper">
    251                                                                                         <div class="aiohm-key-input-group">
    252                                                                                                 <input type="password" id="shareai_api_key" name="aiohm_kb_settings[shareai_api_key]" value="<?php echo esc_attr( $aiohm_settings['shareai_api_key'] ?? '' ); ?>" placeholder="Enter your ShareAI API key" class="regular-text">
    253                                                                                                 <button type="button" class="aiohm-show-hide-key" data-target="shareai_api_key"><span class="dashicons dashicons-visibility"></span></button>
    254                                                                                         </div>
    255                                                                                         <div class="aiohm-api-key-actions">
    256                                                                                                 <button type="button" class="button aiohm-shareai-btn aiohm-test-api-key" data-target="shareai_api_key" data-type="shareai"><?php esc_html_e( 'Test API & Usage', 'aiohm-knowledge-assistant' ); ?></button>
    257                                                                                                 <button type="button" class="button aiohm-shareai-btn aiohm-save-api-key" data-target="shareai_api_key" data-type="shareai"><?php esc_html_e( 'Save', 'aiohm-knowledge-assistant' ); ?></button>
    258                                                                                         </div>
    259                                                                                 </div>
    260                                                                         </div>
    261                                                                        
    262                                                                         <div class="shareai-setting-row">
    263                                                                                 <label for="shareai_model" class="shareai-inline-label"><?php esc_html_e( 'Model:', 'aiohm-knowledge-assistant' ); ?></label>
    264                                                                                 <select id="shareai_model" name="aiohm_kb_settings[shareai_model]" class="regular-text">
    265                                                                                         <optgroup label="Command Models">
    266                                                                                                 <option value="deepseek-r1:7b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'deepseek-r1:7b' ); ?>>DeepSeek R1 7B</option>
    267                                                                                                 <option value="deepseek-r1:14b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'deepseek-r1:14b' ); ?>>DeepSeek R1 14B</option>
    268                                                                                                 <option value="deepseek-r1:32b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'deepseek-r1:32b' ); ?>>DeepSeek R1 32B</option>
    269                                                                                                 <option value="deepseek-r1:671b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'deepseek-r1:671b' ); ?>>DeepSeek R1 671B</option>
    270                                                                                                 <option value="llama4:17b-scout-16e-instruct-fp16" <?php selected( $aiohm_settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16', 'llama4:17b-scout-16e-instruct-fp16' ); ?>>Llama 4 17B Scout (Recommended)</option>
    271                                                                                                 <option value="llama4:90b-instruct-fp16" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'llama4:90b-instruct-fp16' ); ?>>Llama 4 90B Instruct</option>
    272                                                                                                 <option value="qwen2.5:0.5b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:0.5b' ); ?>>Qwen 2.5 0.5B</option>
    273                                                                                                 <option value="qwen2.5:1.5b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:1.5b' ); ?>>Qwen 2.5 1.5B</option>
    274                                                                                                 <option value="qwen2.5:3b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:3b' ); ?>>Qwen 2.5 3B</option>
    275                                                                                                 <option value="qwen2.5:7b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:7b' ); ?>>Qwen 2.5 7B</option>
    276                                                                                                 <option value="qwen2.5:14b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:14b' ); ?>>Qwen 2.5 14B</option>
    277                                                                                                 <option value="qwen2.5:32b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:32b' ); ?>>Qwen 2.5 32B</option>
    278                                                                                                 <option value="qwen2.5:72b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:72b' ); ?>>Qwen 2.5 72B</option>
    279                                                                                         </optgroup>
    280                                                                                         <optgroup label="Chat Models">
    281                                                                                                 <option value="llama3.2:1b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'llama3.2:1b' ); ?>>Llama 3.2 1B</option>
    282                                                                                                 <option value="llama3.2:3b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'llama3.2:3b' ); ?>>Llama 3.2 3B</option>
    283                                                                                                 <option value="llama3.3:70b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'llama3.3:70b' ); ?>>Llama 3.3 70B</option>
    284                                                                                                 <option value="qwen2.5-coder:1.5b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5-coder:1.5b' ); ?>>Qwen 2.5 Coder 1.5B</option>
    285                                                                                                 <option value="qwen2.5-coder:7b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5-coder:7b' ); ?>>Qwen 2.5 Coder 7B</option>
    286                                                                                                 <option value="qwen2.5-coder:14b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5-coder:14b' ); ?>>Qwen 2.5 Coder 14B</option>
    287                                                                                                 <option value="qwen2.5-coder:32b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5-coder:32b' ); ?>>Qwen 2.5 Coder 32B</option>
    288                                                                                         </optgroup>
    289                                                                                 </select>
    290                                                                         </div>
    291                                                                        
    292                                                                         <div class="shareai-usage-notice">
    293                                                                                 <p><strong><?php esc_html_e( 'Affordable AI tokens with ShareAI', 'aiohm-knowledge-assistant' ); ?></strong><br>
    294                                                                                 <?php esc_html_e( 'ShareAI connects you to a global compute network, making AI more affordable or free if you share your device\'s idle power.', 'aiohm-knowledge-assistant' ); ?></p>
    295                                                                                
    296                                                                                 <p><strong><?php esc_html_e( 'To get started:', 'aiohm-knowledge-assistant' ); ?></strong><br>
    297                                                                                 <?php
    298                                                                                         printf(
    299                                                                                                 wp_kses(
    300                                                                                                         // translators: %s is the URL to the ShareAI Console
    301                                                                                                         __( 'Generate your API key in the <a href="%s" target="_blank">ShareAI Console</a>, add it to AIOHM settings, and ensure your chosen model is active.', 'aiohm-knowledge-assistant' ),
    302                                                                                                         array(
    303                                                                                                                 'a' => array(
    304                                                                                                                         'href' => array(),
    305                                                                                                                         'target' => array(),
    306                                                                                                                 ),
    307                                                                                                         )
    308                                                                                                 ),
    309                                                                                                 esc_url( 'https://console.shareai.now/app/api-key/?utm_source=AIOHM&utm_medium=plugin&utm_campaign=shareai_integration' )
    310                                                                                         );
    311                                                                                         ?>
    312                                                                                         </p>
    313                                                                         </div>
    314                                                                 </div>
    315                                                         </div>
    316 
    317                                                         <!-- Right Column: Model Information -->
    318                                                         <div class="aiohm-shareai-info-column">
    319                                                                 <div class="aiohm-model-info-box">
    320                                                                         <h4 class="aiohm-model-info-title"><?php esc_html_e( 'Model Information', 'aiohm-knowledge-assistant' ); ?></h4>
    321                                                                         <div id="aiohm-model-info-content" class="aiohm-model-info-content">
    322                                                                                 <!-- Default placeholder content -->
    323                                                                                 <div class="aiohm-model-placeholder">
    324                                                                                         <div class="aiohm-placeholder-icon">📋</div>
    325                                                                                         <h5><?php esc_html_e( 'Select a Model and Save', 'aiohm-knowledge-assistant' ); ?></h5>
    326                                                                                         <p><?php esc_html_e( 'Choose your preferred ShareAI model from the dropdown and click "Save" to view detailed information about the model\'s capabilities, training, and best use cases.', 'aiohm-knowledge-assistant' ); ?></p>
    327                                                                                         <div class="aiohm-placeholder-steps">
    328                                                                                                 <div class="aiohm-step">
    329                                                                                                         <span class="aiohm-step-number">1</span>
    330                                                                                                         <span><?php esc_html_e( 'Select model from dropdown', 'aiohm-knowledge-assistant' ); ?></span>
    331                                                                                                 </div>
    332                                                                                                 <div class="aiohm-step">
    333                                                                                                         <span class="aiohm-step-number">2</span>
    334                                                                                                         <span><?php esc_html_e( 'Click "Save" button', 'aiohm-knowledge-assistant' ); ?></span>
    335                                                                                                 </div>
    336                                                                                                 <div class="aiohm-step">
    337                                                                                                         <span class="aiohm-step-number">3</span>
    338                                                                                                         <span><?php esc_html_e( 'View model details here', 'aiohm-knowledge-assistant' ); ?></span>
    339                                                                                                 </div>
    340                                                                                         </div>
    341                                                                                 </div>
    342                                                                         </div>
    343                                                                 </div>
    344                                                         </div>
    345                                                 </div>
    346                 </div>
    347 
    348 
    349200                <?php $aiohm_uses_wp_connectors = function_exists( 'wp_get_connectors' ); ?>
    350201
    351                 <div class="aiohm-premium-services-columns <?php echo $aiohm_uses_wp_connectors ? 'aiohm-single-premium-column' : ''; ?>">
    352                         <?php if ( ! $aiohm_uses_wp_connectors ) : ?>
    353                         <!-- Left Column: Gemini and OpenAI -->
     202                <?php if ( ! $aiohm_uses_wp_connectors ) : ?>
     203                <div class="aiohm-premium-services-columns aiohm-single-premium-column">
    354204                        <div class="aiohm-premium-column">
    355205                                <!-- Gemini -->
    … …  
    370220                                                printf(
    371221                                                        wp_kses(
     222                                                                /* translators: %s: Google AI Studio URL */
    372223                                                                __( 'You can get your Gemini API key from the <a href="%s" target="_blank">Google AI Studio</a>.', 'aiohm-knowledge-assistant' ),
    373224                                                                array(
    … …  
    383234                                        </p>
    384235                                </div>
    385 
    386                                 <!-- OpenAI -->
    387                                 <h3 class="aiohm-service-title"><?php esc_html_e( 'OpenAI API Key', 'aiohm-knowledge-assistant' ); ?></h3>
    388                                 <div class="aiohm-service-content">
    389                                         <div class="aiohm-api-key-wrapper">
    390                                                 <div class="aiohm-key-input-group">
    391                                                         <input type="password" id="openai_api_key" name="aiohm_kb_settings[openai_api_key]" value="<?php echo esc_attr( $aiohm_settings['openai_api_key'] ?? '' ); ?>" class="regular-text">
    392                                                         <button type="button" class="aiohm-show-hide-key" data-target="openai_api_key"><span class="dashicons dashicons-visibility"></span></button>
    393                                                 </div>
    394                                                 <div class="aiohm-api-key-actions">
    395                                                         <button type="button" class="button button-secondary aiohm-test-api-key" data-target="openai_api_key" data-type="openai"><?php esc_html_e( 'Test API', 'aiohm-knowledge-assistant' ); ?></button>
    396                                                         <button type="button" class="button button-secondary aiohm-save-api-key" data-target="openai_api_key" data-type="openai"><?php esc_html_e( 'Save', 'aiohm-knowledge-assistant' ); ?></button>
    397                                                 </div>
    398                                         </div>
    399                                         <p class="description">
    400                                         <?php
    401                                                 printf(
    402                                                         wp_kses(
    403                                                                 __( 'You can get your OpenAI API key from the <a href="%s" target="_blank">OpenAI API keys page</a>.', 'aiohm-knowledge-assistant' ),
    404                                                                 array(
    405                                                                         'a' => array(
    406                                                                                 'href' => array(),
    407                                                                                 'target' => array(),
    408                                                                         ),
    409                                                                 )
    410                                                         ),
    411                                                         esc_url( 'https://platform.openai.com/account/api-keys' )
    412                                                 );
    413                                         ?>
    414                                         </p>
    415                                 </div>
    416236                        </div>
    417                         <?php endif; ?>
    418 
    419                         <!-- Right Column: Claude and Groq -->
    420                         <div class="aiohm-premium-column">
    421                                 <?php if ( ! $aiohm_uses_wp_connectors ) : ?>
    422                                 <!-- Claude -->
    423                                 <h3 class="aiohm-service-title"><?php esc_html_e( 'Claude API Key', 'aiohm-knowledge-assistant' ); ?></h3>
    424                                 <div class="aiohm-service-content">
    425                                         <div class="aiohm-api-key-wrapper">
    426                                                 <div class="aiohm-key-input-group">
    427                                                         <input type="password" id="claude_api_key" name="aiohm_kb_settings[claude_api_key]" value="<?php echo esc_attr( $aiohm_settings['claude_api_key'] ?? '' ); ?>" class="regular-text">
    428                                                         <button type="button" class="aiohm-show-hide-key" data-target="claude_api_key"><span class="dashicons dashicons-visibility"></span></button>
    429                                                 </div>
    430                                                 <div class="aiohm-api-key-actions">
    431                                                         <button type="button" class="button button-secondary aiohm-test-api-key" data-target="claude_api_key" data-type="claude"><?php esc_html_e( 'Test API', 'aiohm-knowledge-assistant' ); ?></button>
    432                                                         <button type="button" class="button button-secondary aiohm-save-api-key" data-target="claude_api_key" data-type="claude"><?php esc_html_e( 'Save', 'aiohm-knowledge-assistant' ); ?></button>
    433                                                 </div>
    434                                         </div>
    435                                         <p class="description">
    436                                         <?php
    437                                                 printf(
    438                                                         wp_kses(
    439                                                                 __( 'You can get your Claude API key from your <a href="%s" target="_blank">Anthropic Account Settings</a>.', 'aiohm-knowledge-assistant' ),
    440                                                                 array(
    441                                                                         'a' => array(
    442                                                                                 'href' => array(),
    443                                                                                 'target' => array(),
    444                                                                         ),
    445                                                                 )
    446                                                         ),
    447                                                         esc_url( 'https://console.anthropic.com/account/keys' )
    448                                                 );
    449                                         ?>
    450                                         </p>
    451                                 </div>
    452                                 <?php endif; ?>
    453 
    454                                
    455         <div class="aiohm-card">
    456             <h3 class="aiohm-service-title">
    457                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/groq-icon.svg' ); ?>" alt="Groq" class="aiohm-service-icon" />
    458                 <?php esc_html_e( 'Groq', 'aiohm-knowledge-assistant' ); ?>
    459             </h3>
    460 
    461             <div class="aiohm-shareai-two-column-layout">
    462                 <div class="aiohm-shareai-settings-column">
    463                     <div class="aiohm-shareai-settings-box">
    464                         <div class="shareai-setting-row">
    465                             <label for="groq_api_key" class="shareai-inline-label"><?php esc_html_e( 'API Key:', 'aiohm-knowledge-assistant' ); ?></label>
    466                             <div class="aiohm-api-key-wrapper">
    467                                 <div class="aiohm-key-input-group">
    468                                     <input type="password" id="groq_api_key" name="aiohm_kb_settings[groq_api_key]" value="<?php echo esc_attr( $aiohm_settings['groq_api_key'] ?? '' ); ?>" placeholder="Enter your Groq API key" class="regular-text">
    469                                     <button type="button" class="aiohm-show-hide-key" data-target="groq_api_key"><span class="dashicons dashicons-visibility"></span></button>
    470                                 </div>
    471                                 <div class="aiohm-api-key-actions">
    472                                     <button type="button" class="button aiohm-shareai-btn aiohm-test-api-key" data-target="groq_api_key" data-type="groq"><?php esc_html_e( 'Test API', 'aiohm-knowledge-assistant' ); ?></button>
    473                                     <button type="button" class="button aiohm-shareai-btn aiohm-save-api-key" data-target="groq_api_key" data-type="groq"><?php esc_html_e( 'Save', 'aiohm-knowledge-assistant' ); ?></button>
    474                                 </div>
    475                             </div>
    476                         </div>
    477 
    478                         <div class="shareai-setting-row">
    479                             <label for="groq_model" class="shareai-inline-label"><?php esc_html_e( 'Model:', 'aiohm-knowledge-assistant' ); ?></label>
    480                             <select id="groq_model" name="aiohm_kb_settings[groq_model]" class="regular-text">
    481                                 <option value="groq-default" <?php selected( $aiohm_settings['groq_model'] ?? '', 'groq-default' ); ?>>Groq Default (Recommended)</option>
    482                                 <option value="groq-small" <?php selected( $aiohm_settings['groq_model'] ?? '', 'groq-small' ); ?>>Groq Small</option>
    483                                 <option value="groq-medium" <?php selected( $aiohm_settings['groq_model'] ?? '', 'groq-medium' ); ?>>Groq Medium</option>
    484                                 <option value="groq-large" <?php selected( $aiohm_settings['groq_model'] ?? '', 'groq-large' ); ?>>Groq Large</option>
    485                             </select>
    486                         </div>
    487 
    488                         <div class="shareai-usage-notice">
    489                             <p><strong><?php esc_html_e( 'Groq API Access', 'aiohm-knowledge-assistant' ); ?></strong><br>
    490                             <?php esc_html_e( 'Use your Groq API key for fast, low-latency model inference in AIOHM.', 'aiohm-knowledge-assistant' ); ?></p>
    491 
    492                             <p><strong><?php esc_html_e( 'To get started:', 'aiohm-knowledge-assistant' ); ?></strong><br>
    493                             <?php
    494                                 printf(
    495                                     wp_kses(
    496                                         /* translators: %s is the URL to the Groq Console */
    497                                         __( 'Generate your API key in the <a href="%s" target="_blank">Groq Console</a>, add it to AIOHM settings, and ensure your chosen model is active.', 'aiohm-knowledge-assistant' ),
    498                                         array(
    499                                             'a' => array(
    500                                                 'href' => array(),
    501                                                 'target' => array(),
    502                                             ),
    503                                         )
    504                                     ),
    505                                     esc_url( 'https://console.groq.com/keys' )
    506                                 );
    507                             ?></p>
    508                         </div>
    509                     </div>
    510                 </div>
    511 
    512                 <div class="aiohm-shareai-info-column">
    513                     <div class="aiohm-model-info-box">
    514                         <h4 class="aiohm-model-info-title"><?php esc_html_e( 'Groq Model Information', 'aiohm-knowledge-assistant' ); ?></h4>
    515                         <div class="aiohm-model-info-content">
    516                             <div class="aiohm-model-placeholder">
    517                                 <div class="aiohm-placeholder-icon">⚡</div>
    518                                 <h5><?php esc_html_e( 'Save your Groq API key first', 'aiohm-knowledge-assistant' ); ?></h5>
    519                                 <p><?php esc_html_e( 'Enter and save your Groq key to access model details and performance recommendations.', 'aiohm-knowledge-assistant' ); ?></p>
    520                             </div>
    521                         </div>
    522                     </div>
    523                 </div>
    524             </div>
    525         </div>
     237                </div>
     238                <?php endif; ?>
    526239
    527240        <div class="aiohm-card">
  • aiohm-knowledge-assistant/tags/3.1.0/templates/partials/header.php

    r3801374 r3833232  
    3939                        <li>
    4040                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=aiohm-pro-features' ) ); ?>">
    41                                         <?php esc_html_e( 'Pro Features', 'aiohm-knowledge-assistant' ); ?>
     41                                        <?php esc_html_e( 'Advanced', 'aiohm-knowledge-assistant' ); ?>
    4242                                </a>
    4343                        </li>
  • aiohm-knowledge-assistant/trunk/README.md

    r3801412 r3833232  
    1313- PDF, CSV, TXT and JSON document import
    1414- Brand voice settings
    15 - AI providers: OpenAI, Claude, Gemini, Groq and ShareAI
     15- AI providers: ShareAI and Ollama, plus Google Gemini, OpenAI and Anthropic Claude when your site connects them in WordPress 7 Connectors
    1616- Local AI with Ollama, so content can stay on your own server
    17 - MCP endpoint, so MCP clients such as Claude Desktop can query your knowledge base
     17- MCP endpoint, so desktop and mobile MCP clients can query your knowledge base
    1818- White-label mode for agencies
    1919
    … …  
    2222- WordPress 6.2 or later
    2323- PHP 7.4 or later
    24 - An API key for one AI provider, or a reachable Ollama server
     24- A ShareAI connection (Connect ShareAI), a Gemini API key, or a local Ollama server
    2525
    2626## Install
    … …  
    3838composer install --no-dev --optimize-autoloader
    3939```
     40
     41## ShareAI data and deletion
     42
     43"Connect ShareAI" links a ShareAI account to one WordPress site with OAuth (authorization code and PKCE, public client, no shared secret).
     44
     45- **What the site stores:** encrypted access and refresh tokens, their expiry, the approved scopes, the ShareAI account name and identifier, the last billing stop ShareAI reported, and a daily question count. All of it lives in the site's own WordPress database (`aiohm_kb_shareai_connection`, `aiohm_kb_shareai_daily_usage`). Your ShareAI password never reaches the site.
     46- **What the relay sees:** ShareAI returns to `https://www.ohm.events/wp-json/aiohm-kb/v1/shareai/relay` (OHM Events Agency, the maker of this plugin), which shows the destination site and sends the browser back to it with ShareAI's one-time code. The relay stores nothing and never sees a token. The code is useless without the PKCE verifier that stays on the site.
     47- **How to delete it:** in WordPress, open AIOHM, then Settings, and click Disconnect on the ShareAI card. The plugin revokes the tokens at ShareAI and deletes them from the site. Deleting the plugin does the same. You can also remove the app from your ShareAI account at any time.
     48- **Billing:** requests are charged to the connected ShareAI wallet at the model price plus a 10% builder markup for AIOHM, shown by ShareAI before approval.
    4049
    4150## Contributing
  • aiohm-knowledge-assistant/trunk/aiohm-knowledge-assistant.php

    r3801412 r3833232  
    44 * Plugin URI:  https://knowledge.aiohm.app/
    55 * Description: WordPress 7.0-ready AI knowledge assistant with intelligent chatbot, brand voice alignment, privacy controls, and multi-provider AI support.
    6  * Version:     3.0.0
     6 * Version:     3.1.0
    77 * Author:      OHM Events Agency
    88 * Author URI:  https://www.ohm.events
    … …  
    2929 */
    3030
    31 define("AIOHM_KB_VERSION", "3.0.0");
     31define("AIOHM_KB_VERSION", "3.1.0");
    3232define("AIOHM_KB_PLUGIN_FILE", __FILE__);
    3333define("AIOHM_KB_PLUGIN_DIR", plugin_dir_path(__FILE__));
    … …  
    278278            "shortcode-private-assistant.php",
    279279            "frontend-widget.php",
     280            "shareai-connect.php",
    280281        ];
    281282
    … …  
    289290                require_once $file_path;
    290291            }
     292        }
     293
     294        if (class_exists("AIOHM_KB_ShareAI_Connect")) {
     295            AIOHM_KB_ShareAI_Connect::init();
    291296        }
    292297
    … …  
    438443            "external_api_consent" => true,
    439444
    440             "openai_api_key" => "",
     445            "shareai_model" => "deepseek/deepseek-v4-flash",
    441446            "gemini_api_key" => "",
    442             "claude_api_key" => "",
    443             "shareai_api_key" => "",
    444             "shareai_model" => "llama4:17b-scout-16e-instruct-fp16",
    445             "groq_api_key" => "",
    446             "groq_model" => "llama-3.3-70b-versatile",
    447447            "private_llm_server_url" => "",
    448448            "private_llm_model" => "llama2",
    449             "default_ai_provider" => "ollama",
     449            "default_ai_provider" => "shareai",
    450450
    451451            "pro_features" => [
    … …  
    467467                "qa_temperature" => "0.8",
    468468                "business_name" => get_bloginfo("name"),
     469                // Muse is the plugin's ambassador: the public assistant's
     470                // default name and face. Site owners can rename her.
     471                "assistant_name" => "Muse",
     472                "ai_avatar" => AIOHM_KB_PLUGIN_URL . "assets/images/muse-avatar.webp",
    469473            ],
    470474
    … …  
    511515        }
    512516
    513         $encrypted_api_keys = [
    514             "openai_api_key",
    515             "gemini_api_key",
    516             "claude_api_key",
    517             "groq_api_key",
    518         ];
     517        $encrypted_api_keys = ["gemini_api_key"];
    519518        foreach ($encrypted_api_keys as $key) {
    520519            if (!empty($settings[$key])) {
    … …  
    528527        }
    529528
    530         if (!empty($settings["shareai_api_key"])) {
    531             if (
    532                 strlen($settings["shareai_api_key"]) > 100 ||
    533                 preg_match("/[+\/=]/", $settings["shareai_api_key"])
    534             ) {
    535                 $current_settings = get_option("aiohm_kb_settings", []);
    536                 // The key is corrupted (looks like base64), clear it from both the current settings and the database option.
    537                 $current_settings["shareai_api_key"] = "";
     529        // ShareAI now runs only through Connect ShareAI. A key pasted in an
     530        // earlier version is no longer used, so it is removed, not kept.
     531        if (array_key_exists("shareai_api_key", $settings)) {
     532            $current_settings = get_option("aiohm_kb_settings", []);
     533            if (is_array($current_settings) && array_key_exists("shareai_api_key", $current_settings)) {
     534                unset($current_settings["shareai_api_key"]);
    538535                update_option("aiohm_kb_settings", $current_settings);
    539                 $settings["shareai_api_key"] = "";
     536            }
     537            unset($settings["shareai_api_key"]);
     538        }
     539
     540        return self::migrate_removed_ai_providers($settings);
     541    }
     542
     543    /**
     544     * Point settings that still name a removed AI provider (OpenAI, Claude,
     545     * Groq) at a supported one. This runs on read only: nothing is written
     546     * back and stored API keys stay in the database untouched.
     547     *
     548     * @param array $settings Merged plugin settings.
     549     * @return array Settings with supported provider and model values.
     550     */
     551    private static function migrate_removed_ai_providers($settings)
     552    {
     553        if (
     554            !function_exists("aiohm_kb_resolve_ai_provider") ||
     555            !function_exists("aiohm_kb_ai_provider_ids")
     556        ) {
     557            return $settings;
     558        }
     559
     560        $stored_provider = (string) ($settings["default_ai_provider"] ?? "");
     561        $provider = null;
     562        if ($stored_provider !== "") {
     563            // An empty value keeps its existing meaning: pick the first
     564            // provider that is set up at request time.
     565            if (in_array($stored_provider, aiohm_kb_ai_provider_ids(), true)) {
     566                $provider = $stored_provider;
     567            } else {
     568                // A removed provider (OpenAI, Claude, Groq) moves to ShareAI,
     569                // or to Gemini when only a Gemini key is set. Ollama is left
     570                // out: it ships enabled at localhost, which a hosted site
     571                // rarely runs.
     572                $provider =
     573                    function_exists("aiohm_kb_gemini_available") &&
     574                    !aiohm_kb_shareai_available($settings) &&
     575                    aiohm_kb_gemini_available($settings)
     576                        ? "gemini"
     577                        : "shareai";
     578            }
     579            $settings["default_ai_provider"] = $provider;
     580        }
     581
     582        foreach (["mirror_mode", "muse_mode"] as $mode) {
     583            if (!isset($settings[$mode]) || !is_array($settings[$mode])) {
     584                continue;
     585            }
     586            $mode_model = (string) ($settings[$mode]["ai_model"] ?? "");
     587            if ($mode_model === "") {
     588                continue;
     589            }
     590            if (0 === strpos($mode_model, "shareai")) {
     591                // ShareAI always follows the shareai_model setting.
     592                $settings[$mode]["ai_model"] = aiohm_kb_default_model_for_provider("shareai", $settings);
     593            } elseif (!aiohm_kb_is_supported_ai_model($mode_model)) {
     594                if (null === $provider) {
     595                    $provider = aiohm_kb_resolve_ai_provider("", $settings);
     596                }
     597                $settings[$mode]["ai_model"] = aiohm_kb_default_model_for_provider($provider, $settings);
    540598            }
    541599        }
    … …  
    9791037                "aiohm_app_email" => "",
    9801038
    981                 "openai_api_key" => "",
     1039                "shareai_model" => "deepseek/deepseek-v4-flash",
    9821040                "gemini_api_key" => "",
    983                 "claude_api_key" => "",
    984                 "shareai_api_key" => "",
    985                 "shareai_model" => "llama4:17b-scout-16e-instruct-fp16",
    9861041                "private_llm_server_url" => "",
    9871042                "private_llm_model" => "llama2",
    988                 "default_ai_provider" => "",
     1043                "default_ai_provider" => "shareai",
    9891044
    9901045                "chat_enabled" => true,
    … …  
    11271182     *
    11281183     * @param string $api_key API key to validate
    1129      * @param string $provider Provider type (openai, claude, gemini, shareai)
     1184     * @param string $provider Provider type (shareai, gemini)
    11301185     * @return string|WP_Error Sanitized API key or WP_Error if invalid
    11311186     */
    … …  
    11481203
    11491204        switch ($provider) {
    1150             case "openai":
    1151                 if (!preg_match('/^sk-[a-zA-Z0-9]{20,}$/', $sanitized)) {
     1205            case "shareai":
     1206                $sanitized = preg_replace("/[^a-zA-Z0-9\-]/", "", $sanitized);
     1207                if (strlen($sanitized) < 10) {
    11521208                    return new WP_Error(
    1153                         "invalid_openai_key",
     1209                        "invalid_shareai_key",
    11541210                        __(
    1155                             "Invalid OpenAI API key format.",
    1156                             "aiohm-knowledge-assistant",
    1157                         ),
    1158                     );
    1159                 }
    1160                 break;
    1161             case "claude":
    1162                 if (!preg_match('/^sk-ant-[a-zA-Z0-9_-]{90,}$/', $sanitized)) {
    1163                     return new WP_Error(
    1164                         "invalid_claude_key",
    1165                         __(
    1166                             "Invalid Claude API key format.",
     1211                            "ShareAI API key too short.",
    11671212                            "aiohm-knowledge-assistant",
    11681213                        ),
    … …  
    11811226                }
    11821227                break;
    1183             case "shareai":
    1184                 $sanitized = preg_replace("/[^a-zA-Z0-9\-]/", "", $sanitized);
    1185                 if (strlen($sanitized) < 10) {
    1186                     return new WP_Error(
    1187                         "invalid_shareai_key",
    1188                         __(
    1189                             "ShareAI API key too short.",
    1190                             "aiohm-knowledge-assistant",
    1191                         ),
    1192                     );
    1193                 }
    1194                 break;
    1195             case "groq":
    1196                 if (!preg_match('/^gsk_[a-zA-Z0-9]{50,}$/', $sanitized)) {
    1197                     return new WP_Error(
    1198                         "invalid_groq_key",
    1199                         __(
    1200                             "Invalid Groq API key format.",
    1201                             "aiohm-knowledge-assistant",
    1202                         ),
    1203                     );
    1204                 }
    1205                 break;
    12061228        }
    12071229
    … …  
    13701392
    13711393        $patterns = [
    1372             "/sk-[a-zA-Z0-9_-]{20,}/" => "OPENAI_API_KEY_HIDDEN",
    1373             "/pk-[a-zA-Z0-9_-]{20,}/" => "OPENAI_PUBLIC_KEY_HIDDEN",
    1374 
    1375             "/sk-ant-[a-zA-Z0-9_-]{90,}/" => "CLAUDE_API_KEY_HIDDEN",
     1394            "/sk-[a-zA-Z0-9_-]{20,}/" => "SECRET_KEY_HIDDEN",
     1395            "/pk-[a-zA-Z0-9_-]{20,}/" => "PUBLIC_KEY_HIDDEN",
     1396
     1397            "/sk-ant-[a-zA-Z0-9_-]{90,}/" => "SECRET_KEY_HIDDEN",
    13761398
    13771399            "/AIza[a-zA-Z0-9_-]{35}/" => "GEMINI_API_KEY_HIDDEN",
  • aiohm-knowledge-assistant/trunk/assets/css/aiohm-admin-settings.css

    r3545079 r3833232  
    737737                padding: 8px 16px;
    738738        }
     739
     740/* Run on ShareAI card (2026-11-19) */
     741.aiohm-shareai-connect { margin: 16px 0 24px; }
     742.aiohm-shareai-connect__head { display: flex; align-items: flex-start; gap: 16px; }
     743.aiohm-shareai-connect__head h2 { margin: 0 0 4px; font-size: 18px; color: #193f10; letter-spacing: 0; }
     744.aiohm-shareai-connect__head > div { flex: 1; min-width: 0; }
     745/* Official ShareAI icon: its own corners, never cropped or rounded (shareai.now/brand-guidance). */
     746.aiohm-shareai-connect__icon { display: block; width: 40px; height: 40px; flex-shrink: 0; }
     747.aiohm-shareai-connect__status { flex-shrink: 0; font-size: 12px; font-weight: 700; padding: 4px 10px; border-radius: 999px; background: #ebebeb; color: #444; white-space: nowrap; }
     748.aiohm-shareai-connect__status.is-on { background: #e4efe0; color: #193f10; }
     749.aiohm-shareai-connect__status.is-off { background: #fbe9e7; color: #8a1f11; }
     750.aiohm-shareai-connect__facts { margin: 16px 0; padding-left: 20px; list-style: disc; line-height: 1.6; }
     751.aiohm-shareai-connect__warn { color: #8a1f11; }
     752.aiohm-shareai-connect__stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 16px 0; }
     753.aiohm-shareai-connect__stats > div { border: 1px solid #ddd; border-radius: 8px; padding: 10px 12px; }
     754.aiohm-shareai-connect__stats dt { font-size: 11px; font-weight: 700; text-transform: uppercase; color: #666; }
     755.aiohm-shareai-connect__stats dd { margin: 4px 0 0; font-weight: 600; overflow-wrap: anywhere; }
     756.aiohm-shareai-connect__form label { display: block; font-weight: 600; margin-bottom: 4px; }
     757.aiohm-shareai-connect__form select, .aiohm-shareai-connect__form input[type=number] { max-width: 420px; width: 100%; }
     758.aiohm-shareai-connect__form .description { display: block; margin-top: 4px; }
     759.aiohm-shareai-connect__actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
     760/* ShareAI's button pattern, same spec as the AIOHM platform's ShareAI buttons:
     761   white surface, warm border, official 32px icon beside the label, 50px tall, visible focus. */
     762.aiohm-shareai-btn-official { display: inline-flex; align-items: center; justify-content: center; gap: 16px; min-height: 50px; box-sizing: border-box; padding: 9px 20px 9px 16px; border: 1px solid #e2d9cc; border-radius: 9px; background: #fff; color: #24201a; box-shadow: 0 3px 12px rgba(0, 0, 0, .067); font-size: 14px; font-weight: 650; line-height: 1.3; letter-spacing: 0; text-decoration: none; transition: border-color .15s ease, box-shadow .15s ease; }
     763.aiohm-shareai-btn-official:hover { border-color: #ffb07a; color: #24201a; box-shadow: 0 4px 14px rgba(0, 0, 0, .12); }
     764.aiohm-shareai-btn-official:focus-visible { outline: 2px solid #ff9a4c; outline-offset: 2px; color: #24201a; box-shadow: none; }
     765.aiohm-shareai-btn-official img { display: block; flex-shrink: 0; width: 32px; height: 32px; }
     766@media (prefers-reduced-motion: reduce) { .aiohm-shareai-btn-official { transition: none; } }
     767.aiohm-shareai-connect__disconnect { color: #8a1f11 !important; }
  • aiohm-knowledge-assistant/trunk/assets/css/aiohm-provider-icons.css

    r3376955 r3833232  
    1212}
    1313
    14 /* 6-Column Grid Layout for all providers */
     14/* 3-column grid layout for all providers */
    1515.aiohm-provider-grid {
    1616        display: grid;
    17         grid-template-columns: repeat(6, 1fr);
     17        /* Tiles share one row and wrap only when the box runs out of room. */
     18        grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
     19        /* Its row is a flex container: take the full width, or the grid shrinks to one tile. */
     20        flex: 1 1 100%;
     21        width: 100%;
    1822        gap: 12px;
    1923        margin: 15px 0;
    20 }
    21 
    22 
    23 @media (max-width: 1400px) {
    24         .aiohm-provider-grid {
    25                 grid-template-columns: repeat(3, 1fr);
    26         }
    27 }
    28 
    29 @media (max-width: 1000px) {
    30         .aiohm-provider-grid {
    31                 grid-template-columns: repeat(2, 1fr);
    32         }
    3324}
    3425
    … …  
    125116
    126117/* Provider-specific icon styling */
    127 .aiohm-provider-option[data-provider="openai"] .aiohm-provider-icon {
    128         border-radius: 8px;
    129         overflow: hidden;
    130 }
    131 
    132118.aiohm-provider-option[data-provider="google"] .aiohm-provider-icon {
    133119        border-radius: 50%;
    134         overflow: hidden;
    135 }
    136 
    137 .aiohm-provider-option[data-provider="anthropic"] .aiohm-provider-icon {
    138         border-radius: 8px;
    139120        overflow: hidden;
    140121}
    … …  
    328309        outline-offset: 2px;
    329310}
     311/* The official ShareAI icon carries its own corners; rounding it would crop them. */
     312.aiohm-provider-icon img[src*="shareai-icon"] {
     313        border-radius: 0;
     314}
  • aiohm-knowledge-assistant/trunk/assets/js/aiohm-admin-modes.js

    r3545079 r3833232  
    400400        const apiValue = $('#' + targetInput).val();
    401401       
    402         // Special handling for ShareAI - save both API key and model
    403         if (apiType === 'shareai') {
    404             const selectedModel = $('#shareai_model').val();
    405            
    406             if (!apiValue.trim()) {
    407                 showAdminNotice('Please enter an API key before saving.', 'warning');
    408                 return;
    409             }
    410            
    411             if (!selectedModel) {
    412                 showAdminNotice('Please select a model before saving.', 'warning');
    413                 return;
    414             }
    415            
    416             // Disable button and show loading state
    417             $btn.prop('disabled', true).text('Saving...');
    418            
    419             // Save API key first, then model
    420             let apiSaveCompleted = false;
    421             let modelSaveCompleted = false;
    422             let apiSaveSuccess = false;
    423             let modelSaveSuccess = false;
    424             let apiSaveMessage = '';
    425             let modelSaveMessage = '';
    426            
    427             function checkBothSavesComplete() {
    428                 if (apiSaveCompleted && modelSaveCompleted) {
    429                     // Re-enable button and restore original text
    430                     $btn.prop('disabled', false).text(originalText);
    431                    
    432                     if (apiSaveSuccess && modelSaveSuccess) {
    433                         // Success state
    434                         $btn.addClass('success');
    435                         showAdminNotice('ShareAI settings saved successfully!', 'success');
    436                        
    437                         // Now display the model information
    438                         updateModelInfo(selectedModel);
    439                        
    440                         // Reset button state after 2 seconds
    441                         setTimeout(function() {
    442                             $btn.removeClass('success');
    443                         }, 2000);
    444                     } else {
    445                         const errorMessages = [];
    446                         if (!apiSaveSuccess) errorMessages.push(apiSaveMessage);
    447                         if (!modelSaveSuccess) errorMessages.push(modelSaveMessage);
    448                         showAdminNotice('Error: ' + errorMessages.join(', '), 'error');
    449                     }
    450                 }
    451             }
    452            
    453             // Save API key
    454             $.post(config.ajax_url, {
    455                 action: 'aiohm_save_individual_api_key',
    456                 nonce: config.nonce || $('#aiohm_nonce').val() || $('[name*="nonce"]').val(),
    457                 api_type: 'shareai',
    458                 setting_name: 'shareai_api_key',
    459                 api_value: apiValue
    460             }).done(function(response) {
    461                 apiSaveSuccess = response.success;
    462                 apiSaveMessage = response.data?.message || 'Could not save API key';
    463             }).fail(function() {
    464                 apiSaveSuccess = false;
    465                 apiSaveMessage = 'Server error saving API key';
    466             }).always(function() {
    467                 apiSaveCompleted = true;
    468                 checkBothSavesComplete();
    469             });
    470            
    471             // Save model selection
    472             $.post(config.ajax_url, {
    473                 action: 'aiohm_save_individual_api_key',
    474                 nonce: config.nonce || $('#aiohm_nonce').val() || $('[name*="nonce"]').val(),
    475                 api_type: 'shareai_model',
    476                 setting_name: 'shareai_model',
    477                 api_value: selectedModel
    478             }).done(function(response) {
    479                 modelSaveSuccess = response.success;
    480                 modelSaveMessage = response.data?.message || 'Could not save model';
    481             }).fail(function() {
    482                 modelSaveSuccess = false;
    483                 modelSaveMessage = 'Server error saving model';
    484             }).always(function() {
    485                 modelSaveCompleted = true;
    486                 checkBothSavesComplete();
    487             });
    488            
    489             return; // Exit early for ShareAI
    490         }
    491402       
    492403        // Standard handling for other API providers
    … …  
    502413        let settingName;
    503414        switch(apiType) {
    504             case 'openai':
    505                 settingName = 'openai_api_key';
    506                 break;
    507415            case 'gemini':
    508416                settingName = 'gemini_api_key';
    509                 break;
    510             case 'claude':
    511                 settingName = 'claude_api_key';
    512417                break;
    513418            case 'ollama':
  • aiohm-knowledge-assistant/trunk/assets/js/aiohm-admin-settings.js

    r3545079 r3833232  
    116116        // Map key types to setting names
    117117        const settingMap = {
    118             'shareai': 'shareai_api_key',
    119             'openai': 'openai_api_key',
    120118            'gemini': 'gemini_api_key',
    121             'claude': 'claude_api_key',
    122             'groq': 'groq_api_key',
    123119            'ollama': 'private_llm_server_url'
    124120        };
    … …  
    322318       
    323319        // Update breakdown table
    324         const providers = ['openai', 'gemini', 'claude', 'shareai'];
     320        const providers = ['shareai', 'gemini', 'ollama'];
    325321        providers.forEach(provider => {
    326322            const providerData = data.providers?.[provider] || {};
  • aiohm-knowledge-assistant/trunk/includes/ai-gpt-client.php

    r3801374 r3833232  
    22/**
    33 * AI client for multi-provider API requests
    4  * Handles OpenAI, Google Gemini, Claude, and ShareAI integrations
     4 * Handles ShareAI, Google Gemini and Ollama integrations
    55 */
    66if ( ! defined( 'ABSPATH' ) ) {
    77        exit;
     8}
     9
     10if ( ! function_exists( 'aiohm_kb_ai_provider_ids' ) ) {
     11        /**
     12         * The supported AI providers, in display and fallback order.
     13         *
     14         * @return array Provider IDs.
     15         */
     16        function aiohm_kb_ai_provider_ids() {
     17                return array( 'shareai', 'gemini', 'ollama', 'openai', 'anthropic' );
     18        }
     19}
     20
     21if ( ! function_exists( 'aiohm_kb_wp_connector_provider_ids' ) ) {
     22        /**
     23         * Providers AIOHM reaches only through WordPress Connectors and the
     24         * WordPress AI Client: their keys live in WordPress, never in AIOHM.
     25         *
     26         * @return array Provider IDs.
     27         */
     28        function aiohm_kb_wp_connector_provider_ids() {
     29                return array( 'openai', 'anthropic' );
     30        }
     31}
     32
     33if ( ! function_exists( 'aiohm_kb_wp_connector_provider_available' ) ) {
     34        /**
     35         * A WordPress Connector provider is usable when WordPress has the AI
     36         * Client and the connector has a key.
     37         *
     38         * @param string $provider openai or anthropic.
     39         * @return bool
     40         */
     41        function aiohm_kb_wp_connector_provider_available( $provider ) {
     42                return function_exists( 'wp_ai_client_prompt' )
     43                        && in_array( $provider, aiohm_kb_wp_connector_provider_ids(), true )
     44                        && function_exists( 'aiohm_kb_is_wp_ai_connector_configured' )
     45                        && aiohm_kb_is_wp_ai_connector_configured( $provider );
     46        }
     47}
     48
     49if ( ! function_exists( 'aiohm_kb_shareai_available' ) ) {
     50        /**
     51         * ShareAI is usable once the site owner has connected a ShareAI account.
     52         *
     53         * @param array $settings Plugin settings.
     54         * @return bool
     55         */
     56        function aiohm_kb_shareai_available( $settings ) {
     57                return class_exists( 'AIOHM_KB_ShareAI_Connect' ) && AIOHM_KB_ShareAI_Connect::is_connected();
     58        }
     59}
     60
     61if ( ! function_exists( 'aiohm_kb_gemini_available' ) ) {
     62        /**
     63         * Gemini is usable with a saved API key or a WordPress Connector key.
     64         *
     65         * @param array $settings Plugin settings.
     66         * @return bool
     67         */
     68        function aiohm_kb_gemini_available( $settings ) {
     69                return ! empty( $settings['gemini_api_key'] )
     70                        || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) );
     71        }
     72}
     73
     74if ( ! function_exists( 'aiohm_kb_ollama_available' ) ) {
     75        /**
     76         * Ollama is usable when it is enabled and has a server URL.
     77         *
     78         * @param array $settings Plugin settings.
     79         * @return bool
     80         */
     81        function aiohm_kb_ollama_available( $settings ) {
     82                $pro_features = isset( $settings['pro_features'] ) && is_array( $settings['pro_features'] ) ? $settings['pro_features'] : array();
     83                $enabled      = ! empty( $pro_features['ollama_enabled'] );
     84                $server_url   = $pro_features['ollama_server_url'] ?? ( $settings['private_llm_server_url'] ?? '' );
     85                return $enabled && ! empty( $server_url );
     86        }
     87}
     88
     89if ( ! function_exists( 'aiohm_kb_ai_provider_available' ) ) {
     90        /**
     91         * Check whether a supported provider is set up.
     92         *
     93         * @param string $provider Provider ID.
     94         * @param array  $settings Plugin settings.
     95         * @return bool
     96         */
     97        function aiohm_kb_ai_provider_available( $provider, $settings ) {
     98                switch ( $provider ) {
     99                        case 'shareai':
     100                                return aiohm_kb_shareai_available( $settings );
     101                        case 'gemini':
     102                                return aiohm_kb_gemini_available( $settings );
     103                        case 'ollama':
     104                                return aiohm_kb_ollama_available( $settings );
     105                        case 'openai':
     106                        case 'anthropic':
     107                                return aiohm_kb_wp_connector_provider_available( $provider );
     108                        default:
     109                                return false;
     110                }
     111        }
     112}
     113
     114if ( ! function_exists( 'aiohm_kb_resolve_ai_provider' ) ) {
     115        /**
     116         * Map a stored provider ID to a supported one.
     117         *
     118         * Supported IDs pass through. Anything else, including the removed
     119         * openai, claude and groq providers, becomes the first set-up provider
     120         * of shareai, gemini and ollama, or shareai when none is set up.
     121         *
     122         * @param string $provider Stored provider ID.
     123         * @param array  $settings Plugin settings.
     124         * @return string Supported provider ID.
     125         */
     126        function aiohm_kb_resolve_ai_provider( $provider, $settings ) {
     127                $provider = is_string( $provider ) ? $provider : '';
     128                if ( '' !== $provider && function_exists( 'aiohm_kb_normalize_wp_ai_provider_id' ) ) {
     129                        $provider = aiohm_kb_normalize_wp_ai_provider_id( $provider );
     130                }
     131                // Connector providers count only while WordPress still has their key.
     132                if ( in_array( $provider, aiohm_kb_ai_provider_ids(), true )
     133                        && ( ! in_array( $provider, aiohm_kb_wp_connector_provider_ids(), true ) || aiohm_kb_ai_provider_available( $provider, $settings ) ) ) {
     134                        return $provider;
     135                }
     136                foreach ( aiohm_kb_ai_provider_ids() as $candidate ) {
     137                        if ( aiohm_kb_ai_provider_available( $candidate, $settings ) ) {
     138                                return $candidate;
     139                        }
     140                }
     141                return 'shareai';
     142        }
     143}
     144
     145if ( ! function_exists( 'aiohm_kb_default_model_for_provider' ) ) {
     146        /**
     147         * The chat model value to send for a provider.
     148         *
     149         * ShareAI uses the shareai_model setting, Gemini the existing Gemini
     150         * model ID, and Ollama the model saved in its own settings.
     151         *
     152         * @param string $provider Provider ID.
     153         * @param array  $settings Plugin settings.
     154         * @return string Model value for AIOHM_KB_AI_GPT_Client::get_chat_completion().
     155         */
     156        function aiohm_kb_default_model_for_provider( $provider, $settings ) {
     157                switch ( $provider ) {
     158                        case 'gemini':
     159                                return 'gemini-pro';
     160                        case 'ollama':
     161                                return 'ollama';
     162                        case 'openai':
     163                        case 'anthropic':
     164                                return 'wp-' . $provider;
     165                        case 'shareai':
     166                        default:
     167                                $shareai_model = (string) ( $settings['shareai_model'] ?? '' );
     168                                if ( '' === $shareai_model ) {
     169                                        $shareai_model = 'deepseek/deepseek-v4-flash';
     170                                }
     171                                return 'shareai-' . $shareai_model;
     172                }
     173        }
     174}
     175
     176if ( ! function_exists( 'aiohm_kb_is_supported_ai_model' ) ) {
     177        /**
     178         * Whether a mode model value belongs to a supported provider.
     179         *
     180         * @param string $model Model value.
     181         * @return bool
     182         */
     183        function aiohm_kb_is_supported_ai_model( $model ) {
     184                $model = (string) $model;
     185                return 0 === strpos( $model, 'gemini' )
     186                        || 0 === strpos( $model, 'shareai' )
     187                        || 0 === strpos( $model, 'ollama' )
     188                        || in_array( $model, array( 'wp-openai', 'wp-anthropic' ), true );
     189        }
    8190}
    9191
    … …  
    34216                        return 'gemini';
    35217                }
    36                 if ( false !== strpos( $haystack, 'anthropic' ) || false !== strpos( $haystack, 'claude' ) ) {
    37                         return 'claude';
    38                 }
    39                 if ( false !== strpos( $haystack, 'openai' ) || false !== strpos( $haystack, 'gpt' ) ) {
    40                         return 'openai';
    41                 }
    42                 if ( false !== strpos( $haystack, 'groq' ) ) {
    43                         return 'groq';
    44                 }
    45218                if ( false !== strpos( $haystack, 'shareai' ) ) {
    46219                        return 'shareai';
    … …  
    49222                        return 'ollama';
    50223                }
     224                if ( false !== strpos( $haystack, 'anthropic' ) || false !== strpos( $haystack, 'claude' ) ) {
     225                        return 'anthropic';
     226                }
     227                if ( false !== strpos( $haystack, 'openai' ) || false !== strpos( $haystack, 'chatgpt' ) ) {
     228                        return 'openai';
     229                }
    51230
    52231                return sanitize_key( $provider_id );
    … …  
    62241         */
    63242        function aiohm_kb_get_wp_connector_api_key( $provider ) {
    64                 $provider       = aiohm_kb_normalize_wp_ai_provider_id( $provider );
     243                $provider = aiohm_kb_normalize_wp_ai_provider_id( $provider );
     244                // AIOHM reads the Google (Gemini), OpenAI and Anthropic connectors.
     245                if ( ! in_array( $provider, array( 'gemini', 'openai', 'anthropic' ), true ) ) {
     246                        return '';
     247                }
     248
    65249                $env_names      = array();
    66250                $constant_names = array();
    … …  
    68252
    69253                $defaults = array(
    70                         'openai' => array(
     254                        'gemini'    => array(
     255                                'env'     => array( 'GOOGLE_API_KEY', 'GEMINI_API_KEY' ),
     256                                'const'   => array( 'GOOGLE_API_KEY', 'GEMINI_API_KEY' ),
     257                                'options' => array( 'connectors_ai_google_api_key', 'connectors_ai_gemini_api_key' ),
     258                        ),
     259                        'openai'    => array(
    71260                                'env'     => array( 'OPENAI_API_KEY' ),
    72261                                'const'   => array( 'OPENAI_API_KEY' ),
    73262                                'options' => array( 'connectors_ai_openai_api_key' ),
    74263                        ),
    75                         'gemini' => array(
    76                                 'env'     => array( 'GOOGLE_API_KEY', 'GEMINI_API_KEY' ),
    77                                 'const'   => array( 'GOOGLE_API_KEY', 'GEMINI_API_KEY' ),
    78                                 'options' => array( 'connectors_ai_google_api_key', 'connectors_ai_gemini_api_key' ),
    79                         ),
    80                         'claude' => array(
    81                                 'env'     => array( 'ANTHROPIC_API_KEY', 'CLAUDE_API_KEY' ),
    82                                 'const'   => array( 'ANTHROPIC_API_KEY', 'CLAUDE_API_KEY' ),
    83                                 'options' => array( 'connectors_ai_anthropic_api_key', 'connectors_ai_claude_api_key' ),
     264                        'anthropic' => array(
     265                                'env'     => array( 'ANTHROPIC_API_KEY' ),
     266                                'const'   => array( 'ANTHROPIC_API_KEY' ),
     267                                'options' => array( 'connectors_ai_anthropic_api_key' ),
    84268                        ),
    85269                );
    … …  
    136320                if ( is_array( $legacy_credentials ) ) {
    137321                        $legacy_ids = array(
    138                                 'openai' => array( 'openai' ),
    139                                 'gemini' => array( 'google', 'gemini' ),
    140                                 'claude' => array( 'anthropic', 'claude' ),
     322                                'gemini'    => array( 'google', 'gemini' ),
     323                                'openai'    => array( 'openai' ),
     324                                'anthropic' => array( 'anthropic' ),
    141325                        );
    142326
    … …  
    167351
    168352        private $settings;
    169         private $openai_api_key;
    170353        private $gemini_api_key;
    171         private $claude_api_key;
    172         private $shareai_api_key;
    173         private $groq_api_key;
    174354        private $ollama_server_url;
    175355        private $ollama_model;
    … …  
    181361                        $this->settings = $settings;
    182362                }
    183                 $this->openai_api_key  = $this->settings['openai_api_key'] ?? '';
    184                 $this->gemini_api_key  = $this->settings['gemini_api_key'] ?? '';
    185                 $this->claude_api_key  = $this->settings['claude_api_key'] ?? '';
    186                 if ( empty( $this->openai_api_key ) ) {
    187                         $this->openai_api_key = aiohm_kb_get_wp_connector_api_key( 'openai' );
    188                 }
     363                $this->gemini_api_key = $this->settings['gemini_api_key'] ?? '';
    189364                if ( empty( $this->gemini_api_key ) ) {
    190365                        $this->gemini_api_key = aiohm_kb_get_wp_connector_api_key( 'gemini' );
    191366                }
    192                 if ( empty( $this->claude_api_key ) ) {
    193                         $this->claude_api_key = aiohm_kb_get_wp_connector_api_key( 'claude' );
    194                 }
    195                 $this->shareai_api_key = $this->settings['shareai_api_key'] ?? '';
    196                 $this->groq_api_key    = $this->settings['groq_api_key'] ?? '';
    197367
    198368                // Ollama settings - check both pro_features and legacy settings
    … …  
    213383         * Check if API key is properly configured for the given provider
    214384         *
    215          * @param string $provider The AI provider (openai, gemini, claude, shareai, groq, ollama)
     385         * @param string $provider The AI provider (shareai, gemini, ollama)
    216386         * @return bool True if API key is configured
    217387         */
    218388        public function is_api_key_configured( $provider ) {
    219389                switch ( $provider ) {
    220                         case 'openai':
    221                                 return ! empty( $this->openai_api_key );
     390                        case 'shareai':
     391                                return aiohm_kb_shareai_available( $this->settings );
    222392                        case 'gemini':
    223393                                return ! empty( $this->gemini_api_key );
    224                         case 'claude':
    225                                 return ! empty( $this->claude_api_key );
    226                         case 'shareai':
    227                                 return ! empty( $this->shareai_api_key );
    228                         case 'groq':
    229                                 return ! empty( $this->groq_api_key );
    230394                        case 'ollama':
    231395                                return ! empty( $this->ollama_server_url );
    … …  
    371535                if ( is_string( $data ) ) {
    372536                        $patterns = array(
    373                                 '/sk-[a-zA-Z0-9_-]{20,}/'                => 'OPENAI_API_KEY_HIDDEN',
    374                                 '/pk-[a-zA-Z0-9_-]{20,}/'                => 'OPENAI_PUBLIC_KEY_HIDDEN',
    375                                 '/sk-ant-[a-zA-Z0-9_-]{90,}/'            => 'CLAUDE_API_KEY_HIDDEN',
     537                                '/sk-[a-zA-Z0-9_-]{20,}/'                => 'SECRET_KEY_HIDDEN',
     538                                '/pk-[a-zA-Z0-9_-]{20,}/'                => 'PUBLIC_KEY_HIDDEN',
     539                                '/sk-ant-[a-zA-Z0-9_-]{90,}/'            => 'SECRET_KEY_HIDDEN',
    376540                                '/AIza[a-zA-Z0-9_-]{35}/'                => 'GEMINI_API_KEY_HIDDEN',
    377541                                '/[a-zA-Z0-9_-]{32,}/'                   => 'POTENTIAL_API_KEY_HIDDEN',
    … …  
    411575                }
    412576
    413                 $provider = $this->settings['default_ai_provider'] ?? 'openai';
     577                $provider = aiohm_kb_resolve_ai_provider( $this->settings['default_ai_provider'] ?? '', $this->settings );
    414578
    415579                switch ( $provider ) {
    416580                        case 'gemini':
    417581                                return $this->generate_gemini_embeddings( $text );
    418                         case 'claude':
    419                                 return $this->generate_claude_embeddings( $text );
    420                         case 'shareai':
    421                                 return $this->generate_shareai_embeddings( $text );
    422582                        case 'ollama':
    423583                                return $this->generate_ollama_embeddings( $text );
    424584                        case 'openai':
     585                        case 'anthropic':
     586                                // Connector providers run chat only; search uses keywords.
     587                                throw new Exception( 'This AI provider is used for chat only. Search uses keywords.' );
     588                        case 'shareai':
    425589                        default:
    426                                 return $this->generate_openai_embeddings( $text );
    427                 }
    428         }
    429 
    430         private function generate_openai_embeddings( $text ) {
    431                 if ( empty( $this->openai_api_key ) ) {
    432                         throw new Exception( 'OpenAI API key is required for embeddings.' );
    433                 }
    434 
    435                 $url  = 'https://api.openai.com/v1/embeddings';
    436                 $data = array(
    437                         'model' => 'text-embedding-ada-002',
    438                         'input' => $this->sanitize_text_for_json( $text ),
    439                 );
    440 
    441                 $body = json_encode( $data );
    442                 if ( $body === false ) {
    443                         throw new Exception( 'Failed to JSON-encode embedding request. Content may contain invalid characters.' );
    444                 }
    445 
    446                 $response = $this->make_http_request( $url, $body, 'openai' );
    447 
    448                 if ( isset( $response['data'][0]['embedding'] ) ) {
    449                         return $response['data'][0]['embedding'];
    450                 } else {
    451                         $error_message = $response['error']['message'] ?? 'Invalid embedding response from OpenAI API.';
    452                         throw new Exception( esc_html( $error_message ) );
     590                                return $this->generate_shareai_embeddings( $text );
    453591                }
    454592        }
    … …  
    483621        }
    484622
    485         private function generate_claude_embeddings( $text ) {
    486                 // Claude API does not currently have a dedicated embedding endpoint.
    487                 // This functionality is not supported.
    488                 throw new Exception( 'Claude does not support embeddings. Please select a different provider for embedding generation.' );
    489         }
    490 
    491623        private function generate_shareai_embeddings( $text ) {
     624                // A connected ShareAI account can embed; a pasted API key cannot.
     625                if ( class_exists( 'AIOHM_KB_ShareAI_Connect' ) && AIOHM_KB_ShareAI_Connect::is_connected() ) {
     626                        if ( ! $this->has_shareai_consent() ) {
     627                                throw new Exception( 'ShareAI service requires user consent. Please enable it in Settings and review our Terms of Service.' );
     628                        }
     629                        $embedding_model = (string) ( $this->settings['shareai_embedding_model'] ?? '' );
     630                        if ( '' !== $embedding_model ) {
     631                                return AIOHM_KB_ShareAI_Connect::embedding( $text, $embedding_model );
     632                        }
     633                        // No ShareAI embedding model chosen: keep searching with the
     634                        // provider that built the existing knowledge base vectors.
     635                        $previous = (string) ( $this->settings['shareai_previous_provider'] ?? '' );
     636                        if ( in_array( $previous, array( 'gemini', 'ollama' ), true ) ) {
     637                                $settings                        = $this->settings;
     638                                $settings['default_ai_provider'] = $previous;
     639                                $client                          = new self( $settings );
     640                                return $client->generate_embeddings( $text );
     641                        }
     642                        throw new Exception( 'Choose a ShareAI embedding model in the AIOHM settings, or switch to a provider that supports embeddings.' );
     643                }
     644
    492645                // ShareAI API does not currently have a dedicated embedding endpoint.
    493646                // This functionality is not supported.
    … …  
    496649
    497650
    498         public function get_chat_completion( $system_message, $user_message, $temperature = 0.7, $model = 'gpt-3.5-turbo' ) {
    499                 $default_provider = $this->settings['default_ai_provider'] ?? 'openai';
    500                 if ( function_exists( 'aiohm_kb_normalize_wp_ai_provider_id' ) ) {
    501                         $default_provider = aiohm_kb_normalize_wp_ai_provider_id( $default_provider );
    502                 }
    503 
    504                 if ( strpos( $model, 'gemini' ) === 0 || ( ( empty( $model ) || 'gpt-3.5-turbo' === $model ) && ( 'gemini' === $default_provider || 'google' === $default_provider ) ) ) {
    505                         return $this->get_gemini_chat_completion( $system_message, $user_message, $temperature, $model );
    506                 }
    507 
    508                 if ( strpos( $model, 'claude' ) === 0 || ( ( empty( $model ) || 'gpt-3.5-turbo' === $model ) && ( 'claude' === $default_provider || 'anthropic' === $default_provider ) ) ) {
    509                         return $this->get_claude_chat_completion( $system_message, $user_message, $temperature, $model );
    510                 }
    511 
    512                 if ( strpos( $model, 'groq' ) === 0 || ( ( empty( $model ) || 'gpt-3.5-turbo' === $model ) && 'groq' === $default_provider ) ) {
    513                         return $this->get_groq_chat_completion( $system_message, $user_message, $temperature, $model );
    514                 }
    515 
    516                 if ( strpos( $model, 'shareai' ) === 0 || $default_provider === 'shareai' ) {
    517                         return $this->get_shareai_chat_completion( $system_message, $user_message, $temperature, $model );
    518                 }
    519 
    520                 if ( $model === 'ollama' || $default_provider === 'ollama' ) {
    521                         return $this->get_ollama_chat_completion( $system_message, $user_message, $temperature, $model );
    522                 }
    523 
    524                 return $this->get_openai_chat_completion( $system_message, $user_message, $temperature, $model );
     651        public function get_chat_completion( $system_message, $user_message, $temperature = 0.7, $model = '' ) {
     652                $model    = (string) $model;
     653                $provider = aiohm_kb_resolve_ai_provider( $this->settings['default_ai_provider'] ?? '', $this->settings );
     654
     655                // An explicit model for a supported provider wins. Any other value,
     656                // including models of removed providers, uses the default provider.
     657                if ( 0 === strpos( $model, 'gemini' ) ) {
     658                        $provider = 'gemini';
     659                } elseif ( 0 === strpos( $model, 'shareai' ) ) {
     660                        $provider = 'shareai';
     661                } elseif ( 0 === strpos( $model, 'ollama' ) ) {
     662                        $provider = 'ollama';
     663                } elseif ( in_array( $model, array( 'wp-openai', 'wp-anthropic' ), true ) ) {
     664                        $provider = substr( $model, 3 );
     665                }
     666
     667                switch ( $provider ) {
     668                        case 'openai':
     669                        case 'anthropic':
     670                                return $this->get_wp_connector_chat_completion( $provider, $system_message, $user_message, $temperature );
     671                        case 'gemini':
     672                                return $this->get_gemini_chat_completion( $system_message, $user_message, $temperature, $model );
     673                        case 'ollama':
     674                                return $this->get_ollama_chat_completion( $system_message, $user_message, $temperature, $model );
     675                        case 'shareai':
     676                        default:
     677                                return $this->get_shareai_chat_completion( $system_message, $user_message, $temperature, $model );
     678                }
     679        }
     680
     681        /**
     682         * Chat through the WordPress AI Client with a provider set up in
     683         * Settings > Connectors. WordPress holds the key and picks the model.
     684         *
     685         * @param string $provider openai or anthropic.
     686         * @throws Exception When the provider is not connected or the request fails.
     687         */
     688        private function get_wp_connector_chat_completion( $provider, $system_message, $user_message, $temperature ) {
     689                if ( empty( $this->settings['external_api_consent'] ) ) {
     690                        throw new Exception( esc_html__( 'External API calls require user consent. Please enable this option in settings.', 'aiohm-knowledge-assistant' ) );
     691                }
     692                if ( ! aiohm_kb_wp_connector_provider_available( $provider ) ) {
     693                        throw new Exception( esc_html__( 'Add this provider in Settings > Connectors in WordPress, or choose another AI provider in the AIOHM settings.', 'aiohm-knowledge-assistant' ) );
     694                }
     695                if ( ! $this->check_rate_limit( $provider ) ) {
     696                        throw new Exception( esc_html__( 'AI rate limit exceeded. Please try again later.', 'aiohm-knowledge-assistant' ) );
     697                }
     698
     699                $text = wp_ai_client_prompt( (string) $user_message )
     700                        ->using_provider( $provider )
     701                        ->using_system_instruction( (string) $system_message )
     702                        ->using_temperature( (float) $temperature )
     703                        ->generate_text();
     704
     705                if ( is_wp_error( $text ) ) {
     706                        throw new Exception( esc_html( $this->get_safe_error_message( $text->get_error_message(), 'openai' === $provider ? 'OpenAI' : 'Anthropic' ) ) );
     707                }
     708                $text = (string) $text;
     709                if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
     710                        AIOHM_KB_Core_Init::log_ai_usage( $provider, intval( ( strlen( $system_message ) + strlen( $user_message ) + strlen( $text ) ) / 4 ), 0 );
     711                }
     712                return $text;
    525713        }
    526714
    … …  
    578766        }
    579767
    580         private function get_claude_chat_completion( $system_message, $user_message, $temperature, $model ) {
    581                 if ( empty( $this->claude_api_key ) ) {
    582                         throw new Exception( 'Claude API key is required for chat completions.' );
    583                 }
    584 
    585                 $claude_model_map = array(
    586                         'claude-3-sonnet' => 'claude-3-sonnet-20240229',
    587                         'claude-3-haiku'  => 'claude-3-haiku-20240307',
    588                         'claude-3-opus'   => 'claude-3-opus-20240229',
    589                 );
    590 
    591                 $actual_model = $claude_model_map[ $model ] ?? 'claude-3-sonnet-20240229';
    592                 $url          = 'https://api.anthropic.com/v1/messages';
    593 
    594                 $data = array(
    595                         'model'       => $actual_model,
    596                         'max_tokens'  => 4000,
    597                         'temperature' => floatval( $temperature ),
    598                         'system'      => $this->sanitize_text_for_json( $system_message ),
    599                         'messages'    => array(
    600                                 array(
    601                                         'role'    => 'user',
    602                                         'content' => $this->sanitize_text_for_json( $user_message ),
    603                                 ),
    604                         ),
    605                 );
    606 
    607                 $body = json_encode( $data );
    608                 if ( $body === false ) {
    609                         throw new Exception( 'Failed to JSON-encode chat request.' );
    610                 }
    611 
    612                 $response = $this->make_http_request( $url, $body, 'claude' );
    613 
    614                 if ( isset( $response['content'][0]['text'] ) ) {
    615                         $content          = $response['content'][0]['text'];
    616                         $estimated_tokens = ( strlen( $system_message ) + strlen( $user_message ) + strlen( $content ) ) / 4;
    617                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    618                                 AIOHM_KB_Core_Init::log_ai_usage( 'claude', intval( $estimated_tokens ), 0 );
    619                         }
    620                         return $content;
    621                 } else {
    622                         $error_message = $response['error']['message'] ?? 'Invalid chat response from Claude API.';
    623                         throw new Exception( esc_html( $this->get_safe_error_message( $error_message, 'Claude' ) ) );
    624                 }
    625         }
    626 
    627768        private function get_shareai_chat_completion( $system_message, $user_message, $temperature, $model ) {
    628769                // WordPress.org compliance: Check for ShareAI consent
    … …  
    631772                }
    632773
    633                 if ( empty( $this->shareai_api_key ) ) {
    634                         throw new Exception( 'ShareAI API key is required for chat completions.' );
    635                 }
    636 
    637                 if ( ! $this->check_rate_limit( 'shareai' ) ) {
    638                         throw new Exception( 'ShareAI API rate limit exceeded. Please try again later.' );
    639                 }
    640 
    641                 $shareai_model = $this->settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    642                 if ( strpos( $model, 'shareai-' ) === 0 ) {
    643                         $shareai_model = str_replace( 'shareai-', '', $model );
    644                 }
    645 
    646                 $url = 'https://api.shareai.now/api/v1/chat/completions';
    647 
    648                 $combined_message = $system_message . "\n\n" . 'User question: ' . $user_message;
    649 
    650                 $data = array(
    651                         'model'       => $shareai_model,
    652                         'messages'    => array(
    653                                 array(
    654                                         'role'    => 'user',
    655                                         'content' => $this->sanitize_text_for_json( $combined_message ),
    656                                 ),
    657                         ),
    658                         'temperature' => floatval( $temperature ),
    659                         'max_tokens'  => 4000,
    660                 );
    661 
    662                 $body = json_encode( $data );
    663                 if ( $body === false ) {
    664                         throw new Exception( 'Failed to JSON-encode chat request.' );
    665                 }
    666 
    667                 try {
    668                         $response = $this->make_http_request( $url, $body, 'shareai' );
    669                 } catch ( Exception $e ) {
    670                         throw new Exception( esc_html( $this->get_safe_error_message( $e->getMessage(), 'ShareAI' ) ) );
    671                 }
    672 
    673                 if ( isset( $response['choices'][0]['message']['content'] ) ) {
    674                         $content          = $response['choices'][0]['message']['content'];
    675                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    676                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    677                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    678                         }
    679                         return $content;
    680                 } elseif ( isset( $response['message'] ) ) {
    681                         $message = $response['message'];
    682 
    683                         $final_content = '';
    684                         if ( is_string( $message ) ) {
    685                                 $decoded = json_decode( $message, true );
    686                                 if ( $decoded !== null && isset( $decoded['content'] ) ) {
    687                                         $final_content = $decoded['content'];
    688                                 } else {
    689                                         $final_content = $message;
    690                                 }
    691                         } elseif ( is_array( $message ) && isset( $message['content'] ) ) {
    692                                 $final_content = $message['content'];
    693                         } else {
    694                                 $final_content = is_string( $message ) ? $message : json_encode( $message );
    695                         }
    696 
    697                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $final_content ) ) / 4;
    698                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    699                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    700                         }
    701                         return $final_content;
    702                 } elseif ( isset( $response['response'] ) ) {
    703                         $content          = $response['response'];
    704                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    705                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    706                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    707                         }
    708                         return $content;
    709                 } elseif ( isset( $response['content'] ) ) {
    710                         $content          = $response['content'];
    711                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    712                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    713                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    714                         }
    715                         return $content;
    716                 } elseif ( isset( $response['text'] ) ) {
    717                         $content          = $response['text'];
    718                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    719                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    720                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    721                         }
    722                         return $content;
    723                 } elseif ( isset( $response['data']['text'] ) ) {
    724                         $content          = $response['data']['text'];
    725                         $estimated_tokens = ( strlen( $combined_message ) + strlen( $content ) ) / 4;
    726                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    727                                 AIOHM_KB_Core_Init::log_ai_usage( 'shareai', intval( $estimated_tokens ), 0 );
    728                         }
    729                         return $content;
    730                 } else {
    731                         $error_message = $response['error']['message'] ?? 'Invalid chat response from ShareAI API.';
    732                         throw new Exception( esc_html( $error_message ) );
    733                 }
    734         }
    735 
    736         private function get_groq_chat_completion( $system_message, $user_message, $temperature, $model ) {
    737                 if ( empty( $this->groq_api_key ) ) {
    738                         throw new Exception( 'Groq API key is required for chat completions.' );
    739                 }
    740 
    741                 // Map UI model names to actual Groq API model names
    742                 $groq_model_map = array(
    743                         'groq-llama-3.3-70b-versatile' => 'llama-3.3-70b-versatile',
    744                         'groq-llama-3.1-70b-versatile' => 'llama-3.3-70b-versatile', // Fallback for deprecated model
    745                 );
    746                 $actual_model = $groq_model_map[ $model ] ?? 'llama-3.3-70b-versatile';
    747 
    748                 $url  = 'https://api.groq.com/openai/v1/chat/completions';
    749                 $data = array(
    750                         'model'       => $actual_model,
    751                         'messages'    => array(
    752                                 array(
    753                                         'role'    => 'system',
    754                                         'content' => $this->sanitize_text_for_json( $system_message ),
    755                                 ),
    756                                 array(
    757                                         'role'    => 'user',
    758                                         'content' => $this->sanitize_text_for_json( $user_message ),
    759                                 ),
    760                         ),
    761                         'temperature' => floatval( $temperature ),
    762                 );
    763 
    764                 $body = json_encode( $data );
    765                 if ( $body === false ) {
    766                         throw new Exception( 'Failed to JSON-encode chat request.' );
    767                 }
    768 
    769                 $response = $this->make_http_request( $url, $body, 'groq' );
    770 
    771                 if ( isset( $response['choices'][0]['message']['content'] ) ) {
    772                         $content       = $response['choices'][0]['message']['content'];
    773                         $total_tokens  = $response['usage']['total_tokens'] ?? 0;
    774 
    775                         // Log usage for Groq
    776                         if ( $total_tokens > 0 ) {
    777                                 AIOHM_KB_Core_Init::log_ai_usage( 'groq', intval( $total_tokens ), 0 );
    778                         }
    779                         return $content;
    780                 } else {
    781                         $error_message = $response['error']['message'] ?? 'Invalid chat response from Groq API.';
    782                         throw new Exception( esc_html( $error_message ) );
    783                 }
    784         }
    785 
    786         private function get_openai_chat_completion( $system_message, $user_message, $temperature, $model ) {
    787                 if ( empty( $this->openai_api_key ) ) {
    788                         throw new Exception( 'OpenAI API key is required for chat completions.' );
    789                 }
    790 
    791                 $url  = 'https://api.openai.com/v1/chat/completions';
    792                 $data = array(
    793                         'model'       => $model,
    794                         'messages'    => array(
    795                                 array(
    796                                         'role'    => 'system',
    797                                         'content' => $this->sanitize_text_for_json( $system_message ),
    798                                 ),
    799                                 array(
    800                                         'role'    => 'user',
    801                                         'content' => $this->sanitize_text_for_json( $user_message ),
    802                                 ),
    803                         ),
    804                         'temperature' => floatval( $temperature ),
    805                 );
    806 
    807                 $body = json_encode( $data );
    808                 if ( $body === false ) {
    809                         throw new Exception( 'Failed to JSON-encode chat request.' );
    810                 }
    811 
    812                 $response = $this->make_http_request( $url, $body, 'openai' );
    813 
    814                 if ( isset( $response['choices'][0]['message']['content'] ) ) {
    815                         $content       = $response['choices'][0]['message']['content'];
    816                         $tokens_used   = $response['usage']['total_tokens'] ?? intval( ( strlen( $system_message ) + strlen( $user_message ) + strlen( $content ) ) / 4 );
    817                         $cost_estimate = $this->estimate_openai_cost( $model, $tokens_used );
    818                         if ( class_exists( 'AIOHM_KB_Core_Init' ) ) {
    819                                 AIOHM_KB_Core_Init::log_ai_usage( 'openai', $tokens_used, $cost_estimate );
    820                         }
    821                         return $content;
    822                 } else {
    823                         $error_message = $response['error']['message'] ?? 'Invalid chat response from OpenAI API.';
    824                         throw new Exception( esc_html( $error_message ) );
    825                 }
    826         }
    827 
    828         private function estimate_openai_cost( $model, $tokens ) {
    829                 $pricing = array(
    830                         'gpt-4'             => 0.03,
    831                         'gpt-4-turbo'       => 0.01,
    832                         'gpt-3.5-turbo'     => 0.002,
    833                         'gpt-3.5-turbo-16k' => 0.004,
    834                 );
    835 
    836                 $rate = $pricing[ $model ] ?? 0.002;
    837                 return ( $tokens / 1000000 ) * $rate;
     774                // ShareAI runs on the owner's connected account and wallet (AIOHM's
     775                // builder plan). There is no pasted API key route.
     776                if ( class_exists( 'AIOHM_KB_ShareAI_Connect' ) && AIOHM_KB_ShareAI_Connect::is_connected() ) {
     777                        if ( ! $this->check_rate_limit( 'shareai' ) ) {
     778                                throw new Exception( 'ShareAI API rate limit exceeded. Please try again later.' );
     779                        }
     780                        $connected_model = (string) ( $this->settings['shareai_model'] ?? '' );
     781                        if ( strpos( $model, 'shareai-' ) === 0 ) {
     782                                $connected_model = str_replace( 'shareai-', '', $model );
     783                        }
     784                        return AIOHM_KB_ShareAI_Connect::chat( $system_message, $user_message, $temperature, $connected_model );
     785                }
     786
     787                throw new Exception( 'Connect ShareAI in the AIOHM settings to use ShareAI.' );
    838788        }
    839789
    … …  
    844794
    845795                $headers = array( 'Content-Type' => 'application/json' );
    846                 if ( $api_type === 'openai' ) {
    847                         $headers['Authorization'] = 'Bearer ' . $this->openai_api_key;
    848                 } elseif ( $api_type === 'gemini' ) {
     796                if ( $api_type === 'gemini' ) {
    849797                        $headers['x-goog-api-key'] = $this->gemini_api_key;
    850                 } elseif ( $api_type === 'claude' ) {
    851                         $headers['Authorization']     = 'Bearer ' . $this->claude_api_key;
    852                         $headers['anthropic-version'] = '2023-06-01';
    853                 } elseif ( $api_type === 'groq' ) {
    854                         $headers['Authorization'] = 'Bearer ' . $this->groq_api_key;
    855                 } elseif ( $api_type === 'shareai' ) {
    856                         $headers['Authorization'] = 'Bearer ' . $this->shareai_api_key;
    857798                }
    858799
    … …  
    955896        }
    956897
    957         public function test_claude_api_connection() {
    958                 if ( empty( $this->claude_api_key ) ) {
     898        /**
     899         * Check the connected ShareAI account: a valid access token (refreshed when
     900         * needed) means the connection works.
     901         *
     902         * @return array{success: bool, error?: string}
     903         */
     904        public function test_shareai_api_connection() {
     905                if ( ! class_exists( 'AIOHM_KB_ShareAI_Connect' ) || ! AIOHM_KB_ShareAI_Connect::is_connected() ) {
    959906                        return array(
    960907                                'success' => false,
    961                                 'error'   => 'Claude API key is missing.',
     908                                'error'   => 'ShareAI is not connected. Click Connect ShareAI in the AIOHM settings.',
    962909                        );
    963910                }
    964911                try {
    965                         $this->get_chat_completion( 'Test prompt', "Say 'hello'.", 0.5, 'claude-3-sonnet' );
     912                        AIOHM_KB_ShareAI_Connect::access_token();
    966913                        return array( 'success' => true );
    967914                } catch ( Exception $e ) {
    … …  
    973920        }
    974921
    975         public function test_shareai_api_connection() {
    976                 // WordPress.org compliance: Check for ShareAI consent
    977                 if ( ! $this->has_shareai_consent() ) {
    978                         return array(
    979                                 'success' => false,
    980                                 'error'   => 'ShareAI service requires user consent. Please enable it in Settings.',
    981                         );
    982                 }
    983 
    984                 if ( empty( $this->shareai_api_key ) ) {
    985                         return array(
    986                                 'success' => false,
    987                                 'error'   => 'ShareAI API key is missing.',
    988                         );
    989                 }
    990 
    991                 // Check if this looks like a base64 encoded string (which would be wrong)
    992                 if ( strlen( $this->shareai_api_key ) > 200 && preg_match( '/^[A-Za-z0-9+\/=]+$/', $this->shareai_api_key ) ) {
    993                 }
    994 
    995                 // Check if key has any unusual characters that might indicate corruption
    996                 if ( preg_match( '/[^A-Za-z0-9\-_.]/', $this->shareai_api_key ) ) {
    997                 }
    998 
    999                 // First test basic connectivity without auth
    1000                 $basic_test = wp_remote_get( 'https://api.shareai.now/api/v1/', array( 'timeout' => 10 ) );
    1001                 if ( is_wp_error( $basic_test ) ) {
    1002                 } else {
    1003                 }
    1004 
    1005                 // Use the key info endpoint to test connection without consuming tokens
    1006                 $key_info_url = 'https://api.shareai.now/api/v1/iam/key/info';
    1007 
    1008                 try {
    1009                         $response = wp_remote_get(
    1010                                 $key_info_url,
    1011                                 array(
    1012                                         'headers' => array(
    1013                                                 'Content-Type'  => 'application/json',
    1014                                                 'Authorization' => 'Bearer ' . $this->shareai_api_key,
    1015                                         ),
    1016                                         'timeout' => 30,
    1017                                 )
    1018                         );
    1019 
    1020                         if ( is_wp_error( $response ) ) {
    1021                                 return array(
    1022                                         'success' => false,
    1023                                         'error'   => 'Connection error: ' . $response->get_error_message(),
    1024                                 );
    1025                         }
    1026 
    1027                         $response_code = wp_remote_retrieve_response_code( $response );
    1028                         $response_body = wp_remote_retrieve_body( $response );
    1029 
    1030                         if ( $response_code !== 200 ) {
    1031                                 // If key info endpoint fails, fall back to minimal chat test
    1032                                 return $this->test_shareai_fallback_connection();
    1033                         }
    1034 
    1035                         $decoded = json_decode( $response_body, true );
    1036                         if ( $decoded === null ) {
    1037                                 return $this->test_shareai_fallback_connection();
    1038                         }
    1039 
    1040                         // Check for valid key info response and extract usage information
    1041                         $usage_info = $this->extract_shareai_usage_from_response( $decoded );
    1042 
    1043                         if ( isset( $decoded['valid'] ) && $decoded['valid'] === true ) {
    1044                                 $message = 'ShareAI connection successful - API key is valid';
    1045                                 if ( $usage_info['has_usage'] ) {
    1046                                         $message .= sprintf(
    1047                                                 ' | Tokens used: %d | Requests: %d',
    1048                                                 $usage_info['tokens_used'],
    1049                                                 $usage_info['requests_made']
    1050                                         );
    1051                                         if ( $usage_info['quota_remaining'] !== null ) {
    1052                                                 $message .= sprintf( ' | Quota remaining: %s', $usage_info['quota_remaining'] );
    1053                                         }
    1054                                 }
    1055                                 return array(
    1056                                         'success'  => true,
    1057                                         'message'  => $message,
    1058                                         'key_info' => $decoded,
    1059                                         'usage'    => $usage_info,
    1060                                 );
    1061                         } elseif ( isset( $decoded['status'] ) && $decoded['status'] === 'active' ) {
    1062                                 $message = 'ShareAI connection successful - API key is active';
    1063                                 if ( $usage_info['has_usage'] ) {
    1064                                         $message .= sprintf(
    1065                                                 ' | Tokens used: %d | Requests: %d',
    1066                                                 $usage_info['tokens_used'],
    1067                                                 $usage_info['requests_made']
    1068                                         );
    1069                                 }
    1070                                 return array(
    1071                                         'success'  => true,
    1072                                         'message'  => $message,
    1073                                         'key_info' => $decoded,
    1074                                         'usage'    => $usage_info,
    1075                                 );
    1076                         } elseif ( isset( $decoded['keyId'] ) || isset( $decoded['key_id'] ) || isset( $decoded['id'] ) ) {
    1077                                 // Key info returned some identifier, consider it successful
    1078                                 $message = 'ShareAI connection successful - Key info retrieved';
    1079                                 if ( $usage_info['has_usage'] ) {
    1080                                         $message .= sprintf(
    1081                                                 ' | Tokens used: %d | Requests: %d',
    1082                                                 $usage_info['tokens_used'],
    1083                                                 $usage_info['requests_made']
    1084                                         );
    1085                                 }
    1086                                 return array(
    1087                                         'success'  => true,
    1088                                         'message'  => $message,
    1089                                         'key_info' => $decoded,
    1090                                         'usage'    => $usage_info,
    1091                                 );
    1092                         } elseif ( isset( $decoded['error'] ) ) {
    1093                                 return array(
    1094                                         'success' => false,
    1095                                         'error'   => 'ShareAI API Error: ' . $decoded['error'],
    1096                                 );
    1097                         } else {
    1098                                 // If key info doesn't work as expected, fall back to minimal chat test
    1099                                 return $this->test_shareai_fallback_connection();
    1100                         }
    1101                 } catch ( Exception $e ) {
    1102                         return array(
    1103                                 'success' => false,
    1104                                 'error'   => 'Connection test failed: ' . $e->getMessage(),
    1105                         );
    1106                 }
    1107         }
    1108 
    1109         /**
    1110          * Extract usage information from ShareAI API response
    1111          *
    1112          * @param array $decoded The decoded API response
    1113          * @return array Usage information
    1114          */
    1115         private function extract_shareai_usage_from_response( $decoded ) {
    1116                 $usage_info = array(
    1117                         'has_usage'       => false,
    1118                         'tokens_used'     => 0,
    1119                         'requests_made'   => 0,
    1120                         'quota_remaining' => null,
    1121                         'quota_limit'     => null,
    1122                         'reset_date'      => null,
    1123                 );
    1124 
    1125                 // Parse different possible response formats for usage data
    1126                 if ( isset( $decoded['usage'] ) ) {
    1127                         $usage                         = $decoded['usage'];
    1128                         $usage_info['has_usage']       = true;
    1129                         $usage_info['tokens_used']     = $usage['tokens'] ?? $usage['total_tokens'] ?? 0;
    1130                         $usage_info['requests_made']   = $usage['requests'] ?? $usage['total_requests'] ?? 0;
    1131                         $usage_info['quota_remaining'] = $usage['remaining'] ?? $usage['quota_remaining'] ?? null;
    1132                         $usage_info['quota_limit']     = $usage['limit'] ?? $usage['quota_limit'] ?? null;
    1133                         $usage_info['reset_date']      = $usage['reset_date'] ?? $usage['quota_reset'] ?? null;
    1134                 } elseif ( isset( $decoded['tokens'] ) || isset( $decoded['requests'] ) ) {
    1135                         // Direct usage fields in root
    1136                         $usage_info['has_usage']       = true;
    1137                         $usage_info['tokens_used']     = $decoded['tokens'] ?? $decoded['total_tokens'] ?? 0;
    1138                         $usage_info['requests_made']   = $decoded['requests'] ?? $decoded['total_requests'] ?? 0;
    1139                         $usage_info['quota_remaining'] = $decoded['remaining'] ?? $decoded['quota_remaining'] ?? null;
    1140                         $usage_info['quota_limit']     = $decoded['limit'] ?? $decoded['quota_limit'] ?? null;
    1141                 }
    1142 
    1143                 return $usage_info;
    1144         }
    1145 
    1146         private function test_shareai_fallback_connection() {
    1147 
    1148                 // Fallback to minimal chat test if key info endpoint doesn't work
    1149                 $test_url       = 'https://api.shareai.now/api/v1/chat/completions';
    1150                 $selected_model = $this->settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    1151 
    1152                 $test_data = array(
    1153                         'model'      => $selected_model,
    1154                         'messages'   => array(
    1155                                 array(
    1156                                         'role'    => 'user',
    1157                                         'content' => 'Hi',
    1158                                 ),
    1159                         ),
    1160                         'max_tokens' => 10, // Minimal tokens to reduce consumption
    1161                 );
    1162 
    1163                 try {
    1164                         $response = wp_remote_post(
    1165                                 $test_url,
    1166                                 array(
    1167                                         'headers' => array(
    1168                                                 'Content-Type'  => 'application/json',
    1169                                                 'Authorization' => 'Bearer ' . $this->shareai_api_key,
    1170                                         ),
    1171                                         'body'    => json_encode( $test_data ),
    1172                                         'timeout' => 30,
    1173                                 )
    1174                         );
    1175 
    1176                         if ( is_wp_error( $response ) ) {
    1177                                 return array(
    1178                                         'success' => false,
    1179                                         'error'   => 'Connection error: ' . $response->get_error_message(),
    1180                                 );
    1181                         }
    1182 
    1183                         $response_code = wp_remote_retrieve_response_code( $response );
    1184                         $response_body = wp_remote_retrieve_body( $response );
    1185 
    1186                         if ( $response_code !== 200 ) {
    1187                                 return array(
    1188                                         'success' => false,
    1189                                         'error'   => 'HTTP ' . $response_code . ': ' . $response_body,
    1190                                 );
    1191                         }
    1192 
    1193                         $decoded = json_decode( $response_body, true );
    1194                         if ( $decoded === null ) {
    1195                                 return array(
    1196                                         'success' => false,
    1197                                         'error'   => 'Invalid JSON response: ' . json_last_error_msg(),
    1198                                 );
    1199                         }
    1200 
    1201                         // Check for any valid response format
    1202                         if ( isset( $decoded['choices'][0]['message']['content'] ) ||
    1203                                 isset( $decoded['message'] ) ||
    1204                                 isset( $decoded['response'] ) ||
    1205                                 isset( $decoded['content'] ) ||
    1206                                 isset( $decoded['text'] ) ) {
    1207                                 return array(
    1208                                         'success' => true,
    1209                                         'message' => 'ShareAI connection successful (fallback test)',
    1210                                 );
    1211                         } else {
    1212                                 return array(
    1213                                         'success' => true,
    1214                                         'message' => 'ShareAI connection successful (unknown format)',
    1215                                 );
    1216                         }
    1217                 } catch ( Exception $e ) {
    1218                         return array(
    1219                                 'success' => false,
    1220                                 'error'   => 'Fallback connection test failed: ' . $e->getMessage(),
    1221                         );
    1222                 }
    1223         }
    1224 
    1225         /**
    1226          * Get ShareAI usage information without consuming tokens
    1227          *
    1228          * @return array Usage information or error
    1229          */
    1230         public function get_shareai_usage_info() {
    1231                 if ( empty( $this->shareai_api_key ) ) {
    1232                         return array(
    1233                                 'success' => false,
    1234                                 'error'   => 'ShareAI API key is missing.',
    1235                         );
    1236                 }
    1237 
    1238                 $key_info_url = 'https://api.shareai.now/api/v1/iam/key/info';
    1239 
    1240                 try {
    1241                         $response = wp_remote_get(
    1242                                 $key_info_url,
    1243                                 array(
    1244                                         'headers' => array(
    1245                                                 'Content-Type'  => 'application/json',
    1246                                                 'Authorization' => 'Bearer ' . $this->shareai_api_key,
    1247                                         ),
    1248                                         'timeout' => 30,
    1249                                 )
    1250                         );
    1251 
    1252                         if ( is_wp_error( $response ) ) {
    1253                                 return array(
    1254                                         'success' => false,
    1255                                         'error'   => 'Connection error: ' . $response->get_error_message(),
    1256                                 );
    1257                         }
    1258 
    1259                         $response_code = wp_remote_retrieve_response_code( $response );
    1260                         $response_body = wp_remote_retrieve_body( $response );
    1261 
    1262                         if ( $response_code !== 200 ) {
    1263                                 return array(
    1264                                         'success' => false,
    1265                                         'error'   => 'HTTP ' . $response_code . ': ' . $response_body,
    1266                                 );
    1267                         }
    1268 
    1269                         $decoded = json_decode( $response_body, true );
    1270                         if ( $decoded === null ) {
    1271                                 return array(
    1272                                         'success' => false,
    1273                                         'error'   => 'Invalid JSON response: ' . json_last_error_msg(),
    1274                                 );
    1275                         }
    1276 
    1277                         // Extract usage information from the response
    1278                         $usage_info = array(
    1279                                 'success'         => true,
    1280                                 'tokens_used'     => 0,
    1281                                 'requests_made'   => 0,
    1282                                 'quota_remaining' => null,
    1283                                 'quota_limit'     => null,
    1284                                 'reset_date'      => null,
    1285                         );
    1286 
    1287                         // Parse different possible response formats for usage data
    1288                         if ( isset( $decoded['usage'] ) ) {
    1289                                 $usage                         = $decoded['usage'];
    1290                                 $usage_info['tokens_used']     = $usage['tokens'] ?? $usage['total_tokens'] ?? 0;
    1291                                 $usage_info['requests_made']   = $usage['requests'] ?? $usage['total_requests'] ?? 0;
    1292                                 $usage_info['quota_remaining'] = $usage['remaining'] ?? $usage['quota_remaining'] ?? null;
    1293                                 $usage_info['quota_limit']     = $usage['limit'] ?? $usage['quota_limit'] ?? null;
    1294                                 $usage_info['reset_date']      = $usage['reset_date'] ?? $usage['quota_reset'] ?? null;
    1295                         } elseif ( isset( $decoded['tokens'] ) || isset( $decoded['requests'] ) ) {
    1296                                 // Direct usage fields in root
    1297                                 $usage_info['tokens_used']     = $decoded['tokens'] ?? $decoded['total_tokens'] ?? 0;
    1298                                 $usage_info['requests_made']   = $decoded['requests'] ?? $decoded['total_requests'] ?? 0;
    1299                                 $usage_info['quota_remaining'] = $decoded['remaining'] ?? $decoded['quota_remaining'] ?? null;
    1300                                 $usage_info['quota_limit']     = $decoded['limit'] ?? $decoded['quota_limit'] ?? null;
    1301                         }
    1302 
    1303                         $usage_info['raw_response'] = $decoded;
    1304 
    1305                         return $usage_info;
    1306 
    1307                 } catch ( Exception $e ) {
    1308                         return array(
    1309                                 'success' => false,
    1310                                 'error'   => 'Failed to get usage info: ' . $e->getMessage(),
    1311                         );
    1312                 }
    1313         }
    1314 
    1315 
    1316922        /**
    1317923         * Get the current AI provider based on settings
    … …  
    1320926         */
    1321927        public function get_current_provider() {
    1322                 $provider = $this->settings['default_ai_provider'] ?? ($this->settings['ai_provider'] ?? 'openai');
    1323                 if ( function_exists( 'aiohm_kb_normalize_wp_ai_provider_id' ) ) {
    1324                         $provider = aiohm_kb_normalize_wp_ai_provider_id( $provider );
    1325                 }
    1326 
    1327                 // Map old provider names to current ones
    1328                 $provider_mapping = array(
    1329                         'gpt'       => 'openai',
    1330                         'openai'    => 'openai',
    1331                         'gemini'    => 'google',
    1332                         'google'    => 'google',
    1333                         'claude'    => 'anthropic',
    1334                         'anthropic' => 'anthropic',
    1335                         'shareai'   => 'shareai',
    1336                 );
    1337 
    1338                 return $provider_mapping[ $provider ] ?? 'openai';
     928                return aiohm_kb_resolve_ai_provider( $this->settings['default_ai_provider'] ?? ( $this->settings['ai_provider'] ?? '' ), $this->settings );
    1339929        }
    1340930
    … …  
    1354944                if ( ! $model ) {
    1355945                        $provider = $this->get_current_provider();
    1356                         switch ( $provider ) {
    1357                                 case 'openai':
    1358                                         $model = 'gpt-4';
    1359                                         break;
    1360                                 case 'gemini':
    1361                                 case 'google':
    1362                                         $model = 'gemini-2.5-flash';
    1363                                         break;
    1364                                 case 'anthropic':
    1365                                         $model = 'claude-3-sonnet-20240229';
    1366                                         break;
    1367                                 default:
    1368                                         $model = 'gemini-2.5-flash';
     946                        if ( 'gemini' === $provider ) {
     947                                $model = 'gemini-2.5-flash';
     948                        } else {
     949                                $model = aiohm_kb_default_model_for_provider( $provider, $this->settings );
    1369950                        }
    1370951                }
    1371952
    1372953                return $this->get_chat_completion( '', $prompt, $temperature, $model );
    1373         }
    1374 
    1375         /**
    1376          * Test Groq API connection
    1377          *
    1378          * @return array Result with success status and message
    1379          */
    1380         public function test_groq_api_connection() {
    1381                 if ( empty( $this->groq_api_key ) ) {
    1382                         return array(
    1383                                 'success' => false,
    1384                                 'error'   => 'Groq API key is missing.',
    1385                         );
    1386                 }
    1387 
    1388                 try {
    1389                         // Use a simple direct API call for testing
    1390                         $url = 'https://api.groq.com/openai/v1/chat/completions';
    1391 
    1392                         $data = array(
    1393                                 'model' => 'llama-3.3-70b-versatile',
    1394                                 'messages' => array(
    1395                                         array( 'role' => 'user', 'content' => 'Say hello in one word' ),
    1396                                 ),
    1397                                 'max_tokens' => 5,
    1398                         );
    1399 
    1400                         $response = wp_remote_post(
    1401                                 $url,
    1402                                 array(
    1403                                         'headers' => array(
    1404                                                 'Content-Type'  => 'application/json',
    1405                                                 'Authorization' => 'Bearer ' . $this->groq_api_key,
    1406                                         ),
    1407                                         'body'    => json_encode( $data ),
    1408                                         'timeout' => 30,
    1409                                 )
    1410                         );
    1411 
    1412                         if ( is_wp_error( $response ) ) {
    1413                                 return array(
    1414                                         'success' => false,
    1415                                         'error'   => 'Connection error: ' . $response->get_error_message(),
    1416                                 );
    1417                         }
    1418 
    1419                         $status_code = wp_remote_retrieve_response_code( $response );
    1420                         $body        = wp_remote_retrieve_body( $response );
    1421 
    1422                         if ( $status_code === 200 ) {
    1423                                 $decoded = json_decode( $body, true );
    1424                                 if ( isset( $decoded['choices'] ) && ! empty( $decoded['choices'] ) ) {
    1425                                         return array(
    1426                                                 'success' => true,
    1427                                                 'message' => 'Groq connection successful!',
    1428                                         );
    1429                                 }
    1430                         }
    1431 
    1432                         $decoded = json_decode( $body, true );
    1433                         $error_message = $decoded['error']['message'] ?? 'Unknown API error';
    1434 
    1435                         return array(
    1436                                 'success' => false,
    1437                                 'error'   => $error_message,
    1438                         );
    1439 
    1440                 } catch ( Exception $e ) {
    1441                         return array(
    1442                                 'success' => false,
    1443                                 'error'   => 'Connection test failed: ' . $e->getMessage(),
    1444                         );
    1445                 }
    1446954        }
    1447955
    … …  
    1460968
    1461969                // Future implementation would handle direct file uploads to:
    1462                 // - OpenAI's file upload API
     970                // - ShareAI document models
    1463971                // - Gemini's document processing
    1464                 // - Claude's document analysis
     972                // - Local Ollama vision models
    1465973
    1466974                throw new Exception( 'Direct file processing not yet implemented. Use text extraction approach.' );
    … …  
    15751083        }
    15761084}
     1085
     1086if ( ! function_exists( 'aiohm_kb_no_provider_notice' ) ) {
     1087        /**
     1088         * Tell administrators when no AI provider is usable, so a site that relied
     1089         * on a removed key (OpenAI, Claude, Groq or a pasted ShareAI key) does not
     1090         * go quiet without a word. Shown on the AIOHM screens, the Dashboard and
     1091         * the Plugins screen, and only while nothing is set up.
     1092         */
     1093        function aiohm_kb_no_provider_notice() {
     1094                if ( ! current_user_can( 'manage_options' ) || ! function_exists( 'get_current_screen' ) ) {
     1095                        return;
     1096                }
     1097                $screen = get_current_screen();
     1098                $id     = $screen ? (string) $screen->id : '';
     1099                if ( false === strpos( $id, 'aiohm' ) && ! in_array( $id, array( 'dashboard', 'plugins' ), true ) ) {
     1100                        return;
     1101                }
     1102                $settings = class_exists( 'AIOHM_KB_Assistant' ) ? AIOHM_KB_Assistant::get_settings() : array();
     1103                foreach ( aiohm_kb_ai_provider_ids() as $provider ) {
     1104                        if ( aiohm_kb_ai_provider_available( $provider, $settings ) ) {
     1105                                return;
     1106                        }
     1107                }
     1108                $settings_url = admin_url( 'admin.php?page=aiohm-settings#aiohm-shareai-connect' );
     1109                echo '<div class="notice notice-warning"><p><strong>' . esc_html__( 'AIOHM Knowledge Assistant has no AI provider yet, so the assistant cannot answer.', 'aiohm-knowledge-assistant' ) . '</strong> ';
     1110                echo esc_html__( 'Connect ShareAI, set up a local Ollama server, or add OpenAI, Anthropic or Google in Settings > Connectors.', 'aiohm-knowledge-assistant' );
     1111                echo ' <a href="' . esc_url( $settings_url ) . '">' . esc_html__( 'Open AIOHM settings', 'aiohm-knowledge-assistant' ) . '</a></p></div>';
     1112        }
     1113        add_action( 'admin_notices', 'aiohm_kb_no_provider_notice' );
     1114}
  • aiohm-knowledge-assistant/trunk/includes/core-init.php

    r3545079 r3833232  
    517517     */
    518518    private static function is_provider_configured($settings, $provider) {
    519         switch ($provider) {
    520             case 'shareai':
    521                 return !empty($settings['shareai_api_key']);
    522             case 'openai':
    523                 return !empty($settings['openai_api_key'])
    524                     || (function_exists('aiohm_kb_is_wp_ai_connector_configured') && aiohm_kb_is_wp_ai_connector_configured('openai'));
    525             case 'gemini':
    526                 return !empty($settings['gemini_api_key'])
    527                     || (function_exists('aiohm_kb_is_wp_ai_connector_configured') && aiohm_kb_is_wp_ai_connector_configured('gemini'));
    528             case 'claude':
    529                 return !empty($settings['claude_api_key'])
    530                     || (function_exists('aiohm_kb_is_wp_ai_connector_configured') && aiohm_kb_is_wp_ai_connector_configured('claude'));
    531             default:
    532                 return false;
    533         }
     519        return aiohm_kb_ai_provider_available((string) $provider, $settings);
    534520    }
    535521
    … …  
    1003989                $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    1004990            }
    1005             $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];
     991            $provider_priority = aiohm_kb_ai_provider_ids();
    1006992           
    1007993            // If no default set, find first available provider
    … …  
    10261012           
    10271013            // Set appropriate model based on provider
    1028             switch ($default_provider) {
    1029                 case 'shareai':
    1030                     $model = $settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    1031                     break;
    1032                 case 'gemini':
    1033                     $model = 'gemini-pro';
    1034                     break;
    1035                 case 'claude':
    1036                     $model = 'claude-3-sonnet-20240229';
    1037                     break;
    1038                 case 'openai':
    1039                     $model = 'gpt-4';
    1040                     break;
    1041                 default:
    1042                     $model = 'gpt-4'; // Final fallback
    1043                     break;
    1044             }
     1014            $model = aiohm_kb_default_model_for_provider($default_provider, $settings);
    10451015           
    10461016            // Enhanced formatting instructions for better readability
    … …  
    11021072
    11031073    public static function handle_frontend_chat_ajax() {
    1104         // Enhanced rate limiting for chat requests - stricter for public endpoints
    1105         $user_id = get_current_user_id() ?: 0;
    1106         $rate_limit = $user_id > 0 ? 50 : 20; // Lower limit for non-authenticated users
    1107        
    1108         if (!AIOHM_KB_Assistant::check_enhanced_rate_limit('frontend_chat', $user_id, $rate_limit)) {
    1109             wp_send_json_error(['reply' => __('Chat rate limit exceeded. Please wait before sending more messages.', 'aiohm-knowledge-assistant')]);
    1110         }
    1111 
    11121074        if (!check_ajax_referer('aiohm_chat_nonce', 'nonce', false)) {
    11131075            wp_send_json_error(['reply' => __('Security check failed.', 'aiohm-knowledge-assistant')]);
    11141076        }
    1115        
    1116         // Additional validation for public endpoints
    11171077        if (!isset($_POST['message']) || !is_string($_POST['message'])) {
    11181078            wp_send_json_error(['reply' => __('Invalid message format.', 'aiohm-knowledge-assistant')]);
    … …  
    11201080
    11211081        try {
    1122             $user_message = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : '';
    1123            
    1124             // Enhanced message validation
    1125             if (empty(trim($user_message))) {
    1126                 wp_send_json_error(['reply' => __('Message cannot be empty.', 'aiohm-knowledge-assistant')]);
    1127             }
    1128            
    1129             if (strlen($user_message) > 2000) {
    1130                 wp_send_json_error(['reply' => __('Message is too long. Please limit to 2000 characters.', 'aiohm-knowledge-assistant')]);
    1131             }
    1132            
    1133             // Check for potentially malicious content
    1134             if (preg_match('/<script|<iframe|javascript:|vbscript:|onload=|onerror=/i', $user_message)) {
    1135                 wp_send_json_error(['reply' => __('Message contains invalid content.', 'aiohm-knowledge-assistant')]);
    1136             }
    1137            
    1138             $settings = AIOHM_KB_Assistant::get_settings();
    1139             $mirror_settings = $settings['mirror_mode'] ?? [];
    1140 
    1141             $ai_client = new AIOHM_KB_AI_GPT_Client();
    1142             $rag_engine = new AIOHM_KB_RAG_Engine();
    1143            
     1082            $answer = self::answer_public_question(sanitize_textarea_field(wp_unslash($_POST['message'])));
     1083            wp_send_json_success(['reply' => $answer['reply'], 'sources' => $answer['sources'], 'assistant_name' => $answer['assistant_name']]);
     1084        } catch (Exception $e) {
     1085            wp_send_json_error(['reply' => $e->getMessage()]);
     1086        }
     1087    }
     1088
     1089    /**
     1090     * Muse's public answer to one visitor question, from this site's public
     1091     * knowledge base. Used by the plugin's own chat and by any site widget
     1092     * that wants Muse (for example a theme's floating assistant).
     1093     *
     1094     * @param string $user_message The visitor's question.
     1095     * @return array{reply: string, sources: array<int, array{title: string, url: string}>, assistant_name: string}
     1096     * @throws Exception With a message that is safe to show the visitor.
     1097     */
     1098    public static function answer_public_question($user_message) {
     1099        $user_message = trim((string) $user_message);
     1100        $user_id = get_current_user_id() ?: 0;
     1101        if (!AIOHM_KB_Assistant::check_enhanced_rate_limit('frontend_chat', $user_id, $user_id > 0 ? 50 : 20)) {
     1102            throw new Exception(esc_html__('Chat rate limit exceeded. Please wait before sending more messages.', 'aiohm-knowledge-assistant'));
     1103        }
     1104        if ($user_message === '') {
     1105            throw new Exception(esc_html__('Message cannot be empty.', 'aiohm-knowledge-assistant'));
     1106        }
     1107        if (strlen($user_message) > 2000) {
     1108            throw new Exception(esc_html__('Message is too long. Please limit to 2000 characters.', 'aiohm-knowledge-assistant'));
     1109        }
     1110        if (preg_match('/<script|<iframe|javascript:|vbscript:|onload=|onerror=/i', $user_message)) {
     1111            throw new Exception(esc_html__('Message contains invalid content.', 'aiohm-knowledge-assistant'));
     1112        }
     1113
     1114        $settings = AIOHM_KB_Assistant::get_settings();
     1115        $mirror_settings = $settings['mirror_mode'] ?? [];
     1116        $assistant_name = trim((string) ($mirror_settings['assistant_name'] ?? '')) ?: 'Muse';
     1117
     1118        $ai_client = new AIOHM_KB_AI_GPT_Client();
     1119        $rag_engine = new AIOHM_KB_RAG_Engine();
     1120
     1121        $context_data = [];
     1122        try {
    11441123            $context_data = $rag_engine->find_relevant_context($user_message, 5);
    1145             $context_string = "";
    1146             $has_context = false;
    1147            
    1148             if (!empty($context_data)) {
    1149                 foreach ($context_data as $data) {
    1150                     $context_string .= "Source: " . $data['entry']['title'] . "\nContent: " . $data['entry']['content'] . "\n\n";
    1151                 }
    1152                 $has_context = true;
    1153             }
    1154            
    1155             // Check if this is a greeting or basic interaction that doesn't need knowledge base context
    1156             $greeting_patterns = ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening', 'greetings', 'how are you', 'what\'s up', 'sup', 'heloo', 'helo', 'hllo'];
    1157             $is_greeting = false;
    1158            
    1159             // Also check for very short messages (likely greetings)
    1160             $is_short_message = strlen(trim($user_message)) <= 10;
    1161            
    1162             foreach ($greeting_patterns as $pattern) {
    1163                 if (stripos($user_message, $pattern) !== false) {
    1164                     $is_greeting = true;
     1124        } catch (Exception $e) {
     1125            $context_data = [];
     1126        }
     1127
     1128        $context_string = '';
     1129        $sources = [];
     1130        foreach ((array) $context_data as $data) {
     1131            $entry = $data['entry'] ?? [];
     1132            $context_string .= 'Source: ' . ($entry['title'] ?? '') . "\nContent: " . ($entry['content'] ?? '') . "\n\n";
     1133            $meta = json_decode((string) ($entry['metadata'] ?? ''), true);
     1134            $post_id = is_array($meta) ? (int) ($meta['post_id'] ?? 0) : 0;
     1135            $url = $post_id > 0 ? get_permalink($post_id) : '';
     1136            if ($url && !isset($sources[$url])) {
     1137                $sources[$url] = ['title' => wp_strip_all_tags((string) ($entry['title'] ?? get_the_title($post_id))), 'url' => $url];
     1138            }
     1139        }
     1140        $has_context = $context_string !== '';
     1141
     1142        $greeting_patterns = ['hello', 'hi', 'hey', 'good morning', 'good afternoon', 'good evening', 'greetings', 'how are you', 'what\'s up', 'sup', 'heloo', 'helo', 'hllo'];
     1143        $is_greeting = strlen($user_message) <= 10;
     1144        foreach ($greeting_patterns as $pattern) {
     1145            if (stripos($user_message, $pattern) !== false) {
     1146                $is_greeting = true;
     1147                break;
     1148            }
     1149        }
     1150        if (!$has_context && !$is_greeting) {
     1151            $context_string = 'No relevant context found in the knowledge base.';
     1152        } elseif (!$has_context) {
     1153            $context_string = 'GREETING DETECTED: respond warmly, introduce yourself by name, and offer to help. No knowledge base context is needed for a greeting.';
     1154        }
     1155
     1156        // Muse's identity comes first, whatever prompt the site owner wrote.
     1157        $identity = "Your name is %assistant_name%. You are the AI guide of %site_name%, built on the AIOHM Knowledge Assistant. "
     1158            . "When you introduce yourself, use your name. Answer from the knowledge base below. Never invent prices, results, testimonials, clients or integrations; "
     1159            . "when the knowledge base does not cover a question, say so plainly and suggest contacting the team.\n\n";
     1160        $system_message = $identity . ($mirror_settings['qa_system_message'] ?? 'You are a helpful assistant.');
     1161        $temperature = floatval($mirror_settings['qa_temperature'] ?? 0.8);
     1162
     1163        $default_provider = $settings['default_ai_provider'] ?? null;
     1164        if (function_exists('aiohm_kb_normalize_wp_ai_provider_id')) {
     1165            $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
     1166        }
     1167        if (!$default_provider || !self::is_provider_configured($settings, $default_provider)) {
     1168            foreach (aiohm_kb_ai_provider_ids() as $provider) {
     1169                if (self::is_provider_configured($settings, $provider)) {
     1170                    $default_provider = $provider;
    11651171                    break;
    11661172                }
    11671173            }
    1168            
    1169             // Consider it a greeting if it's a short message or matches greeting patterns
    1170             $is_greeting = $is_greeting || $is_short_message;
    1171            
    1172             if (!$has_context && !$is_greeting) {
    1173                 $context_string = "No relevant context found in the knowledge base.";
    1174             } elseif (!$has_context && $is_greeting) {
    1175                 $context_string = "GREETING DETECTED: This is a friendly greeting or casual message. You should respond warmly and naturally as the brand representative. Introduce yourself, welcome them, and offer to help. You DO NOT need knowledge base context for basic greetings and social interactions. Be conversational and friendly.";
    1176             }
    1177 
    1178             $system_message = $mirror_settings['qa_system_message'] ?? 'You are a helpful assistant.';
    1179             $temperature = floatval($mirror_settings['qa_temperature'] ?? 0.8);
    1180            
    1181             // Use the user's selected default AI provider with smart fallback
    1182             $default_provider = $settings['default_ai_provider'] ?? null;
    1183             if (function_exists('aiohm_kb_normalize_wp_ai_provider_id')) {
    1184                 $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    1185             }
    1186             $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];
    1187            
    1188             // If no default set, find first available provider
    1189             if (!$default_provider) {
    1190                 foreach ($provider_priority as $provider) {
    1191                     if (self::is_provider_configured($settings, $provider)) {
    1192                         $default_provider = $provider;
    1193                         break;
    1194                     }
    1195                 }
    1196             }
    1197            
    1198             // If default provider not configured, fallback to next available
    1199             if (!self::is_provider_configured($settings, $default_provider)) {
    1200                 foreach ($provider_priority as $provider) {
    1201                     if (self::is_provider_configured($settings, $provider)) {
    1202                         $default_provider = $provider;
    1203                         break;
    1204                     }
    1205                 }
    1206             }
    1207            
    1208             // Set appropriate model based on provider (Mirror Mode)
    1209             switch ($default_provider) {
    1210                 case 'shareai':
    1211                     $model = $settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    1212                     break;
    1213                 case 'gemini':
    1214                     $model = 'gemini-pro';
    1215                     break;
    1216                 case 'claude':
    1217                     $model = 'claude-3-sonnet-20240229';
    1218                     break;
    1219                 case 'openai':
    1220                     $model = 'gpt-3.5-turbo';
    1221                     break;
    1222                 default:
    1223                     $model = 'gpt-3.5-turbo'; // Final fallback
    1224                     break;
    1225             }
    1226            
    1227             // Apply variable replacements to system message
    1228             $replacements = [
    1229                 '{context}'        => $context_string,
    1230                 '%site_name%'      => get_bloginfo('name'),
    1231                 '%site_tagline%'   => get_bloginfo('description'),
    1232                 '%business_name%'  => $mirror_settings['business_name'] ?? get_bloginfo('name'),
    1233                 '%day_of_week%'    => wp_date('l'),
    1234                 '%current_date%'   => wp_date(get_option('date_format')),
    1235                 '%current_time%'   => wp_date(get_option('time_format')),
    1236             ];
    1237             $final_system_message = str_replace(array_keys($replacements), array_values($replacements), $system_message);
    1238 
     1174        }
     1175        $model = aiohm_kb_default_model_for_provider($default_provider, $settings);
     1176
     1177        $replacements = [
     1178            '{context}'         => $context_string,
     1179            '%assistant_name%'  => $assistant_name,
     1180            '%site_name%'       => get_bloginfo('name'),
     1181            '%site_tagline%'    => get_bloginfo('description'),
     1182            '%business_name%'   => $mirror_settings['business_name'] ?? get_bloginfo('name'),
     1183            '%day_of_week%'     => wp_date('l'),
     1184            '%current_date%'    => wp_date(get_option('date_format')),
     1185            '%current_time%'    => wp_date(get_option('time_format')),
     1186        ];
     1187        $final_system_message = str_replace(array_keys($replacements), array_values($replacements), $system_message);
     1188
     1189        try {
    12391190            $answer = $ai_client->get_chat_completion($final_system_message, $user_message, $temperature, $model);
    1240            
    1241             // Apply variable replacements to the AI response as well in case it contains placeholders
    1242             // Use strtr instead of str_replace to avoid partial matches and conflicts
    1243             $final_answer = strtr($answer, $replacements);
    1244 
    1245             wp_send_json_success(['reply' => $final_answer]);
    1246 
    12471191        } catch (Exception $e) {
    1248             wp_send_json_error(['reply' => __('An error occurred while processing your request. Please try again.', 'aiohm-knowledge-assistant')]);
    1249         }
     1192            // Keep provider internals private; ShareAI's own wording and
     1193            // messages written for visitors (the daily limit) are already safe.
     1194            $text = $e->getMessage();
     1195            $visitor_safe = (class_exists('AIOHM_KB_Visitor_Message_Exception') && $e instanceof AIOHM_KB_Visitor_Message_Exception)
     1196                || (stripos($text, 'ShareAI') !== false && strpos($text, 'API Error') === false);
     1197            throw new Exception(esc_html($visitor_safe
     1198                ? $text
     1199                : __('An error occurred while processing your request. Please try again.', 'aiohm-knowledge-assistant')));
     1200        }
     1201
     1202        return [
     1203            'reply' => strtr($answer, $replacements),
     1204            'sources' => array_values(array_slice($sources, 0, 5)),
     1205            'assistant_name' => $assistant_name,
     1206        ];
    12501207    }
    12511208   
    … …  
    14351392                $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    14361393            }
    1437             $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];
     1394            $provider_priority = aiohm_kb_ai_provider_ids();
    14381395           
    14391396            // If no default set, find first available provider
    … …  
    14581415           
    14591416            // Set appropriate model based on provider (Mirror Mode Test)
    1460             switch ($default_provider) {
    1461                 case 'shareai':
    1462                     $model = $current_settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16';
    1463                     break;
    1464                 case 'gemini':
    1465                     $model = 'gemini-pro';
    1466                     break;
    1467                 case 'claude':
    1468                     $model = 'claude-3-sonnet-20240229';
    1469                     break;
    1470                 case 'openai':
    1471                     $model = 'gpt-3.5-turbo';
    1472                     break;
    1473                 default:
    1474                     $model = 'gpt-3.5-turbo'; // Final fallback
    1475                     break;
    1476             }
     1417            $model = aiohm_kb_default_model_for_provider($default_provider, $current_settings);
    14771418           
    14781419            $answer = $ai_client->get_chat_completion($final_system_message, $user_message, $temperature, $model);
    … …  
    15031444            $system_prompt = wp_kses_post($posted_settings['system_prompt'] ?? 'You are a helpful brand assistant.');
    15041445            $temperature = floatval($posted_settings['temperature'] ?? 0.7);
    1505             $model = sanitize_text_field($posted_settings['ai_model'] ?? 'gpt-4');
     1446            $model = sanitize_text_field($posted_settings['ai_model'] ?? '');
    15061447   
    15071448            // Initialize AI client with current settings
    … …  
    15541495                    // Check prerequisites - validate API key for selected provider
    15551496                    $settings = AIOHM_KB_Assistant::get_settings();
    1556                     $default_provider = $settings['default_ai_provider'] ?? 'openai';
    1557                     if (function_exists('aiohm_kb_normalize_wp_ai_provider_id')) {
    1558                         $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    1559                     }
     1497                    $default_provider = aiohm_kb_resolve_ai_provider($settings['default_ai_provider'] ?? '', $settings);
    15601498                   
    15611499                    // Check if the selected default provider has proper configuration
    15621500                    $api_key_exists = false;
    15631501                    $provider_names = [
     1502                        'shareai' => 'ShareAI',
     1503                        'gemini' => 'Gemini',
     1504                        'ollama' => 'Ollama',
    15641505                        'openai' => 'OpenAI',
    1565                         'gemini' => 'Gemini',
    1566                         'claude' => 'Claude',
    1567                         'shareai' => 'ShareAI',
    1568                         'groq' => 'Groq',
    1569                         'ollama' => 'Ollama'
     1506                        'anthropic' => 'Anthropic'
    15701507                    ];
    15711508                   
    1572                     switch ($default_provider) {
    1573                         case 'openai':
    1574                             $api_key_exists = !empty($settings['openai_api_key']);
    1575                             break;
    1576                         case 'gemini':
    1577                             $api_key_exists = !empty($settings['gemini_api_key']);
    1578                             break;
    1579                         case 'claude':
    1580                             $api_key_exists = !empty($settings['claude_api_key']);
    1581                             break;
    1582                         case 'shareai':
    1583                             $api_key_exists = !empty($settings['shareai_api_key']);
    1584                             break;
    1585                         case 'groq':
    1586                             $api_key_exists = !empty($settings['groq_api_key']);
    1587                             break;
    1588                         case 'ollama':
    1589                             $ollama_enabled = $settings['pro_features']['ollama_enabled'] ?? false;
    1590                             $ollama_url = $settings['pro_features']['ollama_server_url'] ?? ($settings['private_llm_server_url'] ?? '');
    1591                             $api_key_exists = $ollama_enabled && !empty($ollama_url);
    1592                             break;
    1593                         default:
    1594                             $api_key_exists = false;
    1595                     }
     1509                    $api_key_exists = aiohm_kb_ai_provider_available($default_provider, $settings);
    15961510                   
    15971511                    if (!$api_key_exists) {
    … …  
    17271641        $api_key = '';
    17281642        switch ($key_type) {
    1729             case 'openai':
    1730                 $api_key = $settings['openai_api_key'] ?? '';
    1731                 if ( empty( $api_key ) && function_exists( 'aiohm_kb_get_wp_connector_api_key' ) ) {
    1732                     $api_key = aiohm_kb_get_wp_connector_api_key( 'openai' );
    1733                 }
     1643            case 'shareai':
     1644                // ShareAI has no key: the test checks the connected account.
     1645                $api_key = aiohm_kb_shareai_available($settings) ? 'connected' : '';
    17341646                break;
    17351647            case 'gemini':
    … …  
    17391651                }
    17401652                break;
    1741             case 'claude':
    1742                 $api_key = $settings['claude_api_key'] ?? '';
    1743                 if ( empty( $api_key ) && function_exists( 'aiohm_kb_get_wp_connector_api_key' ) ) {
    1744                     $api_key = aiohm_kb_get_wp_connector_api_key( 'claude' );
    1745                 }
    1746                 break;
    1747             case 'shareai':
    1748                 $api_key = $settings['shareai_api_key'] ?? '';
    1749                 break;
    1750             case 'groq':
    1751                 $api_key = $settings['groq_api_key'] ?? '';
    1752                 break;
    17531653        }
    17541654       
    … …  
    17581658        try {
    17591659            switch ($key_type) {
    1760                 case 'openai':
     1660                case 'shareai':
    17611661                    $ai_client = new AIOHM_KB_AI_GPT_Client($settings);
    1762                     $result = $ai_client->test_api_connection();
     1662                    $result = $ai_client->test_shareai_api_connection();
    17631663                    if ($result['success']) {
    1764                         wp_send_json_success(['message' => __('OpenAI connection successful!', 'aiohm-knowledge-assistant')]);
     1664                        wp_send_json_success(['message' => __('ShareAI connection successful!', 'aiohm-knowledge-assistant')]);
    17651665                    } else {
    1766                         // translators: %s is the OpenAI API error message
    1767                         wp_send_json_error(['message' => sprintf(__('OpenAI connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
     1666                        // translators: %s is the ShareAI API error message
     1667                        wp_send_json_error(['message' => sprintf(__('ShareAI connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
    17681668                    }
    17691669                    break;
    … …  
    17781678                    }
    17791679                    break;
    1780                 case 'claude':
    1781                     $ai_client = new AIOHM_KB_AI_GPT_Client($settings);
    1782                     $result = $ai_client->test_claude_api_connection();
    1783                     if ($result['success']) {
    1784                         wp_send_json_success(['message' => __('Claude connection successful!', 'aiohm-knowledge-assistant')]);
    1785                     } else {
    1786                         // translators: %s is the Claude API error message
    1787                         wp_send_json_error(['message' => sprintf(__('Claude connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
    1788                     }
    1789                     break;
    1790                 case 'shareai':
    1791                     $ai_client = new AIOHM_KB_AI_GPT_Client($settings);
    1792                     $result = $ai_client->test_shareai_api_connection();
    1793                     if ($result['success']) {
    1794                         wp_send_json_success(['message' => __('ShareAI connection successful!', 'aiohm-knowledge-assistant')]);
    1795                     } else {
    1796                         // translators: %s is the ShareAI API error message
    1797                         wp_send_json_error(['message' => sprintf(__('ShareAI connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
    1798                     }
    1799                     break;
    1800                 case 'groq':
    1801                     $ai_client = new AIOHM_KB_AI_GPT_Client($settings);
    1802                     $result = $ai_client->test_groq_api_connection();
    1803                     if ($result['success']) {
    1804                         wp_send_json_success(['message' => __('Groq connection successful!', 'aiohm-knowledge-assistant')]);
    1805                     } else {
    1806                         // translators: %s is the Groq API error message
    1807                         wp_send_json_error(['message' => sprintf(__('Groq connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);
    1808                     }
    1809                     break;
    18101680                default:
    18111681                    wp_send_json_error(['message' => __('Invalid key type specified.', 'aiohm-knowledge-assistant')]);
    … …  
    18551725           
    18561726            // Enhanced API key validation and encryption
    1857             if (in_array($setting_name, ['openai_api_key', 'gemini_api_key', 'claude_api_key', 'groq_api_key'])) {
     1727            $supported_key_settings = ['gemini_api_key'];
     1728            if (substr($setting_name, -8) === '_api_key' && !in_array($setting_name, $supported_key_settings, true)) {
     1729                // Keys for providers AIOHM no longer supports are not accepted.
     1730                wp_send_json_error(['message' => __('This AI provider is no longer supported.', 'aiohm-knowledge-assistant')]);
     1731            }
     1732
     1733            if ($setting_name === 'gemini_api_key') {
    18581734                // Validate API key format using new validation function
    18591735                $provider = str_replace('_api_key', '', $setting_name);
    … …  
    18661742                // Encrypt the validated API key
    18671743                $current_settings[$setting_name] = AIOHM_KB_Assistant::encrypt_api_key($validated_key);
    1868             } elseif ($setting_name === 'shareai_api_key') {
    1869                 // Validate ShareAI key
    1870                 $validated_key = AIOHM_KB_Assistant::validate_and_sanitize_api_key($api_value, 'shareai');
    1871                
    1872                 if (is_wp_error($validated_key)) {
    1873                     wp_send_json_error(['message' => $validated_key->get_error_message()]);
    1874                 }
    1875                
    1876                 $current_settings[$setting_name] = $validated_key;
    18771744            } else {
    18781745                // For non-API keys (like models), save as plain text with additional validation
    … …  
    19361803                    wp_send_json_success(['message' => __('ShareAI model saved successfully!', 'aiohm-knowledge-assistant')]);
    19371804                } else {
    1938                     // translators: %s is the API provider name (e.g., OpenAI, Claude)
     1805                    // translators: %s is the API provider name (e.g., Gemini, ShareAI)
    19391806                    wp_send_json_success(['message' => sprintf(__('%s API key saved successfully!', 'aiohm-knowledge-assistant'), ucfirst($api_type))]);
    19401807                }
    … …  
    24062273        $settings['mirror_mode']['ai_avatar'] = esc_url_raw($settings_input['ai_avatar'] ?? '');
    24072274        $settings['mirror_mode']['welcome_message'] = wp_kses_post(trim($settings_input['welcome_message'] ?? ''));
    2408         $settings['mirror_mode']['ai_model'] = sanitize_text_field($settings_input['ai_model'] ?? 'gpt-3.5-turbo');
     2275        $settings['mirror_mode']['ai_model'] = sanitize_text_field($settings_input['ai_model'] ?? '');
    24092276       
    24102277        // Handle URL sanitization with proper validation
    … …  
    25012368        }
    25022369       
    2503         $settings['muse_mode']['ai_model'] = sanitize_text_field($muse_input['ai_model'] ?? 'gpt-4');
     2370        $settings['muse_mode']['ai_model'] = sanitize_text_field($muse_input['ai_model'] ?? '');
    25042371        $settings['muse_mode']['temperature'] = floatval($muse_input['temperature'] ?? 0.7);
    25052372        $settings['muse_mode']['start_fullscreen'] = isset($muse_input['start_fullscreen']) ? 1 : 0;
    … …  
    25552422            } else {
    25562423                // Fallback to default provider if no Mirror Mode model is set
    2557                 $default_provider = $settings['default_ai_provider'] ?? 'openai';
    2558                 if (function_exists('aiohm_kb_normalize_wp_ai_provider_id')) {
    2559                     $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider);
    2560                 }
    2561                 switch ($default_provider) {
    2562                     case 'gemini':
    2563                         $model = 'gemini-pro';
    2564                         break;
    2565                     case 'claude':
    2566                         $model = 'claude-3-sonnet';
    2567                         break;
    2568                     case 'shareai':
    2569                         $model = 'shareai-llama4:17b-scout-16e-instruct-fp16';
    2570                         break;
    2571                     case 'openai':
    2572                     default:
    2573                         $model = 'gpt-3.5-turbo';
    2574                         break;
    2575                 }
     2424                $default_provider = aiohm_kb_resolve_ai_provider($settings['default_ai_provider'] ?? '', $settings);
     2425                $model = aiohm_kb_default_model_for_provider($default_provider, $settings);
    25762426            }
    25772427           
    … …  
    40243874            // Format provider data
    40253875            $providers = [
    4026                 'openai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],
     3876                'shareai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],
    40273877                'gemini' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],
    4028                 'claude' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],
    4029                 'shareai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00']
     3878                'ollama' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00']
    40303879            ];
    40313880
    … …  
    43694218                $research_prompt,
    43704219                0.3,
    4371                 $settings['muse_mode']['ai_model'] ?? 'gpt-3.5-turbo'
     4220                $settings['muse_mode']['ai_model'] ?? ''
    43724221            );
    43734222           
    … …  
    55665415            // Test each configured API
    55675416            $apis_to_test = [
    5568                 'openai' => $settings['openai_api_key'] ?? '',
     5417                'shareai' => aiohm_kb_shareai_available($settings) ? 'connected' : '',
    55695418                'gemini' => $settings['gemini_api_key'] ?? '',
    5570                 'claude' => $settings['claude_api_key'] ?? '',
    5571                 'shareai' => $settings['shareai_api_key'] ?? ''
     5419                'ollama' => aiohm_kb_ollama_available($settings) ? ($settings['pro_features']['ollama_server_url'] ?? ($settings['private_llm_server_url'] ?? '')) : ''
    55725420            ];
    55735421           
    … …  
    55895437                   
    55905438                    switch ($provider) {
    5591                         case 'openai':
    5592                             $test_result = $ai_client->test_api_connection();
     5439                        case 'shareai':
     5440                            $test_result = $ai_client->test_shareai_api_connection();
    55935441                            break;
    55945442                        case 'gemini':
    55955443                            $test_result = $ai_client->test_gemini_api_connection();
    55965444                            break;
    5597                         case 'claude':
    5598                             $test_result = $ai_client->test_claude_api_connection();
    5599                             break;
    5600                         case 'shareai':
    5601                             $test_result = $ai_client->test_shareai_api_connection();
     5445                        case 'ollama':
     5446                            $test_result = $ai_client->test_ollama_api_connection();
    56025447                            break;
    56035448                    }
  • aiohm-knowledge-assistant/trunk/includes/parsers/ai-fallback-parser.php

    r3545079 r3833232  
    6464                $settings = AIOHM_KB_Assistant::get_settings();
    6565
    66                 // Check if any AI provider is configured
    67                 $providers = array( 'openai_api_key', 'gemini_api_key', 'claude_api_key' );
    68                 foreach ( $providers as $provider ) {
    69                         if ( ! empty( $settings[ $provider ] ) ) {
     66                // Check if any supported AI provider (ShareAI, Gemini, Ollama) is set up.
     67                foreach ( aiohm_kb_ai_provider_ids() as $provider ) {
     68                        if ( aiohm_kb_ai_provider_available( $provider, $settings ) ) {
    7069                                return true;
    7170                        }
    72                 }
    73 
    74                 if ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) ) {
    75                         if ( aiohm_kb_is_wp_ai_connector_configured( 'openai' ) ||
    76                                  aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) ||
    77                                  aiohm_kb_is_wp_ai_connector_configured( 'claude' ) ) {
    78                                 return true;
    79                         }
    80                 }
    81 
    82                 if ( ! empty( get_option( 'connectors_ai_openai_api_key' ) ) ||
    83                          ! empty( get_option( 'connectors_ai_google_api_key' ) ) ||
    84                          ! empty( get_option( 'connectors_ai_gemini_api_key' ) ) ||
    85                          ! empty( get_option( 'connectors_ai_anthropic_api_key' ) ) ||
    86                          ! empty( get_option( 'connectors_ai_claude_api_key' ) ) ||
    87                          ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY ) ||
    88                          ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY ) ||
    89                          ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY ) ||
    90                          ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY ) ||
    91                          ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY ) ||
    92                          getenv( 'OPENAI_API_KEY' ) ||
    93                          getenv( 'GOOGLE_API_KEY' ) ||
    94                          getenv( 'GEMINI_API_KEY' ) ||
    95                          getenv( 'ANTHROPIC_API_KEY' ) ||
    96                          getenv( 'CLAUDE_API_KEY' ) ) {
    97                         return true;
    9871                }
    9972
    … …  
    469442                        $system_message = 'You are an expert document parser. Extract clean, readable text content from the provided document data. Remove any metadata, formatting artifacts, or technical gibberish. Return only the meaningful text content.';
    470443
    471                         $response = $this->ai_client->get_chat_completion( $system_message, $prompt, 0.3 );
     444                        $settings = AIOHM_KB_Assistant::get_settings();
     445                        $provider = $this->get_active_provider( $settings );
     446                        $model    = '' !== $provider ? aiohm_kb_default_model_for_provider( $provider, $settings ) : '';
     447
     448                        $response = $this->ai_client->get_chat_completion( $system_message, $prompt, 0.3, $model );
    472449
    473450                        if ( empty( $response ) ) {
    … …  
    545522
    546523        /**
     524         * The provider the parser sends requests to: the default provider when
     525         * it is set up, else the first set-up one of ShareAI, Gemini and Ollama.
     526         *
     527         * @param array $settings Plugin settings.
     528         * @return string Provider ID, or an empty string when none is set up.
     529         */
     530        private function get_active_provider( $settings ) {
     531                $provider = aiohm_kb_resolve_ai_provider( $settings['default_ai_provider'] ?? '', $settings );
     532                if ( aiohm_kb_ai_provider_available( $provider, $settings ) ) {
     533                        return $provider;
     534                }
     535                foreach ( aiohm_kb_ai_provider_ids() as $candidate ) {
     536                        if ( aiohm_kb_ai_provider_available( $candidate, $settings ) ) {
     537                                return $candidate;
     538                        }
     539                }
     540                return '';
     541        }
     542
     543        /**
    547544         * Get AI model information
    548545         *
    … …  
    552549                $settings = AIOHM_KB_Assistant::get_settings();
    553550
    554                 $aiohm_has_openai = ! empty( $settings['openai_api_key'] )
    555                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    556                         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    557                         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    558                         || getenv( 'OPENAI_API_KEY' );
    559 
    560                 $aiohm_has_gemini = ! empty( $settings['gemini_api_key'] )
    561                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    562                         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    563                         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    564                         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    565                         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    566                         || getenv( 'GOOGLE_API_KEY' )
    567                         || getenv( 'GEMINI_API_KEY' );
    568 
    569                 $aiohm_has_claude = ! empty( $settings['claude_api_key'] )
    570                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    571                         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    572                         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    573                         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    574                         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    575                         || getenv( 'ANTHROPIC_API_KEY' )
    576                         || getenv( 'CLAUDE_API_KEY' );
    577 
    578                 // Determine which AI provider was used
    579                 if ( $aiohm_has_openai ) {
    580                         return array(
    581                                 'provider' => 'openai',
    582                                 'model'    => $settings['openai_model'] ?? 'gpt-3.5-turbo',
    583                         );
    584                 } elseif ( $aiohm_has_gemini ) {
    585                         return array(
    586                                 'provider' => 'gemini',
    587                                 'model'    => 'gemini-pro',
    588                         );
    589                 } elseif ( $aiohm_has_claude ) {
    590                         return array(
    591                                 'provider' => 'claude',
    592                                 'model'    => 'claude-3',
    593                         );
     551                switch ( $this->get_active_provider( $settings ) ) {
     552                        case 'shareai':
     553                                $model = (string) ( $settings['shareai_model'] ?? '' );
     554                                return array(
     555                                        'provider' => 'shareai',
     556                                        'model'    => '' !== $model ? $model : 'deepseek/deepseek-v4-flash',
     557                                );
     558                        case 'gemini':
     559                                return array(
     560                                        'provider' => 'gemini',
     561                                        'model'    => 'gemini-pro',
     562                                );
     563                        case 'ollama':
     564                                return array(
     565                                        'provider' => 'ollama',
     566                                        'model'    => $settings['pro_features']['ollama_model'] ?? ( $settings['private_llm_model'] ?? 'llama3.2:latest' ),
     567                                );
    594568                }
    595569
  • aiohm-knowledge-assistant/trunk/includes/rag-engine.php

    r3801374 r3833232  
    5151                }
    5252                return $table_name;
     53        }
     54
     55        /**
     56         * An embedding for the text, or null when no provider can embed right now
     57         * (for example ShareAI without an embedding model and no Gemini or Ollama).
     58         * Entries without a vector are still stored and found by full-text search.
     59         *
     60         * @param AIOHM_KB_AI_GPT_Client $ai_client Client to ask.
     61         * @param string                 $text      Text to embed.
     62         * @return array|null
     63         */
     64        private function try_embedding( $ai_client, $text ) {
     65                try {
     66                        $vector = $ai_client->generate_embeddings( $text );
     67                } catch ( Exception $e ) {
     68                        return null;
     69                }
     70                return ( is_array( $vector ) && ! empty( $vector ) ) ? $vector : null;
     71        }
     72
     73        /**
     74         * Cosine similarity, or null when the vectors cannot be compared (missing,
     75         * or built by a different embedding model with another dimension).
     76         *
     77         * @param array      $query_vector Query embedding.
     78         * @param array|null $vector       Stored embedding.
     79         * @return float|null
     80         */
     81        private function cosine_similarity( $query_vector, $vector ) {
     82                if ( ! is_array( $vector ) || count( $vector ) !== count( $query_vector ) ) {
     83                        return null;
     84                }
     85                $dot_product = array_sum( array_map( fn( $a, $b ) => $a * $b, $query_vector, $vector ) );
     86                $mag_a       = sqrt( array_sum( array_map( fn( $a ) => $a * $a, $query_vector ) ) );
     87                $mag_b       = sqrt( array_sum( array_map( fn( $b ) => $b * $b, $vector ) ) );
     88                if ( $mag_a <= 0 || $mag_b <= 0 ) {
     89                        return null;
     90                }
     91                return $dot_product / ( $mag_a * $mag_b );
    5392        }
    5493
    … …  
    104143                $successful_inserts = 0;
    105144                foreach ( $chunks as $chunk_index => $chunk ) {
    106                         $embedding = $ai_client->generate_embeddings( $chunk );
    107 
    108                         if ( ! $embedding || empty( $embedding ) ) {
    109                                 continue; // Skip chunks that fail embedding generation
    110                         }
     145                        // No embedding provider: keep the chunk, full-text search finds it.
     146                        $embedding = $this->try_embedding( $ai_client, $chunk );
    111147
    112148                        $chunk_metadata = array_merge( $metadata, array(
    … …  
    121157                                'title'        => $title,
    122158                                'content'      => $chunk,
    123                                 'vector_data'  => json_encode( $embedding ),
     159                                'vector_data'  => null === $embedding ? null : json_encode( $embedding ),
    124160                                'metadata'     => json_encode( $chunk_metadata ),
    125161                                'is_public'    => $is_public,
    … …  
    197233
    198234                $ai_client = new AIOHM_KB_AI_GPT_Client();
    199                 $embedding = $ai_client->generate_embeddings( $chunk );
    200 
    201                 if ( ! $embedding || empty( $embedding ) ) {
    202                         throw new Exception( 'Failed to generate embeddings.' );
    203                 }
     235                // No embedding provider: keep the chunk, full-text search finds it.
     236                $embedding = $this->try_embedding( $ai_client, $chunk );
    204237
    205238                $metadata = array(
    … …  
    216249                        'title'        => $title,
    217250                        'content'      => $chunk,
    218                         'vector_data'  => json_encode( $embedding ),
     251                        'vector_data'  => null === $embedding ? null : json_encode( $embedding ),
    219252                        'metadata'     => json_encode( $metadata ),
    220253                        'is_public'    => 0,
    … …  
    282315                        $system_message_key = ( $scope === 'private' ) ? 'system_prompt' : 'qa_system_message';
    283316                        $system_message     = $ai_settings[ $system_message_key ] ?? 'You are a helpful assistant.';
    284                         $model_name         = $ai_settings['ai_model'] ?? 'gpt-3.5-turbo';
     317                        $model_name         = $ai_settings['ai_model'] ?? '';
    285318                        $temperature        = $ai_settings['temperature'] ?? 0.7;
    286319
    … …  
    465498                }
    466499
    467                 $ai_client       = new AIOHM_KB_AI_GPT_Client();
    468                 $query_embedding = $ai_client->generate_embeddings( $query_text );
     500                // No embedding provider right now (for example ShareAI without
     501                // embeddings and no Gemini key): rank by full-text relevance below.
     502                $query_embedding = $this->try_embedding( new AIOHM_KB_AI_GPT_Client(), $query_text );
    469503
    470504                $keywords = preg_replace( '/[^a-z0-9\s]/i', '', strtolower( $query_text ) );
    … …  
    472506                $table_name = $this->table_name;
    473507                $safe_table = $this->get_safe_table_name( $wpdb->prefix . 'aiohm_vector_entries' );
     508
     509                // Without an embedding, full-text relevance is the ranking.
     510                if ( null === $query_embedding ) {
     511                        if ( '' === trim( $keywords ) ) {
     512                                return array();
     513                        }
     514                        $keyword_rows = $wpdb->get_results(
     515                                $wpdb->prepare(
     516                                        'SELECT id, title, content, content_type, metadata, vector_data FROM `' . esc_sql( $safe_table ) . '` WHERE user_id = 0 AND is_public = 1 AND MATCH(content) AGAINST(%s IN NATURAL LANGUAGE MODE) LIMIT %d',
     517                                        trim( $keywords ),
     518                                        (int) $limit
     519                                ),
     520                                ARRAY_A
     521                        ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
     522                        $keyword_hits = array();
     523                        foreach ( $this->filter_public_context_entries( (array) $keyword_rows ) as $entry ) {
     524                                $keyword_hits[] = array(
     525                                        'score' => null,
     526                                        'entry' => $entry,
     527                                );
     528                        }
     529                        return $keyword_hits;
     530                }
    474531
    475532                if ( ! empty( trim( $keywords ) ) ) {
    … …  
    571628                }
    572629
     630                if ( null === $query_embedding ) {
     631                        return array();
     632                }
     633
    573634                // Recheck persisted visibility even for cached candidates, so revocation is immediate.
    574635                $pre_filtered_entries = $this->filter_public_context_entries( $pre_filtered_entries );
    575636                $similarities = array();
    576637                foreach ( $pre_filtered_entries as $entry ) {
    577                         $vector = json_decode( $entry['vector_data'], true );
    578                         if ( is_array( $vector ) ) {
    579                                 $dot_product = array_sum( array_map( fn( $a, $b ) => $a * $b, $query_embedding, $vector ) );
    580                                 $mag_a       = sqrt( array_sum( array_map( fn( $a ) => $a * $a, $query_embedding ) ) );
    581                                 $mag_b       = sqrt( array_sum( array_map( fn( $b ) => $b * $b, $vector ) ) );
    582                                 if ( $mag_a > 0 && $mag_b > 0 ) {
    583                                         $similarities[] = array(
    584                                                 'score' => $dot_product / ( $mag_a * $mag_b ),
    585                                                 'entry' => $entry,
    586                                         );
    587                                 }
     638                        $vector = ! empty( $entry['vector_data'] ) ? json_decode( $entry['vector_data'], true ) : null;
     639                        $score  = $this->cosine_similarity( $query_embedding, $vector );
     640                        if ( null !== $score ) {
     641                                $similarities[] = array(
     642                                        'score' => $score,
     643                                        'entry' => $entry,
     644                                );
    588645                        }
    589646                }
    … …  
    11221179        public function find_context_for_user( $query_text, $user_id, $limit = 5 ) {
    11231180                global $wpdb;
    1124                 $ai_client       = new AIOHM_KB_AI_GPT_Client();
    1125                 $query_embedding = $ai_client->generate_embeddings( $query_text );
     1181                $query_embedding = $this->try_embedding( new AIOHM_KB_AI_GPT_Client(), $query_text );
    11261182        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
    11271183                // User context search query requires direct database access for vector similarity operations
    … …  
    11291185                // Validate table name for security
    11301186                $safe_table = $this->get_safe_table_name( $wpdb->prefix . 'aiohm_vector_entries' );
     1187
     1188                // Without an embedding, full-text relevance is the ranking.
     1189                if ( null === $query_embedding ) {
     1190                        $keywords = trim( preg_replace( '/[^\p{L}\p{N}\s]/u', ' ', (string) $query_text ) );
     1191                        if ( '' === $keywords ) {
     1192                                return array();
     1193                        }
     1194                        $keyword_rows = $wpdb->get_results(
     1195                                $wpdb->prepare(
     1196                                        'SELECT id, title, content, content_type, metadata, vector_data FROM `' . esc_sql( $safe_table ) . '` WHERE ( user_id = 0 OR user_id = %d ) AND MATCH(content) AGAINST(%s IN NATURAL LANGUAGE MODE) LIMIT %d',
     1197                                        $user_id,
     1198                                        $keywords,
     1199                                        (int) $limit
     1200                                ),
     1201                                ARRAY_A
     1202                        );
     1203                        $keyword_hits = array();
     1204                        foreach ( (array) $keyword_rows as $entry ) {
     1205                                $keyword_hits[] = array(
     1206                                        'score' => null,
     1207                                        'entry' => $entry,
     1208                                );
     1209                        }
     1210                        return $keyword_hits;
     1211                }
    11311212
    11321213                $all_entries = $wpdb->get_results(
    … …  
    11411222                foreach ( $all_entries as $entry ) {
    11421223                        $vector = ! empty( $entry['vector_data'] ) ? json_decode( $entry['vector_data'], true ) : null;
    1143                         if ( is_array( $vector ) ) {
    1144                                 $dot_product = array_sum( array_map( fn( $a, $b ) => $a * $b, $query_embedding, $vector ) );
    1145                                 $mag_a       = sqrt( array_sum( array_map( fn( $a ) => $a * $a, $query_embedding ) ) );
    1146                                 $mag_b       = sqrt( array_sum( array_map( fn( $b ) => $b * $b, $vector ) ) );
    1147                                 if ( $mag_a > 0 && $mag_b > 0 ) {
    1148                                         $similarities[] = array(
    1149                                                 'score' => $dot_product / ( $mag_a * $mag_b ),
    1150                                                 'entry' => $entry,
    1151                                         );
    1152                                 }
     1224                        $score  = $this->cosine_similarity( $query_embedding, $vector );
     1225                        if ( null !== $score ) {
     1226                                $similarities[] = array(
     1227                                        'score' => $score,
     1228                                        'entry' => $entry,
     1229                                );
    11531230                        }
    11541231                }
  • aiohm-knowledge-assistant/trunk/includes/settings-page.php

    r3801374 r3833232  
    160160
    161161                // Pro Features tab (shows upgrade notice in FREE, full features in PRO)
    162                 add_submenu_page( 'aiohm-knowledge-assistant', 'Pro Features', 'Pro Features', 'manage_options', 'aiohm-pro-features', array( $this, 'render_pro_features_page' ) );
     162                add_submenu_page( 'aiohm-knowledge-assistant', __( 'Advanced', 'aiohm-knowledge-assistant' ), __( 'Advanced', 'aiohm-knowledge-assistant' ), 'manage_options', 'aiohm-pro-features', array( $this, 'render_pro_features_page' ) );
    163163
    164164                // Get Help page
    … …  
    989989                                : sanitize_key( $setting_value );
    990990
    991                         if ( ! in_array( $setting_value, array( 'shareai', 'openai', 'claude', 'gemini', 'groq', 'ollama' ), true ) ) {
     991                        if ( ! in_array( $setting_value, aiohm_kb_ai_provider_ids(), true ) ) {
    992992                                wp_send_json_error( 'Invalid AI provider selected' );
    993993                                return;
    … …  
    10931093
    10941094                // Sanitize API keys and encrypt them for storage
    1095                 $api_keys = array( 'openai_api_key', 'gemini_api_key', 'claude_api_key' );
     1095                $api_keys = array( 'gemini_api_key' );
    10961096                foreach ( $api_keys as $field ) {
    10971097                        if ( isset( $input[ $field ] ) ) {
    … …  
    11101110                }
    11111111
    1112                 // ShareAI API key and model are handled via AJAX, but sanitize if submitted with main form
    1113                 if ( isset( $input['shareai_api_key'] ) ) {
    1114                         $sanitized['shareai_api_key'] = sanitize_text_field( trim( $input['shareai_api_key'] ) );
     1112                // Connect ShareAI choices (saved from the ShareAI card).
     1113                foreach ( array( 'shareai_model', 'shareai_embedding_model', 'shareai_previous_provider' ) as $field ) {
     1114                        if ( isset( $input[ $field ] ) ) {
     1115                                $sanitized[ $field ] = sanitize_text_field( trim( (string) $input[ $field ] ) );
     1116                        }
     1117                }
     1118                if ( isset( $input['shareai_daily_cap'] ) ) {
     1119                        $sanitized['shareai_daily_cap'] = absint( $input['shareai_daily_cap'] );
    11151120                }
    11161121
    … …  
    11281133                                ? aiohm_kb_normalize_wp_ai_provider_id( $input['default_ai_provider'] )
    11291134                                : sanitize_key( $input['default_ai_provider'] );
    1130                         if ( in_array( $provider, array( 'shareai', 'openai', 'claude', 'gemini', 'groq', 'ollama' ), true ) ) {
     1135                        if ( in_array( $provider, aiohm_kb_ai_provider_ids(), true ) ) {
    11311136                                $sanitized['default_ai_provider'] = $provider;
    11321137                        }
    … …  
    12021207                        $temperature = floatval( $muse_settings['temperature'] ?? 0.7 );
    12031208                        $assistant_name = $muse_settings['assistant_name'] ?? 'Muse';
    1204                         $ai_model = $muse_settings['ai_model'] ?? 'gpt-3.5-turbo';
     1209                        $ai_model = $muse_settings['ai_model'] ?? '';
    12051210                       
    12061211                        // Initialize AI client
    … …  
    12081213                       
    12091214                        // Check if any AI provider is configured
    1210                         $providers = array( 'openai', 'gemini', 'claude', 'groq', 'shareai' );
     1215                        $providers = aiohm_kb_ai_provider_ids();
    12111216                        $has_api_key = false;
    12121217                        foreach ( $providers as $provider ) {
  • aiohm-knowledge-assistant/trunk/includes/shortcode-qa.php

    r3545079 r3833232  
    9999
    100100                        // Check if any AI provider is configured
    101                         $has_api_key = ! empty( $settings['openai_api_key'] ) ||
    102                                                         ! empty( $settings['gemini_api_key'] ) ||
    103                                                         ! empty( $settings['claude_api_key'] ) ||
    104                                                         ! empty( $settings['shareai_api_key'] ) ||
    105                                                         ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) &&
    106                                                                 ( aiohm_kb_is_wp_ai_connector_configured( 'openai' ) ||
    107                                                                   aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) ||
    108                                                                   aiohm_kb_is_wp_ai_connector_configured( 'claude' ) ) ) ||
    109                                                         ! empty( get_option( 'connectors_ai_openai_api_key' ) ) ||
    110                                                         ! empty( get_option( 'connectors_ai_google_api_key' ) ) ||
    111                                                         ! empty( get_option( 'connectors_ai_gemini_api_key' ) ) ||
    112                                                         ! empty( get_option( 'connectors_ai_anthropic_api_key' ) ) ||
    113                                                         ! empty( get_option( 'connectors_ai_claude_api_key' ) ) ||
    114                                                         ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY ) ||
    115                                                         ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY ) ||
    116                                                         ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY ) ||
    117                                                         ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY ) ||
    118                                                         ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY ) ||
    119                                                         getenv( 'OPENAI_API_KEY' ) ||
    120                                                         getenv( 'GOOGLE_API_KEY' ) ||
    121                                                         getenv( 'GEMINI_API_KEY' ) ||
    122                                                         getenv( 'ANTHROPIC_API_KEY' ) ||
    123                                                         getenv( 'CLAUDE_API_KEY' );
     101                        $has_api_key = false;
     102                        foreach ( aiohm_kb_ai_provider_ids() as $aiohm_provider ) {
     103                                if ( aiohm_kb_ai_provider_available( $aiohm_provider, $settings ) ) {
     104                                        $has_api_key = true;
     105                                        break;
     106                                }
     107                        }
    124108
    125109                        if ( ! $has_api_key ) {
    … …  
    138122                        } else {
    139123                                // Fallback to default provider if no Mirror Mode model is set
    140                                 $default_provider = $settings['default_ai_provider'] ?? 'openai';
    141                                 switch ( $default_provider ) {
    142                                         case 'gemini':
    143                                                 $model = 'gemini-pro';
    144                                                 break;
    145                                         case 'claude':
    146                                                 $model = 'claude-3-sonnet';
    147                                                 break;
    148                                         case 'shareai':
    149                                                 $model = 'shareai-llama4:17b-scout-16e-instruct-fp16';
    150                                                 break;
    151                                         case 'openai':
    152                                         default:
    153                                                 $model = 'gpt-3.5-turbo';
    154                                                 break;
    155                                 }
     124                                $default_provider = aiohm_kb_resolve_ai_provider( $settings['default_ai_provider'] ?? '', $settings );
     125                                $model            = aiohm_kb_default_model_for_provider( $default_provider, $settings );
    156126                        }
    157127
  • aiohm-knowledge-assistant/trunk/includes/uninstall-cleanup.php

    r3801374 r3833232  
    1313function aiohm_kb_uninstall_cleanup()
    1414{
     15    // ShareAI tokens never outlive the plugin, whatever the data setting.
     16    aiohm_kb_uninstall_shareai();
     17
    1518    // Check if user wants to delete data on uninstall
    1619    $settings = get_option("aiohm_kb_settings", []);
    … …  
    9396    wp_cache_flush();
    9497}
     98
     99/**
     100 * Revoke the ShareAI grant and delete its tokens. The plugin's classes are
     101 * not loaded during uninstall, so the token is decrypted here with the same
     102 * key the plugin used to encrypt it.
     103 */
     104function aiohm_kb_uninstall_shareai()
     105{
     106    $data = get_option("aiohm_kb_shareai_connection", []);
     107    if (is_array($data) && function_exists("openssl_decrypt")) {
     108        $key = wp_hash(SECURE_AUTH_KEY . LOGGED_IN_KEY);
     109        foreach (["refresh_token", "access_token"] as $type) {
     110            $raw = base64_decode((string) ($data[$type] ?? ""), true);
     111            if ($raw === false || strlen($raw) < 17) {
     112                continue;
     113            }
     114            $token = openssl_decrypt(substr($raw, 16), "AES-256-CBC", $key, 0, substr($raw, 0, 16));
     115            if (is_string($token) && $token !== "") {
     116                wp_remote_post("https://auth.shareai.now/oauth/revoke", [
     117                    "timeout" => 10,
     118                    "body" => [
     119                        "token" => $token,
     120                        "token_type_hint" => $type,
     121                        "client_id" => defined("AIOHM_KB_SHAREAI_CLIENT_ID") ? AIOHM_KB_SHAREAI_CLIENT_ID : "90bd7595f6bb64f73a28dc18e96b7a6d",
     122                    ],
     123                ]);
     124            }
     125        }
     126    }
     127    delete_option("aiohm_kb_shareai_connection");
     128    delete_option("aiohm_kb_shareai_refresh_lock");
     129    delete_option("aiohm_kb_shareai_daily_usage");
     130}
  • aiohm-knowledge-assistant/trunk/readme.txt

    r3801412 r3833232  
    1 === AIOHM Knowledge Assistant PRO ===
     1=== AIOHM Knowledge Assistant ===
    22Contributors: ohmevents
    33Tags: ai assistant, knowledge base, chatbot, brand voice, personalized ai
    44Requires at least: 6.2
    55Tested up to: 7.1
    6 Stable tag: 3.0.0
     6Stable tag: 3.1.0
    77Requires PHP: 7.4
    88License: GPLv2 or later
    … …  
    2121* **Public Chatbot**: Add an intelligent chatbot to your website that answers visitor questions based on your content
    2222* **Knowledge Base Management**: Scan and index your WordPress posts, pages, and uploaded documents
    23 * **Multi-Provider AI Support**: Choose from OpenAI, Google Gemini, Anthropic Claude, Groq, and ShareAI
     23* **Multi-Provider AI Support**: Choose from ShareAI, Google Gemini or a local Ollama server
    2424* **Brand Voice Configuration**: Set up your chatbot's personality and communication style
    2525* **Content Processing**: Support for PDF, CSV, TXT, and JSON document formats
    … …  
    3434* Automatic indexing of WordPress posts, pages, and uploaded files
    3535* Support for PDF, CSV, TXT, and JSON document formats
    36 * Advanced semantic search with vector embeddings
     36* Full-text search on every setup, plus semantic search when Gemini or Ollama provides embeddings
    3737* Smart content chunking for optimal AI processing
    3838
    3939**Multi-Provider AI Integration**
    40 * OpenAI GPT models (GPT-5)
    41 * Google Gemini Pro with advanced embeddings
    42 * Anthropic Claude for sophisticated reasoning
    43 * Groq for ultra-fast inference with Llama and Mistral models
    44 * ShareAI for specialized model access
     40* ShareAI, connected with your ShareAI account (Connect ShareAI)
     41* Google Gemini with embeddings
     42* OpenAI and Anthropic Claude for chat, when your site connects them in Settings > Connectors (WordPress 7)
    4543* **Ollama Local AI for completely private, on-premise processing**
    4644* ServBay Ollama server integration for development environments
    … …  
    9290* WordPress 6.2 or higher
    9391* PHP 7.4 or higher
    94 * API key from at least one supported provider (OpenAI, Claude, Gemini, Groq, or ShareAI)
     92* A ShareAI connection (Connect ShareAI), a Gemini API key, or a local Ollama server
    9593* Optional: Paid Memberships Pro for advanced access control
    9694
    9795## Privacy & External Services
    9896
    99 This plugin connects to external AI services only when configured with user-provided API keys. All communications use secure HTTPS connections, and no conversation data is stored on external servers beyond temporary processing requirements.
     97This plugin connects to external AI services only after you connect ShareAI, add a Gemini API key, or point it at your own Ollama server. All communications use secure HTTPS connections, and no conversation data is stored on external servers beyond temporary processing requirements.
    10098
    10199**Supported AI Services:**
    102100* ShareAI API (shareai.now) - [Terms](https://shareai.now/terms) | [Docs](https://shareai.now/documentation/)
    103 * OpenAI API (api.openai.com) - [Terms](https://openai.com/terms/) | [Privacy](https://openai.com/privacy/)
    104101* Google Gemini API (generativelanguage.googleapis.com) - [Terms](https://ai.google.dev/terms) | [Privacy](https://policies.google.com/privacy)
    105 * Anthropic Claude API (api.anthropic.com) - [Terms](https://www.anthropic.com/terms) | [Privacy](https://www.anthropic.com/privacy)
    106 * Groq API (api.groq.com) - [Terms](https://groq.com/terms-of-service/) | [Privacy](https://groq.com/privacy-policy/)
     102* OpenAI (api.openai.com) and Anthropic (api.anthropic.com), only when you connect them in WordPress Settings > Connectors. WordPress keeps those keys and sends the requests through its own AI Client. - OpenAI [Terms](https://openai.com/policies/terms-of-use/) | [Privacy](https://openai.com/policies/privacy-policy/) - Anthropic [Terms](https://www.anthropic.com/legal/commercial-terms) | [Privacy](https://www.anthropic.com/legal/privacy)
     103* Ollama (optional): requests go only to the Ollama server URL you enter, for example http://localhost:11434 on your own machine.
    107104
    108105User consent is required before making any external API calls. All API keys are encrypted and stored securely in your WordPress database.
     106
     107**Connect ShareAI (optional):**
     108ShareAI is connected with "Connect ShareAI" on the settings page. When you do:
     109
     110* Your browser goes to ShareAI (auth.shareai.now and console.shareai.now) to sign in and approve the AIOHM Knowledge Assistant plan.
     111* ShareAI returns you to AIOHM's relay page on www.ohm.events (OHM Events Agency). The relay receives only ShareAI's one-time code and your site's admin address, shows you which site you are connecting, and sends you back there. It stores nothing and never receives a token.
     112* Your site exchanges the code for tokens itself. The tokens are encrypted and stored in your WordPress database, and are revoked and removed when you click Disconnect or delete the plugin.
     113* Chat requests go to api.shareai.now and are paid from your ShareAI wallet at the model price plus a 10% builder markup that goes to AIOHM, the maker of this plugin. ShareAI shows this markup before you approve.
     114* ShareAI: [Terms](https://shareai.now/terms) | [Privacy](https://shareai.now/privacy). AIOHM (OHM Events Agency): [Terms](https://www.ohm.events/terms-and-conditions/) | [Privacy](https://www.ohm.events/privacy-policy/).
    109115
    110116== Installation ==
    … …  
    1121181. Upload the plugin files to `/wp-content/plugins/aiohm-knowledge-assistant/`
    1131192. Activate the plugin through the WordPress Plugins menu
    114 3. Navigate to AIOHM > Settings and configure your AI provider API key
     1203. Navigate to AIOHM > Settings and click Connect ShareAI, or add a Gemini API key, or point AIOHM at your Ollama server
    1151214. Run the content scan to build your knowledge base
    1161225. Configure your brand voice settings
    … …  
    121127= What AI providers are supported? =
    122128
    123 AIOHM supports OpenAI (GPT-3.5, GPT-4), Google Gemini Pro, Anthropic Claude, Groq (ultra-fast inference), and ShareAI. You need only one API key to get started.
     129AIOHM supports ShareAI and a local Ollama server, and also Google Gemini, OpenAI and Anthropic Claude when your site connects them in WordPress 7 Settings > Connectors. You need only one to get started: connect your ShareAI account, point AIOHM at your Ollama server, or add a provider in Connectors. OpenAI and Claude run chat; search then uses keywords.
     130
     131= Does AIOHM earn anything when I use ShareAI? =
     132
     133Yes, when your assistant runs on ShareAI. ShareAI adds a 10% builder markup to your AI usage and pays it to AIOHM. That is how this free plugin is funded. ShareAI shows the markup before you approve. Google Gemini and a local Ollama server carry no markup.
    124134
    125135= How does this differ from other AI chatbot plugins? =
    … …  
    169179
    170180== Changelog ==
     181
     182= 3.1.0 =
     183* ADDED: Connect ShareAI. Sign in to ShareAI once, with no API key to copy. Chat runs on your ShareAI wallet, with a 10% builder markup for AIOHM shown by ShareAI before you approve.
     184* ADDED: OpenAI and Anthropic Claude through WordPress 7 Connectors. They appear as AI providers only after your site connects them, and WordPress keeps their keys.
     185* CHANGED: The AI provider list always shows ShareAI and Ollama. Gemini, OpenAI and Claude appear once your site connects them.
     186* CHANGED: ShareAI now runs only through Connect ShareAI. The ShareAI API key field is gone, and a key saved by an earlier version is deleted. Sites that used a key click Connect ShareAI once.
     187* ADDED: Daily question limit for visitors, so a busy chat cannot drain your ShareAI wallet.
     188* ADDED: ShareAI chat and embedding models are read from your account instead of a fixed list.
     189* FIXED: The knowledge base no longer fails to index when no embedding provider is available. Entries are stored and found by full-text search, so a ShareAI-only site works.
     190* CHANGED: AIOHM no longer stores OpenAI, Anthropic or Groq API keys. OpenAI and Claude work through WordPress Connectors instead; Groq is removed. A site that relied on a removed key switches to the first provider that is set up.
     191* ADDED: An admin notice on the AIOHM screens, the Dashboard and the Plugins screen while no AI provider is set up, with a link to the settings.
     192* ADDED: Default ShareAI embedding model (text-embedding-3-small). While ShareAI does not offer embeddings for an account, AIOHM pauses those calls and search uses keywords.
     193* CHANGED: ShareAI buttons follow ShareAI's application guidance, with the official ShareAI icon.
     194* CHANGED: The plugin is listed as AIOHM Knowledge Assistant, and its "Pro Features" page is now called "Advanced".
     195* FIXED: Visitors now see the daily question limit message instead of a general error.
     196* FIXED: Plugin Check errors for unescaped exception messages.
    171197
    172198= 3.0.0 =
    … …  
    308334== Upgrade Notice ==
    309335
     336= 3.1.0 =
     337ShareAI now connects with your ShareAI account (Connect ShareAI) instead of an API key. OpenAI and Claude work through WordPress 7 Connectors. If your site used an OpenAI, Claude, Groq or ShareAI key, set up a provider after updating.
     338
    310339= 1.4.1 =
    311340CRITICAL FIX: Resolves knowledge base content not appearing after scanning. Essential update for users experiencing empty manage knowledge base tables after content scanning operations.
    … …  
    322351== Screenshots ==
    323352
    324 1. **Dashboard Overview** - Complete control center for AI assistant setup and management
    325 2. **Mirror Mode Configuration** - Set up your public chatbot with brand voice and personality
    326 3. **Muse Mode Settings** - Configure your private AI assistant for creative workflows
    327 4. **Knowledge Base Manager** - View, organize, and manage all indexed content
    328 5. **Brand Soul Questionnaire** - Define your unique voice and communication style
    329 6. **Public Chat Interface** - Clean, responsive chatbot for website visitors
    330 7. **Private Assistant Interface** - Full-featured AI assistant for authenticated users
    331 8. **Content Scanning** - Automatic indexing of posts, pages, and uploaded documents
     3531. **Answers from your content** - The live preview answers a visitor question from the site's own pages
     3542. **Connect ShareAI** - Connect your ShareAI account once, with the 10% builder markup shown up front
     3553. **Scan your site** - Posts, pages, products and media files ready to index
     3564. **Knowledge base manager** - Choose what is public and what stays private
     3575. **Four-step setup** - From choosing an AI provider to adding the chat to your site
  • aiohm-knowledge-assistant/trunk/templates/admin-dashboard.php

    r3801374 r3833232  
    4747                                                <div class="benefit">
    4848                                                        <h3><?php esc_html_e( '1. Configure AI Provider', 'aiohm-knowledge-assistant' ); ?></h3>
    49                                                         <p><?php esc_html_e( 'Add your OpenAI, Claude, Gemini, or ShareAI API key to get started.', 'aiohm-knowledge-assistant' ); ?></p>
     49                                                        <p><?php esc_html_e( 'Connect ShareAI, add a Gemini API key, or point AIOHM at a local Ollama server to get started.', 'aiohm-knowledge-assistant' ); ?></p>
    5050                                                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=aiohm-settings' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Configure AI', 'aiohm-knowledge-assistant' ); ?></a>
    5151                                                </div>
    … …  
    7777                                                <div class="benefit">
    7878                                                        <h3><?php esc_html_e( 'Multi-Provider AI Support', 'aiohm-knowledge-assistant' ); ?></h3>
    79                                                         <p><?php esc_html_e( 'OpenAI GPT, Claude, Gemini, and ShareAI integration. Use your own API keys.', 'aiohm-knowledge-assistant' ); ?></p>
     79                                                        <p><?php esc_html_e( 'ShareAI, Google Gemini and local Ollama. Use your own account or API key.', 'aiohm-knowledge-assistant' ); ?></p>
    8080                                                </div>
    8181                                                <div class="benefit">
    … …  
    110110                                                <div class="benefit">
    111111                                                        <h3><?php esc_html_e( 'Step 1: AI Configuration', 'aiohm-knowledge-assistant' ); ?></h3>
    112                                                         <p><?php esc_html_e( 'Go to Settings and add your AI provider API key (OpenAI, Claude, Gemini, or ShareAI).', 'aiohm-knowledge-assistant' ); ?></p>
     112                                                        <p><?php esc_html_e( 'Go to Settings and set up an AI provider: ShareAI, Gemini or Ollama.', 'aiohm-knowledge-assistant' ); ?></p>
    113113                                                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=aiohm-settings' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Configure AI', 'aiohm-knowledge-assistant' ); ?></a>
    114114                                                </div>
  • aiohm-knowledge-assistant/trunk/templates/admin-mirror-mode.php

    r3545079 r3833232  
    107107                                                </div>
    108108                                                <?php
    109                                                 $aiohm_has_openai = ! empty( $aiohm_global_settings['openai_api_key'] )
    110                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    111                                                         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    112                                                         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    113                                                         || getenv( 'OPENAI_API_KEY' );
    114 
    115                                                 $aiohm_has_gemini = ! empty( $aiohm_global_settings['gemini_api_key'] )
    116                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    117                                                         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    118                                                         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    119                                                         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    120                                                         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    121                                                         || getenv( 'GOOGLE_API_KEY' )
    122                                                         || getenv( 'GEMINI_API_KEY' );
    123 
    124                                                 $aiohm_has_claude = ! empty( $aiohm_global_settings['claude_api_key'] )
    125                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    126                                                         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    127                                                         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    128                                                         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    129                                                         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    130                                                         || getenv( 'ANTHROPIC_API_KEY' )
    131                                                         || getenv( 'CLAUDE_API_KEY' );
    132 
    133                                                 $aiohm_has_groq = ! empty( $aiohm_global_settings['groq_api_key'] );
    134                                                 $aiohm_has_shareai = ! empty( $aiohm_global_settings['shareai_api_key'] );
     109                                                $aiohm_has_shareai         = aiohm_kb_shareai_available( $aiohm_global_settings );
     110                                                $aiohm_has_gemini          = aiohm_kb_gemini_available( $aiohm_global_settings );
     111                                                $aiohm_has_ollama          = aiohm_kb_ollama_available( $aiohm_global_settings );
     112                                                $aiohm_shareai_model_value = aiohm_kb_default_model_for_provider( 'shareai', $aiohm_global_settings );
     113                                                $aiohm_ollama_model_name   = $aiohm_global_settings['pro_features']['ollama_model'] ?? ( $aiohm_global_settings['private_llm_model'] ?? 'llama3.2:latest' );
     114                                                $aiohm_selected_model      = (string) ( $aiohm_settings['ai_model'] ?? '' );
     115                                                if ( '' === $aiohm_selected_model ) {
     116                                                        $aiohm_selected_model = aiohm_kb_default_model_for_provider(
     117                                                                aiohm_kb_resolve_ai_provider( $aiohm_global_settings['default_ai_provider'] ?? '', $aiohm_global_settings ),
     118                                                                $aiohm_global_settings
     119                                                        );
     120                                                }
    135121                                                ?>
    136122                                                <select id="ai_model_selector" name="aiohm_kb_settings[mirror_mode][ai_model]">
    137                                                         <?php if ($aiohm_has_openai): ?>
    138                                                                 <option value="gpt-3.5-turbo" <?php selected(
    139             $aiohm_settings["ai_model"] ?? "gpt-3.5-turbo",
    140             "gpt-3.5-turbo",
    141         ); ?>>OpenAI: GPT-3.5 Turbo (Fast & Reliable)</option>
    142                                                                 <option value="gpt-4" <?php selected(
    143             $aiohm_settings["ai_model"] ?? "",
    144             "gpt-4",
    145         ); ?>>OpenAI: GPT-4 (Advanced)</option>
     123                                                        <?php if ( $aiohm_has_shareai ) : ?>
     124                                                                <option value="<?php echo esc_attr( $aiohm_shareai_model_value ); ?>" <?php selected( $aiohm_selected_model, $aiohm_shareai_model_value ); ?>>
     125                                                                        <?php
     126                                                                        /* translators: %s: ShareAI model ID */
     127                                                                        echo esc_html( sprintf( __( 'ShareAI: %s', 'aiohm-knowledge-assistant' ), substr( $aiohm_shareai_model_value, strlen( 'shareai-' ) ) ) );
     128                                                                        ?>
     129                                                                </option>
    146130                                                        <?php endif; ?>
    147                                                         <?php if ($aiohm_has_gemini): ?>
    148                                                                 <option value="gemini-pro" <?php selected(
    149             $aiohm_settings["ai_model"] ?? "",
    150             "gemini-pro",
    151         ); ?>>Google: Gemini Pro</option>
     131                                                        <?php if ( $aiohm_has_gemini ) : ?>
     132                                                                <option value="gemini-pro" <?php selected( $aiohm_selected_model, 'gemini-pro' ); ?>><?php esc_html_e( 'Google: Gemini Pro', 'aiohm-knowledge-assistant' ); ?></option>
    152133                                                        <?php endif; ?>
    153                                                         <?php if ($aiohm_has_claude): ?>
    154                                                                 <option value="claude-3-sonnet" <?php selected(
    155             $aiohm_settings["ai_model"] ?? "",
    156             "claude-3-sonnet",
    157         ); ?>>Anthropic: Claude 3 Sonnet</option>
     134                                                        <?php if ( $aiohm_has_ollama ) : ?>
     135                                                                <option value="ollama" <?php selected( $aiohm_selected_model, 'ollama' ); ?>>
     136                                                                        <?php
     137                                                                        /* translators: %s: Ollama model name */
     138                                                                        echo esc_html( sprintf( __( 'Ollama: %s', 'aiohm-knowledge-assistant' ), $aiohm_ollama_model_name ) );
     139                                                                        ?>
     140                                                                </option>
    158141                                                        <?php endif; ?>
    159                                                         <?php if ($aiohm_has_groq): ?>
    160                                                                 <option value="groq-llama-3.3-70b-versatile" <?php selected(
    161             $aiohm_settings["ai_model"] ?? "",
    162             "groq-llama-3.3-70b-versatile",
    163         ); ?>>Groq: Llama 3.3 70B (Ultra-Fast)</option>
     142                                                        <?php if ( aiohm_kb_wp_connector_provider_available( 'openai' ) ) : ?>
     143                                                                <option value="wp-openai" <?php selected( $aiohm_selected_model, 'wp-openai' ); ?>><?php esc_html_e( 'OpenAI (WordPress Connectors)', 'aiohm-knowledge-assistant' ); ?></option>
    164144                                                        <?php endif; ?>
    165                                                         <?php if ($aiohm_has_shareai): ?>
    166                                                                 <option value="shareai-llama4:17b-scout-16e-instruct-fp16" <?php selected(
    167             $aiohm_settings["ai_model"] ?? "",
    168             "shareai-llama4:17b-scout-16e-instruct-fp16",
    169         ); ?>>ShareAI</option>
     145                                                        <?php if ( aiohm_kb_wp_connector_provider_available( 'anthropic' ) ) : ?>
     146                                                                <option value="wp-anthropic" <?php selected( $aiohm_selected_model, 'wp-anthropic' ); ?>><?php esc_html_e( 'Anthropic Claude (WordPress Connectors)', 'aiohm-knowledge-assistant' ); ?></option>
    170147                                                        <?php endif; ?>
    171148                                                </select>
  • aiohm-knowledge-assistant/trunk/templates/admin-muse-mode.php

    r3545079 r3833232  
    175175                                                </div>
    176176                                                <?php
    177                                                 $aiohm_has_openai = ! empty( $aiohm_global_settings['openai_api_key'] )
    178                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    179                                                         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    180                                                         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    181                                                         || getenv( 'OPENAI_API_KEY' );
    182 
    183                                                 $aiohm_has_gemini = ! empty( $aiohm_global_settings['gemini_api_key'] )
    184                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    185                                                         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    186                                                         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    187                                                         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    188                                                         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    189                                                         || getenv( 'GOOGLE_API_KEY' )
    190                                                         || getenv( 'GEMINI_API_KEY' );
    191 
    192                                                 $aiohm_has_claude = ! empty( $aiohm_global_settings['claude_api_key'] )
    193                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    194                                                         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    195                                                         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    196                                                         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    197                                                         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    198                                                         || getenv( 'ANTHROPIC_API_KEY' )
    199                                                         || getenv( 'CLAUDE_API_KEY' );
    200 
    201                                                 $aiohm_has_groq = ! empty( $aiohm_global_settings['groq_api_key'] );
    202                                                 $aiohm_has_shareai = ! empty( $aiohm_global_settings['shareai_api_key'] );
     177                                                $aiohm_has_shareai         = aiohm_kb_shareai_available( $aiohm_global_settings );
     178                                                $aiohm_has_gemini          = aiohm_kb_gemini_available( $aiohm_global_settings );
     179                                                $aiohm_has_ollama          = aiohm_kb_ollama_available( $aiohm_global_settings );
     180                                                $aiohm_shareai_model_value = aiohm_kb_default_model_for_provider( 'shareai', $aiohm_global_settings );
     181                                                $aiohm_ollama_model_name   = $aiohm_global_settings['pro_features']['ollama_model'] ?? ( $aiohm_global_settings['private_llm_model'] ?? 'llama3.2:latest' );
     182                                                $aiohm_selected_model      = (string) ( $aiohm_settings['ai_model'] ?? '' );
     183                                                if ( '' === $aiohm_selected_model ) {
     184                                                        $aiohm_selected_model = aiohm_kb_default_model_for_provider(
     185                                                                aiohm_kb_resolve_ai_provider( $aiohm_global_settings['default_ai_provider'] ?? '', $aiohm_global_settings ),
     186                                                                $aiohm_global_settings
     187                                                        );
     188                                                }
    203189                                                ?>
    204190                                                <select id="ai_model_selector" name="aiohm_kb_settings[muse_mode][ai_model]">
    205                                                         <?php if ($aiohm_has_openai): ?>
    206                                                                 <option value="gpt-3.5-turbo" <?php selected(
    207             $aiohm_settings["ai_model"] ?? "gpt-3.5-turbo",
    208             "gpt-3.5-turbo",
    209         ); ?>>OpenAI: GPT-3.5 Turbo</option>
    210                                                                 <option value="gpt-4" <?php selected(
    211             $aiohm_settings["ai_model"] ?? "",
    212             "gpt-4",
    213         ); ?>>OpenAI: GPT-4</option>
     191                                                        <?php if ( $aiohm_has_shareai ) : ?>
     192                                                                <option value="<?php echo esc_attr( $aiohm_shareai_model_value ); ?>" <?php selected( $aiohm_selected_model, $aiohm_shareai_model_value ); ?>>
     193                                                                        <?php
     194                                                                        /* translators: %s: ShareAI model ID */
     195                                                                        echo esc_html( sprintf( __( 'ShareAI: %s', 'aiohm-knowledge-assistant' ), substr( $aiohm_shareai_model_value, strlen( 'shareai-' ) ) ) );
     196                                                                        ?>
     197                                                                </option>
    214198                                                        <?php endif; ?>
    215                                                         <?php if ($aiohm_has_gemini): ?>
    216                                                                 <option value="gemini-pro" <?php selected(
    217             $aiohm_settings["ai_model"] ?? "",
    218             "gemini-pro",
    219         ); ?>>Google: Gemini Pro</option>
     199                                                        <?php if ( $aiohm_has_gemini ) : ?>
     200                                                                <option value="gemini-pro" <?php selected( $aiohm_selected_model, 'gemini-pro' ); ?>><?php esc_html_e( 'Google: Gemini Pro', 'aiohm-knowledge-assistant' ); ?></option>
    220201                                                        <?php endif; ?>
    221                                                         <?php if ($aiohm_has_claude): ?>
    222                                                                 <option value="claude-3-sonnet" <?php selected(
    223             $aiohm_settings["ai_model"] ?? "",
    224             "claude-3-sonnet",
    225         ); ?>>Anthropic: Claude 3 Sonnet</option>
     202                                                        <?php if ( $aiohm_has_ollama ) : ?>
     203                                                                <option value="ollama" <?php selected( $aiohm_selected_model, 'ollama' ); ?>>
     204                                                                        <?php
     205                                                                        /* translators: %s: Ollama model name */
     206                                                                        echo esc_html( sprintf( __( 'Ollama: %s', 'aiohm-knowledge-assistant' ), $aiohm_ollama_model_name ) );
     207                                                                        ?>
     208                                                                </option>
    226209                                                        <?php endif; ?>
    227                                                         <?php if ($aiohm_has_groq): ?>
    228                                                                 <option value="groq-llama-3.3-70b-versatile" <?php selected(
    229             $aiohm_settings["ai_model"] ?? "",
    230             "groq-llama-3.3-70b-versatile",
    231         ); ?>>Groq: Llama 3.3 70B (Ultra-Fast)</option>
     210                                                        <?php if ( aiohm_kb_wp_connector_provider_available( 'openai' ) ) : ?>
     211                                                                <option value="wp-openai" <?php selected( $aiohm_selected_model, 'wp-openai' ); ?>><?php esc_html_e( 'OpenAI (WordPress Connectors)', 'aiohm-knowledge-assistant' ); ?></option>
    232212                                                        <?php endif; ?>
    233                                                         <?php if ($aiohm_has_shareai): ?>
    234                                                                 <option value="shareai-llama4:17b-scout-16e-instruct-fp16" <?php selected(
    235             $aiohm_settings["ai_model"] ?? "",
    236             "shareai-llama4:17b-scout-16e-instruct-fp16",
    237         ); ?>>ShareAI</option>
     213                                                        <?php if ( aiohm_kb_wp_connector_provider_available( 'anthropic' ) ) : ?>
     214                                                                <option value="wp-anthropic" <?php selected( $aiohm_selected_model, 'wp-anthropic' ); ?>><?php esc_html_e( 'Anthropic Claude (WordPress Connectors)', 'aiohm-knowledge-assistant' ); ?></option>
    238215                                                        <?php endif; ?>
    239216                                                </select>
  • aiohm-knowledge-assistant/trunk/templates/admin-pro-features.php

    r3801374 r3833232  
    4040
    4141<div class="wrap aiohm-settings-page">
    42         <h1><?php esc_html_e( 'Pro Features - Private Knowledge Hub', 'aiohm-knowledge-assistant' ); ?></h1>
     42        <h1><?php esc_html_e( 'Advanced: Private Knowledge Hub', 'aiohm-knowledge-assistant' ); ?></h1>
    4343        <p class="page-description"><?php esc_html_e( 'Advanced settings for local AI processing, MCP integration, and private knowledge hub functionality.', 'aiohm-knowledge-assistant' ); ?></p>
    4444
    … …  
    281281                                                                        <th scope="row"><?php esc_html_e('Token Name', 'aiohm-knowledge-assistant'); ?></th>
    282282                                                                        <td>
    283                                                                                 <input type="text" name="token_name" placeholder="<?php esc_attr_e('e.g., Mobile App, Claude Desktop', 'aiohm-knowledge-assistant'); ?>" required maxlength="255" class="regular-text">
     283                                                                                <input type="text" name="token_name" placeholder="<?php esc_attr_e('e.g., Mobile app, desktop MCP client', 'aiohm-knowledge-assistant'); ?>" required maxlength="255" class="regular-text">
    284284                                                                                <p class="description"><?php esc_html_e('A descriptive name to identify this token', 'aiohm-knowledge-assistant'); ?></p>
    285285                                                                        </td>
    … …  
    339339                <div class="aiohm-save-section">
    340340                        <p class="submit">
    341                                 <input type="submit" name="submit" id="submit" class="button button-primary button-large" value="<?php esc_attr_e( 'Save All Pro Features Settings', 'aiohm-knowledge-assistant' ); ?>">
     341                                <input type="submit" name="submit" id="submit" class="button button-primary button-large" value="<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>">
    342342                        </p>
    343343                </div>
    … …  
    548548                        success: function(response) {
    549549                                console.log('AJAX response:', response);
    550                                 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Pro Features Settings', 'aiohm-knowledge-assistant' ); ?>');
     550                                $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>');
    551551                               
    552552                                if (response.success) {
    … …  
    573573                        error: function(xhr, status, error) {
    574574                                console.error('AJAX error:', xhr, status, error);
    575                                 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Pro Features Settings', 'aiohm-knowledge-assistant' ); ?>');
     575                                $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>');
    576576                                $('#aiohm-admin-notice').removeClass('notice-success notice-info').addClass('notice-error').find('p').text('Save failed: ' + error);
    577577                        }
  • aiohm-knowledge-assistant/trunk/templates/admin-scan-website.php

    r3545079 r3833232  
    99// The controller (settings-page.php) prepares these variables before including this template.
    1010$aiohm_settings         = class_exists( 'AIOHM_KB_Assistant' ) ? AIOHM_KB_Assistant::get_settings() : array();
    11 $aiohm_default_provider = $aiohm_settings['default_ai_provider'] ?? 'openai';
    12 
    13 // Check if the selected default provider has an API key configured
    14 $aiohm_has_openai = ! empty( $aiohm_settings['openai_api_key'] )
    15         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    16         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    17         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    18         || getenv( 'OPENAI_API_KEY' );
    19 
    20 $aiohm_has_gemini = ! empty( $aiohm_settings['gemini_api_key'] )
    21         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    22         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    23         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    24         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    25         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    26         || getenv( 'GOOGLE_API_KEY' )
    27         || getenv( 'GEMINI_API_KEY' );
    28 
    29 $aiohm_has_claude = ! empty( $aiohm_settings['claude_api_key'] )
    30         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    31         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    32         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    33         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    34         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    35         || getenv( 'ANTHROPIC_API_KEY' )
    36         || getenv( 'CLAUDE_API_KEY' );
    37 
    38 $aiohm_has_shareai = ! empty( $aiohm_settings['shareai_api_key'] );
    39 
    40 $aiohm_api_key_exists = false;
    41 switch ( $aiohm_default_provider ) {
    42         case 'openai':
    43                 $aiohm_api_key_exists = $aiohm_has_openai;
    44                 break;
    45         case 'gemini':
    46                 $aiohm_api_key_exists = $aiohm_has_gemini;
    47                 break;
    48         case 'claude':
    49                 $aiohm_api_key_exists = $aiohm_has_claude;
    50                 break;
    51         case 'shareai':
    52                 $aiohm_api_key_exists = $aiohm_has_shareai;
    53                 break;
    54         default:
    55                 // For unknown providers, don't assume OpenAI - require proper configuration
    56                 $aiohm_api_key_exists = false;
    57 }
     11$aiohm_default_provider = aiohm_kb_resolve_ai_provider( $aiohm_settings['default_ai_provider'] ?? '', $aiohm_settings );
     12
     13// Check if the selected default provider is set up.
     14$aiohm_api_key_exists = aiohm_kb_ai_provider_available( $aiohm_default_provider, $aiohm_settings );
    5815
    5916// Also get provider display name for better error messaging
    6017$aiohm_provider_names        = array(
    61         'openai'  => 'OpenAI',
     18        'shareai' => 'ShareAI',
    6219        'gemini'  => 'Gemini',
    63         'claude'  => 'Claude',
    64         'shareai' => 'ShareAI',
     20        'ollama'  => 'Ollama',
    6521);
    6622$aiohm_current_provider_name = $aiohm_provider_names[ $aiohm_default_provider ] ?? 'Unknown Provider';
    … …  
    8137                        <?php
    8238                                printf(
    83                                         /* translators: %s is the name of the AI provider (e.g., OpenAI, Gemini, Claude) */
     39                                        /* translators: %s is the name of the AI provider (e.g., ShareAI, Gemini, Ollama) */
    8440                                        esc_html__( 'Content scanning is disabled because your %s API key has not been configured. Please add your key to enable this feature.', 'aiohm-knowledge-assistant' ),
    8541                                        esc_html( $aiohm_current_provider_name )
  • aiohm-knowledge-assistant/trunk/templates/admin-settings.php

    r3801374 r3833232  
    2424        </div>
    2525
     26        <?php include AIOHM_KB_PLUGIN_DIR . 'templates/admin-shareai-connect.php'; ?>
    2627
    2728        <form id="aiohm-settings-form" method="post" action="options.php">
    … …  
    3637                                        <div class="aiohm-shareai-settings-box">
    3738                                                <?php
    38                                                 $aiohm_has_openai  = ! empty( $aiohm_settings['openai_api_key'] )
    39                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'openai' ) )
    40                                                         || ! empty( get_option( 'connectors_ai_openai_api_key' ) )
    41                                                         || ( defined( 'OPENAI_API_KEY' ) && OPENAI_API_KEY )
    42                                                         || getenv( 'OPENAI_API_KEY' );
    43                                                 $aiohm_has_gemini  = ! empty( $aiohm_settings['gemini_api_key'] )
    44                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'gemini' ) )
    45                                                         || ! empty( get_option( 'connectors_ai_google_api_key' ) )
    46                                                         || ! empty( get_option( 'connectors_ai_gemini_api_key' ) )
    47                                                         || ( defined( 'GOOGLE_API_KEY' ) && GOOGLE_API_KEY )
    48                                                         || ( defined( 'GEMINI_API_KEY' ) && GEMINI_API_KEY )
    49                                                         || getenv( 'GOOGLE_API_KEY' )
    50                                                         || getenv( 'GEMINI_API_KEY' );
    51                                                 $aiohm_has_claude  = ! empty( $aiohm_settings['claude_api_key'] )
    52                                                         || ( function_exists( 'aiohm_kb_is_wp_ai_connector_configured' ) && aiohm_kb_is_wp_ai_connector_configured( 'claude' ) )
    53                                                         || ! empty( get_option( 'connectors_ai_anthropic_api_key' ) )
    54                                                         || ! empty( get_option( 'connectors_ai_claude_api_key' ) )
    55                                                         || ( defined( 'ANTHROPIC_API_KEY' ) && ANTHROPIC_API_KEY )
    56                                                         || ( defined( 'CLAUDE_API_KEY' ) && CLAUDE_API_KEY )
    57                                                         || getenv( 'ANTHROPIC_API_KEY' )
    58                                                         || getenv( 'CLAUDE_API_KEY' );
    59                                                 $aiohm_has_shareai = ! empty( $aiohm_settings['shareai_api_key'] );
    60                                                 $aiohm_has_groq    = ! empty( $aiohm_settings['groq_api_key'] );
     39                                                $aiohm_has_shareai   = aiohm_kb_shareai_available( $aiohm_settings );
     40                                                $aiohm_has_gemini    = aiohm_kb_gemini_available( $aiohm_settings );
     41                                                $aiohm_has_openai    = aiohm_kb_wp_connector_provider_available( 'openai' );
     42                                                $aiohm_has_anthropic = aiohm_kb_wp_connector_provider_available( 'anthropic' );
    6143
    6244                                                // Check for Ollama
    … …  
    6446                                                $aiohm_has_ollama   = ! empty( $aiohm_pro_features['ollama_enabled'] );
    6547
    66                                                 $aiohm_has_any_api = $aiohm_has_openai || $aiohm_has_gemini || $aiohm_has_claude || $aiohm_has_shareai || $aiohm_has_groq || $aiohm_has_ollama;
     48                                                // ShareAI and Ollama are always offered. Other providers appear
     49                                                // only once the site connects them (WordPress Connectors or a key).
     50                                                $aiohm_has_any_api = true;
    6751                                                $aiohm_enabled_provider_values = array();
    6852                                                foreach (
    6953                                                        array(
    7054                                                                'shareai' => $aiohm_has_shareai,
    71                                                                 'openai'  => $aiohm_has_openai,
    72                                                                 'claude'  => $aiohm_has_claude,
    7355                                                                'gemini'  => $aiohm_has_gemini,
    74                                                                 'groq'    => $aiohm_has_groq,
    7556                                                                'ollama'  => $aiohm_has_ollama,
     57                                                                'openai'    => $aiohm_has_openai,
     58                                                                'anthropic' => $aiohm_has_anthropic,
    7659                                                        ) as $aiohm_provider_value => $aiohm_provider_enabled
    7760                                                ) {
    … …  
    9679                                                <div class="shareai-setting-row">
    9780                                                       
    98                                                         <!-- All AI Providers (6-column grid) -->
     81                                                        <!-- All AI Providers (3-column grid) -->
    9982                                                        <div class="aiohm-provider-selection aiohm-provider-grid">
    10083                                                                <label class="aiohm-provider-option <?php echo ! $aiohm_has_shareai ? 'disabled' : ''; ?>" data-provider="shareai">
    10184                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="shareai" <?php checked( $aiohm_default_ai_provider, 'shareai' ); ?> <?php echo ! $aiohm_has_shareai ? 'disabled' : ''; ?>>
    10285                                                                        <div class="aiohm-provider-icon">
    103                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/shareai-icon.jpeg' ); ?>" alt="ShareAI">
     86                                                                                <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/shareai-icon-64.png' ); ?>" alt="ShareAI">
    10487                                                                        </div>
    10588                                                                        <div class="aiohm-provider-info">
    10689                                                                                <div class="aiohm-provider-name">ShareAI</div>
    107                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_shareai ? 'Affordable AI' : 'API Key Required'; ?></div>
     90                                                                                <div class="aiohm-provider-description"><?php echo $aiohm_has_shareai ? esc_html__( 'Affordable AI', 'aiohm-knowledge-assistant' ) : esc_html__( 'Connect ShareAI above', 'aiohm-knowledge-assistant' ); ?></div>
    10891                                                                        </div>
    10992                                                                        <?php if ( ! $aiohm_has_shareai ) : ?>
    … …  
    11295                                                                </label>
    11396                                                               
    114                                                                 <label class="aiohm-provider-option <?php echo ! $aiohm_has_openai ? 'disabled' : ''; ?>" data-provider="openai">
    115                                                                         <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="openai" <?php checked( $aiohm_default_ai_provider, 'openai' ); ?> <?php echo ! $aiohm_has_openai ? 'disabled' : ''; ?>>
    116                                                                         <div class="aiohm-provider-icon">
    117                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/openai-icon.svg' ); ?>" alt="OpenAI">
    118                                                                         </div>
    119                                                                         <div class="aiohm-provider-info">
    120                                                                                 <div class="aiohm-provider-name">OpenAI</div>
    121                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_openai ? 'GPT-4, GPT-3.5' : 'API Key Required'; ?></div>
    122                                                                         </div>
    123                                                                         <?php if ( ! $aiohm_has_openai ) : ?>
    124                                                                         <div class="aiohm-provider-overlay">🔒</div>
    125                                                                         <?php endif; ?>
    126                                                                 </label>
    127                                                                
    128                                                                 <label class="aiohm-provider-option <?php echo ! $aiohm_has_claude ? 'disabled' : ''; ?>" data-provider="anthropic">
    129                                                                         <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="claude" <?php checked( $aiohm_default_ai_provider, 'claude' ); ?> <?php echo ! $aiohm_has_claude ? 'disabled' : ''; ?>>
    130                                                                         <div class="aiohm-provider-icon">
    131                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/claude-icon.svg' ); ?>" alt="Anthropic Claude">
    132                                                                         </div>
    133                                                                         <div class="aiohm-provider-info">
    134                                                                                 <div class="aiohm-provider-name">Claude</div>
    135                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_claude ? 'Anthropic AI' : 'API Key Required'; ?></div>
    136                                                                         </div>
    137                                                                         <?php if ( ! $aiohm_has_claude ) : ?>
    138                                                                         <div class="aiohm-provider-overlay">🔒</div>
    139                                                                         <?php endif; ?>
    140                                                                 </label>
    141                                                                
    142                                                                 <label class="aiohm-provider-option <?php echo ! $aiohm_has_gemini ? 'disabled' : ''; ?>" data-provider="google">
    143                                                                         <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="gemini" <?php checked( $aiohm_default_ai_provider, 'gemini' ); ?> <?php echo ! $aiohm_has_gemini ? 'disabled' : ''; ?>>
    144                                                                         <div class="aiohm-provider-icon">
    145                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/gemini-icon.svg' ); ?>" alt="Google Gemini">
    146                                                                         </div>
    147                                                                         <div class="aiohm-provider-info">
    148                                                                                 <div class="aiohm-provider-name">Gemini</div>
    149                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_gemini ? 'Google AI' : 'API Key Required'; ?></div>
    150                                                                         </div>
    151                                                                         <?php if ( ! $aiohm_has_gemini ) : ?>
    152                                                                         <div class="aiohm-provider-overlay">🔒</div>
    153                                                                         <?php endif; ?>
    154                                                                 </label>
    155 
    156                                                                 <label class="aiohm-provider-option <?php echo ! $aiohm_has_groq ? 'disabled' : ''; ?>" data-provider="groq">
    157                                                                         <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="groq" <?php checked( $aiohm_default_ai_provider, 'groq' ); ?> <?php echo ! $aiohm_has_groq ? 'disabled' : ''; ?>>
    158                                                                         <div class="aiohm-provider-icon">
    159                                                                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/groq-icon.svg' ); ?>" alt="Groq">
    160                                                                         </div>
    161                                                                         <div class="aiohm-provider-info">
    162                                                                                 <div class="aiohm-provider-name">Groq</div>
    163                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_groq ? 'Ultra-Fast AI' : 'API Key Required'; ?></div>
    164                                                                         </div>
    165                                                                         <?php if ( ! $aiohm_has_groq ) : ?>
    166                                                                         <div class="aiohm-provider-overlay">🔒</div>
    167                                                                         <?php endif; ?>
    168                                                                 </label>
    169 
    17097                                                                <label class="aiohm-provider-option <?php echo ! $aiohm_has_ollama ? 'disabled' : ''; ?>" data-provider="ollama">
    17198                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="ollama" <?php checked( $aiohm_default_ai_provider, 'ollama' ); ?> <?php echo ! $aiohm_has_ollama ? 'disabled' : ''; ?>>
    … …  
    175102                                                                        <div class="aiohm-provider-info">
    176103                                                                                <div class="aiohm-provider-name">Ollama</div>
    177                                                                                 <div class="aiohm-provider-description"><?php echo $aiohm_has_ollama ? 'Local AI' : 'Pro Feature'; ?></div>
     104                                                                                <div class="aiohm-provider-description"><?php echo $aiohm_has_ollama ? esc_html__( 'Local AI', 'aiohm-knowledge-assistant' ) : esc_html__( 'Set up in Advanced', 'aiohm-knowledge-assistant' ); ?></div>
    178105                                                                        </div>
    179106                                                                        <?php if ( ! $aiohm_has_ollama ) : ?>
    … …  
    181108                                                                        <?php endif; ?>
    182109                                                                </label>
     110
     111                                                                <?php if ( $aiohm_has_gemini ) : ?>
     112                                                                <label class="aiohm-provider-option" data-provider="google">
     113                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="gemini" <?php checked( $aiohm_default_ai_provider, 'gemini' ); ?>>
     114                                                                        <div class="aiohm-provider-icon">
     115                                                                                <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/gemini-icon.svg' ); ?>" alt="Google Gemini">
     116                                                                        </div>
     117                                                                        <div class="aiohm-provider-info">
     118                                                                                <div class="aiohm-provider-name">Gemini</div>
     119                                                                                <div class="aiohm-provider-description"><?php esc_html_e( 'Google AI', 'aiohm-knowledge-assistant' ); ?></div>
     120                                                                        </div>
     121                                                                </label>
     122                                                                <?php endif; ?>
     123
     124                                                                <?php if ( $aiohm_has_openai ) : ?>
     125                                                                <label class="aiohm-provider-option" data-provider="openai">
     126                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="openai" <?php checked( $aiohm_default_ai_provider, 'openai' ); ?>>
     127                                                                        <div class="aiohm-provider-icon">
     128                                                                                <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/openai-icon.svg' ); ?>" alt="OpenAI">
     129                                                                        </div>
     130                                                                        <div class="aiohm-provider-info">
     131                                                                                <div class="aiohm-provider-name">OpenAI</div>
     132                                                                                <div class="aiohm-provider-description"><?php esc_html_e( 'WordPress Connectors', 'aiohm-knowledge-assistant' ); ?></div>
     133                                                                        </div>
     134                                                                </label>
     135                                                                <?php endif; ?>
     136
     137                                                                <?php if ( $aiohm_has_anthropic ) : ?>
     138                                                                <label class="aiohm-provider-option" data-provider="anthropic">
     139                                                                        <input type="radio" name="aiohm_kb_settings[default_ai_provider]" value="anthropic" <?php checked( $aiohm_default_ai_provider, 'anthropic' ); ?>>
     140                                                                        <div class="aiohm-provider-icon">
     141                                                                                <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/claude-icon.svg' ); ?>" alt="Anthropic Claude">
     142                                                                        </div>
     143                                                                        <div class="aiohm-provider-info">
     144                                                                                <div class="aiohm-provider-name">Claude</div>
     145                                                                                <div class="aiohm-provider-description"><?php esc_html_e( 'WordPress Connectors', 'aiohm-knowledge-assistant' ); ?></div>
     146                                                                        </div>
     147                                                                </label>
     148                                                                <?php endif; ?>
    183149
    184150                                                        </div>
    … …  
    225191                                                <div class="aiohm-privacy-notice">
    226192                                                        <p><strong><?php esc_html_e( 'Data Processing Notice:', 'aiohm-knowledge-assistant' ); ?></strong></p>
    227                                                         <p><?php esc_html_e( 'This plugin makes API calls to external AI services (OpenAI, Google Gemini, Claude, ShareAI, etc.) to process your content and provide AI responses.', 'aiohm-knowledge-assistant' ); ?></p>
     193                                                        <p><?php esc_html_e( 'This plugin sends requests to the AI service you choose (ShareAI, or Google Gemini, OpenAI or Anthropic when your site connects them) to process your content and write AI responses. A local Ollama server keeps requests on your own server.', 'aiohm-knowledge-assistant' ); ?></p>
    228194                                                </div>
    229195                                        </div>
    … …  
    232198                </div>
    233199
    234                 <!-- Free AI Services Section -->
    235                 <div class="aiohm-card">
    236                         <h2><?php esc_html_e( 'Free AI Services & Connectors', 'aiohm-knowledge-assistant' ); ?></h2>
    237                         <p class="aiohm-section-description"><?php esc_html_e( 'Get started with AI for free using these services and connectors. Perfect for testing and development.', 'aiohm-knowledge-assistant' ); ?></p>
    238                        
    239                         <!-- ShareAI Configuration -->
    240                         <h3 class="aiohm-service-title">
    241                                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/shareai-icon.jpeg' ); ?>" alt="ShareAI" class="aiohm-service-icon" />
    242                                 <?php esc_html_e( 'ShareAI', 'aiohm-knowledge-assistant' ); ?>
    243                         </h3>
    244                         <div class="aiohm-shareai-two-column-layout">
    245                                                         <!-- Left Column: Settings -->
    246                                                         <div class="aiohm-shareai-settings-column">
    247                                                                 <div class="aiohm-shareai-settings-box">
    248                                                                         <div class="shareai-setting-row">
    249                                                                                 <label for="shareai_api_key" class="shareai-inline-label"><?php esc_html_e( 'API Key:', 'aiohm-knowledge-assistant' ); ?></label>
    250                                                                                 <div class="aiohm-api-key-wrapper">
    251                                                                                         <div class="aiohm-key-input-group">
    252                                                                                                 <input type="password" id="shareai_api_key" name="aiohm_kb_settings[shareai_api_key]" value="<?php echo esc_attr( $aiohm_settings['shareai_api_key'] ?? '' ); ?>" placeholder="Enter your ShareAI API key" class="regular-text">
    253                                                                                                 <button type="button" class="aiohm-show-hide-key" data-target="shareai_api_key"><span class="dashicons dashicons-visibility"></span></button>
    254                                                                                         </div>
    255                                                                                         <div class="aiohm-api-key-actions">
    256                                                                                                 <button type="button" class="button aiohm-shareai-btn aiohm-test-api-key" data-target="shareai_api_key" data-type="shareai"><?php esc_html_e( 'Test API & Usage', 'aiohm-knowledge-assistant' ); ?></button>
    257                                                                                                 <button type="button" class="button aiohm-shareai-btn aiohm-save-api-key" data-target="shareai_api_key" data-type="shareai"><?php esc_html_e( 'Save', 'aiohm-knowledge-assistant' ); ?></button>
    258                                                                                         </div>
    259                                                                                 </div>
    260                                                                         </div>
    261                                                                        
    262                                                                         <div class="shareai-setting-row">
    263                                                                                 <label for="shareai_model" class="shareai-inline-label"><?php esc_html_e( 'Model:', 'aiohm-knowledge-assistant' ); ?></label>
    264                                                                                 <select id="shareai_model" name="aiohm_kb_settings[shareai_model]" class="regular-text">
    265                                                                                         <optgroup label="Command Models">
    266                                                                                                 <option value="deepseek-r1:7b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'deepseek-r1:7b' ); ?>>DeepSeek R1 7B</option>
    267                                                                                                 <option value="deepseek-r1:14b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'deepseek-r1:14b' ); ?>>DeepSeek R1 14B</option>
    268                                                                                                 <option value="deepseek-r1:32b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'deepseek-r1:32b' ); ?>>DeepSeek R1 32B</option>
    269                                                                                                 <option value="deepseek-r1:671b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'deepseek-r1:671b' ); ?>>DeepSeek R1 671B</option>
    270                                                                                                 <option value="llama4:17b-scout-16e-instruct-fp16" <?php selected( $aiohm_settings['shareai_model'] ?? 'llama4:17b-scout-16e-instruct-fp16', 'llama4:17b-scout-16e-instruct-fp16' ); ?>>Llama 4 17B Scout (Recommended)</option>
    271                                                                                                 <option value="llama4:90b-instruct-fp16" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'llama4:90b-instruct-fp16' ); ?>>Llama 4 90B Instruct</option>
    272                                                                                                 <option value="qwen2.5:0.5b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:0.5b' ); ?>>Qwen 2.5 0.5B</option>
    273                                                                                                 <option value="qwen2.5:1.5b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:1.5b' ); ?>>Qwen 2.5 1.5B</option>
    274                                                                                                 <option value="qwen2.5:3b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:3b' ); ?>>Qwen 2.5 3B</option>
    275                                                                                                 <option value="qwen2.5:7b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:7b' ); ?>>Qwen 2.5 7B</option>
    276                                                                                                 <option value="qwen2.5:14b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:14b' ); ?>>Qwen 2.5 14B</option>
    277                                                                                                 <option value="qwen2.5:32b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:32b' ); ?>>Qwen 2.5 32B</option>
    278                                                                                                 <option value="qwen2.5:72b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5:72b' ); ?>>Qwen 2.5 72B</option>
    279                                                                                         </optgroup>
    280                                                                                         <optgroup label="Chat Models">
    281                                                                                                 <option value="llama3.2:1b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'llama3.2:1b' ); ?>>Llama 3.2 1B</option>
    282                                                                                                 <option value="llama3.2:3b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'llama3.2:3b' ); ?>>Llama 3.2 3B</option>
    283                                                                                                 <option value="llama3.3:70b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'llama3.3:70b' ); ?>>Llama 3.3 70B</option>
    284                                                                                                 <option value="qwen2.5-coder:1.5b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5-coder:1.5b' ); ?>>Qwen 2.5 Coder 1.5B</option>
    285                                                                                                 <option value="qwen2.5-coder:7b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5-coder:7b' ); ?>>Qwen 2.5 Coder 7B</option>
    286                                                                                                 <option value="qwen2.5-coder:14b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5-coder:14b' ); ?>>Qwen 2.5 Coder 14B</option>
    287                                                                                                 <option value="qwen2.5-coder:32b" <?php selected( $aiohm_settings['shareai_model'] ?? '', 'qwen2.5-coder:32b' ); ?>>Qwen 2.5 Coder 32B</option>
    288                                                                                         </optgroup>
    289                                                                                 </select>
    290                                                                         </div>
    291                                                                        
    292                                                                         <div class="shareai-usage-notice">
    293                                                                                 <p><strong><?php esc_html_e( 'Affordable AI tokens with ShareAI', 'aiohm-knowledge-assistant' ); ?></strong><br>
    294                                                                                 <?php esc_html_e( 'ShareAI connects you to a global compute network, making AI more affordable or free if you share your device\'s idle power.', 'aiohm-knowledge-assistant' ); ?></p>
    295                                                                                
    296                                                                                 <p><strong><?php esc_html_e( 'To get started:', 'aiohm-knowledge-assistant' ); ?></strong><br>
    297                                                                                 <?php
    298                                                                                         printf(
    299                                                                                                 wp_kses(
    300                                                                                                         // translators: %s is the URL to the ShareAI Console
    301                                                                                                         __( 'Generate your API key in the <a href="%s" target="_blank">ShareAI Console</a>, add it to AIOHM settings, and ensure your chosen model is active.', 'aiohm-knowledge-assistant' ),
    302                                                                                                         array(
    303                                                                                                                 'a' => array(
    304                                                                                                                         'href' => array(),
    305                                                                                                                         'target' => array(),
    306                                                                                                                 ),
    307                                                                                                         )
    308                                                                                                 ),
    309                                                                                                 esc_url( 'https://console.shareai.now/app/api-key/?utm_source=AIOHM&utm_medium=plugin&utm_campaign=shareai_integration' )
    310                                                                                         );
    311                                                                                         ?>
    312                                                                                         </p>
    313                                                                         </div>
    314                                                                 </div>
    315                                                         </div>
    316 
    317                                                         <!-- Right Column: Model Information -->
    318                                                         <div class="aiohm-shareai-info-column">
    319                                                                 <div class="aiohm-model-info-box">
    320                                                                         <h4 class="aiohm-model-info-title"><?php esc_html_e( 'Model Information', 'aiohm-knowledge-assistant' ); ?></h4>
    321                                                                         <div id="aiohm-model-info-content" class="aiohm-model-info-content">
    322                                                                                 <!-- Default placeholder content -->
    323                                                                                 <div class="aiohm-model-placeholder">
    324                                                                                         <div class="aiohm-placeholder-icon">📋</div>
    325                                                                                         <h5><?php esc_html_e( 'Select a Model and Save', 'aiohm-knowledge-assistant' ); ?></h5>
    326                                                                                         <p><?php esc_html_e( 'Choose your preferred ShareAI model from the dropdown and click "Save" to view detailed information about the model\'s capabilities, training, and best use cases.', 'aiohm-knowledge-assistant' ); ?></p>
    327                                                                                         <div class="aiohm-placeholder-steps">
    328                                                                                                 <div class="aiohm-step">
    329                                                                                                         <span class="aiohm-step-number">1</span>
    330                                                                                                         <span><?php esc_html_e( 'Select model from dropdown', 'aiohm-knowledge-assistant' ); ?></span>
    331                                                                                                 </div>
    332                                                                                                 <div class="aiohm-step">
    333                                                                                                         <span class="aiohm-step-number">2</span>
    334                                                                                                         <span><?php esc_html_e( 'Click "Save" button', 'aiohm-knowledge-assistant' ); ?></span>
    335                                                                                                 </div>
    336                                                                                                 <div class="aiohm-step">
    337                                                                                                         <span class="aiohm-step-number">3</span>
    338                                                                                                         <span><?php esc_html_e( 'View model details here', 'aiohm-knowledge-assistant' ); ?></span>
    339                                                                                                 </div>
    340                                                                                         </div>
    341                                                                                 </div>
    342                                                                         </div>
    343                                                                 </div>
    344                                                         </div>
    345                                                 </div>
    346                 </div>
    347 
    348 
    349200                <?php $aiohm_uses_wp_connectors = function_exists( 'wp_get_connectors' ); ?>
    350201
    351                 <div class="aiohm-premium-services-columns <?php echo $aiohm_uses_wp_connectors ? 'aiohm-single-premium-column' : ''; ?>">
    352                         <?php if ( ! $aiohm_uses_wp_connectors ) : ?>
    353                         <!-- Left Column: Gemini and OpenAI -->
     202                <?php if ( ! $aiohm_uses_wp_connectors ) : ?>
     203                <div class="aiohm-premium-services-columns aiohm-single-premium-column">
    354204                        <div class="aiohm-premium-column">
    355205                                <!-- Gemini -->
    … …  
    370220                                                printf(
    371221                                                        wp_kses(
     222                                                                /* translators: %s: Google AI Studio URL */
    372223                                                                __( 'You can get your Gemini API key from the <a href="%s" target="_blank">Google AI Studio</a>.', 'aiohm-knowledge-assistant' ),
    373224                                                                array(
    … …  
    383234                                        </p>
    384235                                </div>
    385 
    386                                 <!-- OpenAI -->
    387                                 <h3 class="aiohm-service-title"><?php esc_html_e( 'OpenAI API Key', 'aiohm-knowledge-assistant' ); ?></h3>
    388                                 <div class="aiohm-service-content">
    389                                         <div class="aiohm-api-key-wrapper">
    390                                                 <div class="aiohm-key-input-group">
    391                                                         <input type="password" id="openai_api_key" name="aiohm_kb_settings[openai_api_key]" value="<?php echo esc_attr( $aiohm_settings['openai_api_key'] ?? '' ); ?>" class="regular-text">
    392                                                         <button type="button" class="aiohm-show-hide-key" data-target="openai_api_key"><span class="dashicons dashicons-visibility"></span></button>
    393                                                 </div>
    394                                                 <div class="aiohm-api-key-actions">
    395                                                         <button type="button" class="button button-secondary aiohm-test-api-key" data-target="openai_api_key" data-type="openai"><?php esc_html_e( 'Test API', 'aiohm-knowledge-assistant' ); ?></button>
    396                                                         <button type="button" class="button button-secondary aiohm-save-api-key" data-target="openai_api_key" data-type="openai"><?php esc_html_e( 'Save', 'aiohm-knowledge-assistant' ); ?></button>
    397                                                 </div>
    398                                         </div>
    399                                         <p class="description">
    400                                         <?php
    401                                                 printf(
    402                                                         wp_kses(
    403                                                                 __( 'You can get your OpenAI API key from the <a href="%s" target="_blank">OpenAI API keys page</a>.', 'aiohm-knowledge-assistant' ),
    404                                                                 array(
    405                                                                         'a' => array(
    406                                                                                 'href' => array(),
    407                                                                                 'target' => array(),
    408                                                                         ),
    409                                                                 )
    410                                                         ),
    411                                                         esc_url( 'https://platform.openai.com/account/api-keys' )
    412                                                 );
    413                                         ?>
    414                                         </p>
    415                                 </div>
    416236                        </div>
    417                         <?php endif; ?>
    418 
    419                         <!-- Right Column: Claude and Groq -->
    420                         <div class="aiohm-premium-column">
    421                                 <?php if ( ! $aiohm_uses_wp_connectors ) : ?>
    422                                 <!-- Claude -->
    423                                 <h3 class="aiohm-service-title"><?php esc_html_e( 'Claude API Key', 'aiohm-knowledge-assistant' ); ?></h3>
    424                                 <div class="aiohm-service-content">
    425                                         <div class="aiohm-api-key-wrapper">
    426                                                 <div class="aiohm-key-input-group">
    427                                                         <input type="password" id="claude_api_key" name="aiohm_kb_settings[claude_api_key]" value="<?php echo esc_attr( $aiohm_settings['claude_api_key'] ?? '' ); ?>" class="regular-text">
    428                                                         <button type="button" class="aiohm-show-hide-key" data-target="claude_api_key"><span class="dashicons dashicons-visibility"></span></button>
    429                                                 </div>
    430                                                 <div class="aiohm-api-key-actions">
    431                                                         <button type="button" class="button button-secondary aiohm-test-api-key" data-target="claude_api_key" data-type="claude"><?php esc_html_e( 'Test API', 'aiohm-knowledge-assistant' ); ?></button>
    432                                                         <button type="button" class="button button-secondary aiohm-save-api-key" data-target="claude_api_key" data-type="claude"><?php esc_html_e( 'Save', 'aiohm-knowledge-assistant' ); ?></button>
    433                                                 </div>
    434                                         </div>
    435                                         <p class="description">
    436                                         <?php
    437                                                 printf(
    438                                                         wp_kses(
    439                                                                 __( 'You can get your Claude API key from your <a href="%s" target="_blank">Anthropic Account Settings</a>.', 'aiohm-knowledge-assistant' ),
    440                                                                 array(
    441                                                                         'a' => array(
    442                                                                                 'href' => array(),
    443                                                                                 'target' => array(),
    444                                                                         ),
    445                                                                 )
    446                                                         ),
    447                                                         esc_url( 'https://console.anthropic.com/account/keys' )
    448                                                 );
    449                                         ?>
    450                                         </p>
    451                                 </div>
    452                                 <?php endif; ?>
    453 
    454                                
    455         <div class="aiohm-card">
    456             <h3 class="aiohm-service-title">
    457                 <img src="<?php echo esc_url( AIOHM_KB_PLUGIN_URL . 'assets/images/groq-icon.svg' ); ?>" alt="Groq" class="aiohm-service-icon" />
    458                 <?php esc_html_e( 'Groq', 'aiohm-knowledge-assistant' ); ?>
    459             </h3>
    460 
    461             <div class="aiohm-shareai-two-column-layout">
    462                 <div class="aiohm-shareai-settings-column">
    463                     <div class="aiohm-shareai-settings-box">
    464                         <div class="shareai-setting-row">
    465                             <label for="groq_api_key" class="shareai-inline-label"><?php esc_html_e( 'API Key:', 'aiohm-knowledge-assistant' ); ?></label>
    466                             <div class="aiohm-api-key-wrapper">
    467                                 <div class="aiohm-key-input-group">
    468                                     <input type="password" id="groq_api_key" name="aiohm_kb_settings[groq_api_key]" value="<?php echo esc_attr( $aiohm_settings['groq_api_key'] ?? '' ); ?>" placeholder="Enter your Groq API key" class="regular-text">
    469                                     <button type="button" class="aiohm-show-hide-key" data-target="groq_api_key"><span class="dashicons dashicons-visibility"></span></button>
    470                                 </div>
    471                                 <div class="aiohm-api-key-actions">
    472                                     <button type="button" class="button aiohm-shareai-btn aiohm-test-api-key" data-target="groq_api_key" data-type="groq"><?php esc_html_e( 'Test API', 'aiohm-knowledge-assistant' ); ?></button>
    473                                     <button type="button" class="button aiohm-shareai-btn aiohm-save-api-key" data-target="groq_api_key" data-type="groq"><?php esc_html_e( 'Save', 'aiohm-knowledge-assistant' ); ?></button>
    474                                 </div>
    475                             </div>
    476                         </div>
    477 
    478                         <div class="shareai-setting-row">
    479                             <label for="groq_model" class="shareai-inline-label"><?php esc_html_e( 'Model:', 'aiohm-knowledge-assistant' ); ?></label>
    480                             <select id="groq_model" name="aiohm_kb_settings[groq_model]" class="regular-text">
    481                                 <option value="groq-default" <?php selected( $aiohm_settings['groq_model'] ?? '', 'groq-default' ); ?>>Groq Default (Recommended)</option>
    482                                 <option value="groq-small" <?php selected( $aiohm_settings['groq_model'] ?? '', 'groq-small' ); ?>>Groq Small</option>
    483                                 <option value="groq-medium" <?php selected( $aiohm_settings['groq_model'] ?? '', 'groq-medium' ); ?>>Groq Medium</option>
    484                                 <option value="groq-large" <?php selected( $aiohm_settings['groq_model'] ?? '', 'groq-large' ); ?>>Groq Large</option>
    485                             </select>
    486                         </div>
    487 
    488                         <div class="shareai-usage-notice">
    489                             <p><strong><?php esc_html_e( 'Groq API Access', 'aiohm-knowledge-assistant' ); ?></strong><br>
    490                             <?php esc_html_e( 'Use your Groq API key for fast, low-latency model inference in AIOHM.', 'aiohm-knowledge-assistant' ); ?></p>
    491 
    492                             <p><strong><?php esc_html_e( 'To get started:', 'aiohm-knowledge-assistant' ); ?></strong><br>
    493                             <?php
    494                                 printf(
    495                                     wp_kses(
    496                                         /* translators: %s is the URL to the Groq Console */
    497                                         __( 'Generate your API key in the <a href="%s" target="_blank">Groq Console</a>, add it to AIOHM settings, and ensure your chosen model is active.', 'aiohm-knowledge-assistant' ),
    498                                         array(
    499                                             'a' => array(
    500                                                 'href' => array(),
    501                                                 'target' => array(),
    502                                             ),
    503                                         )
    504                                     ),
    505                                     esc_url( 'https://console.groq.com/keys' )
    506                                 );
    507                             ?></p>
    508                         </div>
    509                     </div>
    510                 </div>
    511 
    512                 <div class="aiohm-shareai-info-column">
    513                     <div class="aiohm-model-info-box">
    514                         <h4 class="aiohm-model-info-title"><?php esc_html_e( 'Groq Model Information', 'aiohm-knowledge-assistant' ); ?></h4>
    515                         <div class="aiohm-model-info-content">
    516                             <div class="aiohm-model-placeholder">
    517                                 <div class="aiohm-placeholder-icon">⚡</div>
    518                                 <h5><?php esc_html_e( 'Save your Groq API key first', 'aiohm-knowledge-assistant' ); ?></h5>
    519                                 <p><?php esc_html_e( 'Enter and save your Groq key to access model details and performance recommendations.', 'aiohm-knowledge-assistant' ); ?></p>
    520                             </div>
    521                         </div>
    522                     </div>
    523                 </div>
    524             </div>
    525         </div>
     237                </div>
     238                <?php endif; ?>
    526239
    527240        <div class="aiohm-card">
  • aiohm-knowledge-assistant/trunk/templates/partials/header.php

    r3801374 r3833232  
    3939                        <li>
    4040                                <a href="<?php echo esc_url( admin_url( 'admin.php?page=aiohm-pro-features' ) ); ?>">
    41                                         <?php esc_html_e( 'Pro Features', 'aiohm-knowledge-assistant' ); ?>
     41                                        <?php esc_html_e( 'Advanced', 'aiohm-knowledge-assistant' ); ?>
    4242                                </a>
    4343                        </li>
Note: See TracChangeset for help on using the changeset viewer.