MaybeLogMessage($message); // Use the local Ollama endpoint $url = "http://localhost:11434/api/chat"; // No API key needed for local Ollama, ignore $apiKey parameter // Make the API request using WordPress HTTP API $response = \wp_remote_post($url, [ 'headers' => [ 'Content-Type' => 'application/json', ], 'body' => json_encode([ "model" => "deepseek-r1:14b", // Your local model name "messages" => $message, // Same message array as before "max_tokens" => 3000, // Supported by Ollama "stream" => false, // Ensure full response (non-streaming) "context" => [] // Explicitly set empty context ]), 'timeout' => 300 ]); // Check if the request failed if (is_wp_error($response)) { throw new FriendlyException($response->get_error_message()); } // Get HTTP response code and body $httpCode = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $decodedBody = json_decode($body, true); // Convert JSON response to array // Check for Ollama-specific error (e.g., model not found) $errorMessage = Sanitizer::GetStringValueFromPath($decodedBody, ['error'], 'Unknown error'); // Ollama returns 200 for success, 404 or 500 for errors if ($httpCode !== 200) { throw new FriendlyException("Local DeepSeek API error: " . $errorMessage); } // Ollama’s response has "message" directly, no "choices" array $content = Sanitizer::GetStringValueFromPath($decodedBody, ['message', 'content'], null); if ($content === null) { throw new FriendlyException("There was no response from the local AI, please try again"); } LogManager::LogDebug("Local DeepSeek Response:\r\n" . $content); $content = preg_replace('/.*?<\/think>/is', '', $content); // Optional: Trim any extra whitespace left behind $content = trim($content); $startPos = strpos($content, '{'); $endPos = strrpos($content, '}'); if ($startPos !== false && $endPos !== false && $startPos < $endPos) { $content = substr($content, $startPos, $endPos - $startPos + 1); } else { throw new FriendlyException("Invalid response format from the local AI."); } return $content; } public function GetModelName() { return 'deepseek-r1:14b'; // Reflect the local model name } }