Deploying On-Device LLMs on Mobile: A Practical Guide to Building a Fully Offline Local Agent

    This article shares a practical approach to running small-parameter large language models entirely on mobile devices, enabling a fully offline local agent for personal knowledge management and life-logging apps. It covers the motivation for on-device inference, pitfalls of cross-platform plugins, a stable architecture built on native inference APIs and custom platform channels, and key engineering considerations for production deployment. The guide offers reusable patterns for teams aiming to build privacy-preserving, network-independent AI capabilities on phones.

    Why Move Large Models to Mobile Phones

    With the maturity of small-parameter open-source LLMs, running inference directly on mobile devices has moved from lab experiments to engineering practicality. For our app—a purely local personal knowledge management and life-logging tool—this opens up a new possibility: all user data stays on the device, while agent capabilities such as intelligent Q&A, content summarization, and semantic retrieval are executed locally without any cloud dependency.

    Our original architecture relied on user-supplied model services: the app itself was not tied to any specific model, and users could configure credentials for mainstream cloud LLMs themselves. However, the pure cloud approach had several unavoidable issues:

    • Privacy concerns: Highly sensitive data like diaries and notes—many users are inherently reluctant to send them to any third-party server.
    • Network dependency: Agent capabilities become unusable in weak or no-network scenarios.
    • Uncontrolled costs: Frequent automatic summarization and content organization tasks generate continuous API call fees.

    Therefore, adding a fully offline inference option became a necessity. On-device models with 2B–4B parameters, after quantization, occupy about 2–3 GB of storage, and their capabilities are sufficient for daily tasks such as text rewriting, key-point extraction, and simple Q&A—exactly the primary workload for personal knowledge management scenarios.

    First Attempt: Pitfalls of an Existing Cross-Platform Plugin

    To validate quickly, we initially used a community-provided Flutter wrapper plugin. It internally wrapped the official on-device inference runtime and offered a very concise API—only a few lines of code to get a chat conversation running. However, stress testing on real devices revealed a serious problem: the plugin occasionally caused the entire device to reboot—not just the app crashing, but the whole phone powering off and restarting.

    The debugging process was worth documenting:

    1. The same phone, the same model file, but the official sample app (which directly used the native Kotlin API of the inference runtime) worked entirely without this issue.
    2. The key difference was the extra Flutter plugin layer. We suspected that the problem lay in thread scheduling between the native layer and the Dart layer, GPU resource lifecycle management, or repeated initialization of engine instances leading to memory spikes.
    3. Since the failure occurred at the underlying runtime level, the Flutter side received no meaningful stack trace, making the cause extremely difficult to pinpoint.

    Lesson 1: On-device inference is a resource-intensive operation. Every additional cross-platform abstraction layer reduces stability and debuggability. For features that are going into production, we strongly recommend developing directly against the official native API and keeping the cross-layer boundaries under your own control.

    Refactoring Approach: Native Inference Engine + Custom Platform Channels

    After abandoning the ready-made plugin, we restructured the architecture as follows:

    1. Dart business layer → MethodChannel → Kotlin plugin layer → On-device inference engine

    The solution is split into three parts:

    1. Kotlin Side: Singleton Engine + On-Demand Sessions

    The core cost of on-device inference lies in model loading—a 2.6 GB model file needs to be read into GPU memory, and initialization takes several seconds. This must never be repeated for every request. Therefore, we adopted a “heavy engine, light session” pattern:

    1. // The engine is initialized only once: load the model into GPU
    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. // Every inference creates a new lightweight session and releases it after use
    12. engine.createConversation(config).use { conversation ->
    13. conversation.sendMessageAsync(userText).collect { partial ->
    14. // Stream tokens back to Dart via EventChannel
    15. }
    16. }

    Key points:

    • Engine singleton: Only one instance per process, guarded by a mutex lock to prevent concurrent initialization.
    • Session open-close immediately: Each session holds its own context and KV cache. Not reusing sessions avoids context pollution and promptly frees GPU memory.
    • Streaming output: Tokens are pushed back incrementally, which gives a much better first-token latency experience for long responses than waiting for the full result.

    After switching to this approach, inference speed returned to normal and the device-reboot issue disappeared completely.

    2. Dart Side: Unified Abstraction, Transparent to Upper Layers

    On the Dart side, we implemented a local model client that implements the same interface as the cloud model. The agent scheduling logic at higher layers does not need to know whether the underlying inference is local or cloud-based—switching only requires changing a single configuration item:

    1. abstract class LLMClient {
    2. Stream<String> chat(List<Message> messages, ChatOptions options);
    3. }
    4. class OnDeviceClient implements LLMClient { ... }
    5. class RemoteApiClient implements LLMClient { ... }

    Lesson 2: From day one, abstract “local” and “cloud” behind the same interface. This not only makes switching cost zero, but also leaves an extension point for future hybrid scheduling (simple tasks local, complex tasks cloud).

    3. Channel Design: MethodChannel for Control, EventChannel for Data

    • Initialization, cancellation, and parameter updates go through MethodChannel.
    • Streaming token output goes through EventChannel, avoiding the overhead of repeated MethodChannel callbacks.
    • Native inference must run on a dedicated thread and must never block the platform thread, otherwise the system watchdog may be triggered.

    Other Engineering Considerations

    • Model distribution: A 2–3 GB model is not suitable for bundling inside the app installer. It is recommended to download on first use, with resumable download and integrity verification, storing the file in the app’s private directory.
    • Device tiering: On low-end devices with insufficient memory, the app should degrade gracefully and prompt users to switch to a cloud solution, rather than forcing execution and causing OOM.
    • Power consumption and heat: Continuous inference will significantly raise device temperature. For long tasks, rate limiting is advised, and the UI should clearly indicate the thermal impact.
    • Context length: On-device memory is limited. Very long conversations require history truncation or summarization compression—you cannot simply transfer the long-context habits from cloud-based models.

    Conclusion

    On-device LLMs make “data never leaves the device” intelligent applications a reality, but the biggest lesson from our deployment is: don’t trade stability for convenience. Bypassing incomplete cross-platform plugins, directly calling the official native inference API, and unifying the local/cloud difference behind a single interface—these three steps form the solid foundation of our local agent. For teams looking to build offline AI capabilities, this path is worth referencing.