array( 'name' => 'OpenAI', 'type' => 'openai', 'base_url' => 'https://api.openai.com/v1/chat/completions', 'model' => 'gpt-4o-mini', ), 'anthropic' => array( 'name' => 'Anthropic', 'type' => 'anthropic', 'base_url' => 'https://api.anthropic.com/v1/messages', 'model' => 'claude-3-5-haiku-latest', ), 'gemini' => array( 'name' => 'Gemini', 'type' => 'gemini', 'base_url' => '', 'model' => 'gemini-1.5-flash-latest', ), 'openrouter' => array( 'name' => 'OpenRouter', 'type' => 'openai', 'base_url' => 'https://openrouter.ai/api/v1/chat/completions', 'model' => 'openai/gpt-4o-mini', ), 'nine_router' => array( 'name' => '9Router', 'type' => 'openai', 'base_url' => 'http://localhost:20128/v1/chat/completions', 'model' => 'kr/claude-sonnet-4.5', 'allow_empty_key' => true, ), 'xai' => array( 'name' => 'xAI (Grok)', 'type' => 'openai', 'base_url' => 'https://api.x.ai/v1/chat/completions', 'model' => 'grok-3-mini', ), 'deepseek' => array( 'name' => 'DeepSeek', 'type' => 'openai', 'base_url' => 'https://api.deepseek.com/v1/chat/completions', 'model' => 'deepseek-chat', ), 'groq' => array( 'name' => 'Groq', 'type' => 'openai', 'base_url' => 'https://api.groq.com/openai/v1/chat/completions', 'model' => 'llama-3.3-70b-versatile', ), 'mistral' => array( 'name' => 'Mistral', 'type' => 'openai', 'base_url' => 'https://api.mistral.ai/v1/chat/completions', 'model' => 'mistral-small-latest', ), 'perplexity' => array( 'name' => 'Perplexity', 'type' => 'openai', 'base_url' => 'https://api.perplexity.ai/chat/completions', 'model' => 'sonar', ), 'together' => array( 'name' => 'Together AI', 'type' => 'openai', 'base_url' => 'https://api.together.xyz/v1/chat/completions', 'model' => 'meta-llama/Llama-3.3-70B-Instruct-Turbo', ), 'fireworks' => array( 'name' => 'Fireworks AI', 'type' => 'openai', 'base_url' => 'https://api.fireworks.ai/inference/v1/chat/completions', 'model' => 'accounts/fireworks/models/llama-v3p1-8b-instruct', ), 'cerebras' => array( 'name' => 'Cerebras', 'type' => 'openai', 'base_url' => 'https://api.cerebras.ai/v1/chat/completions', 'model' => 'llama3.1-8b', ), 'cohere' => array( 'name' => 'Cohere', 'type' => 'openai', 'base_url' => 'https://api.cohere.com/compatibility/v1/chat/completions', 'model' => 'command-r-plus', ), 'nvidia_nim' => array( 'name' => 'NVIDIA NIM', 'type' => 'openai', 'base_url' => 'https://integrate.api.nvidia.com/v1/chat/completions', 'model' => 'meta/llama-3.1-70b-instruct', ), 'nebius' => array( 'name' => 'Nebius AI', 'type' => 'openai', 'base_url' => 'https://api.studio.nebius.com/v1/chat/completions', 'model' => 'meta-llama/Meta-Llama-3.1-70B-Instruct', ), 'siliconflow' => array( 'name' => 'SiliconFlow', 'type' => 'openai', 'base_url' => 'https://api.siliconflow.cn/v1/chat/completions', 'model' => 'Qwen/Qwen2.5-72B-Instruct', ), 'hyperbolic' => array( 'name' => 'Hyperbolic', 'type' => 'openai', 'base_url' => 'https://api.hyperbolic.xyz/v1/chat/completions', 'model' => 'meta-llama/Meta-Llama-3.1-70B-Instruct', ), 'chutes' => array( 'name' => 'Chutes AI', 'type' => 'openai', 'base_url' => 'https://llm.chutes.ai/v1/chat/completions', 'model' => 'deepseek-ai/DeepSeek-V3', ), 'qwen' => array( 'name' => 'Qwen / Alibaba Intl', 'type' => 'openai', 'base_url' => 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions', 'model' => 'qwen-plus', ), 'alibaba_cn' => array( 'name' => 'Alibaba China', 'type' => 'openai', 'base_url' => 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions', 'model' => 'qwen-plus', ), 'glm' => array( 'name' => 'GLM', 'type' => 'openai', 'base_url' => 'https://open.bigmodel.cn/api/paas/v4/chat/completions', 'model' => 'glm-4-flash', ), 'kimi' => array( 'name' => 'Kimi', 'type' => 'openai', 'base_url' => 'https://api.moonshot.ai/v1/chat/completions', 'model' => 'moonshot-v1-8k', ), 'minimax' => array( 'name' => 'Minimax', 'type' => 'openai', 'base_url' => 'https://api.minimax.io/v1/text/chatcompletion_openai/v2', 'model' => 'MiniMax-Text-01', ), 'volcengine_ark' => array( 'name' => 'Volcengine Ark', 'type' => 'openai', 'base_url' => 'https://ark.cn-beijing.volces.com/api/v3/chat/completions', 'model' => 'YOUR_ENDPOINT_ID', ), 'byteplus_modelark' => array( 'name' => 'BytePlus ModelArk', 'type' => 'openai', 'base_url' => 'https://ark.ap-southeast.bytepluses.com/api/v3/chat/completions', 'model' => 'YOUR_ENDPOINT_ID', ), 'cloudflare' => array( 'name' => 'Cloudflare Workers AI', 'type' => 'openai', 'base_url' => 'https://api.cloudflare.com/client/v4/accounts/YOUR_ACCOUNT_ID/ai/v1/chat/completions', 'model' => '@cf/meta/llama-3.1-8b-instruct', ), 'azure_openai' => array( 'name' => 'Azure OpenAI', 'type' => 'azure', 'base_url' => 'https://YOUR_RESOURCE.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT/chat/completions?api-version=2024-02-15-preview', 'model' => 'YOUR_DEPLOYMENT', ), 'ollama_local' => array( 'name' => 'Ollama Local', 'type' => 'openai', 'base_url' => 'http://localhost:11434/v1/chat/completions', 'model' => 'llama3.1', 'allow_empty_key' => true, ), 'ollama_cloud' => array( 'name' => 'Ollama Cloud', 'type' => 'openai', 'base_url' => 'https://ollama.com/api/chat', 'model' => 'gpt-oss:20b', ), ); $provider_icons = array( 'openai' => array('icon' => 'OA', 'icon_bg' => '#0f172a', 'icon_color' => '#ffffff'), 'anthropic' => array('icon' => 'A', 'icon_bg' => '#f4efe7', 'icon_color' => '#1f2937'), 'gemini' => array('icon' => 'G', 'icon_bg' => '#e8f0fe', 'icon_color' => '#1a73e8'), 'openrouter' => array('icon' => 'OR', 'icon_bg' => '#eef2ff', 'icon_color' => '#4f46e5'), 'nine_router' => array('icon' => '9R', 'icon_bg' => '#ecfdf3', 'icon_color' => '#2f855a'), 'xai' => array('icon' => 'xAI', 'icon_bg' => '#111827', 'icon_color' => '#f9fafb'), 'deepseek' => array('icon' => 'DS', 'icon_bg' => '#e0edff', 'icon_color' => '#1d4ed8'), 'groq' => array('icon' => 'GQ', 'icon_bg' => '#fff1e8', 'icon_color' => '#f97316'), 'mistral' => array('icon' => 'M', 'icon_bg' => '#fff7cc', 'icon_color' => '#c2410c'), 'perplexity' => array('icon' => 'P', 'icon_bg' => '#ecfeff', 'icon_color' => '#0e7490'), 'together' => array('icon' => 'T', 'icon_bg' => '#f5e8ff', 'icon_color' => '#7e22ce'), 'fireworks' => array('icon' => 'FW', 'icon_bg' => '#ffe4e6', 'icon_color' => '#be123c'), 'cerebras' => array('icon' => 'CB', 'icon_bg' => '#fff1f2', 'icon_color' => '#9f1239'), 'cohere' => array('icon' => 'Co', 'icon_bg' => '#e7f8ef', 'icon_color' => '#047857'), 'nvidia_nim' => array('icon' => 'NV', 'icon_bg' => '#dcfce7', 'icon_color' => '#15803d'), 'nebius' => array('icon' => 'N', 'icon_bg' => '#ecfccb', 'icon_color' => '#3f6212'), 'siliconflow' => array('icon' => 'SF', 'icon_bg' => '#eef2ff', 'icon_color' => '#3730a3'), 'hyperbolic' => array('icon' => 'H', 'icon_bg' => '#e0f2fe', 'icon_color' => '#0369a1'), 'chutes' => array('icon' => 'CH', 'icon_bg' => '#f8fafc', 'icon_color' => '#111827'), 'qwen' => array('icon' => 'Q', 'icon_bg' => '#eef2ff', 'icon_color' => '#4338ca'), 'alibaba_cn' => array('icon' => 'Ali', 'icon_bg' => '#fff7ed', 'icon_color' => '#ea580c'), 'glm' => array('icon' => 'Z', 'icon_bg' => '#f8fafc', 'icon_color' => '#111827'), 'kimi' => array('icon' => 'K', 'icon_bg' => '#111827', 'icon_color' => '#ffffff'), 'minimax' => array('icon' => 'MM', 'icon_bg' => '#ffe4ef', 'icon_color' => '#db2777'), 'volcengine_ark' => array('icon' => 'VA', 'icon_bg' => '#e0f2fe', 'icon_color' => '#0284c7'), 'byteplus_modelark' => array('icon' => 'BP', 'icon_bg' => '#e0e7ff', 'icon_color' => '#2563eb'), 'cloudflare' => array('icon' => 'CF', 'icon_bg' => '#ffedd5', 'icon_color' => '#ea580c'), 'azure_openai' => array('icon' => 'Az', 'icon_bg' => '#dbeafe', 'icon_color' => '#1d4ed8'), 'ollama_local' => array('icon' => 'OL', 'icon_bg' => '#f8fafc', 'icon_color' => '#111827'), 'ollama_cloud' => array('icon' => 'OC', 'icon_bg' => '#f8fafc', 'icon_color' => '#111827'), ); foreach ($providers as $slug => $provider) { $providers[$slug] = array_merge( array('icon' => strtoupper(substr($provider['name'], 0, 1)), 'icon_bg' => '#eef2f7', 'icon_color' => '#344054'), $provider, isset($provider_icons[$slug]) ? $provider_icons[$slug] : array() ); } return $providers; } } if (!function_exists('aikct_get_saved_ai_providers')) { function aikct_get_saved_ai_providers() { $saved = get_option('aikct_ai_providers', array()); if (is_array($saved) && isset($saved['nine_router']) && is_array($saved['nine_router'])) { $oldRouteLabels = array('auto', 'free', 'cheap', 'subscription'); if (isset($saved['nine_router']['model']) && in_array($saved['nine_router']['model'], $oldRouteLabels, true)) { $saved['nine_router']['model'] = 'kr/claude-sonnet-4.5'; } } return is_array($saved) ? $saved : array(); } } if (!function_exists('aikct_get_ai_provider_model_presets')) { function aikct_get_ai_provider_model_presets() { return array( 'openai' => array('gpt-4o-mini', 'gpt-4o', 'gpt-4.1-mini', 'gpt-4.1', 'o4-mini'), 'gemini' => array('gemini-1.5-flash-latest', 'gemini-1.5-pro-latest', 'gemini-2.0-flash', 'gemini-2.5-flash'), 'anthropic' => array('claude-3-5-haiku-latest', 'claude-3-5-sonnet-latest', 'claude-3-7-sonnet-latest'), 'deepseek' => array('deepseek-chat', 'deepseek-reasoner'), 'openrouter' => array('openai/gpt-4o-mini', 'anthropic/claude-3.5-sonnet', 'google/gemini-flash-1.5', 'deepseek/deepseek-chat'), 'nine_router' => array('cx/gpt-5.5', 'cx/gpt-5.4', 'cx/gpt-5.3-codex', 'cx/gpt-5.2-codex', 'cx/gpt-5.1-codex-max', 'xai/grok-4', 'kr/claude-sonnet-4.5', 'kr/claude-haiku-4.5', 'kr/glm-5', 'kr/MiniMax-M2.5', 'kr/qwen3-coder-next', 'kr/deepseek-3.2', 'glm/glm-5.1', 'glm/glm-5', 'glm/glm-4.7', 'cc/claude-opus-4-7', 'cc/claude-opus-4-6', 'cc/claude-sonnet-4-6', 'cc/claude-sonnet-4-5-20250929', 'cc/claude-haiku-4-5-20251001'), 'xai' => array('grok-4', 'grok-3-mini', 'grok-3', 'grok-2'), 'qwen' => array('qwen-plus', 'qwen-max', 'qwen-turbo'), 'mistral' => array('mistral-small-latest', 'mistral-large-latest', 'codestral-latest'), 'cohere' => array('command-r-plus', 'command-r', 'command-a-03-2025'), 'perplexity' => array('sonar', 'sonar-pro', 'sonar-reasoning'), 'together' => array('meta-llama/Llama-3.3-70B-Instruct-Turbo', 'Qwen/Qwen2.5-72B-Instruct-Turbo'), 'groq' => array('llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'mixtral-8x7b-32768'), 'glm' => array('glm-4-flash', 'glm-4-plus', 'glm-4-air'), 'kimi' => array('moonshot-v1-8k', 'moonshot-v1-32k', 'moonshot-v1-128k'), 'ollama_local' => array('llama3.1', 'llama3.2', 'mistral', 'qwen2.5', 'gemma2'), 'ollama_cloud' => array('gpt-oss:20b', 'llama3.1', 'qwen2.5'), ); } } if (!function_exists('aikct_is_custom_openai_endpoint')) { function aikct_is_custom_openai_endpoint($provider, $defaults) { $provider_base_url = isset($provider['base_url']) ? trim((string) $provider['base_url']) : ''; $default_base_url = isset($defaults['base_url']) ? trim((string) $defaults['base_url']) : ''; return !empty($provider['custom_model_id']) || !empty($provider['custom_api_port_url']) || !empty($provider['custom_service_url']) || ($provider_base_url !== '' && $default_base_url !== '' && $provider_base_url !== $default_base_url); } } if (!function_exists('aikct_get_ai_provider_api_key')) { function aikct_get_ai_provider_api_key($provider) { if (!empty($provider['custom_api_key'])) { return trim((string) $provider['custom_api_key']); } if (!empty($provider['api_keys']) && is_array($provider['api_keys'])) { foreach ($provider['api_keys'] as $key_config) { if (!empty($key_config['key']) && (!isset($key_config['status']) || $key_config['status'] === 'active')) { return trim((string) $key_config['key']); } } } return !empty($provider['api_key']) ? trim((string) $provider['api_key']) : ''; } } if (!function_exists('aikct_get_openai_models_url')) { function aikct_get_openai_models_url($provider) { $base_url = ''; if (!empty($provider['custom_service_url'])) { $base_url = trim((string) $provider['custom_service_url']); } elseif (!empty($provider['custom_api_port_url'])) { $base_url = trim((string) $provider['custom_api_port_url']); } elseif (!empty($provider['base_url'])) { $base_url = trim((string) $provider['base_url']); } if ($base_url === '') { return ''; } $parts = wp_parse_url($base_url); if (empty($parts['scheme']) || empty($parts['host'])) { return ''; } $path = isset($parts['path']) ? preg_replace('#/+$#', '', $parts['path']) : ''; $path = preg_replace('#/(chat/completions|responses)$#', '', $path); if (!preg_match('#/models$#', $path)) { $path .= '/models'; } $url = $parts['scheme'] . '://' . $parts['host']; if (!empty($parts['port'])) { $url .= ':' . $parts['port']; } $url .= $path; return $url; } } if (!function_exists('aikct_get_openai_chat_url')) { function aikct_get_openai_chat_url($api_url) { $api_url = trim((string) $api_url); if ($api_url === '') { return ''; } $parts = wp_parse_url($api_url); if (empty($parts['scheme']) || empty($parts['host'])) { return $api_url; } $path = isset($parts['path']) ? preg_replace('#/+$#', '', $parts['path']) : ''; if (preg_match('#/(chat/completions|responses)$#', $path)) { return $api_url; } if (preg_match('#/v1$#', $path)) { $path .= '/chat/completions'; $url = $parts['scheme'] . '://' . $parts['host']; if (!empty($parts['port'])) { $url .= ':' . $parts['port']; } $url .= $path; if (!empty($parts['query'])) { $url .= '?' . $parts['query']; } return $url; } return $api_url; } } if (!function_exists('aikct_fetch_ai_provider_models')) { function aikct_fetch_ai_provider_models($provider, $defaults = array()) { if (!is_array($provider) || !is_array($defaults) || !aikct_is_custom_openai_endpoint($provider, $defaults)) { return array(); } $models_url = aikct_get_openai_models_url($provider); if ($models_url === '') { return array(); } $api_key = aikct_get_ai_provider_api_key($provider); $cache_key = 'aikct_models_' . md5($models_url . '|' . substr($api_key, 0, 12)); $cached = get_transient($cache_key); if (is_array($cached)) { return $cached; } $headers = array('Accept' => 'application/json'); if ($api_key !== '') { $headers['Authorization'] = 'Bearer ' . $api_key; } $response = wp_remote_get($models_url, array( 'headers' => $headers, 'timeout' => 12, 'sslverify' => false, )); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) >= 400) { return array(); } $body = wp_remote_retrieve_body($response); $payload = json_decode($body, true); $models = array(); $items = isset($payload['data']) && is_array($payload['data']) ? $payload['data'] : array(); foreach ($items as $item) { $model_id = is_array($item) && !empty($item['id']) ? $item['id'] : (is_string($item) ? $item : ''); $model_id = trim((string) $model_id); if ($model_id !== '') { $models[] = $model_id; } } $models = array_values(array_unique($models)); if (!empty($models)) { set_transient($cache_key, $models, 5 * MINUTE_IN_SECONDS); } return $models; } } if (!class_exists('AiKctOpenAICompatible')) { class AiKctOpenAICompatible { private $apiKey; private $model; private $apiUrl; private $providerName; private $headers; public function __construct($apiKey, $model, $apiUrl, $providerName = 'AI Provider', $headers = array()) { $this->apiKey = trim((string) $apiKey); $this->model = trim((string) $model); $this->apiUrl = function_exists('aikct_get_openai_chat_url') ? aikct_get_openai_chat_url($apiUrl) : trim((string) $apiUrl); $this->providerName = $providerName; $this->headers = $headers; } private function buildMessages($prompt, $op = '') { $messages = array( array('role' => 'system', 'content' => 'Answer the question based on the context below.'), array('role' => 'system', 'content' => 'The response should be in markdown format.'), array('role' => 'system', 'content' => 'The response should preserve any markdown formatting, links, and styles in the context.'), array('role' => 'system', 'content' => 'Ban ten la AIKCT, mot tro ly ao do plugin AIKCT Engine tao ra, hien tai ban dong vai tac gia va SEOer cho website ' . get_home_url()), ); if ($op !== '') { $chatlog = json_decode(stripslashes(wp_unslash($op)), true); if (json_last_error() === JSON_ERROR_NONE && is_array($chatlog)) { foreach ($chatlog as $entry) { if (!empty($entry['message'])) { $messages[] = array( 'role' => 'user', 'content' => sanitize_textarea_field($entry['message']), ); } } } } $messages[] = array('role' => 'user', 'content' => $prompt); return $messages; } public function sendRequest($prompt, $op = '') { $data = array( 'model' => $this->model, 'temperature' => 0.8, 'max_tokens' => 4000, 'messages' => $this->buildMessages($prompt, $op), ); $headers = array_merge(array( 'Content-Type' => 'application/json', ), $this->headers); if ($this->apiKey !== '') { $headers['Authorization'] = 'Bearer ' . $this->apiKey; } $response = wp_remote_post($this->apiUrl, array( 'body' => wp_json_encode($data), 'headers' => $headers, 'timeout' => 45, 'sslverify' => false, )); if (is_wp_error($response)) { return array( 'output' => 'WP Error: ' . $response->get_error_message(), 'token' => $this->apiKey, 'msg' => 'WP Error: ' . $response->get_error_message(), 'model' => $this->providerName . ' - ' . $this->model, ); } $body = wp_remote_retrieve_body($response); $responseData = json_decode($body, true); $content = $responseData['choices'][0]['message']['content'] ?? ''; if ($content !== '') { return array( 'output' => aikct_engine_markdown($content), 'token' => $this->apiKey, 'msg' => 'Success', 'model' => $this->providerName . ' - ' . $this->model, ); } return array( 'output' => 'Invalid response from API: ' . wp_strip_all_tags($body), 'token' => $this->apiKey, 'msg' => 'Invalid response from API', 'model' => $this->providerName . ' - ' . $this->model, ); } } } if (!class_exists('AiKctAzureOpenAI')) { class AiKctAzureOpenAI extends AiKctOpenAICompatible { public function __construct($apiKey, $model, $apiUrl, $providerName = 'Azure OpenAI') { parent::__construct('', $model, $apiUrl, $providerName, array('api-key' => trim((string) $apiKey))); } } } if (!class_exists('AiKctAnthropic')) { class AiKctAnthropic { private $apiKey; private $model; private $apiUrl; private $providerName; public function __construct($apiKey, $model, $apiUrl, $providerName = 'Anthropic') { $this->apiKey = trim((string) $apiKey); $this->model = trim((string) $model); $this->apiUrl = trim((string) $apiUrl); $this->providerName = $providerName; } public function sendRequest($prompt, $op = '') { $context = 'Answer in markdown. Preserve links and formatting. You are AIKCT, an assistant for website ' . get_home_url() . '.'; if ($op !== '') { $chatlog = json_decode(stripslashes(wp_unslash($op)), true); if (json_last_error() === JSON_ERROR_NONE && is_array($chatlog)) { foreach ($chatlog as $entry) { if (!empty($entry['message'])) { $context .= "\n" . sanitize_textarea_field($entry['message']); } } } } $data = array( 'model' => $this->model, 'max_tokens' => 4000, 'temperature' => 0.8, 'system' => $context, 'messages' => array( array('role' => 'user', 'content' => $prompt), ), ); $response = wp_remote_post($this->apiUrl, array( 'body' => wp_json_encode($data), 'headers' => array( 'Content-Type' => 'application/json', 'x-api-key' => $this->apiKey, 'anthropic-version' => '2023-06-01', ), 'timeout' => 45, 'sslverify' => false, )); if (is_wp_error($response)) { return array( 'output' => 'WP Error: ' . $response->get_error_message(), 'token' => $this->apiKey, 'msg' => 'WP Error: ' . $response->get_error_message(), 'model' => $this->providerName . ' - ' . $this->model, ); } $body = wp_remote_retrieve_body($response); $responseData = json_decode($body, true); $content = $responseData['content'][0]['text'] ?? ''; if ($content !== '') { return array( 'output' => aikct_engine_markdown($content), 'token' => $this->apiKey, 'msg' => 'Success', 'model' => $this->providerName . ' - ' . $this->model, ); } return array( 'output' => 'Invalid response from API: ' . wp_strip_all_tags($body), 'token' => $this->apiKey, 'msg' => 'Invalid response from API', 'model' => $this->providerName . ' - ' . $this->model, ); } } } if (!class_exists('AiKctgpt')) { class AiKctgpt extends AiKctOpenAICompatible { public function __construct($apiKey, $model) { parent::__construct($apiKey, $model, 'https://api.openai.com/v1/chat/completions', 'OpenAI'); } } } class kctaiproxy { private $instances = array(); public $status; public $nameclass; public function __construct($modeOverride = null, $providerOverride = null, $modelOverride = null) { $is_free_api_activated = get_option('aikct_free_api_activated', false); $hasExplicitProvider = $modeOverride === 'current' && $providerOverride !== null && $providerOverride !== ''; if ($is_free_api_activated && class_exists('Openaillm7')) { $this->instances[] = new Openaillm7(); } else { $this->loadConfiguredProviders($modeOverride, $providerOverride, $modelOverride); if (empty($this->instances) && !$hasExplicitProvider) { $this->loadLegacyProviders(); } } $this->status = !empty($this->instances); } private function loadLegacyProviders() { $apiKeyGpt35 = get_option('aikct_apikey_gpt35'); $apiKeyGpt4o = get_option('aikct_apikey_gpt4o'); $apiKeyGemini = get_option('aikct_apikey_gemini'); if (!empty($apiKeyGpt35)) { $this->instances[] = new AiKctgpt($apiKeyGpt35, 'gpt-3.5-turbo'); } if (!empty($apiKeyGpt4o)) { $this->instances[] = new AiKctgpt($apiKeyGpt4o, 'gpt-4o-mini'); } if (!empty($apiKeyGemini) && class_exists('Gemini')) { $this->instances[] = new Gemini($apiKeyGemini, 'gemini-1.5-flash-latest'); } } private function loadConfiguredProviders($modeOverride = null, $providerOverride = null, $modelOverride = null) { $catalog = aikct_get_ai_provider_catalog(); $saved = aikct_get_saved_ai_providers(); $mode = $modeOverride !== null ? sanitize_key($modeOverride) : get_option('aikct_ai_provider_mode', 'router'); $currentProvider = $providerOverride !== null && $providerOverride !== '' ? sanitize_key($providerOverride) : get_option('aikct_ai_current_provider', 'openai'); $hasExplicitProvider = $modeOverride === 'current' && $providerOverride !== null && $providerOverride !== ''; foreach ($catalog as $slug => $defaults) { if ($mode === 'current' && $slug !== $currentProvider) { continue; } $provider = isset($saved[$slug]) && is_array($saved[$slug]) ? array_merge($defaults, $saved[$slug]) : $defaults; $enabled = !empty($provider['enabled']); $apiKey = $this->selectProviderApiKey($slug, $provider); $allowEmptyKey = !empty($provider['allow_empty_key']); if ((!$enabled && !$hasExplicitProvider) || ($apiKey === '' && !$allowEmptyKey)) { continue; } $name = sanitize_text_field($provider['name']); $model = ($mode === 'current' && $slug === $currentProvider && $modelOverride !== null && $modelOverride !== '') ? sanitize_text_field($modelOverride) : sanitize_text_field($provider['model']); $baseUrl = esc_url_raw($provider['base_url']); $this->addProviderInstance($provider, $apiKey, $model, $baseUrl, $name); } if ($mode === 'current' && empty($this->instances) && !$hasExplicitProvider) { foreach ($catalog as $slug => $defaults) { $provider = isset($saved[$slug]) && is_array($saved[$slug]) ? array_merge($defaults, $saved[$slug]) : $defaults; $apiKey = $this->selectProviderApiKey($slug, $provider); $allowEmptyKey = !empty($provider['allow_empty_key']); if (empty($provider['enabled']) || ($apiKey === '' && !$allowEmptyKey)) { continue; } $this->addProviderInstance( $provider, $apiKey, sanitize_text_field($provider['model']), esc_url_raw($provider['base_url']), sanitize_text_field($provider['name']) ); break; } } } private function addProviderInstance($provider, $apiKey, $model, $baseUrl, $name) { if ($provider['type'] === 'gemini' && class_exists('Gemini')) { $this->instances[] = new Gemini($apiKey, $model); } elseif ($provider['type'] === 'anthropic') { $this->instances[] = new AiKctAnthropic($apiKey, $model, $baseUrl, $name); } elseif ($provider['type'] === 'azure') { $this->instances[] = new AiKctAzureOpenAI($apiKey, $model, $baseUrl, $name); } else { $this->instances[] = new AiKctOpenAICompatible($apiKey, $model, $baseUrl, $name); } } private function selectProviderApiKey($slug, $provider) { $keys = array(); if (!empty($provider['api_keys']) && is_array($provider['api_keys'])) { foreach ($provider['api_keys'] as $keyConfig) { if (!is_array($keyConfig)) { continue; } $status = isset($keyConfig['status']) ? $keyConfig['status'] : 'active'; $key = isset($keyConfig['key']) ? trim((string) $keyConfig['key']) : ''; if ($status !== 'failed' && $key !== '') { $keys[] = $keyConfig; } } } if (empty($keys) && !empty($provider['api_key'])) { return trim((string) $provider['api_key']); } if (empty($keys)) { return ''; } $rotation = isset($provider['rotation']) ? $provider['rotation'] : 'round_robin'; if ($rotation === 'failover') { return trim((string) ($keys[0]['key'] ?? '')); } if ($rotation === 'random') { $selected = $keys[array_rand($keys)]; return isset($selected['key']) ? trim((string) $selected['key']) : ''; } if ($rotation === 'least_used') { usort($keys, function($a, $b) { return (int) ($a['used'] ?? 0) <=> (int) ($b['used'] ?? 0); }); return trim((string) ($keys[0]['key'] ?? '')); } if ($rotation === 'weighted') { $weighted = array(); foreach ($keys as $keyConfig) { $weight = max(1, (int) ($keyConfig['weight'] ?? 1)); for ($i = 0; $i < $weight; $i++) { $weighted[] = $keyConfig; } } $selected = $weighted[array_rand($weighted)]; return isset($selected['key']) ? trim((string) $selected['key']) : ''; } $indexOption = 'aikct_ai_key_rotation_' . sanitize_key($slug); $index = (int) get_option($indexOption, 0); $selected = $keys[$index % count($keys)]; update_option($indexOption, $index + 1); return isset($selected['key']) ? trim((string) $selected['key']) : ''; } public function sendRequest($prompt, $op = '') { $randomInstance = $this->instances[array_rand($this->instances)]; $rs = $randomInstance->sendRequest($prompt, $op); if (isset($rs['output'])) { $arr = array('prompt' => $prompt, 'result' => $rs['output']); aikct_pingprompt($arr); } return $rs; } } ?>