Deploying Open-Source LLMs on Mobile: On-Device Agent Practices and Pitfalls
This article explores the practical steps and challenges of deploying open-source large language models (LLMs) on mobile devices to build offline AI agents. It covers critical tech selection criteria, the stability pitfalls of using cross-platform wrappers for on-device inference, and a robust refactored architecture using native engines and platform channels. The guide also details strategies for managing multi-agent concurrency on a single device, offering actionable engineering insights for teams integrating on-device LLMs.
I. Background: Why On-Device Models Are Worth the Effort
For product teams building local mobile Agents, the emergence of open-source on-device large language models (LLMs) represents a genuine turning point. Previously, achieving “fully offline, zero cloud dependency” intelligence on mobile phones heavily relied on extremely small, specialized models, which often failed to meet the reasoning quality required for Agent scenarios. Today, the parameter scale, quantization quality, and inference framework maturity of the new generation of open-source on-device models have reached a usable threshold. Quantized models in the 2B to 4B parameter range can achieve acceptable generation speeds and memory footprints on mid-to-high-end smartphones.
Our team’s product is a purely local AI personal life-logging and knowledge management app. All data is stored on the device, and we previously relied on users configuring their own cloud model APIs to utilize LLM capabilities. To provide a complete experience for privacy-sensitive users, we decided to add a fully offline option—prompting this complete practice of on-device model integration. The process took several days of troubleshooting and navigating various pitfalls. Here, we document our selection logic, architectural evolution, and key decisions, hoping to provide a reference for teams with similar requirements.
II. Three Core Dimensions of Tech Selection
Before diving in, we identified three dimensions that must be considered for on-device model selection:
1. Hardware Adaptability. On-device inference relies heavily on NPU/GPU acceleration. Operator support varies significantly across chip platforms. Models must use GPU Delegates or NPU backends explicitly supported and widely validated by the official inference framework; otherwise, they may fall back to the CPU, causing a sudden drop in speed.
2. Balancing Model Capability and Size. Agent scenarios require models with basic instruction following, structured output (JSON), and multi-turn context capabilities. We ultimately chose to compare two quantized versions: 2B and 4B. The 2B version loads faster and uses just over 2GB of memory, while the 4B version offers better quality but exerts more obvious memory pressure. We recommend stress testing on the minimum supported device specifications before deciding on the default tier.
3. Integration Cost and Stability of the Inference Framework. This is precisely where we encountered our deepest pitfalls, which we will detail below.
III. Pitfall 1: The Stability Trap of Cross-Platform Wrappers
Initially, to save time, we directly used a community-maintained cross-platform wrapper to load the model. Its API design was clean, and theoretically, we could get it running in a few days. However, severe issues emerged during actual testing: not only did the app crash, but it occasionally caused the entire phone to black out and reboot.
This phenomenon is worth analyzing. On the same device with the same model file, the official on-device demo app ran flawlessly. Comparing the two reveals the differences:
- The official demo app directly uses native languages to call the underlying inference engine. The execution chain is short, and memory management is controllable.
- The cross-platform wrapper adds an extra layer of Plugin bridging encapsulation over the underlying engine, involving cross-language memory copies, asynchronous callback forwarding, and thread model transitions.
On-device inference is extremely sensitive to memory and thread timing. After a 2GB-level model is loaded into GPU memory, any improper cross-language reference passing or premature release can trigger an underlying crash, even cascading to the system level. Conclusion: For scenarios involving large memory and GPU/NPU resource management, use native APIs instead of adding an extra wrapper layer. Wrappers are suitable for quick prototype validation, but long-term stress testing is mandatory before entering production.
IV. Refactoring: Native Engine + Platform Channel
After abandoning the wrapper, we switched to writing our own Platform Channel to call the native library of the official on-device inference engine directly. The overall architecture is as follows:
Dart layer (Agent scheduling & UI)↓ MethodChannelKotlin layer LiteRtLmPlugin↓On-device inference engine (GPU backend)
The core design on the Kotlin side is an Engine singleton + on-demand Conversation creation:
// Engine is initialized globally only once: loads ~2.6GB quantized model into GPU memoryval engine = Engine(EngineConfig(modelPath = modelPath,backend = Backend.GPU(),maxNumTokens = 10000,cacheDir = context.cacheDir.absolutePath,))engine.initialize()// Create a lightweight session for each inference, release immediately after useengine.createConversation(config).use { conversation ->conversation.sendMessageAsync(userText).collect { token ->// Stream tokens back to the Dart layer}}
This design has two key points:
First, the Engine lifecycle aligns with the application. Model loading is the most expensive operation (involving disk I/O, memory mapping, and GPU resource initialization). It must be a global singleton and should never be reloaded for every request.
Second, Conversations maintain a lightweight, short lifecycle. Session states (KV Cache, context window) are created on-demand and destroyed after use, preventing context pollution and memory leaks caused by multiple business modules sharing a session.
On the Dart side, we abstracted an LLMClient interface identical to the cloud provider’s. GemmaLocalClient serves as one of its implementations. This makes it completely transparent to the upper-layer Agent framework—switching between local and cloud models only requires changing a single configuration item. This interface abstraction layer was the most valuable investment in this refactoring. We strongly recommend that any product intending to support multiple models implement this first.
After switching to the native solution, inference speeds returned to normal, and the phone rebooting issue disappeared completely.
V. Multi-Agent Concurrency: Global Lock and Queueing Strategy
Our product features multiple Agents working in parallel: a card processing Agent, a knowledge base organizing Agent, and an image/audio analysis Agent. In the era of cloud models, concurrent requests were naturally not an issue. However, on-device, there is only a single model instance in GPU memory. Concurrent inference will directly cause VRAM contention and context corruption.
Our solution was to add a global inference lock: all Agent inference requests enter a serial queue and are scheduled by priority (user-initiated interaction > background automatic tasks). Simultaneously, we control the maxNumTokens of a single request within a reasonable range to prevent long-generation tasks from blocking the queue. In practice, serialization impacted the user experience far less than expected—because on-device generation speed is sufficiently fast, and most Agent tasks are executed asynchronously in the background anyway.
VI. Summary and Recommendations
Three core takeaways from this practice:
- Prioritize Native Links for Stability: For mobile integration involving large model memory management, the cross-platform wrapper layer is the biggest source of uncertainty. For production environments, it is highly recommended to use native APIs directly and build your own bridging.
- Interface Abstraction is the Architectural Cornerstone: Use a unified
LLMClientinterface to isolate cloud and on-device implementations, turning model switching into a configuration issue rather than a code issue. - On-Device Concurrency Must Be Actively Managed: A serial queue + priority scheduling + token limit control is currently the most reliable concurrency strategy under a single on-device model instance.
Open-source on-device models are maturing rapidly. The distance between an offline Agent transitioning from “barely running” to “truly usable” is exactly the distance covered by these engineering details.
