Building Local AI Agents: Proactive Assistants and On-Device LLM Inference
This article explores how to design and implement AI agents that run locally on user devices. It covers the shift from cloud-based inference to on-device execution, a five-layer agent architecture, design principles for proactive event-driven assistants, multi-agent collaboration, engineering practices for long-term memory, resource estimation and optimization for local LLM inference (including quantization, KV cache management, and expert placement for MoE models), security and privacy safeguards, and a practical rollout roadmap with measurable milestones.
1. From Cloud Calls to On-Device Execution
Most AI applications today rely on cloud inference. The user sends a request to a remote data center, the model computes a response, and the result is returned—typically billed per token consumed. This model is easy to scale, but it comes with three clear problems:
- Data leaves your domain: Personal email, calendars, and documents must be uploaded to a third-party environment, raising privacy risks and compliance costs.
- Unpredictable costs: An agent repeatedly calls the model, reads context, and generates intermediate steps. Token consumption grows quickly with task complexity.
- Network dependency: When the network is interrupted or latency fluctuates, both the agent’s responses and its actions are affected.
Running agents on-device is one way to address these issues. Model inference, memory storage, and tool calls all happen on the user’s machine, so data stays local by default. This approach is not free of trade-offs. Personal devices have limited compute, RAM, and VRAM, forcing compromises in model size and response speed. The engineering focus of an on-device agent is therefore to divide responsibilities under constrained resources: keep what can be handled locally on the device, and hand off to the model only what genuinely requires it.
2. Basic Architecture of an On-Device Agent
A practical on-device agent typically consists of five layers. Clear responsibilities per layer make each one easier to replace and test independently.
┌──────────────────────────────────────────┐│ Interaction: notifications, chat UI, ││ user confirmation │├──────────────────────────────────────────┤│ Planning: task decomposition, ││ prioritization, state management │├──────────────────────────────────────────┤│ Memory: session context, long-term ││ memory, retrieval index │├──────────────────────────────────────────┤│ Execution: file operations, browser ││ automation, application control │├──────────────────────────────────────────┤│ Inference: local model serving, ││ quantized models, cache management │└──────────────────────────────────────────┘
The perception layer is the data entry point. It connects to data sources explicitly authorized by the user, such as the email inbox, calendar, and instant messaging channels. It only collects and normalizes data, converting events from different sources into a unified format—for example, “a new email has arrived” or “a meeting starts in 30 minutes.”
The planning layer receives events and decides whether they need handling, then breaks tasks into steps. It also maintains task state, recording whether each step is completed, failed, or awaiting user confirmation.
The memory layer stores what the agent needs to “remember,” divided into short-term context and long-term memory, which will be covered in detail later.
The execution layer turns plans into concrete actions, such as organizing local files, filling out browser forms, or triggering menu operations in desktop applications. This layer must be permission-constrained: every action type declares the minimum permissions it requires.
The inference layer invokes the local model for tasks such as intent recognition, summarization, and constructing tool-call parameters. It should hide model details from upper layers so that higher-level code does not depend on any specific model or runtime.
3. Design Principles for a Proactive Assistant
A conventional agent starts from a user instruction—if the user doesn’t ask, it does nothing. A proactive assistant starts from events: it continuously observes data sources and reminds the user or advances tasks at the right moment.
Designing a proactive assistant requires answering three questions.
1. When should it trigger?
Trigger conditions are usually determined by event type, time window, and importance. For example, a reminder is highly valuable when a meeting starts in under ten minutes and its materials are not yet prepared; an ordinary group message is usually low-value. A simple approach is to assign each event type a base score, then combine it with time factors to compute a final priority.
function score_event(event, now):base = BASE_WEIGHT[event.type]urgency = max(0, 1 - (event.deadline - now) / WINDOW)relevance = user_relevance_model(event)return base * 0.4 + urgency * 0.4 + relevance * 0.2
2. How do you limit interruptions?
If proactive features interrupt the user too often, they get disabled quickly. An “interruption budget” is therefore needed—the number of proactive messages allowed per unit of time. Low-priority events that exceed the budget go into a digest queue and are pushed together at fixed times.
3. How does it improve from feedback?
Every proactive message should record the user’s reaction: accepted, ignored, snoozed, or explicitly rejected. At the end of each day, the system can review that day’s messages, compute adoption rates per event type, and adjust base weights and trigger thresholds accordingly. This review process itself should be visible—users can inspect and modify the rules, avoiding a system that “decides on its own” without being able to explain itself.
4. Multi-Agent Collaboration
When a single agent takes on every responsibility, its context grows rapidly and tasks interfere with each other. Splitting responsibilities across multiple roles is a common solution.
A typical role division includes:
- Planner: understands the goal and produces task steps, but does not execute actions directly.
- Executor: completes concrete steps within a limited tool set, such as reading files or operating the browser.
- Reviewer: checks whether the executor’s output complies with rules—for example, whether it contains sensitive information or exceeds authorized access.
Communication between roles can use shared state or a message queue. Shared state is simple and suits small-scale tasks; a message queue supports asynchronous processing and retries, making it better for long-running tasks.
Multi-agent collaboration must also handle resource conflicts—for instance, two agents modifying the same file simultaneously or competing for desktop focus. Common solutions include resource locks, operation serialization, and priority arbitration. The key principle: any write to user files or system state must pass through a single arbitration point and leave a rollback-able record.
5. Engineering Long-Term Memory
An LLM’s context window is limited, and every call consumes tokens. Long-term memory requires persisting key information and retrieving it when needed.
5.1 A Layered Memory Model
- Working memory: temporary state for the current task, cleared when the task ends.
- Episodic memory: records of specific events, such as “discussed a proposal with someone on a certain date,” with timestamps and sources.
- Semantic memory: stable facts or preferences distilled from many events, such as “the user usually handles expense reports on Monday mornings.”
The three memory types have different lifecycles and update frequencies, so their storage structures and cleanup policies should be designed separately.
5.2 Write Strategy
Not every conversation is worth remembering. Before writing, apply the following processing:
- Summarization and compression: compress long conversations into key points, retaining names, times, decisions, and to-dos.
- Deduplication and merging: for content semantically similar to existing memories, update the original entry instead of creating a new one.
- Importance scoring: score content based on factors such as whether the user explicitly asked to remember it and whether it involves commitments or deadlines. Low-scoring content may be skipped.
5.3 Retrieval Strategy
A common approach combines vector retrieval with keyword retrieval, plus time-based filtering. Vector retrieval excels at matching semantically similar phrasing; keyword retrieval is more reliable for names, technical terms, and identifiers; time filtering excludes stale information. Results should be re-ranked by relevance and recency, placing only a few high-quality fragments into the model context.
5.4 Evaluation
The effectiveness of long-term memory should be measured against your own evaluation set, not just a single leaderboard number. The evaluation set can include multi-turn conversations with several question types: factual recall spanning multiple turns, inference about user preferences, and update scenarios that require correcting old information. Key metrics include recall rate, answer accuracy, and retrieval latency. Different benchmarks use different methodologies, so before comparing scores across projects, confirm that the datasets and scoring rules are consistent.
6. Resource Constraints and Optimization for Local Inference
6.1 Estimating RAM and VRAM
Whether a local model can run depends first on whether RAM and VRAM are sufficient. A rough estimation formula:
Required VRAM ≈ parameter count × bytes per parameter + KV cache + runtime overhead
Bytes per parameter depend on quantization precision: about 2 bytes at half precision, about 0.5 bytes at 4-bit quantization. For a 7-billion-parameter model, half-precision weights occupy roughly 14 GB, and 4-bit quantization brings that down to roughly 3.5 GB—plus KV cache and framework overhead. Actual usage also depends on context length, batch size, and runtime implementation, so measure on the target device.
6.2 Quantization and Cache Management
Quantization is the most direct way to reduce resource usage, but accuracy loss must be validated through task-level evaluation. The KV cache grows linearly with context length and can become a VRAM bottleneck in long conversations. Common cache strategies include capping maximum context length, applying sliding-window truncation to history, and swapping out infrequently used cache pages.
6.3 Layered Placement for Mixture-of-Experts Models
Mixture-of-Experts (MoE) architectures activate only a subset of expert sub-networks per inference step, which enables resource tiering. If the same experts are activated frequently, they can be kept resident in VRAM; low-frequency experts stay in system memory and are swapped in when needed.
function place_experts(stats, vram_budget):ranked = sort_by_activation_frequency(stats, descending)hot = []used = 0for expert in ranked:if used + expert.size <= vram_budget:hot.append(expert)used += expert.sizecold = difference(all_experts, hot)return hot, cold
The benefit of this placement strategy depends on how concentrated the activation distribution is and on the transfer bandwidth between system memory and VRAM. The more concentrated the distribution, the higher the hot-expert hit rate and the lower the average latency. Measure real workloads before deployment rather than designing placement from theoretical assumptions alone.
6.4 Performance Evaluation
Local inference performance should be measured across three dimensions: time to first token, sustained generation speed (tokens per second), and resource usage under concurrent tasks. When testing, record hardware specs, driver version, quantization method, context length, and load conditions—otherwise the results are neither reproducible nor comparable.
7. Security and Privacy
An on-device agent can read and write local files and operate applications, so security design demands even more care than cloud applications.
- Least privilege: each action receives only the permissions needed to complete the task; file access is restricted to designated directories.
- Confirmation for critical operations: irreversible actions—deletion, sending, payment, permission changes—must be explicitly confirmed by the user.
- Auditable logs: record every tool call with its input parameters and results, with sensitive information redacted in the logs themselves.
- Prompt injection defense: instructions appearing in email bodies, web pages, and documents should be treated as data to be processed, not as system instructions. The agent must not execute an operation simply because external content says “please do X.”
- Data classification: set independent access policies for sensitive data such as contacts, finances, and health, and decide which data may enter the model context.
8. Rollout Recommendations
Proceed in the following steps, each with verifiable metrics as its exit criteria.
- Define the scenario: pick one or two high-frequency, low-risk tasks, such as schedule reminders and file archiving.
- Build the basic pipeline: complete the minimal closed loop of perception, planning, and execution, ensuring every step can be replayed.
- Build an evaluation set: collect real task samples, define success criteria, and continuously track task completion rate, false-trigger rate, and interruption rate.
- Optimize resource usage: test different quantization schemes and context lengths on target hardware to find the balance between quality and speed.
- Grant permissions gradually: start with read-only capabilities, then open write and external-send capabilities after stability is proven.
Common pitfalls include pursuing multi-agent architectures too early, neglecting quality control over memory writes, and treating the speed of a single demo as a stable production metric. The value of an on-device agent lies in reliably handling what users actually need over the long term—not in one-off demos.
Conclusion
The core work of running AI agents locally is finding a sound division of labor among privacy, cost, response speed, and model capability. Proactive assistants offer a path from passive response to event-driven operation, while layered memory and tiered resource placement address the engineering constraints of on-device environments. Teams should drive decisions with quantifiable metrics and expand the agent’s capabilities step by step.
