On-Device Open-Source LLMs for Mobile Agents: Implementation Lessons and Pitfalls
This article shares our experience integrating an open-source 2B–4B parameter LLM into the mobile agent architecture of a local-first personal data app. It explains why cloud-only inference fell short, why a cross-platform wrapper caused system-level instability, how we moved to the native inference engine with a singleton engine and per-request conversations, and how we serialized multi-agent inference to control GPU memory and compute. It closes with practical recommendations for teams building on-device LLM agents.
Background: Why Run a Local Agent on a Phone
Our product is a purely local personal life logging and knowledge management app. All data is stored on the user’s device. At the architecture level, multiple agents collaborate: some generate structured cards, some retrieve and organize knowledge-base content, and some analyze assets such as images and audio. The model access layer provides a unified abstraction so users can bring API keys for various cloud LLMs, with the app proxying the calls.
This architecture has an inherent weakness: as long as the model runs in the cloud, the claim of being “purely local” is weakened. The cloud approach has at least three problems:
- Incomplete privacy boundary: User input still has to travel over the network. For privacy-sensitive users, this is an unacceptable single point of trust.
- Offline scenarios fail: In subways, airplane mode, or weak-network environments, core features become unavailable.
- Uncontrollable long-term cost: API billing is usage-based. For high-frequency, lightweight agent tasks such as auto-tagging and summary generation, cost grows linearly with usage time.
We therefore decided to add a fully offline option that does not depend on any cloud service. Newly open-sourced small-parameter models in the 2B–4B range have reached a usable level on mobile GPUs, making on-device deployment mature enough for daily use for the first time. Below is a record of the integration process and the pitfalls we encountered.
Phase 1: The Appeal and Failure of a Wrapper
To save effort, we initially chose a community-maintained cross-platform wrapper. It wrapped the underlying inference engine in a layer with a seemingly simple API, and inference could run in just a few lines of code. But real-device testing exposed a critical problem: the app occasionally caused the entire phone to go black and reboot—not an ordinary crash, but a system-level failure.
Our troubleshooting approach was as follows:
- Rule out model file issues: The same model file ran perfectly in the official demo app.
- Rule out hardware issues: On the same device model and OS version, the official demo app showed no anomalies under long-duration stress testing.
- Locate the difference: The official demo app called the inference engine directly through the native API, while the wrapper added a cross-platform plugin bridge. The problem was most likely in lifecycle management or memory operations at that layer—for example, GPU resources not being released correctly, the engine being initialized repeatedly, or the bridge layer triggering undefined low-level behavior when serializing large blocks of text.
Although we did not fully identify the root cause, the conclusion was clear: in on-device inference scenarios involving GPU memory management, any extra intermediate abstraction layer is a stability risk. Such issues may occur only occasionally during development—after long runtimes, with specific input lengths, or during background switching—but once released, they affect the user’s entire device experience. The risk was unacceptable. We abandoned the wrapper and connected directly to the official native API.
The lesson from this phase can be summarized as one principle: when integrating on-device AI capabilities, prioritize the inference engine’s native interface. Cross-platform wrappers are suitable for prototype validation, not production deployment.
Phase 2: Architecture with a Direct Native Engine
Call Path
The new call path is:
Cross-platform business code → platform channel → native plugin → on-device inference engine
The native plugin follows two core design principles: a global singleton engine and conversations created on demand.
Engine Singleton: Load Once, Reuse Throughout
On-device model files are often several GB, and loading them into GPU memory is an expensive operation. The engine object must be a process-level singleton and initialized only once:
// Native side: initialize Engine only once globallyval engine = Engine(EngineConfig(modelPath = modelPath,backend = Backend.GPU(), // Prefer the GPU acceleration backendmaxNumTokens = 10000, // Limit context window to prevent memory overflowcacheDir = context.cacheDir.absolutePath,))engine.initialize()
Several configuration points deserve elaboration:
- Backend selection: On mobile, prefer the GPU backend, which offers orders-of-magnitude faster generation than the CPU backend. However, keep a fallback switch to the CPU backend because some low-end devices have poor GPU driver compatibility.
- maxNumTokens: Explicitly limiting context length is important. In agent scenarios, without a limit, the KV cache for multi-turn conversations keeps growing and eventually triggers system-level memory reclaim. This was one of the suspicious causes of the early whole-device reboot issue.
- cacheDir: Specify a cache directory so the system can reclaim space when storage is tight and so model-file integrity checks are easier.
Conversations on Demand: Lightweight Objects, Discarded After Use
In contrast to the engine, conversation objects are lightweight. The correct pattern is to create a new one for each inference request, close it after use, and consume output through a streaming interface:
engine.createConversation(config).use { conversation ->conversation.sendMessageAsync(userText).collect { token ->// Stream each token back to the cross-platform layer for a typewriter effect}}
The benefit of this design is that the lifecycle of conversation state (context cache) is clear and controllable, with no state leakage across requests. When the user clears history, the session is closed directly and memory is released immediately.
Transparent Design at the Cross-Platform Layer
On the cross-platform side, we implemented a local model client that implements exactly the same interface abstraction as cloud providers. This design is critical:
// Implements the same LLMClient interface as cloud providersclass LocalModelClient implements LLMClient {// Calls the native plugin through a platform channel and receives tokens as a stream}
For all upper-layer agent code, cloud models and local models are completely transparent—switching to offline mode requires only a configuration change, with no business-logic changes. This is a direct benefit of the model access layer abstraction and further validates the value of dependency inversion in LLM application architecture: business code depends on an abstract interface, not on a specific model service.
After switching to direct native API calls, inference speed returned to normal, the whole-device reboot issue disappeared completely, and long-duration stress testing remained stable.
Phase 3: Resource Control under Multi-Agent Concurrency
After the architecture worked, a new problem appeared: multiple agents work in parallel. In cloud mode, concurrent API calls from multiple agents are no pressure. But in on-device mode, GPU memory and inference compute are exclusive resources on a single device. Multiple conversations running inference at the same time caused:
- Memory peaks to stack, triggering system OOM or memory reclaim, manifesting as interrupted inference or even the app being killed.
- Compute contention, slowing down generation for every agent and making the user experience worse.
Our solution was a global inference lock: maintain a mutex in the native plugin layer, queue all conversation inference requests for serial execution, and allow only one conversation to occupy the GPU for generation at a time. We added two scheduling optimizations:
- Task priority: The agent the user is currently interacting with has the highest priority, while background asset-analysis tasks yield.
- Session reuse: For similar tasks in short intervals, reuse the same conversation context cache as much as possible to avoid repeated prefill overhead.
This strategy reduced peak memory in multi-agent scenarios from an “additive” state to a “single-task” state, greatly improving stability. The cost is a slight drop in background task throughput—in on-device scenarios, stability always comes before throughput.
Summary and Recommendations
Looking back at the entire deployment process, we can distill four recommendations for teams preparing to integrate on-device LLMs:
- Evaluate model selection by on-device maturity: Small models in the 2B–4B range can already achieve usable generation speed on mid-range phone GPUs. On-device offline agents have moved from “demo” to “usable.”
- Be cautious with multi-layer wrappers: Prefer direct native interfaces to the inference engine, and use cross-platform wrappers only for prototype validation. For GPU memory lifecycle management, any intermediate layer may introduce system-level failures that are difficult to diagnose.
- Engine singleton + lightweight conversations is a basic architectural pattern for on-device inference: reuse heavy resources globally and create lightweight objects on demand.
- Concurrency must converge resources: On-device compute is exclusive. Multi-agent architectures need a global lock and priority scheduling, turning “concurrency” into “queuing” and trading controllable latency for stability.
In the future, we plan to explore dynamic switching of model quantization levels, automatic degradation based on device performance, and hybrid routing between on-device small models and cloud large models—simple tasks local, complex tasks in the cloud—to achieve a better balance among privacy, cost, and capability.
