Building a Memorable On-Device AI Agent: A Practical Guide
This guide presents a practical architecture for building on-device AI agents that maintain continuous state instead of resetting after every restart. It covers persistent memory with local structured storage, layered model routing to control inference costs, running agents on mobile devices to access real-world capabilities, using a local knowledge base as a control panel, and packaging recurring workflows into reusable skills. The article also outlines a reference architecture and selection advice for gradually moving from an on-device loop to cloud collaboration.
1. From Stateless Q&A to an Assistant That Keeps Evolving
Many agent applications still behave like one-shot question answering: the context is wiped whenever the process restarts, users have to repeat the same preferences and constraints, and every turn reloads the system prompt and history fragments, which keeps model call volume high. These are not flaws of one particular implementation but common challenges in agent architecture design. Building a genuinely useful long-term assistant requires solving four things at once: persisting state, converging inference costs, expanding the boundaries of execution, and organizing information in the human-machine interface.
From a general technical perspective, this article lays out a practical path for an on-device agent architecture, covering five parts: persistent memory, layered model routing, mobile runtime, knowledge base integration, and skill packaging.
2. Persistent Memory: Giving the Agent Continuous State
2.1 Why “Amnesia on Restart” Is Fatal
A memoryless agent shows three typical symptoms: it loses all context after frequent restarts; users must restate the same constraints repeatedly; and every request carries lengthy history, driving up input-side consumption. The three reinforce each other and form a vicious cycle.
2.2 Use Local Structured Storage to Hold Memory
A common industry approach is to embed a lightweight relational database locally and persist memory in layers:
-- Session and task logsCREATE TABLE task_log (id INTEGER PRIMARY KEY,session_id TEXT,intent TEXT,plan_json TEXT,status TEXT,created_at TEXT);-- Long-term facts and preferences (retrievable)CREATE TABLE memory_fact (id INTEGER PRIMARY KEY,scope TEXT, -- global / project / personkey TEXT,value TEXT,confidence REAL,updated_at TEXT);-- Skill indexCREATE TABLE skill_index (name TEXT PRIMARY KEY,trigger_desc TEXT,entrypoint TEXT,version TEXT);
Three design points are critical. First, memory must be retrievable rather than injected in full: fetch the Top-K fragments by semantic similarity or scope. Second, memory needs confidence scores and timestamps to support conflict resolution and expiration. Third, sensitive credentials belong in the system keystore or encrypted storage and must never be written to memory tables in plaintext.
2.3 The Compounding Effect of Memory
As interactions accumulate, the agent can remember how to call frequently used interfaces, output format preferences, and historical operation paths, reducing trial-and-error rounds in complex workflows. A practical recommendation is to add a “memory write gate”: write to long-term memory only when the user explicitly confirms or the task converges successfully, avoiding noise pollution.
3. Layered Model Routing: Bringing the Cost Curve Down
3.1 A Single Model Is Inevitably Expensive
Using the strongest model for every task is the most common source of cost overruns. The sensible approach is layered routing: hand intent recognition, format conversion, and summarization or classification to small-parameter or local models, and escalate to a large model only for multi-step planning, code generation, and difficult reasoning.
3.2 Give Deterministic Tasks to Code, Not Repeated Reasoning
This is the most effective cost-reduction measure. For any step with clear rules and stable inputs and outputs, the agent should generate and run a script instead of asking the model every round. Illustrative logic:
def route(task):if task.is_deterministic: # format conversion, batch rename, report aggregationreturn run_generated_code(task) # generate once, reuse many timesif task.risk == "high":return call_strong_model(task) # escalate only for critical decisionsreturn call_small_model(task)
Data shared by one practitioner is worth noting: after introducing a multi-model gateway and a “code instead of reasoning” strategy, their recurring call cost dropped from roughly the order of one hundred thirty dollars every five days to roughly the order of ten dollars. The exact numbers vary greatly with task structure; the point is the methodology, not the absolute values.
3.3 Context Budget Governance
Supporting measures include loading prompts in layers, compressing history into summaries, deduplicating repeated content, and persisting batch results while returning only summaries. These typically cut input-side consumption more significantly than switching models.
4. Mobile Runtime: Connecting the Physical World to the Agent
Running the agent on a mobile device is valuable not because it is “cheaper” but because it can access capabilities the cloud cannot reach: sensor readings, notifications and SMS, battery and network status, local files, and the camera. This enables genuine hardware-level automation, such as automatically reading a one-time verification code and filling it in, or adjusting task strategy based on environmental state.
Boundaries matter too. On-device execution involves highly sensitive data, so follow the principle of least privilege: sensitive operations require user confirmation, and sensitive data should be processed locally and stored encrypted. When publishing content to social platforms, prefer official open APIs and follow platform rules, avoiding the compliance and rate-limiting risks of simulating client behavior with scripts.
5. Using a Knowledge Base as the Control Panel to Solve Information Overload
A chat window is naturally unsuited to holding structured state. A more robust pattern is for the agent to write tasks, conclusions, and to-dos into a local knowledge base (plain text with bidirectional-link notes), while the human only reviews structured pages. After one to three weeks of continuous “feeding,” the agent can learn the user’s routine and priorities and proactively generate daily reports, weekly reports, and knowledge cards.
Implementation advice: agree on stable directory and metadata conventions (fixed frontmatter fields), append rather than overwrite when writing, keep a traceable record of every change, and trigger generation with scheduled tasks instead of relying on manual prompts.
6. Skill Packaging: The Core Competitiveness in the AI Era
The real leverage is packaging recurring friction in daily life into reusable skills: financial statement parsing, pairing ingredients from the fridge, organizing reimbursement receipts, and so on. A skill should include a trigger description, input and output contracts, a failure fallback strategy, and a version number, forming a testable and composable asset library.
name: fridge-meal-plannertriggers: ["what to eat today", "clear the inventory"]inputs: {inventory: list, constraints: list}outputs: {menu: list, shopping: list}fallback: ask_userversion: 1.0.0
7. Reference Architecture and Selection Advice
To host memory and scheduling in a managed way, you can combine general cloud capabilities: object storage for skill packages and knowledge base snapshots, a message queue to decouple long-running tasks, a container platform to host execution sandboxes, logging and monitoring with alerting for observability, and a key management service for credentials. Baidu AI Cloud offers corresponding capabilities in these general categories, and you can adopt them incrementally by scale: build the on-device loop first, then migrate to cloud collaboration.
8. Conclusion
The competitiveness of an on-device agent does not come from model parameter count but from whether memory is continuous, whether cost is controllable, whether execution reaches real devices, and whether knowledge is deposited in a structured way. Following the five steps of persistent memory, layered routing, on-device execution, knowledge base panel, and skill packaging turns a one-shot Q&A tool into a long-term companion that keeps adding value through automation.
