{"slug": "run-an-ai-model-in-blazor-with-no-server-and-no-api-key", "title": "Run an AI model in Blazor with no server and no API key", "summary": "A developer published a Blazor WebAssembly example that runs MobileNetV2 image classification entirely in the browser from C#, with no server and no API key. The demo uses SpawnDev.ILGPU.ML to execute the 14 MB ONNX model on the GPU via WebGPU, falling back to WebGL and then WebAssembly, and streams the model through ModelHub into browser storage rather than .NET memory — cutting allocation during load from 82–97 MB with HttpClient to 2.9 MB. Photos are decoded by the browser and their pixels passed to the GPU without being uploaded or copied into .NET arrays.", "body_md": "[Live demo](https://lostbeard.github.io/SpawnDev.Examples/ImageAI/) | [Full example on GitHub](https://github.com/LostBeard/SpawnDev.Examples/tree/main/ImageAI)\n\nAdding AI to an app often means an account, an API key, a bill for every request, and sending your users' data to someone else's server.\n\nFor many jobs you need none of that. A small model can run on the visitor's own device, in the browser, from C#.\n\nWe will build a page that names what is in a photo. The photo is never uploaded. You need the .NET 10 SDK and a browser.\n\nA model is a file. This one is MobileNetV2, a 14 MB image recognition network from the ONNX Model Zoo (Apache-2.0). It knows 1,000 kinds of things, from dog breeds to kitchen tools.\n\nSpawnDev.ILGPU.ML reads the file and runs it on the GPU. It uses WebGPU when the browser has it, then WebGL, then WebAssembly.\n\n```\ndotnet new blazorwasm -o ImageAI --empty\ncd ImageAI\ndotnet add package SpawnDev.ILGPU.ML\ndotnet add package SpawnDev.SpawnJS\ndotnet add package SpawnDev.SpawnJS.Blazor\n```\n\nDownload [mobilenetv2-7.onnx](https://huggingface.co/onnxmodelzoo/mobilenetv2-7/resolve/main/mobilenetv2-7.onnx) into `wwwroot`. For the sample buttons, also save [red-panda.jpg](https://github.com/LostBeard/SpawnDev.Examples/blob/main/ImageAI/wwwroot/red-panda.jpg) and [labrador.jpg](https://github.com/LostBeard/SpawnDev.Examples/blob/main/ImageAI/wwwroot/labrador.jpg) there.\n\nReplace `Program.cs`:\n\n```\nusing ImageAI;\nusing Microsoft.AspNetCore.Components.WebAssembly.Hosting;\nusing SpawnDev.SpawnJS;\n\nvar builder = WebAssemblyHostBuilder.CreateDefault(args);\nbuilder.RootComponents.Add<App>(\"#app\");\n\nbuilder.Services.AddSpawnJSRuntime();\n\nawait builder.Build().SpawnJSRunAsync();\n```\n\nAdd these lines to `_Imports.razor`:\n\n```\n@using SpawnDev.SpawnJS\n@using SpawnDev.SpawnJS.JSObjects\nasync Task LoadModel()\n{\n    if (classifier is not null) return;\n    status = \"Loading the model...\";\n    StateHasChanged();\n    var builder = MLContext.Create();\n    await builder.AllAcceleratorsAsync();\n    context = builder.ToContext();\n    accelerator = await context.CreatePreferredAcceleratorAsync();\n    await LoadSavedShaders();\n    // The browser downloads the model into its own storage, and the weights go from there to the GPU.\n    using var hub = new ModelHub(JS);\n    using var stream = await hub.OpenStreamFromUrlAsync(JS.AppBaseUri + \"mobilenetv2-7.onnx\")\n        ?? throw new Exception(\"this browser has no storage for the model\");\n    session = await InferenceSession.CreateFromStreamAsync(accelerator, stream);\n    classifier = new ClassificationPipeline(session, accelerator);\n}\n```\n\nThe model is loaded when the first photo arrives, so visitors who only look at the page do not download it.\n\n`ModelHub` has the browser download the model into its own storage. The session reads the weights from there and sends them to the GPU, without making the model a .NET array. The next visit uses the stored copy.\n\nThis matters. We first wrote this page with `HttpClient`, which brings the whole model into .NET:\n\n| How the model is loaded | .NET memory allocated while loading | \n|---|---|\n| `HttpClient` | 82 to 97 MB | \n| `ModelHub` | 2.9 MB | \n\nIf you change the model, give the file a new name. A stored copy is found by its address and is not checked again.\n\n`ClassificationPipeline` does the rest of the work around the model: it resizes the photo, prepares the colors, and turns the numbers that come out into names.\n\n```\n// The browser decodes the photo. Its pixels go to the GPU without becoming a .NET array.\nasync Task<ImageData> GetPixels(Blob photo)\n{\n    using var window = new Window();\n    using var bitmap = await window.CreateImageBitmap(photo);\n    using var canvas = new HTMLCanvasElement();\n    canvas.Width = (int)bitmap.Width;\n    canvas.Height = (int)bitmap.Height;\n    using var drawing = canvas.Get2DContext();\n    drawing.DrawImage(bitmap, 0, 0, canvas.Width, canvas.Height);\n    return drawing.GetImageData(0, 0, canvas.Width, canvas.Height);\n}\n```\n\nThe browser already knows how to read JPEG, PNG and WebP files, so we let it. The pixels stay in the browser's memory on their way to the GPU.\n\n```\nasync Task Look(Blob photo)\n{\n    busy = true;\n    answers = [];\n    ShowPhoto(photo);\n    try\n    {\n        await LoadModel();\n        status = firstPhoto ? \"Getting the GPU ready. First photo only...\" : \"Looking...\";\n        StateHasChanged();\n        await Task.Delay(50); // let the page draw\n        using var pixels = await GetPixels(photo);\n        using var data = pixels.Data;\n        var timer = Stopwatch.StartNew();\n        answers = await classifier!.ClassifyAsync(data, pixels.Width, pixels.Height, topK: 3);\n        status = $\"Done in {timer.ElapsedMilliseconds} ms on {accelerator!.AcceleratorType}{(firstPhoto ? \", including getting the GPU ready. Try another.\" : \".\")}\";\n        if (firstPhoto) await SaveShaders();\n        firstPhoto = false;\n    }\n    catch (Exception ex)\n    {\n        status = $\"That did not work: {ex.Message}\";\n    }\n    busy = false;\n}\n```\n\n`ClassifyAsync` takes the pixels and returns the best guesses, each with a label and a confidence.\n\nFor the two sample photos:\n\n| Photo | First guess | Second guess | \n|---|---|---|\n| Red panda | lesser panda, 100% | polecat, 0% | \n| Labrador | Labrador retriever, 71% | golden retriever, 28% | \n\n\"Lesser panda\" is another name for the red panda.\n\nHow long it took on one PC with an RTX 4070, in Chrome with WebGPU:\n\n| Step | Time | \n|---|---|\n| First photo, first visit | about 9 seconds | \n| First photo, next visit | about 1.6 seconds | \n| Every photo after that | about 0.05 to 0.1 seconds for the model | \n\nThe first photo includes loading the model and preparing it for your GPU, so the page says so while you wait. Your times will differ.\n\nBrowsers without WebGPU use WebGL or WebAssembly instead. On the same PC with WebGL, the model took about 1.5 to 1.7 seconds for the first photo and about 0.3 seconds for each one after it.\n\nPreparing the GPU means turning C# kernels into shader code. With WebGPU you can save that code in the browser after the first photo:\n\n``` js\nasync Task SaveShaders()\n{\n    try\n    {\n        using var navigator = new Navigator();\n        using var storage = navigator.Storage;\n        using var folder = await storage.GetDirectory();\n        using var handle = await folder.GetFileHandle(ShaderFile, create: true);\n        using var target = await handle.CreateWritable();\n        await target.Write(ShaderArtifactSerializer.ExportCache());\n        await target.Close();\n    }\n    catch { } // storage is full or blocked: only the next visit is slower\n}\n```\n\nAnd load it on the next visit, before the model:\n\n``` js\nasync Task LoadSavedShaders()\n{\n    try\n    {\n        using var navigator = new Navigator();\n        using var storage = navigator.Storage;\n        using var folder = await storage.GetDirectory();\n        using var handle = await folder.GetFileHandle(ShaderFile);\n        using var file = await handle.GetFile();\n        ShaderArtifactSerializer.ImportCache(await file.Text());\n    }\n    catch { } // nothing saved yet, or it cannot be used: the shaders are generated as usual\n}\n```\n\nIn our test this took the first photo of a return visit from about 4 seconds to about 1.6. If you update the library, the saved code is ignored and made again.\n\nReplace `Pages/Home.razor` with this:\n\n```\n@page \"/\"\n@using System.Diagnostics\n@using ILGPU\n@using ILGPU.Runtime\n@using SpawnDev.ILGPU\n@using SpawnDev.ILGPU.ML\n@using SpawnDev.ILGPU.ML.Hub\n@using SpawnDev.ILGPU.ML.Pipelines\n@inject SpawnJSRuntime JS\n@implements IDisposable\n\n<main>\n    <h1>What is in this photo?</h1>\n    <p>The AI model runs on this device. Your photo is not uploaded anywhere. The first photo takes longer: it downloads the model (14 MB) and gets your GPU ready for it.</p>\n    <p><label>Your photo: <input id=\"pick\" type=\"file\" accept=\"image/*\" disabled=\"@busy\" @onchange=\"UseChosenPhoto\" /></label></p>\n    <button id=\"panda\" disabled=\"@busy\" @onclick='() => UseSample(\"red-panda.jpg\")'>Try a red panda</button>\n    <button id=\"dog\" disabled=\"@busy\" @onclick='() => UseSample(\"labrador.jpg\")'>Try a dog</button>\n    <p id=\"status\" role=\"status\">@status</p>\n    @if (photoUrl is not null)\n    {\n        <img src=\"@photoUrl\" alt=\"The photo being looked at\" />\n    }\n    <ol id=\"answers\">\n        @foreach (var answer in answers)\n        {\n            <li>@answer.Label: @answer.Confidence.ToString(\"P0\")</li>\n        }\n    </ol>\n    <p><small>Sample photos: Wikimedia Commons, CC0. Model: MobileNetV2 from the ONNX Model Zoo, Apache-2.0.</small></p>\n</main>\n\n@code {\n    bool busy;\n    bool firstPhoto = true;\n    string status = \"\";\n    string? photoUrl;\n    ClassificationResult[] answers = [];\n    Context? context;\n    Accelerator? accelerator;\n    InferenceSession? session;\n    ClassificationPipeline? classifier;\n\n    async Task LoadModel()\n    {\n        if (classifier is not null) return;\n        status = \"Loading the model...\";\n        StateHasChanged();\n        var builder = MLContext.Create();\n        await builder.AllAcceleratorsAsync();\n        context = builder.ToContext();\n        accelerator = await context.CreatePreferredAcceleratorAsync();\n        await LoadSavedShaders();\n        // The browser downloads the model into its own storage, and the weights go from there to the GPU.\n        using var hub = new ModelHub(JS);\n        using var stream = await hub.OpenStreamFromUrlAsync(JS.AppBaseUri + \"mobilenetv2-7.onnx\")\n            ?? throw new Exception(\"this browser has no storage for the model\");\n        session = await InferenceSession.CreateFromStreamAsync(accelerator, stream);\n        classifier = new ClassificationPipeline(session, accelerator);\n    }\n\n    async Task Look(Blob photo)\n    {\n        busy = true;\n        answers = [];\n        ShowPhoto(photo);\n        try\n        {\n            await LoadModel();\n            status = firstPhoto ? \"Getting the GPU ready. First photo only...\" : \"Looking...\";\n            StateHasChanged();\n            await Task.Delay(50); // let the page draw\n            using var pixels = await GetPixels(photo);\n            using var data = pixels.Data;\n            var timer = Stopwatch.StartNew();\n            answers = await classifier!.ClassifyAsync(data, pixels.Width, pixels.Height, topK: 3);\n            status = $\"Done in {timer.ElapsedMilliseconds} ms on {accelerator!.AcceleratorType}{(firstPhoto ? \", including getting the GPU ready. Try another.\" : \".\")}\";\n            if (firstPhoto) await SaveShaders();\n            firstPhoto = false;\n        }\n        catch (Exception ex)\n        {\n            status = $\"That did not work: {ex.Message}\";\n        }\n        busy = false;\n    }\n\n    // Getting a WebGPU device ready means generating shader code. Keep it, so the next visit starts faster.\n    const string ShaderFile = \"shaders.json\";\n\n    async Task LoadSavedShaders()\n    {\n        try\n        {\n            using var navigator = new Navigator();\n            using var storage = navigator.Storage;\n            using var folder = await storage.GetDirectory();\n            using var handle = await folder.GetFileHandle(ShaderFile);\n            using var file = await handle.GetFile();\n            ShaderArtifactSerializer.ImportCache(await file.Text());\n        }\n        catch { } // nothing saved yet, or it cannot be used: the shaders are generated as usual\n    }\n\n    async Task SaveShaders()\n    {\n        try\n        {\n            using var navigator = new Navigator();\n            using var storage = navigator.Storage;\n            using var folder = await storage.GetDirectory();\n            using var handle = await folder.GetFileHandle(ShaderFile, create: true);\n            using var target = await handle.CreateWritable();\n            await target.Write(ShaderArtifactSerializer.ExportCache());\n            await target.Close();\n        }\n        catch { } // storage is full or blocked: only the next visit is slower\n    }\n\n    // The browser decodes the photo. Its pixels go to the GPU without becoming a .NET array.\n    async Task<ImageData> GetPixels(Blob photo)\n    {\n        using var window = new Window();\n        using var bitmap = await window.CreateImageBitmap(photo);\n        using var canvas = new HTMLCanvasElement();\n        canvas.Width = (int)bitmap.Width;\n        canvas.Height = (int)bitmap.Height;\n        using var drawing = canvas.Get2DContext();\n        drawing.DrawImage(bitmap, 0, 0, canvas.Width, canvas.Height);\n        return drawing.GetImageData(0, 0, canvas.Width, canvas.Height);\n    }\n\n    async Task UseChosenPhoto()\n    {\n        using var document = JS.GetDocument()!;\n        using var input = document.GetElementById<HTMLInputElement>(\"pick\")!;\n        using var files = input.Files;\n        using var photo = files?.FirstOrDefault();\n        if (photo is not null) await Look(photo);\n    }\n\n    async Task UseSample(string url)\n    {\n        using var response = await JS.Fetch(url);\n        using var photo = await response.Blob();\n        await Look(photo);\n    }\n\n    void ShowPhoto(Blob photo)\n    {\n        if (photoUrl is not null) URL.RevokeObjectURL(photoUrl);\n        photoUrl = URL.CreateObjectURL(photo);\n    }\n\n    public void Dispose()\n    {\n        if (photoUrl is not null) URL.RevokeObjectURL(photoUrl);\n        classifier?.Dispose();\n        session?.Dispose();\n        accelerator?.Dispose();\n        context?.Dispose();\n    }\n}\n```\n\nRun `dotnet run` in your project, or clone the finished one:\n\n```\ngit clone https://github.com/LostBeard/SpawnDev.Examples\ncd SpawnDev.Examples/ImageAI\ndotnet run\n```\n\n", "url": "https://wpnews.pro/news/run-an-ai-model-in-blazor-with-no-server-and-no-api-key", "canonical_source": "https://dev.to/lostbeard/run-an-ai-model-in-blazor-with-no-server-and-no-api-key-33l1", "published_at": "2026-11-26 01:38:14+00:00", "updated_at": "2026-11-26 01:44:34.839155+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "computer-vision", "ai-tools", "developer-tools"], "entities": ["SpawnDev.ILGPU.ML", "SpawnDev.SpawnJS", "Blazor", "MobileNetV2", "ONNX Model Zoo", "WebGPU", "GitHub", "Hugging Face"], "also_reported_by": [], "takeaway": "Streaming an ONNX model through ModelHub into browser storage instead of HttpClient cut .NET memory allocated during load from 82–97 MB to 2.9 MB while still feeding weights to the GPU.", "recommendation": {"advice": "Load client-side ONNX models via ModelHub's browser-storage stream rather than HttpClient to avoid allocating tens of megabytes in .NET, and rename the model file whenever its contents change.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/run-an-ai-model-in-blazor-with-no-server-and-no-api-key", "markdown": "https://wpnews.pro/news/run-an-ai-model-in-blazor-with-no-server-and-no-api-key.md", "text": "https://wpnews.pro/news/run-an-ai-model-in-blazor-with-no-server-and-no-api-key.txt", "jsonld": "https://wpnews.pro/news/run-an-ai-model-in-blazor-with-no-server-and-no-api-key.jsonld"}}