Deploying On-Device LLMs for Local AI Agents: Architecture, Stability, and Concurrency Practices
This article explores the practical implementation of fully offline AI agents powered by on-device large language models (LLMs) for privacy-focused knowledge management applications. It delves into the engineering challenges of moving from cloud to edge computing, sharing insights on architecture selection, native API refactoring to avoid system-level crashes, and concurrency management using global locking mechanisms to ensure robust multi-agent performance on resource-constrained mobile devices.
As AI technology continues to extend to the edge, on-device large language models (LLMs) are becoming the new engine for mobile AI applications. For applications that prioritize privacy protection and personal knowledge management, deploying LLM capabilities entirely on local devices to achieve a zero-cloud-dependency offline agent is a highly attractive but engineering-intensive direction. Using the offline transformation of a local AI knowledge management application as a case study, this article deeply analyzes the architecture design, stability optimization, and concurrency handling experiences of on-device LLMs in practical deployment.
I. Architecture Selection and Initial Pitfalls
When building a fully local Agent product, the primary goal is to equip the application with natural language understanding and generation capabilities without relying on any cloud services. The team focused on the latest open-source lightweight on-device LLMs. These models have moderate parameter sizes and can run smoothly in the limited memory of modern smartphones through quantization technology.
1.1 The Temptation and Trap of Cross-Platform Wrapper Libraries
In the early stages of development, to quickly validate features and save development costs, the team chose a third-party model wrapper library from a cross-platform UI framework. This library performed secondary encapsulation on the underlying on-device inference engine, exposing a very simple API design that could be quickly integrated into existing cross-platform business code.
However, actual testing revealed fatal stability issues. During model inference, the application not only experienced regular crashes, but more seriously, occasionally caused the entire phone to black out and reboot. For a consumer-facing product, an underlying error that causes an operating system-level reboot is absolutely unacceptable.
1.2 Stability Root Cause Analysis and Native Solution Decision
After in-depth comparison and troubleshooting, we found that on the same device and with the same model file, the operation was very stable in the officially provided sample application, with no reboot phenomenon. By analyzing the technical links of both, the reason gradually emerged: the official sample application directly used native development languages to call the underlying inference engine API, while the third-party wrapper library we used added an extra layer of cross-platform plugin communication mechanism on top of the native engine.
This extra layer of encapsulation not only brought memory overhead but also generated unpredictable resource contention when interacting with underlying hardware acceleration (such as GPU/NPU), ultimately leading to protective kernel reboots. Faced with extremely high stability risks, the team decisively abandoned the third-party wrapper library and shifted to directly interfacing with the underlying native APIs.
II. Architecture Refactoring Based on Native Inference Engines
To ensure stability, it was necessary to refactor the cross-platform invocation chain and connect the upper-level business logic with the underlying native APIs.
2.1 Cross-Language Communication Channel Design
The refactored architecture evolved into: Business Logic Layer -> Native Communication Channel -> Native Plugin Layer -> Underlying Inference Engine. By hand-writing the native communication channel, the business layer sends inference requests down to the native-side plugin, which is responsible for calling the underlying inference engine to execute calculations and stream the inference results back in real-time.
2.2 Engine Singleton and On-Demand Conversation Creation
When implementing the model plugin on the native side, the core design concept is “global engine singleton + on-demand conversation creation”. The file size of on-device LLMs is typically in the GB range; repeatedly loading them can cause severe memory jitter or even OOM (Out of Memory). Therefore, the engine instance must be initialized once upon application startup or first invocation, and reside permanently in GPU memory.
The specific inference sessions, however, are lightweight and should be dynamically created based on each user interaction, and destroyed immediately after the interaction ends to release the memory resources occupied by the context. The core logic is as follows:
// Engine global singleton - avoid memory overflow caused by repeatedly loading large model filesval engine = Engine(EngineConfig(modelPath = modelPath,backend = Backend.GPU(), // Prioritize hardware acceleration to improve inference speedmaxNumTokens = 10000, // Set a reasonable context window lengthcacheDir = context.cacheDir.absolutePath,))engine.initialize()// Inference sessions are created on demand and destroyed after use to release context memoryengine.createConversation(config).use { conversation ->conversation.sendMessageAsync(userText).collect {// Handle streaming returned Tokens}}
This design not only remains consistent with official recommended best practices but also completely solves the problem of phone black-screen reboots while ensuring inference speed.
2.3 Client Interface Transparency
To reduce the cognitive burden of upper-level Agent development, we defined a unified LLM client interface in the business logic layer. Whether calling cloud LLMs or local offline models, both implement this interface. As a result, the scheduling logic of the upper-level Agent is completely unaware of the specific source of the underlying model. When users switch between “Cloud Mode” and “Fully Offline Mode” in settings, it is only necessary to change the client instance returned by the underlying factory method, achieving complete transparent decoupling of the model source from the business.
III. Engineering Challenges in Multi-Agent Concurrency
Once the basic inference link was established, the application faced more complex business scenarios. Modern AI applications are often not a single Agent, but a collaborative network composed of multiple specialized Agents.
3.1 Resource Contention and Memory Management
In knowledge management applications, the system may run multiple Agents simultaneously: for example, a card information processing Agent responsible for parsing clipped content, a knowledge base construction Agent responsible for vectorization and archiving, and a multimedia asset analysis Agent responsible for understanding images and audio.
When multiple Agents simultaneously send inference requests to the local on-device model, it causes severe resource contention. The memory and computing power of edge devices are extremely limited, and underlying inference engines usually struggle to support true multi-threaded concurrent inference. If concurrent requests are allowed to pour in, it can easily lead to VRAM overflow or internal state corruption of the inference engine.
3.2 Introduction and Implementation of the Global Lock Mechanism
For on-device high concurrency issues, the safest engineering solution is to introduce a “global inference lock” at the architecture layer. Implement a fair lock or queuing queue in the native plugin layer; all inference requests from different upper-level Agents must first acquire this lock before entering the underlying engine for execution.
Through the global lock, we force the serialization of concurrent inference requests. Although this sacrifices response time to a certain extent, it guarantees the absolute stability of the system and the correctness of inference results. In practical applications, since on-device Agents mostly perform background silent processing and do not require as high real-time performance as interactive dialogue, serial queuing is a completely acceptable compromise solution.
IV. Summary and Outlook
Successfully deploying open-source LLMs on local mobile Agents is a beneficial attempt to sink computing power from the cloud to the edge. In this process, we must discard excessive reliance on third-party quick wrapper libraries, delve into underlying native APIs for refined architecture design, and build truly stable and reliable offline AI products through the memory management strategy of “engine singleton + session on-demand destruction” and the global concurrency lock.
Looking ahead, although fully local Agents protect privacy, they are limited by edge-side computing power and find it difficult to handle ultra-long contexts and complex multimodal inference. The future development trend will inevitably be edge-cloud collaboration: lightweight on-device models will be responsible for intent recognition, privacy data processing, and instant response; cloud computing power, such as Baidu AI Cloud, will be responsible for complex logical deduction and large-scale knowledge retrieval. Only through the deep fusion of cloud-native architecture and on-device AI can we create next-generation intelligent applications with ultimate user experiences.
