On-Device Open-Source LLM Integration: A Practical Guide and Pitfalls to Avoid

    This article documents the real-world engineering process of integrating open-source on-device large language models into a mobile application. It covers the system-level stability issues caused by cross-platform framework wrappers, the architectural shift to a native platform channel connecting directly to the inference engine, the "singleton engine + on-demand session" design pattern, and a global lock with priority queue mechanism for multi-Agent concurrency on resource-constrained devices.

    With the continuous improvement of on-device computing power, deploying large language models (LLMs) directly on mobile devices has become an important trend in bringing AI applications to production. For personal knowledge management apps that place a high priority on privacy, providing fully offline AI Agent capabilities with no dependence on any cloud service is a key step in product evolution. Recently, the industry has released several lightweight open-source on-device LLMs, making this technically feasible. However, in actual product integration, significant engineering challenges emerge — from cross-platform framework wrapping, to native low-level invocation, to concurrent scheduling of multiple Agents. This article documents the entire integration process and the lessons learned.

    1. System-Level Stability Challenges from Cross-Platform Framework Wrappers

    In mobile development, cross-platform frameworks are commonly adopted to improve development efficiency. When we first attempted to integrate an open-source on-device LLM, we chose an existing community plugin for the cross-platform framework to save the cost of low-level adaptation. The plugin wraps a mainstream on-device inference engine with a clean, simple API and appeared to quickly meet the requirement of fully offline operation.

    However, testing on real devices exposed extremely serious stability problems. The solution not only caused occasional crashes of the app itself, but even triggered full black screens and phone reboots. System-level crashes like these are unacceptable, fatal defects for a mobile product.

    After in-depth investigation and comparative testing, we found that on the same phone, loading the same model file, the official app that calls the on-device inference engine through native code ran stably and never rebooted. The root cause lies in the extra wrapper layer that the cross-platform plugin adds on top of the inference engine. When handling LLM inference — a scenario with high memory usage and heavy GPU/NPU load — the wrapper layer’s memory management or low-level resource invocation logic contains defects that easily trigger the operating system’s protection mechanisms. Faced with such a significant stability risk, we decisively abandoned the existing cross-platform plugin and switched to a native direct integration approach.

    2. Architecture Evolution: Bypassing the Wrapper Layer with a Native Platform Channel

    To completely resolve the stability issues, we decided to bypass the cross-platform framework’s wrapper layer and connect directly to the official on-device inference engine SDK through a native platform channel. The overall architecture evolved into: front-end cross-platform business logic -> native platform channel -> self-developed native inference plugin -> on-device inference engine.

    On the native side, we wrote our own inference plugin with a core design philosophy of “singleton engine + on-demand sessions.”

    1. Singleton Engine

    On-device LLMs are typically large, and loading a model file of several gigabytes into GPU memory is an extremely time-consuming and resource-intensive operation. Therefore, the engine instance must remain a singleton throughout the application lifecycle, initialized only on first use to avoid repeated loading.

    2. On-Demand Sessions

    Unlike the heavyweight engine instance, inference session objects are lightweight. A new session is created for each inference interaction and closed and released immediately after use. This design ensures context isolation while avoiding memory leaks.

    The core native-side code logic looks like this:

    1. // 1. Singleton engine initialization (executed only once globally, loads the model into GPU memory)
    2. val engine = Engine(EngineConfig(
    3. modelPath = modelPath,
    4. backend = Backend.GPU(),
    5. maxNumTokens = 10000,
    6. cacheDir = context.cacheDir.absolutePath
    7. ))
    8. engine.initialize()
    9. // 2. Create a lightweight session on demand for each inference, releasing it immediately after use
    10. engine.createConversation(config).use { conversation ->
    11. conversation.sendMessageAsync(userText).collect { ... }
    12. }

    This architectural adjustment aligns with how native applications are implemented. After switching to this solution, on-device inference speed returned fully to normal, and the phone reboot problem was completely resolved. Meanwhile, on the front-end business logic side, we implemented the local inference client with the same interface specification as the cloud-based LLM. For upper-layer AI Agents, whether the underlying call goes to the cloud or runs locally is completely transparent — seamless switching requires changing only a single configuration item.

    3. Resource Scheduling and Global Locking for Multi-Agent Concurrency

    After solving the low-level inference stability, product-level challenges followed. In a complex personal knowledge management application, multiple AI Agents often run in parallel — for example, a Card Agent that processes information cards, a PKM Agent that handles knowledge base retrieval, and a multimedia Asset Agent that analyzes local images and audio.

    If these Agents issue local LLM inference requests simultaneously, they instantly exhaust the phone’s on-device compute and memory, causing the inference engine to block or even the system to freeze. Therefore, a global lock and task queue mechanism must be introduced at the architecture layer.

    1. Global Inference Lock Design

    Given the objective reality of limited on-device compute, the traditional mindset of cloud-style multi-concurrency must be abandoned. We introduced a global semaphore or mutex mechanism to ensure that only one inference task can actually occupy the on-device inference engine’s resources at any given moment. When an Agent initiates an inference request, it must first acquire the global lock.

    2. Task Priority Queue

    Not all Agent tasks are equally urgent. For example, interactively triggered user Q&A should have the highest priority, while background audio transcription or card information extraction can be deferred. Therefore, at the entry point of the global lock, we designed a priority-based task queue. Blocked inference tasks wait in the queue and acquire the lock in order based on priority and arrival time.

    3. Resource Monitoring and Degradation Strategy

    During multi-Agent scheduling, the device’s memory state must also be continuously monitored. If available system memory falls below a safe threshold, low-priority tasks in the queue should be paused, and users may even be prompted to close some background Agents to maintain overall system smoothness.

    4. Conclusion and Outlook

    Integrating open-source on-device LLMs is far from a simple API call — it is a systems engineering effort involving low-level resource scheduling, memory management, and architectural design. From the system reboots initially caused by cross-platform wrapping, to the singleton design of native direct engine integration, to global lock control under multi-Agent concurrency, every step must closely match the physical characteristics of on-device hardware. In the future, as on-device computing power advances further, cloud-edge collaboration will become an even better solution: everyday lightweight inference runs locally to protect privacy, while complex long-context processing is seamlessly scheduled to elastic cloud computing platforms such as Baidu AI Cloud, balancing privacy, performance, and cost. Developers need to find the optimal balance between the two to build AI-native applications with an exceptional experience.