KryonOSDocs
Cloud & AI

On-Device Local AI Bindings

Run local INT8 neural inference directly on ESP32-S3 via System.localAI / LocalAI.

18. On-Device Local AI Engine (System.ai / System.localAI / LocalAI)

Introduced in KryonOS v3.0.0 (API Level 3)

KryonOS features a high-throughput, zero-copy on-device inference engine running directly on the ESP32-S3 Xtensa LX7 dual-core processor using Octal PSRAM and PIE SIMD vector instructions.

For the full architectural specification, 64-byte model compiler details, and low-level memory maps, consult the Detailed Local AI Technical Manual.

18.1 Local AI Method Summary

JavaScript MethodParametersReturn TypeDescription
System.ai.load(filePath)filePath: StringObject | falseMounts .krai or .bin into PSRAM, parses 64-byte header or companion tokenizer in PSRAM, returns { type, params, sizeMB, quant }.
System.ai.unload()NoneBooleanFrees PSRAM model pointers, KV-cache, scratchpads, and clears state.
System.ai.isLoaded()NoneBooleanReturns true if active model is resident in PSRAM.
System.ai.getInfo()NoneObject | nullReturns { type, params, sizeMB, quant, memUsed, psramFree, width, height, classes }.
System.ai.step(input)input: Number | ArrayNumberExecutes single-step forward pass returning next predicted token ID.
System.ai.encode(text)text: StringArray<Number>Native C++ BPE tokenization into integer token IDs.
System.ai.decode(tokenId)tokenId: NumberStringResolves integer token ID to ASCII/UTF-8 string segment.
System.ai.generate(options)options: ObjectBooleanStreaming generation loop with onToken, onComplete, onError, or image DMA rendering.
System.ai.blitFrame([x], [y])x: Number, y: NumberBooleanRe-blits the last synthesized image frame from DMA memory onto the display without re-running inference.
System.ai.setParam(key, val)key: String, val: NumberBooleanUpdates runtime params (temperature, top_k, top_p, scale).
System.ai.reset()NoneBooleanFlushes KV-cache and hidden states without unmounting weights.
System.ai.getLastError()NoneStringReturns description of the last error (e.g. invalid header, no PSRAM, file missing).
System.ai.createSampleModel(path)path: StringBooleanSynthesizes a valid INT8 Transformer test model binary file with vocabulary on flash/SD.

18.2 Complete ES5 Example: Autoregressive Text Generation

// 1. Mount model from SD card
var model = System.ai.load("/sd/models/tiny_chat_int8.bin");
if (!model) {
    console.error("Failed to load model from SD card!");
} else {
    console.log("Model loaded! Parameter count:", model.params);

    // 2. Stream generation asynchronously with callbacks
    System.ai.generate({
        prompt: "The capital of France is",
        max_tokens: 32,
        temperature: 0.7,
        top_k: 40,
        top_p: 0.9,
        onToken: function(word, tokenId) {
            System.print(word);
        },
        onComplete: function() {
            console.log("\n[Generation Complete]");
            System.ai.unload();
        },
        onError: function(err) {
            console.error("AI Error:", err);
        }
    });

    // 3. Main event loop (System.delay pumps background events from Core 1)
    while (System.ai.isLoaded()) {
        System.delay(10);
    }
}

18.3 Complete ES5 Example: On-Device Neural Image Generation (.krai)

// 1. Mount 96x96 DCGAN/VAE sprite generator
var imgModel = System.ai.load("/sd/kryonimage_3m_96_800.krai");
if (imgModel) {
    var info = System.ai.getInfo();
    console.log("Mounted Image Model:", info.width + "x" + info.height, info.classes + " elemental classes");

    // 2. Synthesize conditional "Fire" sprite rendered directly to LCD at (12, 30)
    System.ai.generate({
        prompt: "Fire",       // Class name (e.g. "Fire", "Water", "Electric", "Dragon")
        scale: 1.0,           // Guidance intensity
        temperature: 1.0,     // Latent Gaussian noise variance
        x: 12,                // Screen X position
        y: 30,                // Screen Y position
        onComplete: function() {
            console.log("Neural sprite synthesis complete! Rendered via SPI DMA.");
        },
        onError: function(err) {
            console.error("Image generation failed:", err);
        }
    });
}