Running Open-Source LLMs on Mobile: Practical Lessons for Building Local AI Agents

    This article shares practical lessons from integrating an open-source LLM into a local AI agent on mobile devices. It covers why on-device inference suits personal knowledge management apps, how a cross-platform plugin layer caused a system reboot, how to call the official inference engine directly with a singleton Engine and short-lived Conversations, and how to schedule concurrent requests from multiple agents.

    1. Why On-Device Models Are the New Starting Point for Local Agents

    As lightweight open-source LLMs keep improving, running them on a phone is becoming far more feasible. For developers building local personal knowledge management or life-logging apps, on-device models offer clear benefits:

    • Fully offline: All inference runs on the device, so data never leaves it. This meets privacy requirements by design.
    • No per-call cost: There is no cloud API billing, and the user experience does not depend on network quality.
    • Unified architecture: The upper-layer agent logic only needs to target a common LLM interface. The underlying backend can switch between cloud and local inference freely.

    On-device deployment also has clear constraints. Model files often reach several GB, memory and compute are limited, and inference frameworks are tightly coupled with the operating system. Integration therefore requires careful engineering, not just plugging in an SDK.

    2. Lesson From the First Attempt: Stability Risks in Cross-Platform Wrapper Layers

    Many teams integrating models on mobile first reach for an existing cross-platform wrapper package. These packages usually add a cross-platform plugin on top of the underlying inference engine. Their APIs look simple, and they are quick to adopt.

    On real devices, however, we ran into a problem far more serious than a crash: the entire phone went black and rebooted, rather than the app exiting with an ordinary error.

    Our troubleshooting process is worth reviewing:

    1. Control variables: On the same device with the same model file, the official example app, which calls the inference engine directly through its native API, ran normally.
    2. Isolate the difference: The only difference was the extra cross-platform plugin layer in between.
    3. Make a risk decision: Even though the root cause was not yet clear, a stability risk that can trigger a system-level reboot was unacceptable for a product.

    The general lesson is that in on-device inference, where code is tightly coupled with hardware and drivers, the value of cross-platform wrapper layers needs to be reassessed. Cross-platform frameworks suit UI and business logic. The inference call path should be as short as possible. If an official native API is available, avoid adding an extra abstraction just for convenience.

    3. Bypassing the Wrapper: Direct Integration With the Official Inference Engine

    3.1 Layered architecture

    We built our own Platform Channel so the Dart layer calls the official Android inference library directly. The call path looks like this:

    1. Dart business layer
    2. ↓ MethodChannel
    3. Kotlin plugin layer (LiteRtLmPlugin)
    4. ↓
    5. On-device inference engine

    3.2 Key design: a singleton Engine with on-demand Conversations

    This is the core memory management strategy of the whole solution:

    1. // Engine is a global singleton: loading the model weights (several GB) into GPU memory is very expensive
    2. val engine = Engine(
    3. EngineConfig(
    4. modelPath = modelPath,
    5. backend = Backend.GPU(),
    6. maxNumTokens = 10000,
    7. cacheDir = context.cacheDir.absolutePath,
    8. )
    9. )
    10. engine.initialize()
    11. // Create a lightweight Conversation for each inference and release it after use
    12. engine.createConversation(config).use { conversation ->
    13. conversation.sendMessageAsync(userText).collect { ... }
    14. }

    The design has three main points:

    • Load the model once: Loading several GB of weights into GPU memory is a heavy operation. The engine must be a global singleton to avoid repeated initialization, which can cause memory churn or even out-of-memory errors.
    • Keep conversations lightweight: The context and KV cache for a single exchange are wrapped in a Conversation. It is closed right after use, which prevents GPU memory leaks from accumulating in long sessions.
    • Stream the output: Inference returns tokens through an async stream, so the front end can render them one by one. Time to first token feels much better than waiting for the full response.

    This design matches what the official example app does. After switching to it, inference speed returned to normal and the system reboot stopped. This indirectly confirmed that the problem was in the intermediate wrapper layer.

    3.3 A provider abstraction that upper layers do not see

    On the Dart side, we implemented GemmaLocalClient, which implements the same LLMClient interface as the cloud provider. The upper-layer agent has no knowledge of whether inference runs in the cloud or locally. Switching requires changing only one configuration item.

    This is the prerequisite for a smooth on-device rollout: first unify cloud and local inference behind an interface abstraction, then replace the local backend. Writing separate call logic for the local model would make the code harder to maintain.

    4. Concurrent Multi-Agent Use: Global Locks and Resource Scheduling

    A local agent product often has more than one model caller. A knowledge management app, for example, usually has several agents working in parallel. Some process card content, some maintain the knowledge base, and some analyze images and audio. When they share one on-device inference engine, concurrent scheduling must be handled.

    Core principles:

    • The GPU inference engine serves only one session at a time. On-device memory is limited, and running several sessions concurrently can easily cause out-of-memory errors or severe performance drops.
    • Add a global mutex in the plugin layer. Requests from multiple agents enter a queue and run inference serially. The logic is “parallel in intent, serial in execution.”
    • Prioritize tasks. Requests the user is waiting on get the highest priority. Background analysis, such as image indexing, can wait until the device is idle so it does not take compute away from the foreground experience.
    • Set timeouts and fallbacks. Local inference can slow down when the device overheats or runs low on memory. Set reasonable timeouts and fall back to cloud inference when needed, so the agent workflow does not stop.

    5. Summary and Recommendations

    On-device open-source models open up new possibilities for local agents, but engineering quality determines whether they succeed. These lessons can be reused:

    1. Prefer the official native inference API. Use cross-platform wrapper layers for UI and business logic, not for the inference path.
    2. Use a singleton Engine with short-lived sessions. This is the standard pattern for memory management on devices.
    3. Unify behind an LLMClient abstraction. Cloud and local inference can be switched by configuration, which leaves room for fallback and migration.
    4. Serialize requests and set priorities in multi-agent scenarios. Do not assume on-device compute can handle unlimited concurrency.

    Models will keep improving. What makes on-device agents usable, though, is a set of fairly ordinary engineering details. We hope this record of our pitfalls helps developers building on-device AI applications.