On-Device LLM Agents: Pitfalls of Native Direct Calls and Concurrent Scheduling
This article uses the integration of an on-device open-source LLM into a fully local AI knowledge management app as an example to discuss three issues: how to choose a wrapper library, how to manage memory for the engine and sessions, and how to schedule multiple agents issuing concurrent requests. It covers stability problems with third-party wrapper libraries and troubleshooting, a native direct-call architecture with an engine singleton and per-request sessions, a unified LLM client interface for switching between local and cloud providers, and resource scheduling for multi-agent concurrency using a global lock plus priority, timeout, cancellation, backpressure, and device monitoring mechanisms. It also provides a pre-launch checklist.
Running a fully offline AI Agent on a phone is already feasible. For personal knowledge management apps that prioritize privacy, completing all inference locally without relying on any cloud service is an attractive direction. This article uses the integration of an on-device open-source LLM into a fully local AI knowledge management app as an example to discuss three questions: how to choose a wrapper library for an on-device LLM, how to manage memory for the engine and sessions, and how to schedule multiple Agents when they issue requests at the same time.
The model file in this article is about 2.6 GB. This is the file size, not the parameter count. Parameter count and quantization precision jointly determine memory usage; when converting, refer to the actual model specification.
1. Stability Problems and Troubleshooting with Third-Party Wrapper Libraries
In the early stage of the project, the team first integrated the local model using a third-party wrapper library based on a cross-platform UI framework. Such libraries wrap the inference engine a second time, provide a simple API, and can get basic inference running quickly. After deeper testing, problems appeared one after another: the app crashed, and on a few test devices there were full-device black screens and reboots.
A system-level reboot usually indicates a serious problem in low-level resource management. Common causes include GPU memory exhaustion triggering system protection and unrecoverable deadlocks at the driver layer. Symptoms alone cannot identify the cause. During troubleshooting, the following information should be recorded:
- Device model, OS version, and memory capacity
- Version numbers of the inference engine and wrapper library
- Model file hash and quantization precision
- Input length, concurrency count, and backend type (CPU or GPU) when the problem was triggered
- System logs and app logs before and after the crash
Data safety also matters during troubleshooting. A system reboot may cause unsaved data to be lost. Back up the knowledge base and conversation records before testing, and operate on isolated test data.
On the same device, the vendor’s official reference app could run the same model file stably. Comparing the call paths of the two shows that the official app calls native platform APIs directly, while the third-party wrapper library has an extra plugin layer between the cross-platform runtime and the underlying engine. In a resource-constrained on-device environment, this layer may introduce additional memory allocation overhead or defects in context management. The team ultimately abandoned the third-party wrapper library and switched to native direct calls.
The following table compares the two approaches. Best fit varies by project and is for reference only:
| Dimension | Third-party wrapper library | Native direct calls |
|---|---|---|
| Stability | Depends on wrapper quality; issue diagnosis path is long | Short call chain; easier to diagnose issues |
| Memory control | Limited by wrapper strategy; weaker fine-grained control | You can manage engine lifecycle and sessions yourself |
| Development cost | Fast early; customization becomes difficult later | Slow early; requires maintaining native code |
| Best fit | Prototyping and simple features | Products with high stability and resource requirements |
2. Native Direct-Call Architecture and Engine Singleton
After refactoring, the call path became: business logic layer, native channel, custom native plugin, underlying inference engine.
The core design of the native plugin is “engine singleton, sessions created on demand.” Loading a 2.6 GB model into GPU memory is time-consuming and resource-intensive. If the engine were reinitialized for every inference, latency would be high, and system memory would soon be exhausted. Therefore, the engine is initialized only once during the app lifecycle, while a session is created for each request and released immediately after use.
The following code is illustrative and omits the complete definition of config. For actual parameters, refer to the official documentation of the engine you use.
// Global engine singleton: load the model only once per app lifecycleval engine = Engine(EngineConfig(modelPath = modelPath,backend = Backend.GPU(), // Specify GPU accelerationmaxNumTokens = 10000, // Context window limit, directly affects memory usagecacheDir = context.cacheDir.absolutePath,))engine.initialize()// Create a conversation on demand for each inference and release it immediately after useengine.createConversation(config).use { conversation ->conversation.sendMessageAsync(userText).collect { responseChunk ->// Receive streaming inference results}}
A few notes:
- The larger
maxNumTokensis, the longer the context that can be accommodated and the higher the memory usage. Test the memory limit on target devices first, then decide the value. - Engine initialization should be performed on a background thread to avoid blocking the UI.
- The
useblock ensures that the session is released even in exceptional cases, reducing the risk of memory leaks.
After switching to native direct calls, inference speed returned to the device’s normal level, and full-device reboots no longer occurred in testing. This only shows that the problem disappeared on the test devices and in the test scenarios; it does not mean that all device models will be free of the problem.
Before launch, it is recommended to establish a reproducible checklist that at least includes the following:
- Device matrix: covered device models, OS versions, and memory capacities
- Model hash and quantization precision: ensure the same model file is used for every test
- Engine version: record and lock it
- Test cases: long-text input, multiple consecutive turns, background switching, low battery, and thermal scenarios
- Observability metrics: time to first token, per-inference latency, peak memory, and crash rate
3. Interface Abstraction and Local/Cloud Switching
To keep Agent business logic independent of where the model runs, the team defined a unified LLM client interface. Existing cloud model providers implemented this interface, and the local client implemented the same interface.
After the user enables “fully offline mode” in settings, the system only needs to change one configuration item to switch the model provider from cloud to local. Agent business code does not need to change.
The switching solution also needs to handle the following boundary cases:
- Failure fallback: When local inference fails, provide a clear prompt and let the user decide whether to switch to cloud. Do not switch silently; otherwise data in offline mode may be sent to the cloud.
- Timeout control: Set a timeout for local inference. After timeout, cancel the request and release the session to avoid long UI waits.
- Privacy boundary: In offline mode, all inputs and outputs should not leave the device. The switch state must be clearly displayed in the UI.
4. Resource Scheduling Under Multi-Agent Concurrency
The app includes multiple dedicated Agents, including a Card Agent that processes information cards, a PKM Agent responsible for knowledge base extraction and classification, and an Asset Analysis Agent that analyzes local images and audio. When importing materials in batches, these Agents issue inference requests at the same time.
On-device compute and GPU memory are far more limited than cloud servers. If multiple Agents request inference at the same time, GPU memory may be exhausted instantly, leading to queued-task deadlocks or app crashes.
The team added a global lock at the native plugin layer. Every inference request must acquire the lock before entering the engine, so inference tasks are executed serially on the device. This sacrifices some parallel efficiency but effectively avoids crashes caused by GPU memory contention. Serialization reduces crash risk; it does not guarantee that the system will never fail.
Adding a lock alone also introduces new problems, which require the following supporting mechanisms:
- Priority scheduling: Foreground interactive requests have the highest priority and can jump the queue. Background knowledge base organization tasks have lower priority and run when the device is off-screen or idle.
- Priority inversion protection: When a low-priority task holds the lock, high-priority requests are blocked. You can set a timeout for waiting on the lock and suspend low-priority tasks if the wait is too long.
- Timeout and cancellation: Each request has a timeout. After the user leaves a page, related requests should be canceled promptly and the lock released.
- Backpressure: Limit the wait queue length. When the queue is full, new background tasks should be rejected or delayed, not accumulated indefinitely.
- GPU memory and temperature monitoring: Check available memory and device temperature before inference. When the device overheats and throttles, appropriately reduce concurrency or pause background tasks.
- Thread placement: Neither inference nor lock waiting can be placed on the main thread. Long blocking of the main thread triggers an application not responding (ANR) error.
These mechanisms make the multi-Agent experience more controllable. Specific timeout values, queue lengths, and priority thresholds need to be determined based on stress test results for target devices.
Pre-Launch Checklist
- Issues with the third-party wrapper library have been reproduced and recorded on target devices
- The engine is managed as a singleton, and sessions are released immediately after use
- Model file size, parameter count, and quantization precision have been verified separately
