# Run an AI model in Blazor with no server and no API key

> Source: <https://dev.to/lostbeard/run-an-ai-model-in-blazor-with-no-server-and-no-api-key-33l1>
> Published: 2026-11-26 01:38:14+00:00

**Recommendation:** 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.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

[Live demo](https://lostbeard.github.io/SpawnDev.Examples/ImageAI/) | [Full example on GitHub](https://github.com/LostBeard/SpawnDev.Examples/tree/main/ImageAI)

Adding 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.

For many jobs you need none of that. A small model can run on the visitor's own device, in the browser, from C#.

We 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.

A 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.

SpawnDev.ILGPU.ML reads the file and runs it on the GPU. It uses WebGPU when the browser has it, then WebGL, then WebAssembly.

```
dotnet new blazorwasm -o ImageAI --empty
cd ImageAI
dotnet add package SpawnDev.ILGPU.ML
dotnet add package SpawnDev.SpawnJS
dotnet add package SpawnDev.SpawnJS.Blazor
```

Download [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.

Replace `Program.cs`:

```
using ImageAI;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using SpawnDev.SpawnJS;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");

builder.Services.AddSpawnJSRuntime();

await builder.Build().SpawnJSRunAsync();
```

Add these lines to `_Imports.razor`:

```
@using SpawnDev.SpawnJS
@using SpawnDev.SpawnJS.JSObjects
async Task LoadModel()
{
    if (classifier is not null) return;
    status = "Loading the model...";
    StateHasChanged();
    var builder = MLContext.Create();
    await builder.AllAcceleratorsAsync();
    context = builder.ToContext();
    accelerator = await context.CreatePreferredAcceleratorAsync();
    await LoadSavedShaders();
    // The browser downloads the model into its own storage, and the weights go from there to the GPU.
    using var hub = new ModelHub(JS);
    using var stream = await hub.OpenStreamFromUrlAsync(JS.AppBaseUri + "mobilenetv2-7.onnx")
        ?? throw new Exception("this browser has no storage for the model");
    session = await InferenceSession.CreateFromStreamAsync(accelerator, stream);
    classifier = new ClassificationPipeline(session, accelerator);
}
```

The model is loaded when the first photo arrives, so visitors who only look at the page do not download it.

`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.

This matters. We first wrote this page with `HttpClient`, which brings the whole model into .NET:

| How the model is loaded | .NET memory allocated while loading | 
|---|---|
| `HttpClient` | 82 to 97 MB | 
| `ModelHub` | 2.9 MB | 

If you change the model, give the file a new name. A stored copy is found by its address and is not checked again.

`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.

```
// The browser decodes the photo. Its pixels go to the GPU without becoming a .NET array.
async Task<ImageData> GetPixels(Blob photo)
{
    using var window = new Window();
    using var bitmap = await window.CreateImageBitmap(photo);
    using var canvas = new HTMLCanvasElement();
    canvas.Width = (int)bitmap.Width;
    canvas.Height = (int)bitmap.Height;
    using var drawing = canvas.Get2DContext();
    drawing.DrawImage(bitmap, 0, 0, canvas.Width, canvas.Height);
    return drawing.GetImageData(0, 0, canvas.Width, canvas.Height);
}
```

The 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.

```
async Task Look(Blob photo)
{
    busy = true;
    answers = [];
    ShowPhoto(photo);
    try
    {
        await LoadModel();
        status = firstPhoto ? "Getting the GPU ready. First photo only..." : "Looking...";
        StateHasChanged();
        await Task.Delay(50); // let the page draw
        using var pixels = await GetPixels(photo);
        using var data = pixels.Data;
        var timer = Stopwatch.StartNew();
        answers = await classifier!.ClassifyAsync(data, pixels.Width, pixels.Height, topK: 3);
        status = $"Done in {timer.ElapsedMilliseconds} ms on {accelerator!.AcceleratorType}{(firstPhoto ? ", including getting the GPU ready. Try another." : ".")}";
        if (firstPhoto) await SaveShaders();
        firstPhoto = false;
    }
    catch (Exception ex)
    {
        status = $"That did not work: {ex.Message}";
    }
    busy = false;
}
```

`ClassifyAsync` takes the pixels and returns the best guesses, each with a label and a confidence.

For the two sample photos:

| Photo | First guess | Second guess | 
|---|---|---|
| Red panda | lesser panda, 100% | polecat, 0% | 
| Labrador | Labrador retriever, 71% | golden retriever, 28% | 

"Lesser panda" is another name for the red panda.

How long it took on one PC with an RTX 4070, in Chrome with WebGPU:

| Step | Time | 
|---|---|
| First photo, first visit | about 9 seconds | 
| First photo, next visit | about 1.6 seconds | 
| Every photo after that | about 0.05 to 0.1 seconds for the model | 

The first photo includes loading the model and preparing it for your GPU, so the page says so while you wait. Your times will differ.

Browsers 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.

Preparing the GPU means turning C# kernels into shader code. With WebGPU you can save that code in the browser after the first photo:

``` js
async Task SaveShaders()
{
    try
    {
        using var navigator = new Navigator();
        using var storage = navigator.Storage;
        using var folder = await storage.GetDirectory();
        using var handle = await folder.GetFileHandle(ShaderFile, create: true);
        using var target = await handle.CreateWritable();
        await target.Write(ShaderArtifactSerializer.ExportCache());
        await target.Close();
    }
    catch { } // storage is full or blocked: only the next visit is slower
}
```

And load it on the next visit, before the model:

``` js
async Task LoadSavedShaders()
{
    try
    {
        using var navigator = new Navigator();
        using var storage = navigator.Storage;
        using var folder = await storage.GetDirectory();
        using var handle = await folder.GetFileHandle(ShaderFile);
        using var file = await handle.GetFile();
        ShaderArtifactSerializer.ImportCache(await file.Text());
    }
    catch { } // nothing saved yet, or it cannot be used: the shaders are generated as usual
}
```

In 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.

Replace `Pages/Home.razor` with this:

```
@page "/"
@using System.Diagnostics
@using ILGPU
@using ILGPU.Runtime
@using SpawnDev.ILGPU
@using SpawnDev.ILGPU.ML
@using SpawnDev.ILGPU.ML.Hub
@using SpawnDev.ILGPU.ML.Pipelines
@inject SpawnJSRuntime JS
@implements IDisposable

<main>
    <h1>What is in this photo?</h1>
    <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>
    <p><label>Your photo: <input id="pick" type="file" accept="image/*" disabled="@busy" @onchange="UseChosenPhoto" /></label></p>
    <button id="panda" disabled="@busy" @onclick='() => UseSample("red-panda.jpg")'>Try a red panda</button>
    <button id="dog" disabled="@busy" @onclick='() => UseSample("labrador.jpg")'>Try a dog</button>
    <p id="status" role="status">@status</p>
    @if (photoUrl is not null)
    {
        <img src="@photoUrl" alt="The photo being looked at" />
    }
    <ol id="answers">
        @foreach (var answer in answers)
        {
            <li>@answer.Label: @answer.Confidence.ToString("P0")</li>
        }
    </ol>
    <p><small>Sample photos: Wikimedia Commons, CC0. Model: MobileNetV2 from the ONNX Model Zoo, Apache-2.0.</small></p>
</main>

@code {
    bool busy;
    bool firstPhoto = true;
    string status = "";
    string? photoUrl;
    ClassificationResult[] answers = [];
    Context? context;
    Accelerator? accelerator;
    InferenceSession? session;
    ClassificationPipeline? classifier;

    async Task LoadModel()
    {
        if (classifier is not null) return;
        status = "Loading the model...";
        StateHasChanged();
        var builder = MLContext.Create();
        await builder.AllAcceleratorsAsync();
        context = builder.ToContext();
        accelerator = await context.CreatePreferredAcceleratorAsync();
        await LoadSavedShaders();
        // The browser downloads the model into its own storage, and the weights go from there to the GPU.
        using var hub = new ModelHub(JS);
        using var stream = await hub.OpenStreamFromUrlAsync(JS.AppBaseUri + "mobilenetv2-7.onnx")
            ?? throw new Exception("this browser has no storage for the model");
        session = await InferenceSession.CreateFromStreamAsync(accelerator, stream);
        classifier = new ClassificationPipeline(session, accelerator);
    }

    async Task Look(Blob photo)
    {
        busy = true;
        answers = [];
        ShowPhoto(photo);
        try
        {
            await LoadModel();
            status = firstPhoto ? "Getting the GPU ready. First photo only..." : "Looking...";
            StateHasChanged();
            await Task.Delay(50); // let the page draw
            using var pixels = await GetPixels(photo);
            using var data = pixels.Data;
            var timer = Stopwatch.StartNew();
            answers = await classifier!.ClassifyAsync(data, pixels.Width, pixels.Height, topK: 3);
            status = $"Done in {timer.ElapsedMilliseconds} ms on {accelerator!.AcceleratorType}{(firstPhoto ? ", including getting the GPU ready. Try another." : ".")}";
            if (firstPhoto) await SaveShaders();
            firstPhoto = false;
        }
        catch (Exception ex)
        {
            status = $"That did not work: {ex.Message}";
        }
        busy = false;
    }

    // Getting a WebGPU device ready means generating shader code. Keep it, so the next visit starts faster.
    const string ShaderFile = "shaders.json";

    async Task LoadSavedShaders()
    {
        try
        {
            using var navigator = new Navigator();
            using var storage = navigator.Storage;
            using var folder = await storage.GetDirectory();
            using var handle = await folder.GetFileHandle(ShaderFile);
            using var file = await handle.GetFile();
            ShaderArtifactSerializer.ImportCache(await file.Text());
        }
        catch { } // nothing saved yet, or it cannot be used: the shaders are generated as usual
    }

    async Task SaveShaders()
    {
        try
        {
            using var navigator = new Navigator();
            using var storage = navigator.Storage;
            using var folder = await storage.GetDirectory();
            using var handle = await folder.GetFileHandle(ShaderFile, create: true);
            using var target = await handle.CreateWritable();
            await target.Write(ShaderArtifactSerializer.ExportCache());
            await target.Close();
        }
        catch { } // storage is full or blocked: only the next visit is slower
    }

    // The browser decodes the photo. Its pixels go to the GPU without becoming a .NET array.
    async Task<ImageData> GetPixels(Blob photo)
    {
        using var window = new Window();
        using var bitmap = await window.CreateImageBitmap(photo);
        using var canvas = new HTMLCanvasElement();
        canvas.Width = (int)bitmap.Width;
        canvas.Height = (int)bitmap.Height;
        using var drawing = canvas.Get2DContext();
        drawing.DrawImage(bitmap, 0, 0, canvas.Width, canvas.Height);
        return drawing.GetImageData(0, 0, canvas.Width, canvas.Height);
    }

    async Task UseChosenPhoto()
    {
        using var document = JS.GetDocument()!;
        using var input = document.GetElementById<HTMLInputElement>("pick")!;
        using var files = input.Files;
        using var photo = files?.FirstOrDefault();
        if (photo is not null) await Look(photo);
    }

    async Task UseSample(string url)
    {
        using var response = await JS.Fetch(url);
        using var photo = await response.Blob();
        await Look(photo);
    }

    void ShowPhoto(Blob photo)
    {
        if (photoUrl is not null) URL.RevokeObjectURL(photoUrl);
        photoUrl = URL.CreateObjectURL(photo);
    }

    public void Dispose()
    {
        if (photoUrl is not null) URL.RevokeObjectURL(photoUrl);
        classifier?.Dispose();
        session?.Dispose();
        accelerator?.Dispose();
        context?.Dispose();
    }
}
```

Run `dotnet run` in your project, or clone the finished one:

```
git clone https://github.com/LostBeard/SpawnDev.Examples
cd SpawnDev.Examples/ImageAI
dotnet run
```


