Running Open-Source LLM Agents Fully On-Device: Architecture Lessons and Pitfalls

    A hands-on account of integrating a fully offline, open-source LLM agent into a mobile app: why we abandoned a community cross-platform plugin after device-level crashes, how we rebuilt the bridge on the official native runtime, and how a global inference lock solved multi-agent concurrency on a single on-device model instance.

    Running Open-Source LLM Agents Fully On-Device: Architecture Lessons and Pitfalls

    Why Move an LLM to the Phone Itself

    We are building a fully local AI app for personal life logging and knowledge management. The core design principle is that all data stays on the device, while users can optionally plug in a cloud LLM service as the inference backend. This strikes a good balance between privacy and flexibility, but it has one persistent weakness: without a network connection, all intelligence features stop working.

    As on-device open-source models have shrunk to the 2B–4B parameter range and mobile-GPU-oriented inference runtimes have emerged, a “fully offline, zero-cloud-dependency” local agent became viable for the first time. So we decided to add a purely offline inference option, targeting ordinary mid-to-high-end phones with a model file of roughly 2.6GB.

    The whole effort took several days and plenty of pitfalls. This article documents the integration process, the architectural evolution, and the key decisions, for developers facing similar requirements.

    Lesson One: The Stability Trap of Cross-Platform Plugin Wrappers

    Our app is built on a cross-platform UI framework, so we initially took the easy route and used a community-maintained plugin package. It wraps the underlying on-device inference engine with a clean-looking API — a few lines of code for model loading and chat calls.

    In practice, the problems were severe: it occasionally caused the entire phone to black out and reboot. Note that this was not an app crash, but a device-level restart.

    We ran controlled experiments: on the same phone, with the same model file, the official sample app (which calls the inference engine directly in native code) showed no such issue. The difference was that the community plugin added an extra cross-platform bridging layer on top of the native inference engine. Although the exact root cause of the reboots was never fully isolated, plausible explanations include:

    • The cross-platform channel’s threading model for transferring large data blocks or streaming callbacks does not match the inference engine’s expectations;
    • The plugin layer’s lifecycle management of native resources (GPU memory, inference sessions) is not rigorous enough, and error paths may trigger low-level driver faults;
    • Model loading and inference run on unsuitable threads, causing system-level resource contention.

    Since the local agent is a core capability of the app, this stability risk was unacceptable. We dropped the wrapper and decided to bridge directly against the official native APIs. Lesson one: for capabilities that touch low-level hardware resources (GPU, NPU, large memory), stay as close as possible to the official native APIs and avoid unnecessary intermediate wrappers.

    Step Two: Rebuilding with a Native Bridge Architecture

    After abandoning the off-the-shelf plugin, we implemented our own cross-platform communication channel, connecting directly to the official native inference engine library. The overall architecture became:

    1. UI layer (Dart)
    2. ↓ MethodChannel
    3. Native plugin layer (Kotlin)
    4. ↓ Official SDK calls
    5. On-device inference engine (GPU backend)

    The core design of the native plugin is an Engine singleton with sessions created on demand, consistent with the official sample app:

    1. // Engine is initialized exactly once globally: loads the ~2.6GB model into GPU memory
    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 per inference request, release it when done
    12. engine.createConversation(config).use { conversation ->
    13. conversation.sendMessageAsync(userText).collect { partial ->
    14. // Streamed results are pushed back to the UI layer via an EventChannel
    15. }
    16. }

    Key points of this design:

    1. Model loading is separated from inference sessions. Model loading is the heaviest operation and must happen exactly once globally; conversation objects are lightweight, created and destroyed independently for each inference request. This avoids cross-contamination of conversation history and makes error recovery easier.
    2. Streaming output uses a dedicated event channel. The method-call channel handles requests and final responses, while the event channel pushes tokens one by one. Keeping these responsibilities separate lets the UI render the generation process in real time.
    3. The interface abstraction stays transparent to the upper layers. The UI-side local inference client implements exactly the same interface as the cloud inference client, making it fully transparent to the agent orchestration logic — switching from a cloud model to a local model requires changing only one configuration item.

    After switching to this architecture, inference speed returned to normal and the phone never rebooted again. Lesson two: singleton for heavy resources, create-and-dispose for lightweight sessions — this is the fundamental pattern for on-device inference integration.

    Step Three: Multi-Agent Concurrency and a Global Lock

    Multiple agents run in parallel inside the app: a card-processing agent, a knowledge-base management agent, an image-and-audio asset analysis agent, and so on. In the cloud-model era, concurrency was not an issue — HTTP requests are naturally parallel. On-device models are fundamentally different: the entire device has a single model instance, and GPU memory and compute are exclusive resources.

    If multiple agents send inference requests to the local engine simultaneously, the result ranges from garbled, interleaved outputs and sharp slowdowns to out-of-memory crashes. So we introduced a global inference lock: all local inference requests must go through a unified, serially executed dispatch queue.

    1. Agent A ─┐
    2. Agent B ─┼→ Global lock / serial queue → Local inference engine
    3. Agent C ─┘

    A few implementation notes:

    • Lock at the granularity of “one complete inference” rather than “one token,” so streaming generation is never interrupted;
    • The queue needs timeout and fallback strategies: if local inference is queued for too long and the user permits it, fall back to the cloud model;
    • Time-consuming tasks such as asset analysis should run at lower priority, yielding compute to the user’s immediate interactions.

    Lesson three: a single on-device model instance means inference is inherently a serial resource, and any multi-agent architecture must design its scheduling layer around this constraint.

    Summary and Recommendations

    On-device open-source LLMs have turned “a fully offline local agent” from a concept into a shippable product capability, but the engineering effort goes far beyond calling a cloud API. Looking back, three core lessons stand out: stay close to the official native APIs for stability; use an Engine singleton with create-and-dispose sessions for lifecycle management; and serialize inference globally to fit the constraints of a single model instance. For apps that value data sovereignty and offline availability, this path is worth the investment.