Integrating On-Device LLMs into AI Agent Applications: Concurrency and Architecture Best Practices
This article explores how to integrate on-device open-source large language models into a fully offline, privacy-focused AI Agent application. Drawing on the real-world experience of building a local-only personal knowledge management app, it covers the stability pitfalls of cross-platform wrapper libraries, a robust native-side architecture based on Engine singletons and on-demand conversations, and a global lock mechanism for handling multi-Agent concurrency on resource-constrained mobile devices.
As lightweighting techniques for large language models (LLMs) continue to advance, bringing LLM capabilities down to edge devices such as smartphones has become a key industry trend. For AI Agent applications that prioritize privacy and require fully offline operation, on-device LLMs offer an entirely new starting point. However, in real-world productization, developers must overcome the limitations of edge hardware, the stability of underlying inference engines, and the complexity of multi-task concurrent scheduling. Based on the practical experience of building a fully local AI-powered personal life-logging and knowledge management application, this article dives into the technical challenges and solutions of integrating on-device open-source LLMs in multi-Agent concurrent scenarios.
1. Architectural Requirements and Early Pitfalls of an Offline AI Agent
The core design principle of this fully local AI knowledge management app is that all user data is processed on the device, while also allowing users to bring their own cloud-based models. To further expand usage scenarios, the team decided to introduce lightweight on-device LLMs, creating a fully offline option that does not depend on any cloud service.
1.1 The Stability Trap of Cross-Platform Wrapper Libraries
In the early stages, to reduce integration complexity and speed up development, the team first tried a common cross-platform on-device model wrapper library. This library wraps the underlying inference engine with a secondary layer and offers a clean, simple API that seemed to significantly lower integration costs. However, during real-device testing, extremely serious stability issues emerged: during inference, not only did the app itself crash, but occasionally the entire phone would go black and reboot.
1.2 Root Cause Analysis and a Change of Direction
A full device reboot usually indicates severe memory exhaustion or a GPU driver-level crash at the system layer. Investigation revealed that on the same phone, loading the same model files, the official native sample app provided by the vendor ran stably. The reason: the official sample calls native APIs to interact directly with the underlying inference engine, while the third-party wrapper library inserts an extra plugin layer between the cross-platform language and the native engine. This layer may suffer from resource leaks or timing issues when managing GPU memory and releasing inference contexts, triggering system-level crashes. Since stability is the lifeline of the product, the team decisively abandoned the third-party wrapper library and switched to integrating directly with the official native inference SDK.
2. Architectural Refactoring: A Robust Design Based on Native Calls
To fundamentally resolve the stability issues, the team refactored the application architecture, bypassing all intermediate wrappers by writing their own platform communication channel and calling the native inference engine SDK directly.
2.1 Cross-Platform-to-Native Communication Architecture
The refactored call chain became: cross-platform language layer -> platform communication channel -> custom native plugin -> underlying inference engine. This architecture ensures that all core operations—model loading, GPU memory allocation, and inference computation—are controlled directly by native code, minimizing the memory management uncertainty introduced by cross-platform communication.
2.2 Core Design: Engine Singleton with On-Demand Conversations
In the custom native plugin, the core architecture follows an “Engine singleton + on-demand Conversation” pattern. On-device LLM files are typically large (around 2.6 GB in this case), and loading them into GPU memory is an extremely time-consuming operation. Therefore, the Engine is initialized once at app launch or on first use and kept resident in memory as a singleton, avoiding the performance cost and memory churn of repeated loading.
// Pseudocode example: Engine singleton initializationval engine = Engine(EngineConfig(modelPath = modelPath,backend = Backend.GPU(),maxNumTokens = 10000,cacheDir = context.cacheDir.absolutePath,))engine.initialize()
For each individual inference session, the system dynamically creates a lightweight Conversation object and releases it immediately after inference completes, preventing unbounded context growth.
// Pseudocode example: on-demand Conversation creation and disposalengine.createConversation(config).use { conversation ->conversation.sendMessageAsync(userText).collect { ... }}
2.3 Transparent Interface Design
On the cross-platform language side, the local inference client implements exactly the same LLMClient interface as cloud model providers. Thanks to this abstraction, the upper-layer Agents are completely agnostic to whether the underlying model is a cloud API or an on-device local model. Switching between modes only requires changing a single underlying configuration item, with no modifications to any business logic, greatly improving system extensibility.
3. Advanced Challenge: Multi-Agent Concurrency and the Global Lock Mechanism
With single-inference stability solved, the application moved into complex multi-Agent concurrency scenarios. The knowledge management app contains multiple Agents running in parallel: for example, a Card Agent that processes user-clipped card content, a Knowledge Base Agent that organizes local documents, and a Multimodal Analysis Agent that parses information from images and audio.
3.1 Resource Contention in On-Device Concurrency
In cloud environments, having multiple Agents issue LLM inference requests simultaneously is trivial—compute resources are dynamically scheduled for parallel processing. On edge devices, however, hardware compute and GPU memory are extremely limited. If multiple Agents send inference requests to the underlying engine at the same time, it can easily cause out-of-memory (OOM) errors or even crash the underlying engine again.
3.2 Introducing the Global Lock Mechanism
To achieve “pseudo-parallelism” for multiple Agents on edge devices, the team introduced a global lock mechanism on the native side. All inference requests must acquire the global lock before entering the underlying engine. At any given moment, only one Agent’s inference task can exclusively occupy the engine’s resources, while the remaining tasks enter a waiting queue.
While this design sacrifices some concurrency in absolute terms, it buys absolute system stability. From the user’s perspective, since on-device LLM inference speed is inherently limited and most Agent tasks run silently in the background, the delay caused by queuing is within an acceptable range. The global lock effectively prevents memory contention among concurrent tasks, allowing the multi-Agent architecture to run smoothly on resource-constrained edge devices.
4. Conclusion and Outlook
On-device open-source LLMs open up vast possibilities for fully offline, privacy-focused AI Agent applications. But in real-world implementation, developers must abandon cloud-centric thinking and deeply understand the constraints of edge hardware.
From the full-device crashes caused by cross-platform wrapper libraries, to the robust architecture built on self-implemented native communication channels and singleton-based management, to the global lock scheduling that handles multi-Agent concurrency—this journey demonstrates that the success of an on-device LLM application lies not in stacking model parameters, but in fine-grained resource management, rigorous system architecture design, and deep control over underlying mechanisms. Looking ahead, as edge chip compute power grows and inference engines continue to improve, combined with cloud-edge collaboration using general-purpose cloud services such as Baidu AI Cloud, AI Agents will deliver even more powerful and stable intelligent experiences on the device.
