Changeset 3833232
- Timestamp:
- 11/29/2026 03:15:43 PM (less than one hour ago)
- Location:
- aiohm-knowledge-assistant
- Files:
-
- 13 added
- 6 deleted
- 42 edited
- 1 copied
-
assets/screenshot-1.jpg (added)
-
assets/screenshot-1.png (deleted)
-
assets/screenshot-2.jpg (added)
-
assets/screenshot-2.png (deleted)
-
assets/screenshot-3.jpg (added)
-
assets/screenshot-3.png (deleted)
-
assets/screenshot-4.jpg (added)
-
assets/screenshot-4.png (deleted)
-
assets/screenshot-5.jpg (added)
-
assets/screenshot-5.png (deleted)
-
assets/screenshot-6.png (deleted)
-
tags/3.1.0 (copied) (copied from aiohm-knowledge-assistant/trunk )
-
tags/3.1.0/README.md (modified) (3 diffs)
-
tags/3.1.0/aiohm-knowledge-assistant.php (modified) (13 diffs)
-
tags/3.1.0/assets/css/aiohm-admin-settings.css (modified) (1 diff)
-
tags/3.1.0/assets/css/aiohm-provider-icons.css (modified) (3 diffs)
-
tags/3.1.0/assets/images/muse-avatar.webp (added)
-
tags/3.1.0/assets/images/shareai-icon-64.png (added)
-
tags/3.1.0/assets/js/aiohm-admin-modes.js (modified) (2 diffs)
-
tags/3.1.0/assets/js/aiohm-admin-settings.js (modified) (2 diffs)
-
tags/3.1.0/includes/ai-gpt-client.php (modified) (22 diffs)
-
tags/3.1.0/includes/core-init.php (modified) (23 diffs)
-
tags/3.1.0/includes/parsers/ai-fallback-parser.php (modified) (4 diffs)
-
tags/3.1.0/includes/rag-engine.php (modified) (12 diffs)
-
tags/3.1.0/includes/settings-page.php (modified) (7 diffs)
-
tags/3.1.0/includes/shareai-connect.php (added)
-
tags/3.1.0/includes/shortcode-qa.php (modified) (2 diffs)
-
tags/3.1.0/includes/uninstall-cleanup.php (modified) (2 diffs)
-
tags/3.1.0/readme.txt (modified) (9 diffs)
-
tags/3.1.0/templates/admin-dashboard.php (modified) (3 diffs)
-
tags/3.1.0/templates/admin-mirror-mode.php (modified) (1 diff)
-
tags/3.1.0/templates/admin-muse-mode.php (modified) (1 diff)
-
tags/3.1.0/templates/admin-pro-features.php (modified) (5 diffs)
-
tags/3.1.0/templates/admin-scan-website.php (modified) (2 diffs)
-
tags/3.1.0/templates/admin-settings.php (modified) (11 diffs)
-
tags/3.1.0/templates/admin-shareai-connect.php (added)
-
tags/3.1.0/templates/partials/header.php (modified) (1 diff)
-
trunk/README.md (modified) (3 diffs)
-
trunk/aiohm-knowledge-assistant.php (modified) (13 diffs)
-
trunk/assets/css/aiohm-admin-settings.css (modified) (1 diff)
-
trunk/assets/css/aiohm-provider-icons.css (modified) (3 diffs)
-
trunk/assets/images/muse-avatar.webp (added)
-
trunk/assets/images/shareai-icon-64.png (added)
-
trunk/assets/js/aiohm-admin-modes.js (modified) (2 diffs)
-
trunk/assets/js/aiohm-admin-settings.js (modified) (2 diffs)
-
trunk/includes/ai-gpt-client.php (modified) (22 diffs)
-
trunk/includes/core-init.php (modified) (23 diffs)
-
trunk/includes/parsers/ai-fallback-parser.php (modified) (4 diffs)
-
trunk/includes/rag-engine.php (modified) (12 diffs)
-
trunk/includes/settings-page.php (modified) (7 diffs)
-
trunk/includes/shareai-connect.php (added)
-
trunk/includes/shortcode-qa.php (modified) (2 diffs)
-
trunk/includes/uninstall-cleanup.php (modified) (2 diffs)
-
trunk/readme.txt (modified) (9 diffs)
-
trunk/templates/admin-dashboard.php (modified) (3 diffs)
-
trunk/templates/admin-mirror-mode.php (modified) (1 diff)
-
trunk/templates/admin-muse-mode.php (modified) (1 diff)
-
trunk/templates/admin-pro-features.php (modified) (5 diffs)
-
trunk/templates/admin-scan-website.php (modified) (2 diffs)
-
trunk/templates/admin-settings.php (modified) (11 diffs)
-
trunk/templates/admin-shareai-connect.php (added)
-
trunk/templates/partials/header.php (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
aiohm-knowledge-assistant/tags/3.1.0/README.md
r3801412 r3833232 13 13 - PDF, CSV, TXT and JSON document import 14 14 - Brand voice settings 15 - AI providers: OpenAI, Claude, Gemini, Groq and ShareAI15 - AI providers: ShareAI and Ollama, plus Google Gemini, OpenAI and Anthropic Claude when your site connects them in WordPress 7 Connectors 16 16 - Local AI with Ollama, so content can stay on your own server 17 - MCP endpoint, so MCP clients such as Claude Desktopcan query your knowledge base17 - MCP endpoint, so desktop and mobile MCP clients can query your knowledge base 18 18 - White-label mode for agencies 19 19 … … 22 22 - WordPress 6.2 or later 23 23 - PHP 7.4 or later 24 - A n API key for one AI provider, or a reachableOllama server24 - A ShareAI connection (Connect ShareAI), a Gemini API key, or a local Ollama server 25 25 26 26 ## Install … … 38 38 composer install --no-dev --optimize-autoloader 39 39 ``` 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. 40 49 41 50 ## Contributing -
aiohm-knowledge-assistant/tags/3.1.0/aiohm-knowledge-assistant.php
r3801412 r3833232 4 4 * Plugin URI: https://knowledge.aiohm.app/ 5 5 * 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.06 * Version: 3.1.0 7 7 * Author: OHM Events Agency 8 8 * Author URI: https://www.ohm.events … … 29 29 */ 30 30 31 define("AIOHM_KB_VERSION", "3. 0.0");31 define("AIOHM_KB_VERSION", "3.1.0"); 32 32 define("AIOHM_KB_PLUGIN_FILE", __FILE__); 33 33 define("AIOHM_KB_PLUGIN_DIR", plugin_dir_path(__FILE__)); … … 278 278 "shortcode-private-assistant.php", 279 279 "frontend-widget.php", 280 "shareai-connect.php", 280 281 ]; 281 282 … … 289 290 require_once $file_path; 290 291 } 292 } 293 294 if (class_exists("AIOHM_KB_ShareAI_Connect")) { 295 AIOHM_KB_ShareAI_Connect::init(); 291 296 } 292 297 … … 438 443 "external_api_consent" => true, 439 444 440 " openai_api_key" => "",445 "shareai_model" => "deepseek/deepseek-v4-flash", 441 446 "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",447 447 "private_llm_server_url" => "", 448 448 "private_llm_model" => "llama2", 449 "default_ai_provider" => " ollama",449 "default_ai_provider" => "shareai", 450 450 451 451 "pro_features" => [ … … 467 467 "qa_temperature" => "0.8", 468 468 "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", 469 473 ], 470 474 … … 511 515 } 512 516 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"]; 519 518 foreach ($encrypted_api_keys as $key) { 520 519 if (!empty($settings[$key])) { … … 528 527 } 529 528 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"]); 538 535 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); 540 598 } 541 599 } … … 979 1037 "aiohm_app_email" => "", 980 1038 981 " openai_api_key" => "",1039 "shareai_model" => "deepseek/deepseek-v4-flash", 982 1040 "gemini_api_key" => "", 983 "claude_api_key" => "",984 "shareai_api_key" => "",985 "shareai_model" => "llama4:17b-scout-16e-instruct-fp16",986 1041 "private_llm_server_url" => "", 987 1042 "private_llm_model" => "llama2", 988 "default_ai_provider" => " ",1043 "default_ai_provider" => "shareai", 989 1044 990 1045 "chat_enabled" => true, … … 1127 1182 * 1128 1183 * @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) 1130 1185 * @return string|WP_Error Sanitized API key or WP_Error if invalid 1131 1186 */ … … 1148 1203 1149 1204 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) { 1152 1208 return new WP_Error( 1153 "invalid_ openai_key",1209 "invalid_shareai_key", 1154 1210 __( 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.", 1167 1212 "aiohm-knowledge-assistant", 1168 1213 ), … … 1181 1226 } 1182 1227 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;1206 1228 } 1207 1229 … … 1370 1392 1371 1393 $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", 1376 1398 1377 1399 "/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 737 737 padding: 8px 16px; 738 738 } 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 12 12 } 13 13 14 /* 6-Column Grid Layout for all providers */14 /* 3-column grid layout for all providers */ 15 15 .aiohm-provider-grid { 16 16 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%; 18 22 gap: 12px; 19 23 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 }33 24 } 34 25 … … 125 116 126 117 /* Provider-specific icon styling */ 127 .aiohm-provider-option[data-provider="openai"] .aiohm-provider-icon {128 border-radius: 8px;129 overflow: hidden;130 }131 132 118 .aiohm-provider-option[data-provider="google"] .aiohm-provider-icon { 133 119 border-radius: 50%; 134 overflow: hidden;135 }136 137 .aiohm-provider-option[data-provider="anthropic"] .aiohm-provider-icon {138 border-radius: 8px;139 120 overflow: hidden; 140 121 } … … 328 309 outline-offset: 2px; 329 310 } 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 400 400 const apiValue = $('#' + targetInput).val(); 401 401 402 // Special handling for ShareAI - save both API key and model403 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 state417 $btn.prop('disabled', true).text('Saving...');418 419 // Save API key first, then model420 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 text430 $btn.prop('disabled', false).text(originalText);431 432 if (apiSaveSuccess && modelSaveSuccess) {433 // Success state434 $btn.addClass('success');435 showAdminNotice('ShareAI settings saved successfully!', 'success');436 437 // Now display the model information438 updateModelInfo(selectedModel);439 440 // Reset button state after 2 seconds441 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 key454 $.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: apiValue460 }).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 selection472 $.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: selectedModel478 }).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 ShareAI490 }491 402 492 403 // Standard handling for other API providers … … 502 413 let settingName; 503 414 switch(apiType) { 504 case 'openai':505 settingName = 'openai_api_key';506 break;507 415 case 'gemini': 508 416 settingName = 'gemini_api_key'; 509 break;510 case 'claude':511 settingName = 'claude_api_key';512 417 break; 513 418 case 'ollama': -
aiohm-knowledge-assistant/tags/3.1.0/assets/js/aiohm-admin-settings.js
r3545079 r3833232 116 116 // Map key types to setting names 117 117 const settingMap = { 118 'shareai': 'shareai_api_key',119 'openai': 'openai_api_key',120 118 'gemini': 'gemini_api_key', 121 'claude': 'claude_api_key',122 'groq': 'groq_api_key',123 119 'ollama': 'private_llm_server_url' 124 120 }; … … 322 318 323 319 // Update breakdown table 324 const providers = [' openai', 'gemini', 'claude', 'shareai'];320 const providers = ['shareai', 'gemini', 'ollama']; 325 321 providers.forEach(provider => { 326 322 const providerData = data.providers?.[provider] || {}; -
aiohm-knowledge-assistant/tags/3.1.0/includes/ai-gpt-client.php
r3801374 r3833232 2 2 /** 3 3 * AI client for multi-provider API requests 4 * Handles OpenAI, Google Gemini, Claude, and ShareAIintegrations4 * Handles ShareAI, Google Gemini and Ollama integrations 5 5 */ 6 6 if ( ! defined( 'ABSPATH' ) ) { 7 7 exit; 8 } 9 10 if ( ! 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 21 if ( ! 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 33 if ( ! 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 49 if ( ! 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 61 if ( ! 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 74 if ( ! 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 89 if ( ! 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 114 if ( ! 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 145 if ( ! 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 176 if ( ! 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 } 8 190 } 9 191 … … 34 216 return 'gemini'; 35 217 } 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 }45 218 if ( false !== strpos( $haystack, 'shareai' ) ) { 46 219 return 'shareai'; … … 49 222 return 'ollama'; 50 223 } 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 } 51 230 52 231 return sanitize_key( $provider_id ); … … 62 241 */ 63 242 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 65 249 $env_names = array(); 66 250 $constant_names = array(); … … 68 252 69 253 $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( 71 260 'env' => array( 'OPENAI_API_KEY' ), 72 261 'const' => array( 'OPENAI_API_KEY' ), 73 262 'options' => array( 'connectors_ai_openai_api_key' ), 74 263 ), 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' ), 84 268 ), 85 269 ); … … 136 320 if ( is_array( $legacy_credentials ) ) { 137 321 $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' ), 141 325 ); 142 326 … … 167 351 168 352 private $settings; 169 private $openai_api_key;170 353 private $gemini_api_key; 171 private $claude_api_key;172 private $shareai_api_key;173 private $groq_api_key;174 354 private $ollama_server_url; 175 355 private $ollama_model; … … 181 361 $this->settings = $settings; 182 362 } 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'] ?? ''; 189 364 if ( empty( $this->gemini_api_key ) ) { 190 365 $this->gemini_api_key = aiohm_kb_get_wp_connector_api_key( 'gemini' ); 191 366 } 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'] ?? '';197 367 198 368 // Ollama settings - check both pro_features and legacy settings … … 213 383 * Check if API key is properly configured for the given provider 214 384 * 215 * @param string $provider The AI provider ( openai, gemini, claude, shareai, groq, ollama)385 * @param string $provider The AI provider (shareai, gemini, ollama) 216 386 * @return bool True if API key is configured 217 387 */ 218 388 public function is_api_key_configured( $provider ) { 219 389 switch ( $provider ) { 220 case ' openai':221 return ! empty( $this->openai_api_key);390 case 'shareai': 391 return aiohm_kb_shareai_available( $this->settings ); 222 392 case 'gemini': 223 393 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 );230 394 case 'ollama': 231 395 return ! empty( $this->ollama_server_url ); … … 371 535 if ( is_string( $data ) ) { 372 536 $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', 376 540 '/AIza[a-zA-Z0-9_-]{35}/' => 'GEMINI_API_KEY_HIDDEN', 377 541 '/[a-zA-Z0-9_-]{32,}/' => 'POTENTIAL_API_KEY_HIDDEN', … … 411 575 } 412 576 413 $provider = $this->settings['default_ai_provider'] ?? 'openai';577 $provider = aiohm_kb_resolve_ai_provider( $this->settings['default_ai_provider'] ?? '', $this->settings ); 414 578 415 579 switch ( $provider ) { 416 580 case 'gemini': 417 581 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 );422 582 case 'ollama': 423 583 return $this->generate_ollama_embeddings( $text ); 424 584 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': 425 589 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 ); 453 591 } 454 592 } … … 483 621 } 484 622 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 491 623 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 492 645 // ShareAI API does not currently have a dedicated embedding endpoint. 493 646 // This functionality is not supported. … … 496 649 497 650 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; 525 713 } 526 714 … … 578 766 } 579 767 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 627 768 private function get_shareai_chat_completion( $system_message, $user_message, $temperature, $model ) { 628 769 // WordPress.org compliance: Check for ShareAI consent … … 631 772 } 632 773 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.' ); 838 788 } 839 789 … … 844 794 845 795 $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' ) { 849 797 $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;857 798 } 858 799 … … 955 896 } 956 897 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() ) { 959 906 return array( 960 907 'success' => false, 961 'error' => ' Claude API key is missing.',908 'error' => 'ShareAI is not connected. Click Connect ShareAI in the AIOHM settings.', 962 909 ); 963 910 } 964 911 try { 965 $this->get_chat_completion( 'Test prompt', "Say 'hello'.", 0.5, 'claude-3-sonnet');912 AIOHM_KB_ShareAI_Connect::access_token(); 966 913 return array( 'success' => true ); 967 914 } catch ( Exception $e ) { … … 973 920 } 974 921 975 public function test_shareai_api_connection() {976 // WordPress.org compliance: Check for ShareAI consent977 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 corruption996 if ( preg_match( '/[^A-Za-z0-9\-_.]/', $this->shareai_api_key ) ) {997 }998 999 // First test basic connectivity without auth1000 $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 tokens1006 $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 test1032 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 information1041 $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 successful1078 $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 test1099 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 response1111 *1112 * @param array $decoded The decoded API response1113 * @return array Usage information1114 */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 data1126 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 root1136 $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 work1149 $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 consumption1161 );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 format1202 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 tokens1227 *1228 * @return array Usage information or error1229 */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 response1278 $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 data1288 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 root1297 $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 1316 922 /** 1317 923 * Get the current AI provider based on settings … … 1320 926 */ 1321 927 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 ); 1339 929 } 1340 930 … … 1354 944 if ( ! $model ) { 1355 945 $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 ); 1369 950 } 1370 951 } 1371 952 1372 953 return $this->get_chat_completion( '', $prompt, $temperature, $model ); 1373 }1374 1375 /**1376 * Test Groq API connection1377 *1378 * @return array Result with success status and message1379 */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 testing1390 $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 }1446 954 } 1447 955 … … 1460 968 1461 969 // Future implementation would handle direct file uploads to: 1462 // - OpenAI's file upload API970 // - ShareAI document models 1463 971 // - Gemini's document processing 1464 // - Claude's document analysis972 // - Local Ollama vision models 1465 973 1466 974 throw new Exception( 'Direct file processing not yet implemented. Use text extraction approach.' ); … … 1575 1083 } 1576 1084 } 1085 1086 if ( ! 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 517 517 */ 518 518 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); 534 520 } 535 521 … … 1003 989 $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider); 1004 990 } 1005 $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];991 $provider_priority = aiohm_kb_ai_provider_ids(); 1006 992 1007 993 // If no default set, find first available provider … … 1026 1012 1027 1013 // 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); 1045 1015 1046 1016 // Enhanced formatting instructions for better readability … … 1102 1072 1103 1073 public static function handle_frontend_chat_ajax() { 1104 // Enhanced rate limiting for chat requests - stricter for public endpoints1105 $user_id = get_current_user_id() ?: 0;1106 $rate_limit = $user_id > 0 ? 50 : 20; // Lower limit for non-authenticated users1107 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 1112 1074 if (!check_ajax_referer('aiohm_chat_nonce', 'nonce', false)) { 1113 1075 wp_send_json_error(['reply' => __('Security check failed.', 'aiohm-knowledge-assistant')]); 1114 1076 } 1115 1116 // Additional validation for public endpoints1117 1077 if (!isset($_POST['message']) || !is_string($_POST['message'])) { 1118 1078 wp_send_json_error(['reply' => __('Invalid message format.', 'aiohm-knowledge-assistant')]); … … 1120 1080 1121 1081 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 { 1144 1123 $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; 1165 1171 break; 1166 1172 } 1167 1173 } 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 { 1239 1190 $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 placeholders1242 // Use strtr instead of str_replace to avoid partial matches and conflicts1243 $final_answer = strtr($answer, $replacements);1244 1245 wp_send_json_success(['reply' => $final_answer]);1246 1247 1191 } 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 ]; 1250 1207 } 1251 1208 … … 1435 1392 $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider); 1436 1393 } 1437 $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];1394 $provider_priority = aiohm_kb_ai_provider_ids(); 1438 1395 1439 1396 // If no default set, find first available provider … … 1458 1415 1459 1416 // 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); 1477 1418 1478 1419 $answer = $ai_client->get_chat_completion($final_system_message, $user_message, $temperature, $model); … … 1503 1444 $system_prompt = wp_kses_post($posted_settings['system_prompt'] ?? 'You are a helpful brand assistant.'); 1504 1445 $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'] ?? ''); 1506 1447 1507 1448 // Initialize AI client with current settings … … 1554 1495 // Check prerequisites - validate API key for selected provider 1555 1496 $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); 1560 1498 1561 1499 // Check if the selected default provider has proper configuration 1562 1500 $api_key_exists = false; 1563 1501 $provider_names = [ 1502 'shareai' => 'ShareAI', 1503 'gemini' => 'Gemini', 1504 'ollama' => 'Ollama', 1564 1505 'openai' => 'OpenAI', 1565 'gemini' => 'Gemini', 1566 'claude' => 'Claude', 1567 'shareai' => 'ShareAI', 1568 'groq' => 'Groq', 1569 'ollama' => 'Ollama' 1506 'anthropic' => 'Anthropic' 1570 1507 ]; 1571 1508 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); 1596 1510 1597 1511 if (!$api_key_exists) { … … 1727 1641 $api_key = ''; 1728 1642 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' : ''; 1734 1646 break; 1735 1647 case 'gemini': … … 1739 1651 } 1740 1652 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;1753 1653 } 1754 1654 … … 1758 1658 try { 1759 1659 switch ($key_type) { 1760 case ' openai':1660 case 'shareai': 1761 1661 $ai_client = new AIOHM_KB_AI_GPT_Client($settings); 1762 $result = $ai_client->test_ api_connection();1662 $result = $ai_client->test_shareai_api_connection(); 1763 1663 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')]); 1765 1665 } else { 1766 // translators: %s is the OpenAI API error message1767 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')))]); 1768 1668 } 1769 1669 break; … … 1778 1678 } 1779 1679 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 message1787 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 message1797 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 message1807 wp_send_json_error(['message' => sprintf(__('Groq connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);1808 }1809 break;1810 1680 default: 1811 1681 wp_send_json_error(['message' => __('Invalid key type specified.', 'aiohm-knowledge-assistant')]); … … 1855 1725 1856 1726 // 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') { 1858 1734 // Validate API key format using new validation function 1859 1735 $provider = str_replace('_api_key', '', $setting_name); … … 1866 1742 // Encrypt the validated API key 1867 1743 $current_settings[$setting_name] = AIOHM_KB_Assistant::encrypt_api_key($validated_key); 1868 } elseif ($setting_name === 'shareai_api_key') {1869 // Validate ShareAI key1870 $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;1877 1744 } else { 1878 1745 // For non-API keys (like models), save as plain text with additional validation … … 1936 1803 wp_send_json_success(['message' => __('ShareAI model saved successfully!', 'aiohm-knowledge-assistant')]); 1937 1804 } 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) 1939 1806 wp_send_json_success(['message' => sprintf(__('%s API key saved successfully!', 'aiohm-knowledge-assistant'), ucfirst($api_type))]); 1940 1807 } … … 2406 2273 $settings['mirror_mode']['ai_avatar'] = esc_url_raw($settings_input['ai_avatar'] ?? ''); 2407 2274 $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'] ?? ''); 2409 2276 2410 2277 // Handle URL sanitization with proper validation … … 2501 2368 } 2502 2369 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'] ?? ''); 2504 2371 $settings['muse_mode']['temperature'] = floatval($muse_input['temperature'] ?? 0.7); 2505 2372 $settings['muse_mode']['start_fullscreen'] = isset($muse_input['start_fullscreen']) ? 1 : 0; … … 2555 2422 } else { 2556 2423 // 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); 2576 2426 } 2577 2427 … … 4024 3874 // Format provider data 4025 3875 $providers = [ 4026 ' openai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],3876 'shareai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'], 4027 3877 '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'] 4030 3879 ]; 4031 3880 … … 4369 4218 $research_prompt, 4370 4219 0.3, 4371 $settings['muse_mode']['ai_model'] ?? ' gpt-3.5-turbo'4220 $settings['muse_mode']['ai_model'] ?? '' 4372 4221 ); 4373 4222 … … 5566 5415 // Test each configured API 5567 5416 $apis_to_test = [ 5568 ' openai' => $settings['openai_api_key'] ??'',5417 'shareai' => aiohm_kb_shareai_available($settings) ? 'connected' : '', 5569 5418 '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'] ?? '')) : '' 5572 5420 ]; 5573 5421 … … 5589 5437 5590 5438 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(); 5593 5441 break; 5594 5442 case 'gemini': 5595 5443 $test_result = $ai_client->test_gemini_api_connection(); 5596 5444 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(); 5602 5447 break; 5603 5448 } -
aiohm-knowledge-assistant/tags/3.1.0/includes/parsers/ai-fallback-parser.php
r3545079 r3833232 64 64 $settings = AIOHM_KB_Assistant::get_settings(); 65 65 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 ) ) { 70 69 return true; 71 70 } 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;98 71 } 99 72 … … 469 442 $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.'; 470 443 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 ); 472 449 473 450 if ( empty( $response ) ) { … … 545 522 546 523 /** 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 /** 547 544 * Get AI model information 548 545 * … … 552 549 $settings = AIOHM_KB_Assistant::get_settings(); 553 550 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 ); 594 568 } 595 569 -
aiohm-knowledge-assistant/tags/3.1.0/includes/rag-engine.php
r3801374 r3833232 51 51 } 52 52 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 ); 53 92 } 54 93 … … 104 143 $successful_inserts = 0; 105 144 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 ); 111 147 112 148 $chunk_metadata = array_merge( $metadata, array( … … 121 157 'title' => $title, 122 158 'content' => $chunk, 123 'vector_data' => json_encode( $embedding ),159 'vector_data' => null === $embedding ? null : json_encode( $embedding ), 124 160 'metadata' => json_encode( $chunk_metadata ), 125 161 'is_public' => $is_public, … … 197 233 198 234 $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 ); 204 237 205 238 $metadata = array( … … 216 249 'title' => $title, 217 250 'content' => $chunk, 218 'vector_data' => json_encode( $embedding ),251 'vector_data' => null === $embedding ? null : json_encode( $embedding ), 219 252 'metadata' => json_encode( $metadata ), 220 253 'is_public' => 0, … … 282 315 $system_message_key = ( $scope === 'private' ) ? 'system_prompt' : 'qa_system_message'; 283 316 $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'] ?? ''; 285 318 $temperature = $ai_settings['temperature'] ?? 0.7; 286 319 … … 465 498 } 466 499 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 ); 469 503 470 504 $keywords = preg_replace( '/[^a-z0-9\s]/i', '', strtolower( $query_text ) ); … … 472 506 $table_name = $this->table_name; 473 507 $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 } 474 531 475 532 if ( ! empty( trim( $keywords ) ) ) { … … 571 628 } 572 629 630 if ( null === $query_embedding ) { 631 return array(); 632 } 633 573 634 // Recheck persisted visibility even for cached candidates, so revocation is immediate. 574 635 $pre_filtered_entries = $this->filter_public_context_entries( $pre_filtered_entries ); 575 636 $similarities = array(); 576 637 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 ); 588 645 } 589 646 } … … 1122 1179 public function find_context_for_user( $query_text, $user_id, $limit = 5 ) { 1123 1180 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 ); 1126 1182 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 1127 1183 // User context search query requires direct database access for vector similarity operations … … 1129 1185 // Validate table name for security 1130 1186 $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 } 1131 1212 1132 1213 $all_entries = $wpdb->get_results( … … 1141 1222 foreach ( $all_entries as $entry ) { 1142 1223 $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 ); 1153 1230 } 1154 1231 } -
aiohm-knowledge-assistant/tags/3.1.0/includes/settings-page.php
r3801374 r3833232 160 160 161 161 // 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' ) ); 163 163 164 164 // Get Help page … … 989 989 : sanitize_key( $setting_value ); 990 990 991 if ( ! in_array( $setting_value, a rray( 'shareai', 'openai', 'claude', 'gemini', 'groq', 'ollama'), true ) ) {991 if ( ! in_array( $setting_value, aiohm_kb_ai_provider_ids(), true ) ) { 992 992 wp_send_json_error( 'Invalid AI provider selected' ); 993 993 return; … … 1093 1093 1094 1094 // 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' ); 1096 1096 foreach ( $api_keys as $field ) { 1097 1097 if ( isset( $input[ $field ] ) ) { … … 1110 1110 } 1111 1111 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'] ); 1115 1120 } 1116 1121 … … 1128 1133 ? aiohm_kb_normalize_wp_ai_provider_id( $input['default_ai_provider'] ) 1129 1134 : sanitize_key( $input['default_ai_provider'] ); 1130 if ( in_array( $provider, a rray( 'shareai', 'openai', 'claude', 'gemini', 'groq', 'ollama'), true ) ) {1135 if ( in_array( $provider, aiohm_kb_ai_provider_ids(), true ) ) { 1131 1136 $sanitized['default_ai_provider'] = $provider; 1132 1137 } … … 1202 1207 $temperature = floatval( $muse_settings['temperature'] ?? 0.7 ); 1203 1208 $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'] ?? ''; 1205 1210 1206 1211 // Initialize AI client … … 1208 1213 1209 1214 // Check if any AI provider is configured 1210 $providers = a rray( 'openai', 'gemini', 'claude', 'groq', 'shareai');1215 $providers = aiohm_kb_ai_provider_ids(); 1211 1216 $has_api_key = false; 1212 1217 foreach ( $providers as $provider ) { -
aiohm-knowledge-assistant/tags/3.1.0/includes/shortcode-qa.php
r3545079 r3833232 99 99 100 100 // 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 } 124 108 125 109 if ( ! $has_api_key ) { … … 138 122 } else { 139 123 // 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 ); 156 126 } 157 127 -
aiohm-knowledge-assistant/tags/3.1.0/includes/uninstall-cleanup.php
r3801374 r3833232 13 13 function aiohm_kb_uninstall_cleanup() 14 14 { 15 // ShareAI tokens never outlive the plugin, whatever the data setting. 16 aiohm_kb_uninstall_shareai(); 17 15 18 // Check if user wants to delete data on uninstall 16 19 $settings = get_option("aiohm_kb_settings", []); … … 93 96 wp_cache_flush(); 94 97 } 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 */ 104 function 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 === 2 2 Contributors: ohmevents 3 3 Tags: ai assistant, knowledge base, chatbot, brand voice, personalized ai 4 4 Requires at least: 6.2 5 5 Tested up to: 7.1 6 Stable tag: 3. 0.06 Stable tag: 3.1.0 7 7 Requires PHP: 7.4 8 8 License: GPLv2 or later … … 21 21 * **Public Chatbot**: Add an intelligent chatbot to your website that answers visitor questions based on your content 22 22 * **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 ShareAI23 * **Multi-Provider AI Support**: Choose from ShareAI, Google Gemini or a local Ollama server 24 24 * **Brand Voice Configuration**: Set up your chatbot's personality and communication style 25 25 * **Content Processing**: Support for PDF, CSV, TXT, and JSON document formats … … 34 34 * Automatic indexing of WordPress posts, pages, and uploaded files 35 35 * Support for PDF, CSV, TXT, and JSON document formats 36 * Advanced semantic search with vectorembeddings36 * Full-text search on every setup, plus semantic search when Gemini or Ollama provides embeddings 37 37 * Smart content chunking for optimal AI processing 38 38 39 39 **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) 45 43 * **Ollama Local AI for completely private, on-premise processing** 46 44 * ServBay Ollama server integration for development environments … … 92 90 * WordPress 6.2 or higher 93 91 * PHP 7.4 or higher 94 * A PI 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 95 93 * Optional: Paid Memberships Pro for advanced access control 96 94 97 95 ## Privacy & External Services 98 96 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.97 This 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. 100 98 101 99 **Supported AI Services:** 102 100 * 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/)104 101 * 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. 107 104 108 105 User 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):** 108 ShareAI 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/). 109 115 110 116 == Installation == … … 112 118 1. Upload the plugin files to `/wp-content/plugins/aiohm-knowledge-assistant/` 113 119 2. Activate the plugin through the WordPress Plugins menu 114 3. Navigate to AIOHM > Settings and c onfigure your AI provider API key120 3. Navigate to AIOHM > Settings and click Connect ShareAI, or add a Gemini API key, or point AIOHM at your Ollama server 115 121 4. Run the content scan to build your knowledge base 116 122 5. Configure your brand voice settings … … 121 127 = What AI providers are supported? = 122 128 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. 129 AIOHM 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 133 Yes, 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. 124 134 125 135 = How does this differ from other AI chatbot plugins? = … … 169 179 170 180 == 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. 171 197 172 198 = 3.0.0 = … … 308 334 == Upgrade Notice == 309 335 336 = 3.1.0 = 337 ShareAI 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 310 339 = 1.4.1 = 311 340 CRITICAL FIX: Resolves knowledge base content not appearing after scanning. Essential update for users experiencing empty manage knowledge base tables after content scanning operations. … … 322 351 == Screenshots == 323 352 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 353 1. **Answers from your content** - The live preview answers a visitor question from the site's own pages 354 2. **Connect ShareAI** - Connect your ShareAI account once, with the 10% builder markup shown up front 355 3. **Scan your site** - Posts, pages, products and media files ready to index 356 4. **Knowledge base manager** - Choose what is public and what stays private 357 5. **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 47 47 <div class="benefit"> 48 48 <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 keyto 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> 50 50 <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> 51 51 </div> … … 77 77 <div class="benefit"> 78 78 <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> 80 80 </div> 81 81 <div class="benefit"> … … 110 110 <div class="benefit"> 111 111 <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> 113 113 <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> 114 114 </div> -
aiohm-knowledge-assistant/tags/3.1.0/templates/admin-mirror-mode.php
r3545079 r3833232 107 107 </div> 108 108 <?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 } 135 121 ?> 136 122 <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> 146 130 <?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> 152 133 <?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> 158 141 <?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> 164 144 <?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> 170 147 <?php endif; ?> 171 148 </select> -
aiohm-knowledge-assistant/tags/3.1.0/templates/admin-muse-mode.php
r3545079 r3833232 175 175 </div> 176 176 <?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 } 203 189 ?> 204 190 <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> 214 198 <?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> 220 201 <?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> 226 209 <?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> 232 212 <?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> 238 215 <?php endif; ?> 239 216 </select> -
aiohm-knowledge-assistant/tags/3.1.0/templates/admin-pro-features.php
r3801374 r3833232 40 40 41 41 <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> 43 43 <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> 44 44 … … 281 281 <th scope="row"><?php esc_html_e('Token Name', 'aiohm-knowledge-assistant'); ?></th> 282 282 <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"> 284 284 <p class="description"><?php esc_html_e('A descriptive name to identify this token', 'aiohm-knowledge-assistant'); ?></p> 285 285 </td> … … 339 339 <div class="aiohm-save-section"> 340 340 <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 FeaturesSettings', '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' ); ?>"> 342 342 </p> 343 343 </div> … … 548 548 success: function(response) { 549 549 console.log('AJAX response:', response); 550 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Pro FeaturesSettings', 'aiohm-knowledge-assistant' ); ?>');550 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>'); 551 551 552 552 if (response.success) { … … 573 573 error: function(xhr, status, error) { 574 574 console.error('AJAX error:', xhr, status, error); 575 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Pro FeaturesSettings', 'aiohm-knowledge-assistant' ); ?>');575 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>'); 576 576 $('#aiohm-admin-notice').removeClass('notice-success notice-info').addClass('notice-error').find('p').text('Save failed: ' + error); 577 577 } -
aiohm-knowledge-assistant/tags/3.1.0/templates/admin-scan-website.php
r3545079 r3833232 9 9 // The controller (settings-page.php) prepares these variables before including this template. 10 10 $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 ); 58 15 59 16 // Also get provider display name for better error messaging 60 17 $aiohm_provider_names = array( 61 ' openai' => 'OpenAI',18 'shareai' => 'ShareAI', 62 19 'gemini' => 'Gemini', 63 'claude' => 'Claude', 64 'shareai' => 'ShareAI', 20 'ollama' => 'Ollama', 65 21 ); 66 22 $aiohm_current_provider_name = $aiohm_provider_names[ $aiohm_default_provider ] ?? 'Unknown Provider'; … … 81 37 <?php 82 38 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) */ 84 40 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' ), 85 41 esc_html( $aiohm_current_provider_name ) -
aiohm-knowledge-assistant/tags/3.1.0/templates/admin-settings.php
r3801374 r3833232 24 24 </div> 25 25 26 <?php include AIOHM_KB_PLUGIN_DIR . 'templates/admin-shareai-connect.php'; ?> 26 27 27 28 <form id="aiohm-settings-form" method="post" action="options.php"> … … 36 37 <div class="aiohm-shareai-settings-box"> 37 38 <?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' ); 61 43 62 44 // Check for Ollama … … 64 46 $aiohm_has_ollama = ! empty( $aiohm_pro_features['ollama_enabled'] ); 65 47 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; 67 51 $aiohm_enabled_provider_values = array(); 68 52 foreach ( 69 53 array( 70 54 'shareai' => $aiohm_has_shareai, 71 'openai' => $aiohm_has_openai,72 'claude' => $aiohm_has_claude,73 55 'gemini' => $aiohm_has_gemini, 74 'groq' => $aiohm_has_groq,75 56 'ollama' => $aiohm_has_ollama, 57 'openai' => $aiohm_has_openai, 58 'anthropic' => $aiohm_has_anthropic, 76 59 ) as $aiohm_provider_value => $aiohm_provider_enabled 77 60 ) { … … 96 79 <div class="shareai-setting-row"> 97 80 98 <!-- All AI Providers ( 6-column grid) -->81 <!-- All AI Providers (3-column grid) --> 99 82 <div class="aiohm-provider-selection aiohm-provider-grid"> 100 83 <label class="aiohm-provider-option <?php echo ! $aiohm_has_shareai ? 'disabled' : ''; ?>" data-provider="shareai"> 101 84 <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' : ''; ?>> 102 85 <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"> 104 87 </div> 105 88 <div class="aiohm-provider-info"> 106 89 <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> 108 91 </div> 109 92 <?php if ( ! $aiohm_has_shareai ) : ?> … … 112 95 </label> 113 96 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 170 97 <label class="aiohm-provider-option <?php echo ! $aiohm_has_ollama ? 'disabled' : ''; ?>" data-provider="ollama"> 171 98 <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' : ''; ?>> … … 175 102 <div class="aiohm-provider-info"> 176 103 <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> 178 105 </div> 179 106 <?php if ( ! $aiohm_has_ollama ) : ?> … … 181 108 <?php endif; ?> 182 109 </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; ?> 183 149 184 150 </div> … … 225 191 <div class="aiohm-privacy-notice"> 226 192 <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> 228 194 </div> 229 195 </div> … … 232 198 </div> 233 199 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 <?php298 printf(299 wp_kses(300 // translators: %s is the URL to the ShareAI Console301 __( '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 349 200 <?php $aiohm_uses_wp_connectors = function_exists( 'wp_get_connectors' ); ?> 350 201 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"> 354 204 <div class="aiohm-premium-column"> 355 205 <!-- Gemini --> … … 370 220 printf( 371 221 wp_kses( 222 /* translators: %s: Google AI Studio URL */ 372 223 __( 'You can get your Gemini API key from the <a href="%s" target="_blank">Google AI Studio</a>.', 'aiohm-knowledge-assistant' ), 373 224 array( … … 383 234 </p> 384 235 </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 <?php401 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>416 236 </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; ?> 526 239 527 240 <div class="aiohm-card"> -
aiohm-knowledge-assistant/tags/3.1.0/templates/partials/header.php
r3801374 r3833232 39 39 <li> 40 40 <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' ); ?> 42 42 </a> 43 43 </li> -
aiohm-knowledge-assistant/trunk/README.md
r3801412 r3833232 13 13 - PDF, CSV, TXT and JSON document import 14 14 - Brand voice settings 15 - AI providers: OpenAI, Claude, Gemini, Groq and ShareAI15 - AI providers: ShareAI and Ollama, plus Google Gemini, OpenAI and Anthropic Claude when your site connects them in WordPress 7 Connectors 16 16 - Local AI with Ollama, so content can stay on your own server 17 - MCP endpoint, so MCP clients such as Claude Desktopcan query your knowledge base17 - MCP endpoint, so desktop and mobile MCP clients can query your knowledge base 18 18 - White-label mode for agencies 19 19 … … 22 22 - WordPress 6.2 or later 23 23 - PHP 7.4 or later 24 - A n API key for one AI provider, or a reachableOllama server24 - A ShareAI connection (Connect ShareAI), a Gemini API key, or a local Ollama server 25 25 26 26 ## Install … … 38 38 composer install --no-dev --optimize-autoloader 39 39 ``` 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. 40 49 41 50 ## Contributing -
aiohm-knowledge-assistant/trunk/aiohm-knowledge-assistant.php
r3801412 r3833232 4 4 * Plugin URI: https://knowledge.aiohm.app/ 5 5 * 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.06 * Version: 3.1.0 7 7 * Author: OHM Events Agency 8 8 * Author URI: https://www.ohm.events … … 29 29 */ 30 30 31 define("AIOHM_KB_VERSION", "3. 0.0");31 define("AIOHM_KB_VERSION", "3.1.0"); 32 32 define("AIOHM_KB_PLUGIN_FILE", __FILE__); 33 33 define("AIOHM_KB_PLUGIN_DIR", plugin_dir_path(__FILE__)); … … 278 278 "shortcode-private-assistant.php", 279 279 "frontend-widget.php", 280 "shareai-connect.php", 280 281 ]; 281 282 … … 289 290 require_once $file_path; 290 291 } 292 } 293 294 if (class_exists("AIOHM_KB_ShareAI_Connect")) { 295 AIOHM_KB_ShareAI_Connect::init(); 291 296 } 292 297 … … 438 443 "external_api_consent" => true, 439 444 440 " openai_api_key" => "",445 "shareai_model" => "deepseek/deepseek-v4-flash", 441 446 "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",447 447 "private_llm_server_url" => "", 448 448 "private_llm_model" => "llama2", 449 "default_ai_provider" => " ollama",449 "default_ai_provider" => "shareai", 450 450 451 451 "pro_features" => [ … … 467 467 "qa_temperature" => "0.8", 468 468 "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", 469 473 ], 470 474 … … 511 515 } 512 516 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"]; 519 518 foreach ($encrypted_api_keys as $key) { 520 519 if (!empty($settings[$key])) { … … 528 527 } 529 528 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"]); 538 535 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); 540 598 } 541 599 } … … 979 1037 "aiohm_app_email" => "", 980 1038 981 " openai_api_key" => "",1039 "shareai_model" => "deepseek/deepseek-v4-flash", 982 1040 "gemini_api_key" => "", 983 "claude_api_key" => "",984 "shareai_api_key" => "",985 "shareai_model" => "llama4:17b-scout-16e-instruct-fp16",986 1041 "private_llm_server_url" => "", 987 1042 "private_llm_model" => "llama2", 988 "default_ai_provider" => " ",1043 "default_ai_provider" => "shareai", 989 1044 990 1045 "chat_enabled" => true, … … 1127 1182 * 1128 1183 * @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) 1130 1185 * @return string|WP_Error Sanitized API key or WP_Error if invalid 1131 1186 */ … … 1148 1203 1149 1204 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) { 1152 1208 return new WP_Error( 1153 "invalid_ openai_key",1209 "invalid_shareai_key", 1154 1210 __( 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.", 1167 1212 "aiohm-knowledge-assistant", 1168 1213 ), … … 1181 1226 } 1182 1227 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;1206 1228 } 1207 1229 … … 1370 1392 1371 1393 $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", 1376 1398 1377 1399 "/AIza[a-zA-Z0-9_-]{35}/" => "GEMINI_API_KEY_HIDDEN", -
aiohm-knowledge-assistant/trunk/assets/css/aiohm-admin-settings.css
r3545079 r3833232 737 737 padding: 8px 16px; 738 738 } 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 12 12 } 13 13 14 /* 6-Column Grid Layout for all providers */14 /* 3-column grid layout for all providers */ 15 15 .aiohm-provider-grid { 16 16 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%; 18 22 gap: 12px; 19 23 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 }33 24 } 34 25 … … 125 116 126 117 /* Provider-specific icon styling */ 127 .aiohm-provider-option[data-provider="openai"] .aiohm-provider-icon {128 border-radius: 8px;129 overflow: hidden;130 }131 132 118 .aiohm-provider-option[data-provider="google"] .aiohm-provider-icon { 133 119 border-radius: 50%; 134 overflow: hidden;135 }136 137 .aiohm-provider-option[data-provider="anthropic"] .aiohm-provider-icon {138 border-radius: 8px;139 120 overflow: hidden; 140 121 } … … 328 309 outline-offset: 2px; 329 310 } 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 400 400 const apiValue = $('#' + targetInput).val(); 401 401 402 // Special handling for ShareAI - save both API key and model403 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 state417 $btn.prop('disabled', true).text('Saving...');418 419 // Save API key first, then model420 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 text430 $btn.prop('disabled', false).text(originalText);431 432 if (apiSaveSuccess && modelSaveSuccess) {433 // Success state434 $btn.addClass('success');435 showAdminNotice('ShareAI settings saved successfully!', 'success');436 437 // Now display the model information438 updateModelInfo(selectedModel);439 440 // Reset button state after 2 seconds441 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 key454 $.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: apiValue460 }).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 selection472 $.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: selectedModel478 }).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 ShareAI490 }491 402 492 403 // Standard handling for other API providers … … 502 413 let settingName; 503 414 switch(apiType) { 504 case 'openai':505 settingName = 'openai_api_key';506 break;507 415 case 'gemini': 508 416 settingName = 'gemini_api_key'; 509 break;510 case 'claude':511 settingName = 'claude_api_key';512 417 break; 513 418 case 'ollama': -
aiohm-knowledge-assistant/trunk/assets/js/aiohm-admin-settings.js
r3545079 r3833232 116 116 // Map key types to setting names 117 117 const settingMap = { 118 'shareai': 'shareai_api_key',119 'openai': 'openai_api_key',120 118 'gemini': 'gemini_api_key', 121 'claude': 'claude_api_key',122 'groq': 'groq_api_key',123 119 'ollama': 'private_llm_server_url' 124 120 }; … … 322 318 323 319 // Update breakdown table 324 const providers = [' openai', 'gemini', 'claude', 'shareai'];320 const providers = ['shareai', 'gemini', 'ollama']; 325 321 providers.forEach(provider => { 326 322 const providerData = data.providers?.[provider] || {}; -
aiohm-knowledge-assistant/trunk/includes/ai-gpt-client.php
r3801374 r3833232 2 2 /** 3 3 * AI client for multi-provider API requests 4 * Handles OpenAI, Google Gemini, Claude, and ShareAIintegrations4 * Handles ShareAI, Google Gemini and Ollama integrations 5 5 */ 6 6 if ( ! defined( 'ABSPATH' ) ) { 7 7 exit; 8 } 9 10 if ( ! 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 21 if ( ! 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 33 if ( ! 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 49 if ( ! 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 61 if ( ! 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 74 if ( ! 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 89 if ( ! 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 114 if ( ! 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 145 if ( ! 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 176 if ( ! 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 } 8 190 } 9 191 … … 34 216 return 'gemini'; 35 217 } 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 }45 218 if ( false !== strpos( $haystack, 'shareai' ) ) { 46 219 return 'shareai'; … … 49 222 return 'ollama'; 50 223 } 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 } 51 230 52 231 return sanitize_key( $provider_id ); … … 62 241 */ 63 242 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 65 249 $env_names = array(); 66 250 $constant_names = array(); … … 68 252 69 253 $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( 71 260 'env' => array( 'OPENAI_API_KEY' ), 72 261 'const' => array( 'OPENAI_API_KEY' ), 73 262 'options' => array( 'connectors_ai_openai_api_key' ), 74 263 ), 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' ), 84 268 ), 85 269 ); … … 136 320 if ( is_array( $legacy_credentials ) ) { 137 321 $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' ), 141 325 ); 142 326 … … 167 351 168 352 private $settings; 169 private $openai_api_key;170 353 private $gemini_api_key; 171 private $claude_api_key;172 private $shareai_api_key;173 private $groq_api_key;174 354 private $ollama_server_url; 175 355 private $ollama_model; … … 181 361 $this->settings = $settings; 182 362 } 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'] ?? ''; 189 364 if ( empty( $this->gemini_api_key ) ) { 190 365 $this->gemini_api_key = aiohm_kb_get_wp_connector_api_key( 'gemini' ); 191 366 } 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'] ?? '';197 367 198 368 // Ollama settings - check both pro_features and legacy settings … … 213 383 * Check if API key is properly configured for the given provider 214 384 * 215 * @param string $provider The AI provider ( openai, gemini, claude, shareai, groq, ollama)385 * @param string $provider The AI provider (shareai, gemini, ollama) 216 386 * @return bool True if API key is configured 217 387 */ 218 388 public function is_api_key_configured( $provider ) { 219 389 switch ( $provider ) { 220 case ' openai':221 return ! empty( $this->openai_api_key);390 case 'shareai': 391 return aiohm_kb_shareai_available( $this->settings ); 222 392 case 'gemini': 223 393 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 );230 394 case 'ollama': 231 395 return ! empty( $this->ollama_server_url ); … … 371 535 if ( is_string( $data ) ) { 372 536 $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', 376 540 '/AIza[a-zA-Z0-9_-]{35}/' => 'GEMINI_API_KEY_HIDDEN', 377 541 '/[a-zA-Z0-9_-]{32,}/' => 'POTENTIAL_API_KEY_HIDDEN', … … 411 575 } 412 576 413 $provider = $this->settings['default_ai_provider'] ?? 'openai';577 $provider = aiohm_kb_resolve_ai_provider( $this->settings['default_ai_provider'] ?? '', $this->settings ); 414 578 415 579 switch ( $provider ) { 416 580 case 'gemini': 417 581 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 );422 582 case 'ollama': 423 583 return $this->generate_ollama_embeddings( $text ); 424 584 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': 425 589 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 ); 453 591 } 454 592 } … … 483 621 } 484 622 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 491 623 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 492 645 // ShareAI API does not currently have a dedicated embedding endpoint. 493 646 // This functionality is not supported. … … 496 649 497 650 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; 525 713 } 526 714 … … 578 766 } 579 767 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 627 768 private function get_shareai_chat_completion( $system_message, $user_message, $temperature, $model ) { 628 769 // WordPress.org compliance: Check for ShareAI consent … … 631 772 } 632 773 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.' ); 838 788 } 839 789 … … 844 794 845 795 $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' ) { 849 797 $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;857 798 } 858 799 … … 955 896 } 956 897 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() ) { 959 906 return array( 960 907 'success' => false, 961 'error' => ' Claude API key is missing.',908 'error' => 'ShareAI is not connected. Click Connect ShareAI in the AIOHM settings.', 962 909 ); 963 910 } 964 911 try { 965 $this->get_chat_completion( 'Test prompt', "Say 'hello'.", 0.5, 'claude-3-sonnet');912 AIOHM_KB_ShareAI_Connect::access_token(); 966 913 return array( 'success' => true ); 967 914 } catch ( Exception $e ) { … … 973 920 } 974 921 975 public function test_shareai_api_connection() {976 // WordPress.org compliance: Check for ShareAI consent977 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 corruption996 if ( preg_match( '/[^A-Za-z0-9\-_.]/', $this->shareai_api_key ) ) {997 }998 999 // First test basic connectivity without auth1000 $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 tokens1006 $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 test1032 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 information1041 $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 successful1078 $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 test1099 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 response1111 *1112 * @param array $decoded The decoded API response1113 * @return array Usage information1114 */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 data1126 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 root1136 $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 work1149 $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 consumption1161 );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 format1202 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 tokens1227 *1228 * @return array Usage information or error1229 */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 response1278 $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 data1288 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 root1297 $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 1316 922 /** 1317 923 * Get the current AI provider based on settings … … 1320 926 */ 1321 927 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 ); 1339 929 } 1340 930 … … 1354 944 if ( ! $model ) { 1355 945 $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 ); 1369 950 } 1370 951 } 1371 952 1372 953 return $this->get_chat_completion( '', $prompt, $temperature, $model ); 1373 }1374 1375 /**1376 * Test Groq API connection1377 *1378 * @return array Result with success status and message1379 */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 testing1390 $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 }1446 954 } 1447 955 … … 1460 968 1461 969 // Future implementation would handle direct file uploads to: 1462 // - OpenAI's file upload API970 // - ShareAI document models 1463 971 // - Gemini's document processing 1464 // - Claude's document analysis972 // - Local Ollama vision models 1465 973 1466 974 throw new Exception( 'Direct file processing not yet implemented. Use text extraction approach.' ); … … 1575 1083 } 1576 1084 } 1085 1086 if ( ! 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 517 517 */ 518 518 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); 534 520 } 535 521 … … 1003 989 $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider); 1004 990 } 1005 $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];991 $provider_priority = aiohm_kb_ai_provider_ids(); 1006 992 1007 993 // If no default set, find first available provider … … 1026 1012 1027 1013 // 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); 1045 1015 1046 1016 // Enhanced formatting instructions for better readability … … 1102 1072 1103 1073 public static function handle_frontend_chat_ajax() { 1104 // Enhanced rate limiting for chat requests - stricter for public endpoints1105 $user_id = get_current_user_id() ?: 0;1106 $rate_limit = $user_id > 0 ? 50 : 20; // Lower limit for non-authenticated users1107 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 1112 1074 if (!check_ajax_referer('aiohm_chat_nonce', 'nonce', false)) { 1113 1075 wp_send_json_error(['reply' => __('Security check failed.', 'aiohm-knowledge-assistant')]); 1114 1076 } 1115 1116 // Additional validation for public endpoints1117 1077 if (!isset($_POST['message']) || !is_string($_POST['message'])) { 1118 1078 wp_send_json_error(['reply' => __('Invalid message format.', 'aiohm-knowledge-assistant')]); … … 1120 1080 1121 1081 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 { 1144 1123 $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; 1165 1171 break; 1166 1172 } 1167 1173 } 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 { 1239 1190 $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 placeholders1242 // Use strtr instead of str_replace to avoid partial matches and conflicts1243 $final_answer = strtr($answer, $replacements);1244 1245 wp_send_json_success(['reply' => $final_answer]);1246 1247 1191 } 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 ]; 1250 1207 } 1251 1208 … … 1435 1392 $default_provider = aiohm_kb_normalize_wp_ai_provider_id($default_provider); 1436 1393 } 1437 $provider_priority = ['shareai', 'openai', 'gemini', 'claude'];1394 $provider_priority = aiohm_kb_ai_provider_ids(); 1438 1395 1439 1396 // If no default set, find first available provider … … 1458 1415 1459 1416 // 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); 1477 1418 1478 1419 $answer = $ai_client->get_chat_completion($final_system_message, $user_message, $temperature, $model); … … 1503 1444 $system_prompt = wp_kses_post($posted_settings['system_prompt'] ?? 'You are a helpful brand assistant.'); 1504 1445 $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'] ?? ''); 1506 1447 1507 1448 // Initialize AI client with current settings … … 1554 1495 // Check prerequisites - validate API key for selected provider 1555 1496 $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); 1560 1498 1561 1499 // Check if the selected default provider has proper configuration 1562 1500 $api_key_exists = false; 1563 1501 $provider_names = [ 1502 'shareai' => 'ShareAI', 1503 'gemini' => 'Gemini', 1504 'ollama' => 'Ollama', 1564 1505 'openai' => 'OpenAI', 1565 'gemini' => 'Gemini', 1566 'claude' => 'Claude', 1567 'shareai' => 'ShareAI', 1568 'groq' => 'Groq', 1569 'ollama' => 'Ollama' 1506 'anthropic' => 'Anthropic' 1570 1507 ]; 1571 1508 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); 1596 1510 1597 1511 if (!$api_key_exists) { … … 1727 1641 $api_key = ''; 1728 1642 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' : ''; 1734 1646 break; 1735 1647 case 'gemini': … … 1739 1651 } 1740 1652 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;1753 1653 } 1754 1654 … … 1758 1658 try { 1759 1659 switch ($key_type) { 1760 case ' openai':1660 case 'shareai': 1761 1661 $ai_client = new AIOHM_KB_AI_GPT_Client($settings); 1762 $result = $ai_client->test_ api_connection();1662 $result = $ai_client->test_shareai_api_connection(); 1763 1663 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')]); 1765 1665 } else { 1766 // translators: %s is the OpenAI API error message1767 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')))]); 1768 1668 } 1769 1669 break; … … 1778 1678 } 1779 1679 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 message1787 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 message1797 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 message1807 wp_send_json_error(['message' => sprintf(__('Groq connection failed: %s', 'aiohm-knowledge-assistant'), ($result['error'] ?? __('Unknown error.', 'aiohm-knowledge-assistant')))]);1808 }1809 break;1810 1680 default: 1811 1681 wp_send_json_error(['message' => __('Invalid key type specified.', 'aiohm-knowledge-assistant')]); … … 1855 1725 1856 1726 // 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') { 1858 1734 // Validate API key format using new validation function 1859 1735 $provider = str_replace('_api_key', '', $setting_name); … … 1866 1742 // Encrypt the validated API key 1867 1743 $current_settings[$setting_name] = AIOHM_KB_Assistant::encrypt_api_key($validated_key); 1868 } elseif ($setting_name === 'shareai_api_key') {1869 // Validate ShareAI key1870 $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;1877 1744 } else { 1878 1745 // For non-API keys (like models), save as plain text with additional validation … … 1936 1803 wp_send_json_success(['message' => __('ShareAI model saved successfully!', 'aiohm-knowledge-assistant')]); 1937 1804 } 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) 1939 1806 wp_send_json_success(['message' => sprintf(__('%s API key saved successfully!', 'aiohm-knowledge-assistant'), ucfirst($api_type))]); 1940 1807 } … … 2406 2273 $settings['mirror_mode']['ai_avatar'] = esc_url_raw($settings_input['ai_avatar'] ?? ''); 2407 2274 $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'] ?? ''); 2409 2276 2410 2277 // Handle URL sanitization with proper validation … … 2501 2368 } 2502 2369 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'] ?? ''); 2504 2371 $settings['muse_mode']['temperature'] = floatval($muse_input['temperature'] ?? 0.7); 2505 2372 $settings['muse_mode']['start_fullscreen'] = isset($muse_input['start_fullscreen']) ? 1 : 0; … … 2555 2422 } else { 2556 2423 // 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); 2576 2426 } 2577 2427 … … 4024 3874 // Format provider data 4025 3875 $providers = [ 4026 ' openai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'],3876 'shareai' => ['tokens' => 0, 'requests' => 0, 'cost' => '0.00'], 4027 3877 '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'] 4030 3879 ]; 4031 3880 … … 4369 4218 $research_prompt, 4370 4219 0.3, 4371 $settings['muse_mode']['ai_model'] ?? ' gpt-3.5-turbo'4220 $settings['muse_mode']['ai_model'] ?? '' 4372 4221 ); 4373 4222 … … 5566 5415 // Test each configured API 5567 5416 $apis_to_test = [ 5568 ' openai' => $settings['openai_api_key'] ??'',5417 'shareai' => aiohm_kb_shareai_available($settings) ? 'connected' : '', 5569 5418 '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'] ?? '')) : '' 5572 5420 ]; 5573 5421 … … 5589 5437 5590 5438 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(); 5593 5441 break; 5594 5442 case 'gemini': 5595 5443 $test_result = $ai_client->test_gemini_api_connection(); 5596 5444 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(); 5602 5447 break; 5603 5448 } -
aiohm-knowledge-assistant/trunk/includes/parsers/ai-fallback-parser.php
r3545079 r3833232 64 64 $settings = AIOHM_KB_Assistant::get_settings(); 65 65 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 ) ) { 70 69 return true; 71 70 } 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;98 71 } 99 72 … … 469 442 $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.'; 470 443 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 ); 472 449 473 450 if ( empty( $response ) ) { … … 545 522 546 523 /** 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 /** 547 544 * Get AI model information 548 545 * … … 552 549 $settings = AIOHM_KB_Assistant::get_settings(); 553 550 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 ); 594 568 } 595 569 -
aiohm-knowledge-assistant/trunk/includes/rag-engine.php
r3801374 r3833232 51 51 } 52 52 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 ); 53 92 } 54 93 … … 104 143 $successful_inserts = 0; 105 144 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 ); 111 147 112 148 $chunk_metadata = array_merge( $metadata, array( … … 121 157 'title' => $title, 122 158 'content' => $chunk, 123 'vector_data' => json_encode( $embedding ),159 'vector_data' => null === $embedding ? null : json_encode( $embedding ), 124 160 'metadata' => json_encode( $chunk_metadata ), 125 161 'is_public' => $is_public, … … 197 233 198 234 $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 ); 204 237 205 238 $metadata = array( … … 216 249 'title' => $title, 217 250 'content' => $chunk, 218 'vector_data' => json_encode( $embedding ),251 'vector_data' => null === $embedding ? null : json_encode( $embedding ), 219 252 'metadata' => json_encode( $metadata ), 220 253 'is_public' => 0, … … 282 315 $system_message_key = ( $scope === 'private' ) ? 'system_prompt' : 'qa_system_message'; 283 316 $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'] ?? ''; 285 318 $temperature = $ai_settings['temperature'] ?? 0.7; 286 319 … … 465 498 } 466 499 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 ); 469 503 470 504 $keywords = preg_replace( '/[^a-z0-9\s]/i', '', strtolower( $query_text ) ); … … 472 506 $table_name = $this->table_name; 473 507 $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 } 474 531 475 532 if ( ! empty( trim( $keywords ) ) ) { … … 571 628 } 572 629 630 if ( null === $query_embedding ) { 631 return array(); 632 } 633 573 634 // Recheck persisted visibility even for cached candidates, so revocation is immediate. 574 635 $pre_filtered_entries = $this->filter_public_context_entries( $pre_filtered_entries ); 575 636 $similarities = array(); 576 637 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 ); 588 645 } 589 646 } … … 1122 1179 public function find_context_for_user( $query_text, $user_id, $limit = 5 ) { 1123 1180 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 ); 1126 1182 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching 1127 1183 // User context search query requires direct database access for vector similarity operations … … 1129 1185 // Validate table name for security 1130 1186 $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 } 1131 1212 1132 1213 $all_entries = $wpdb->get_results( … … 1141 1222 foreach ( $all_entries as $entry ) { 1142 1223 $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 ); 1153 1230 } 1154 1231 } -
aiohm-knowledge-assistant/trunk/includes/settings-page.php
r3801374 r3833232 160 160 161 161 // 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' ) ); 163 163 164 164 // Get Help page … … 989 989 : sanitize_key( $setting_value ); 990 990 991 if ( ! in_array( $setting_value, a rray( 'shareai', 'openai', 'claude', 'gemini', 'groq', 'ollama'), true ) ) {991 if ( ! in_array( $setting_value, aiohm_kb_ai_provider_ids(), true ) ) { 992 992 wp_send_json_error( 'Invalid AI provider selected' ); 993 993 return; … … 1093 1093 1094 1094 // 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' ); 1096 1096 foreach ( $api_keys as $field ) { 1097 1097 if ( isset( $input[ $field ] ) ) { … … 1110 1110 } 1111 1111 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'] ); 1115 1120 } 1116 1121 … … 1128 1133 ? aiohm_kb_normalize_wp_ai_provider_id( $input['default_ai_provider'] ) 1129 1134 : sanitize_key( $input['default_ai_provider'] ); 1130 if ( in_array( $provider, a rray( 'shareai', 'openai', 'claude', 'gemini', 'groq', 'ollama'), true ) ) {1135 if ( in_array( $provider, aiohm_kb_ai_provider_ids(), true ) ) { 1131 1136 $sanitized['default_ai_provider'] = $provider; 1132 1137 } … … 1202 1207 $temperature = floatval( $muse_settings['temperature'] ?? 0.7 ); 1203 1208 $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'] ?? ''; 1205 1210 1206 1211 // Initialize AI client … … 1208 1213 1209 1214 // Check if any AI provider is configured 1210 $providers = a rray( 'openai', 'gemini', 'claude', 'groq', 'shareai');1215 $providers = aiohm_kb_ai_provider_ids(); 1211 1216 $has_api_key = false; 1212 1217 foreach ( $providers as $provider ) { -
aiohm-knowledge-assistant/trunk/includes/shortcode-qa.php
r3545079 r3833232 99 99 100 100 // 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 } 124 108 125 109 if ( ! $has_api_key ) { … … 138 122 } else { 139 123 // 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 ); 156 126 } 157 127 -
aiohm-knowledge-assistant/trunk/includes/uninstall-cleanup.php
r3801374 r3833232 13 13 function aiohm_kb_uninstall_cleanup() 14 14 { 15 // ShareAI tokens never outlive the plugin, whatever the data setting. 16 aiohm_kb_uninstall_shareai(); 17 15 18 // Check if user wants to delete data on uninstall 16 19 $settings = get_option("aiohm_kb_settings", []); … … 93 96 wp_cache_flush(); 94 97 } 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 */ 104 function 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 === 2 2 Contributors: ohmevents 3 3 Tags: ai assistant, knowledge base, chatbot, brand voice, personalized ai 4 4 Requires at least: 6.2 5 5 Tested up to: 7.1 6 Stable tag: 3. 0.06 Stable tag: 3.1.0 7 7 Requires PHP: 7.4 8 8 License: GPLv2 or later … … 21 21 * **Public Chatbot**: Add an intelligent chatbot to your website that answers visitor questions based on your content 22 22 * **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 ShareAI23 * **Multi-Provider AI Support**: Choose from ShareAI, Google Gemini or a local Ollama server 24 24 * **Brand Voice Configuration**: Set up your chatbot's personality and communication style 25 25 * **Content Processing**: Support for PDF, CSV, TXT, and JSON document formats … … 34 34 * Automatic indexing of WordPress posts, pages, and uploaded files 35 35 * Support for PDF, CSV, TXT, and JSON document formats 36 * Advanced semantic search with vectorembeddings36 * Full-text search on every setup, plus semantic search when Gemini or Ollama provides embeddings 37 37 * Smart content chunking for optimal AI processing 38 38 39 39 **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) 45 43 * **Ollama Local AI for completely private, on-premise processing** 46 44 * ServBay Ollama server integration for development environments … … 92 90 * WordPress 6.2 or higher 93 91 * PHP 7.4 or higher 94 * A PI 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 95 93 * Optional: Paid Memberships Pro for advanced access control 96 94 97 95 ## Privacy & External Services 98 96 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.97 This 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. 100 98 101 99 **Supported AI Services:** 102 100 * 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/)104 101 * 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. 107 104 108 105 User 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):** 108 ShareAI 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/). 109 115 110 116 == Installation == … … 112 118 1. Upload the plugin files to `/wp-content/plugins/aiohm-knowledge-assistant/` 113 119 2. Activate the plugin through the WordPress Plugins menu 114 3. Navigate to AIOHM > Settings and c onfigure your AI provider API key120 3. Navigate to AIOHM > Settings and click Connect ShareAI, or add a Gemini API key, or point AIOHM at your Ollama server 115 121 4. Run the content scan to build your knowledge base 116 122 5. Configure your brand voice settings … … 121 127 = What AI providers are supported? = 122 128 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. 129 AIOHM 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 133 Yes, 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. 124 134 125 135 = How does this differ from other AI chatbot plugins? = … … 169 179 170 180 == 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. 171 197 172 198 = 3.0.0 = … … 308 334 == Upgrade Notice == 309 335 336 = 3.1.0 = 337 ShareAI 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 310 339 = 1.4.1 = 311 340 CRITICAL FIX: Resolves knowledge base content not appearing after scanning. Essential update for users experiencing empty manage knowledge base tables after content scanning operations. … … 322 351 == Screenshots == 323 352 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 353 1. **Answers from your content** - The live preview answers a visitor question from the site's own pages 354 2. **Connect ShareAI** - Connect your ShareAI account once, with the 10% builder markup shown up front 355 3. **Scan your site** - Posts, pages, products and media files ready to index 356 4. **Knowledge base manager** - Choose what is public and what stays private 357 5. **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 47 47 <div class="benefit"> 48 48 <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 keyto 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> 50 50 <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> 51 51 </div> … … 77 77 <div class="benefit"> 78 78 <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> 80 80 </div> 81 81 <div class="benefit"> … … 110 110 <div class="benefit"> 111 111 <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> 113 113 <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> 114 114 </div> -
aiohm-knowledge-assistant/trunk/templates/admin-mirror-mode.php
r3545079 r3833232 107 107 </div> 108 108 <?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 } 135 121 ?> 136 122 <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> 146 130 <?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> 152 133 <?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> 158 141 <?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> 164 144 <?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> 170 147 <?php endif; ?> 171 148 </select> -
aiohm-knowledge-assistant/trunk/templates/admin-muse-mode.php
r3545079 r3833232 175 175 </div> 176 176 <?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 } 203 189 ?> 204 190 <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> 214 198 <?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> 220 201 <?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> 226 209 <?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> 232 212 <?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> 238 215 <?php endif; ?> 239 216 </select> -
aiohm-knowledge-assistant/trunk/templates/admin-pro-features.php
r3801374 r3833232 40 40 41 41 <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> 43 43 <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> 44 44 … … 281 281 <th scope="row"><?php esc_html_e('Token Name', 'aiohm-knowledge-assistant'); ?></th> 282 282 <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"> 284 284 <p class="description"><?php esc_html_e('A descriptive name to identify this token', 'aiohm-knowledge-assistant'); ?></p> 285 285 </td> … … 339 339 <div class="aiohm-save-section"> 340 340 <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 FeaturesSettings', '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' ); ?>"> 342 342 </p> 343 343 </div> … … 548 548 success: function(response) { 549 549 console.log('AJAX response:', response); 550 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Pro FeaturesSettings', 'aiohm-knowledge-assistant' ); ?>');550 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>'); 551 551 552 552 if (response.success) { … … 573 573 error: function(xhr, status, error) { 574 574 console.error('AJAX error:', xhr, status, error); 575 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Pro FeaturesSettings', 'aiohm-knowledge-assistant' ); ?>');575 $('#submit').prop('disabled', false).val('<?php esc_attr_e( 'Save All Advanced Settings', 'aiohm-knowledge-assistant' ); ?>'); 576 576 $('#aiohm-admin-notice').removeClass('notice-success notice-info').addClass('notice-error').find('p').text('Save failed: ' + error); 577 577 } -
aiohm-knowledge-assistant/trunk/templates/admin-scan-website.php
r3545079 r3833232 9 9 // The controller (settings-page.php) prepares these variables before including this template. 10 10 $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 ); 58 15 59 16 // Also get provider display name for better error messaging 60 17 $aiohm_provider_names = array( 61 ' openai' => 'OpenAI',18 'shareai' => 'ShareAI', 62 19 'gemini' => 'Gemini', 63 'claude' => 'Claude', 64 'shareai' => 'ShareAI', 20 'ollama' => 'Ollama', 65 21 ); 66 22 $aiohm_current_provider_name = $aiohm_provider_names[ $aiohm_default_provider ] ?? 'Unknown Provider'; … … 81 37 <?php 82 38 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) */ 84 40 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' ), 85 41 esc_html( $aiohm_current_provider_name ) -
aiohm-knowledge-assistant/trunk/templates/admin-settings.php
r3801374 r3833232 24 24 </div> 25 25 26 <?php include AIOHM_KB_PLUGIN_DIR . 'templates/admin-shareai-connect.php'; ?> 26 27 27 28 <form id="aiohm-settings-form" method="post" action="options.php"> … … 36 37 <div class="aiohm-shareai-settings-box"> 37 38 <?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' ); 61 43 62 44 // Check for Ollama … … 64 46 $aiohm_has_ollama = ! empty( $aiohm_pro_features['ollama_enabled'] ); 65 47 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; 67 51 $aiohm_enabled_provider_values = array(); 68 52 foreach ( 69 53 array( 70 54 'shareai' => $aiohm_has_shareai, 71 'openai' => $aiohm_has_openai,72 'claude' => $aiohm_has_claude,73 55 'gemini' => $aiohm_has_gemini, 74 'groq' => $aiohm_has_groq,75 56 'ollama' => $aiohm_has_ollama, 57 'openai' => $aiohm_has_openai, 58 'anthropic' => $aiohm_has_anthropic, 76 59 ) as $aiohm_provider_value => $aiohm_provider_enabled 77 60 ) { … … 96 79 <div class="shareai-setting-row"> 97 80 98 <!-- All AI Providers ( 6-column grid) -->81 <!-- All AI Providers (3-column grid) --> 99 82 <div class="aiohm-provider-selection aiohm-provider-grid"> 100 83 <label class="aiohm-provider-option <?php echo ! $aiohm_has_shareai ? 'disabled' : ''; ?>" data-provider="shareai"> 101 84 <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' : ''; ?>> 102 85 <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"> 104 87 </div> 105 88 <div class="aiohm-provider-info"> 106 89 <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> 108 91 </div> 109 92 <?php if ( ! $aiohm_has_shareai ) : ?> … … 112 95 </label> 113 96 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 170 97 <label class="aiohm-provider-option <?php echo ! $aiohm_has_ollama ? 'disabled' : ''; ?>" data-provider="ollama"> 171 98 <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' : ''; ?>> … … 175 102 <div class="aiohm-provider-info"> 176 103 <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> 178 105 </div> 179 106 <?php if ( ! $aiohm_has_ollama ) : ?> … … 181 108 <?php endif; ?> 182 109 </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; ?> 183 149 184 150 </div> … … 225 191 <div class="aiohm-privacy-notice"> 226 192 <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> 228 194 </div> 229 195 </div> … … 232 198 </div> 233 199 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 <?php298 printf(299 wp_kses(300 // translators: %s is the URL to the ShareAI Console301 __( '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 349 200 <?php $aiohm_uses_wp_connectors = function_exists( 'wp_get_connectors' ); ?> 350 201 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"> 354 204 <div class="aiohm-premium-column"> 355 205 <!-- Gemini --> … … 370 220 printf( 371 221 wp_kses( 222 /* translators: %s: Google AI Studio URL */ 372 223 __( 'You can get your Gemini API key from the <a href="%s" target="_blank">Google AI Studio</a>.', 'aiohm-knowledge-assistant' ), 373 224 array( … … 383 234 </p> 384 235 </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 <?php401 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>416 236 </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; ?> 526 239 527 240 <div class="aiohm-card"> -
aiohm-knowledge-assistant/trunk/templates/partials/header.php
r3801374 r3833232 39 39 <li> 40 40 <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' ); ?> 42 42 </a> 43 43 </li>
Note:
See TracChangeset
for help on using the changeset viewer.