Building Mobile Agents with On-Device Open-Source LLMs: Engineering Practices and Lessons

    This article presents a practical integration path for adding agent capabilities to local-first mobile apps using open-source on-device LLMs. It explains why high-level cross-platform wrappers can be risky in production, how to design a native bridge around a singleton inference engine and short-lived conversations, how to serialize multi-agent inference with a global scheduler, and how to unify local and cloud LLM clients behind one interface. It also summarizes engineering lessons on lifecycle management, concurrency, backend fallback, monitoring, and model distribution.

    1. Background: Why On-Device Models Matter for Mobile Agent Products

    For mobile apps built around a local-first philosophy—such as offline personal knowledge management or life-logging products—keeping data on the device is a core product promise. Introducing Agent capabilities into such products creates a dilemma: relying on cloud LLM services breaks offline scenarios and requires user data to leave the device, while abandoning intelligent capabilities leaves an obvious gap in product experience.

    Open-source on-device LLMs offer a third path: model files are bundled directly or downloaded on demand, and inference runs entirely on the device. GB-level quantized models can already run at usable speeds on recent mobile SoCs. With GPU/NPU acceleration backends, short-text tasks can be completed with latency in the seconds range. This makes a fully offline local Agent possible, with no dependency on any cloud service.

    Of course, there is a large amount of engineering detail between “possible” and “usable.” The following sections follow a real integration process step by step.

    2. Step One: Choosing an Integration Path—Hidden Risks of High-Level Wrappers

    When integrating on-device inference, the first path is usually to use a community-maintained high-level wrapper package. If the app itself is built on a cross-platform framework, introducing the corresponding plugin package can get inference running with just a few lines of code, which looks like the least effort-intensive option.

    In actual stress testing, however, the stability problems of this path become fully exposed. A typical severe symptom is not only an app process crash, but an abnormal reboot of the entire phone—black screen, restart, and the user losing all current foreground state. For any released product, this level of failure is unacceptable.

    Why do high-level wrappers have this problem? Analyzing the call chain reveals the key difference:

    • The cross-platform plugin package chain is: Dart/JS layer → plugin bridge layer → platform native wrapper layer → underlying inference engine, with at least one additional third-party wrapper in between;
    • The inference engine’s official native API is exposed directly for platform languages to call, and the official sample app uses this shortest path.

    An extra wrapper layer means memory lifecycle management is more prone to timing mismatches—for example, the bridge layer holds an engine reference while the native layer has already released it—thread switching becomes more complex, and exception propagation paths become longer. The underlying inference engine directly operates on GPU memory on mobile devices, so any release-timing error at any layer can escalate into a system-level failure rather than an ordinary process crash.

    The conclusion is clear: when low-level resource operations are dangerous enough, the shorter the call chain, the better. For production-grade products, high-level wrappers should be abandoned and the inference engine’s official platform-native API should be used directly.

    3. Step Two: Architecture Design—Cross-Platform Bridge + Engine Singleton

    After deciding to use the native API route, the overall architecture becomes a classic layered bridge pattern:

    1. Application logic layer (cross-platform framework)
    2. ↓ cross-platform bridge channel
    3. Platform native plugin layer
    4. ↓
    5. On-device inference engine (GPU backend)

    3.1 Engine Singleton: Load Once, Reuse Globally

    A core characteristic of on-device models is that model size is usually in the GB range, and loading into GPU/unified memory is both time-consuming and resource-intensive. Therefore, engine instances must never be created and destroyed per request; they must be managed as global singletons:

    1. // Initialize the engine only once: load the model into GPU memory
    2. engine = Engine(EngineConfig(
    3. modelPath = localModelPath, // Path to the model file on the device
    4. backend = Backend.GPU(), // GPU acceleration backend
    5. maxTokens = 10000, // Maximum context length
    6. cacheDir = cacheDirectory, // Inference cache directory
    7. ))
    8. engine.initialize()

    Several configuration items deserve separate explanation:

    • Backend selection: The GPU backend is usually several times faster than the CPU backend, but compatibility varies by device model. A robust approach is to implement a GPU-first, CPU-fallback strategy, automatically switching when GPU initialization fails.
    • Cache directory: Temporary data such as the KV cache during inference needs an on-disk location. Be sure to point it to the app’s private cache directory to avoid permission issues and residual file pollution.
    • Context length: A larger limit means higher memory usage. A reasonable value should be estimated based on the Agent’s actual prompt structure (system prompt + tool descriptions + history).

    3.2 Conversation Created on Demand: Lightweight Objects + Timely Release

    In contrast to the Engine, Conversation objects should be lightweight and short-lived. Create a new conversation for each inference task and close it immediately after the task ends:

    1. engine.createConversation(config).use { conversation ->
    2. conversation.sendMessageAsync(userText)
    3. .collect { chunk -> emitToken(chunk) } // Stream tokens
    4. }

    This combination of “heavy engine + light conversation” is consistent with the official sample app and is a classic lifecycle pattern for mobile inference. A conversation holds dialogue context and intermediate state; discarding it after use prevents unbounded context accumulation and memory growth. The streaming interface also greatly shortens the user-perceived wait time for the first token.

    3.3 Key Design Points for the Bridge Layer

    The native plugin layer needs to address three points:

    1. Granularity of channel methods: Initialization, inference, cancellation, and release should be separate methods rather than one “universal call,” so the upper layer can precisely control the lifecycle.
    2. Streaming callback: Token-level streaming output should be passed chunk by chunk through bridge channel event callbacks. Apply backpressure on the channel side to avoid high-frequency callbacks overwhelming the UI thread.
    3. Exception mapping: Native-layer exceptions such as OOM, load failure, and unsupported backend should be mapped to structured error codes and returned to the upper layer, not thrown raw.

    4. Step Three: Multi-Agent Concurrency—Global Inference Lock

    Real Agent products are often not single-Agent architectures. Take a local knowledge management app as an example: it may simultaneously have an Agent for card structuring, an Agent for maintaining the knowledge base, and an asset Agent for analyzing images and audio. These may be triggered in parallel by user actions.

    The problem is that an on-device inference engine is not suitable for truly parallel execution of multiple inference tasks on a single device. GPU memory is rigid—the model itself already occupies the main share—and concurrent inference across multiple sessions also contends for compute resources, degrading latency for all tasks at the same time and potentially triggering memory overflow.

    Therefore, an in-process global inference lock (or task queue) is needed:

    1. class InferenceScheduler {
    2. private val lock = Mutex()
    3. suspend fun run(task: InferenceTask): Output {
    4. lock.withLock {
    5. val conversation = engine.createConversation(task.config)
    6. try {
    7. return conversation.execute(task.input)
    8. } finally {
    9. conversation.close() // Ensure the conversation is released
    10. }
    11. }
    12. }
    13. }

    All Agent inference requests are submitted to the scheduler and executed serially. Each task creates a conversation only after acquiring the lock and closes it immediately after execution. This guarantees exclusive access to the engine while reusing the lightweight conversation pattern from Section 3.2. For tasks with different priorities—such as user-triggered interactive tasks versus background batch tasks—priority ordering can be added at the queue layer so that interactive tasks get inference windows first.

    5. Upper-Layer Abstraction: A Unified Interface for Zero-Cost Local/Cloud Switching

    The value of on-device models is not to replace the cloud, but to fill the offline scenario gap. Therefore, the upper-layer Agent framework should not be aware of whether a request goes to the local device or the cloud. The approach is to define a unified LLMClient abstraction:

    1. interface LLMClient {
    2. suspend fun chat(messages: List<Message>, onToken: (String) -> Unit): Response
    3. }

    Cloud providers (clients for various LLM APIs) and the local on-device client each implement this interface. For the upper-layer Agent, switching to local inference is just a configuration change—this is the correct use of abstraction: capability isomorphism, replaceable implementation.

    It is necessary to face the capability differences between the two. On-device models are inferior to flagship cloud models in context length, inference quality, and tool-calling reliability. Therefore, prompt design for local Agents should be more restrained: simplify system prompts, compress tool descriptions, limit the complexity of a single task, and use on-device models for scenarios they are good at—short context and structured output.

    6. Lessons Learned and Engineering Recommendations

    The experience from the entire integration process can be distilled into several actionable principles:

    1. Use multi-layer community plugins with caution in production: Every additional layer in the call chain reduces stability and debuggability, especially when low-level resources such as GPU memory are involved.
    2. Follow the lifecycle pattern of official samples: Engine singleton + short-lived conversations is a proven and robust design.
    3. Concurrency must be constrained: Single-device inference should be serialized by default and managed uniformly by a scheduler; do not let each Agent initiate inference on its own.
    4. Implement backend fallback: GPU first, CPU fallback, to cover long-tail device differences.
    5. Monitor inference health: First-token latency, token throughput, peak memory, and exception rate should all be reported to provide data for model version upgrades and parameter tuning.
    6. Be restrained with model distribution: For GB-level models, prefer on-demand download + integrity verification + rollback capability, and avoid bundling them into the installation package and bloating its size.

    7. Conclusion

    On-device open-source models have turned “a fully offline local Agent” from a concept into a deliverable product form. However, the difficulty of landing it is generally underestimated—the real challenge is not “whether it can run,” but engineering details such as lifecycle management, concurrency control, and stability assurance. Treating the inference engine as a system resource that must be taken seriously, rather than as an ordinary function to call, is the core mindset for on-device LLM engineering. As the inference quality and speed of on-device models continue to improve, the applicable boundary of this architecture pattern will keep expanding, and it is worth advance planning for every team building local intelligent applications.