Skip to main content

Memory Management

On-device AI models are memory-intensive. Proper memory management is critical for app stability.

Load Only What You Need

Unload When Not Needed

Monitor Memory Before Loading

Performance Optimization

Use Quantized Models

Use Streaming for Better UX

Set Appropriate Token Limits

App Lifecycle

Handle Background/Foreground

Preload Models at Launch

Error Handling

Always Handle Errors

Provide User Feedback

Testing

Test on Real Devices

Measure Performance

Security

Protect API Keys

Clear Sensitive Data

Android-Specific Gotchas

Initialization Order

The SDK initialization on Android requires a strict sequence:
  1. AndroidPlatformContext.initialize(this) — sets up Android storage paths
  2. RunAnywhere.initialize(environment = SDKEnvironment.DEVELOPMENT) — SDK init
  3. CppBridgeModelPaths.setBaseDirectory(path) — model storage path
  4. LlamaCPP.register(priority = 100) — LLM/VLM backend
  5. ONNX.register(priority = 100) — STT/TTS backend
  6. ModelService.registerDefaultModels() — register model definitions

LlamaCPP VLM Registration May Fail

Wrap LlamaCPP.register() in a try/catch. VLM native registration may fail if the .so library doesn’t include nativeRegisterVlm, but LLM text generation still works:

isVLMModelLoaded is a Property

Unlike other model state checks which are suspend functions (isLLMModelLoaded(), isSTTModelLoaded(), isTTSVoiceLoaded()), isVLMModelLoaded is a direct property access — not a suspend function.

JitPack Repository Required

The RunAnywhere SDK has transitive dependencies (android-vad, PRDownloader) hosted on JitPack. Add maven { url = uri("https://jitpack.io") } to your settings.gradle.kts repositories.

Audio Format for STT

STT requires 16kHz mono PCM 16-bit audio. TTS output is WAV format. The voice pipeline assumes a 22050 Hz sample rate for TTS playback.

VLM Image Path Workaround

VLMImage.fromFilePath() requires a file path, not a content URI. Images from the photo picker must be saved to a temporary file first:

Summary Checklist

  • Use quantized models (Q4) for mobile devices
  • Unload models when backgrounding the app
  • Use streaming for long text generation
  • Handle all error categories appropriately
  • Test on physical devices, not simulators
  • Preload commonly used models at app startup
  • Monitor memory before loading large models
  • Secure API keys using BuildConfig or secure storage