On-Device AI Agents: Building Mobile Automation with Local Large Language Models

    This article examines on-device AI agents that run lightweight large language models locally on a phone to automate mobile tasks from natural-language instructions. It presents a four-layer architecture — model, perception, decision, and execution — and walks through the engineering challenges of each: quantization and pure-CPU inference in the model layer, UI-tree serialization via the OS accessibility service in the perception layer, restricted action spaces and prompt design in the decision layer, and closed-loop verification with failure recovery in the execution layer. It also covers performance and resource tuning, device compatibility, privacy and security, end-cloud collaboration, and a quantitative evaluation framework, showing how such agents can move from demo to everyday use.

    1. Introduction: Putting Agents into the Phone

    The “phone agent” has become a popular research direction in recent years. A user issues a request in natural language — “organize the screenshots in my photo library” or “fill out this form” — and the agent performs clicks, swipes, and text input directly on screen. Early approaches relied mostly on cloud-hosted large models: the client captured screenshots and uploaded them, the model ran inference in the cloud, and action instructions were sent back down.

    But in real-world scenarios that are high-frequency, privacy-sensitive, and prone to unstable networks, this pipeline’s problems become apparent:

    • Privacy leakage risk: Screenshots often contain verification codes, chat records, and payment information. Once they leave the device, they are out of the user’s control.
    • Uncontrollable latency: Every decision requires a network round trip of “upload — infer — dispatch,” and stuttering is noticeable on weak networks.
    • Ongoing invocation cost: Each step consumes one cloud inference; the longer the task, the higher the cost.

    On-device agents move the model to the device itself. Take a comparable solution as an example: it is built on a lightweight on-device language model and performs pure CPU inference on the device through a lightweight inference runtime, with no network connection or cloud compute required. The model file is about 2.6GB, and startup on a pure-CPU device may take around 45 seconds. Its control mechanism relies on the mobile OS’s accessibility service to obtain the screen’s UI tree, then identifies, decides on, and operates screen elements, forming a closed-loop automation.

    The advantages of this approach are intuitive: screen data never leaves the device, it works even when the network is down or in airplane mode, and there is no per-use billing for a single task. But its engineering difficulty concentrates on resource constraints and capability boundaries. This article breaks down the technical architecture, examines the key problems at each stage, and offers practical engineering guidance.

    2. Overall Architecture: The Four-Layer Loop of an On-Device Agent

    On-device agents can be abstracted into four connected layers:

    Layer Responsibility Key constraints
    Model Understand task intent, plan the next action Memory footprint, inference speed, context length
    Perception Obtain and structure the current screen state Accessibility permission, node pruning, self-drawn UIs
    Decision Convert natural-language intent into executable actions Stable output format, history context management
    Execution Execute actions and verify results Action reliability, failure recovery, sensitive-action protection

    They form a continuously running loop:

    Perceive → capture screen state → Decide → model generates next action → Execute → executor carries out the action → Verify → did the state meet expectations → if not, re-perceive and enter the next round

    Three points are worth emphasizing:

    1. State-driven, not script-driven. Traditional automation tools rely on developers pre-recording a fixed path and break as soon as the page structure changes slightly. The agent makes a decision based on the current real screen each round, giving it natural adaptability to interface changes.
    2. The action space must be restricted. The model outputs structured actions (which control to click, what text to input), not arbitrary code or system commands. This makes parsing and verification easier and limits the potential blast radius of errors.
    3. Verification is a necessary condition for the loop. A successfully executed action does not mean the task state is correct — a click may miss because a control was not ready. Only by comparing the state before and after execution does the loop truly “close.”

    Now let’s expand each layer.

    3. Model Layer: What It Takes to Run on the CPU

    3.1 Size, Memory, and Quantization

    An on-device model must first solve the size problem to run on resource-constrained devices such as phones and tablets. The larger the model file, the higher the download, storage, and loading costs, and the more memory it consumes at runtime. The industry commonly uses quantization to compress weights — representing parameters with lower numerical precision:

    • FP16/FP32: highest precision, largest size;
    • INT8: about 1/4 the size of FP32, a balanced choice between precision and size;
    • INT4: compressed further to about 1/8 of FP32, common in on-device solutions but sensitive to activation distributions and requiring careful calibration.

    For a typical estimate: a 4-billion-parameter model needs about 16GB of memory for FP32 weights, about 4GB for INT8, and about 2GB for INT4. Keeping the file around the 2.6GB mark usually means low-bit quantization was used, supplemented by reasonable vocabulary and structural pruning.

    It is worth emphasizing that precision loss after quantization directly affects the agent’s decision quality. UI automation tasks demand high semantic understanding — for example, judging whether “Confirm” or “Cancel” is the primary action, or whether an error prompt has appeared. A quantization scheme should be validated with task-level evaluation of its performance on real interfaces, not just the model’s score on general benchmarks.

    3.2 Pure CPU Inference: Where Does Latency Come From?

    Large-model inference has two phases:

    • Prefill: processes the input prompt all at once, compute-intensive and well-suited to parallelism;
    • Decode: generates tokens one by one, reading all weights at each step — a memory-access-intensive task.

    In a pure-CPU setting, the two phases have different bottlenecks:

    • Prefill is limited by CPU compute and memory bandwidth; the longer the prompt, the longer it takes;
    • Decode reads the model weights from memory for every generated token, so its speed is determined mainly by memory bandwidth.

    Therefore, an on-device agent running on pure CPU usually follows a few principles:

    • Control the output length of each step. The model only needs to output one action per step, tens to a hundred or so tokens.
    • Compress prompt content. Screen state and history are the main sources of input and must be trimmed.
    • Reduce unnecessary inference. For deterministic steps, use deterministic policies instead of model inference.

    3.3 Why Cold Start Can Take Tens of Seconds

    In some on-device solutions, model cold start can take around 45 seconds, spent mainly on:

    1. Model loading: reading GB-scale weight files from local storage, noticeably affected by I/O performance and filesystem caching;
    2. Memory allocation and initialization: allocating inference buffers and dequantizing or reordering weights;
    3. Graph construction and compilation: the runtime binds operators and plans memory, possibly including compilation optimizations;
    4. First warm-up: running one inference to trigger cache and memory-allocation paths.

    The following optimizations address these stages:

    • Resident inference engine: keep the agent service running in the background, load the model only once, and reuse the same session for subsequent tasks, turning “cold start” into “warm start”;
    • Preload and warm-up: load the model during idle time and run one minimal inference;
    • Prefer quantization formats: load quantized weights that natively match the runtime, avoiding repeated conversion at runtime;
    • Sensible thread configuration: match the number of inference threads to the CPU core count and big.LITTLE architecture, avoiding scheduling overhead and device overheating.

    3.4 Context and Output Strategy

    On-device models have limited context windows, so how prompts are organized directly determines the success rate:

    • Send only the screen fragment relevant to the current step;
    • Keep only key actions and their results in history, not a full sequence of screenshots;
    • Require the model to output strictly constrained JSON actions, validate the output against a schema, and retry with the error message when validation fails.
    1. # Model wrapper (illustrative pseudocode; the interface is custom)
    2. class LocalLM:
    3. def __init__(self, model_path, threads=4):
    4. self.model_path = model_path
    5. self.threads = threads
    6. self.session = None # inference session handle
    7. def load(self():
    8. # Load and warm up once; only needed once when the on-device process stays resident
    9. self.session = load_runtime(self.model_path, num_threads=self.threads)
    10. self.session.run(prompt="OK", max_tokens=1) # warm-up to avoid first-inference overhead
    11. def decide(self, prompt, max_tokens=128):
    12. # Use a low temperature to improve the stability and parseability of action output
    13. return self.session.run(prompt=prompt, max_tokens=max_tokens, temperature=0.1)

    4. Perception Layer: Turning the Screen into Language the Model Can Read

    4.1 Accessibility Service: Source of Capability and Permission Boundaries

    The typical way an on-device agent obtains interface information is by calling the OS’s accessibility service. It was originally built to serve visually impaired users — for example, screen readers use it to read control text aloud. The agent uses the same interface to read the screen’s UI tree, which contains:

    • control types, such as buttons, text fields, and list items;
    • text content and content descriptions;
    • attributes such as clickable and editable;
    • the control’s bounding coordinates on screen.

    With this tree, the agent can both “understand” the screen semantics and precisely locate operation targets — for example, “click the ‘Submit’ button numbered 12 in the bottom-right corner.” The accessibility service usually also provides interfaces to perform clicks, text input, and scrolling, so perception and execution can be built on the same channel.

    The flip side of this capability is the sensitivity of the permission: once granted, the accessibility service can read nearly everything on screen and simulate user actions. If a malicious app tricks the user into enabling this permission, the consequences may involve privacy leakage or even financial loss. Therefore, any application built on this capability must adhere to four principles:

    • the permission’s purpose must be fully transparent to the user;
    • data is processed only locally;
    • provide a clear toggle and an entry point to revoke authorization at any time;
    • sensitive operations require a second user confirmation.

    4.2 UI Tree Serialization: Making It “Readable” to the Model

    A raw UI tree is a multi-level nested structure with potentially hundreds or even thousands of nodes; serializing it directly can easily exceed the model’s context. Engineering practice usually follows these steps:

    1. Prune: keep only interactive nodes and necessary text nodes — for example, clickable, input-able, and scrollable nodes, plus text carrying key information;
    2. Number: assign a unique id to each retained node so the model can locate targets by outputting just the id;
    3. Flatten: output as a list in reading order, expressing hierarchy through indentation or a depth field;
    4. Add key context: attach the current page title, entered content, screen size, and other context.
    1. # UI tree serialization (illustrative pseudocode)
    2. # Node attributes come from the interface hierarchy provided by the accessibility service
    3. def serialize(ui_root, screen_size):
    4. """
    5. Prune, number, and flatten the UI tree into text the model can read.
    6. Returns: (structured node list, serialized text)
    7. """
    8. nodes = []
    9. def walk(node, depth):
    10. text = node.text or node.content_desc
    11. # Keep only interactive nodes and text nodes that carry key information
    12. keep = node.clickable or node.editable or node.scrollable or text
    13. if keep:
    14. nodes.append({
    15. "id": len(nodes), # globally unique id, referenced directly by the model
    16. "depth": depth, # hierarchy depth
    17. "type": node.class_name, # control type
    18. "text": text,
    19. "clickable": node.clickable,
    20. "editable": node.editable,
    21. "bounds": node.bounds, # screen coordinates, used for verification and fallback clicks
    22. })
    23. for child in node.children:
    24. walk(child, depth + 1)
    25. walk(ui_root, 0)
    26. # Number in reading order (top to bottom, left to right)
    27. nodes.sort(key=lambda n: (n["bounds"].top, n["bounds"].left))
    28. for i, n in enumerate(nodes):
    29. n["id"] = i
    30. lines = [f"# screen {screen_size.width}x{screen_size.height}"]
    31. for n in nodes:
    32. flags = "".join([
    33. "[C]" if n["clickable"] else "",
    34. "[E]" if n["editable"] else "",
    35. ])
    36. lines.append(f'<{n["id"]}{flags} type={n["type"]}> {n["text"] or ""}')
    37. return nodes, "\n".join(lines)

    4.3 Self-Drawn UIs and Screenshot Fallback

    The UI tree is not omnipotent. Many apps use game engines or self-drawing frameworks to render their interfaces, so the control tree often contains only a “root node”; the semantics of content such as video and maps also cannot be obtained from node attributes. In such scenarios, multimodal perception is needed as a fallback:

    • run optical character recognition (OCR) on key regions to extract text;
    • use a vision model to understand image semantics;
    • merge both results into the same state description.

    But the cost of multimodal approaches must be clear: high screenshot resolution means heavy vision-token consumption and slower model inference, which is hard to complete in real time on pure-CPU devices. A more pragmatic strategy is layered perception: rely on the UI tree for structurally clear interfaces, and trigger screenshots and OCR only for self-drawn UIs or when key nodes are missing. This “hybrid perception” balances efficiency and coverage.

    5. Decision Layer: Constraining the Model with a Restricted Action Space

    5.1 Why the Action Space Must Be Restricted

    If the model were allowed to freely generate code or arbitrary instructions, the consequences of a hallucination would be uncontrollable. The safe approach is to define a minimal action set:

    Action Meaning Key parameters
    tap click a control node id
    text enter text into an input field node id, text
    scroll swipe up/down/left/right direction, distance
    open_app open an app app identifier
    wait wait for page load milliseconds
    done end the task result or failure reason

    Also agree that only one action is output each time, returned in JSON format. This both reduces per-step generation length and makes it easy for the executor to parse, verify, and retry.

    5.2 Prompt Design Points

    1. [Role]
    2. You are an automation assistant executing a task on a phone.
    3. [Global task]
    4. {user_task}
    5. [Current screen]
    6. {screen_description}
    7. [Action history]
    8. {history} # keep only the most recent N actions and their results
    9. [Available actions]
    10. tap(id) | text(id, content) | scroll(direction) | open_app(name) | wait(ms) | done(status)
    11. [Output requirements]
    12. - Output only one JSON object, with no explanation;
    13. - You may select only an id listed on the current screen;
    14. - If the current screen cannot proceed further, output done(status="failed") and state the reason.

    There are three design points:

    • Information minimization: provide only the information needed to complete the task;
    • Parseable output: strict JSON format makes programmatic validation easy;
    • Expressible failure: allow the model to proactively declare “cannot continue,” avoiding repeated attempts in place.

    5.3 Output Parsing and Validation

    Model output must pass multiple layers of validation before execution:

    1. Format validation: can it be parsed as JSON, and does it contain the required fields;
    2. Semantic validation: is the action type valid, and does the node id exist on the current screen;
    3. Safety validation: is it a high-risk operation.

    On validation failure, append the error message to the history and let the model retry; on consecutive failures, lower the temperature or simplify the prompt.

    1. import json
    2. import re
    3. ALLOWED_ACTIONS = {"tap", "text", "scroll", "open_app", "wait", "done"}
    4. def parse_action(raw, valid_ids):
    5. # Extract the first JSON object
    6. m = re.search(r"\{.*\}", raw, re.S)
    7. if not m:
    8. return {"error": "no_json"}
    9. try:
    10. obj = json.loads(m.group(0))
    11. except json.JSONDecodeError:
    12. return {"error": "invalid_json"}
    13. name, args = obj.get("action"), obj.get("args", {})
    14. # Double-check the action type and the node id
    15. if name not in ALLOWED_ACTIONS:
    16. return {"error": f"unknown_action:{name}"}
    17. if name in ("tap", "text") and args.get("id") not in valid_ids:
    18. return {"error": "invalid_node_id"}
    19. return {"action": name, "args": args}

    6. Execution and the Loop: Let the Agent “Finish and Confirm”

    6.1 Executor and Coordinate Mapping

    The parsed actions are carried out by the executor. One easily overlooked engineering detail is the conversion of a control’s center-point coordinates.

    The control bounds returned by the accessibility service are usually relative to the window, while injected click events often use absolute screen coordinates. In scenarios involving a status bar, navigation bar, split screen, or foldable devices, the two do not match. If the conversion is wrong, the click lands in the wrong place. For such problems, you can:

    • use the screen screenshot as a unified coordinate baseline;
    • re-query the control bounds before clicking to confirm the target has not shifted.

    6.2 State Verification and Failure Recovery

    After an action is executed, the agent captures the screen state again and compares it with expectations:

    • Matches expectations: record the step result and proceed to the next round;
    • Does not match: determine the failure type:
      • control not ready — wait and retry;
      • control position changed — relocate;
      • an unexpected interruption such as a popup, ad, or permission request appears — handle the interruption first, then return to the main flow;
    • Consecutive failures exceed the threshold: abandon the current subtask or request user intervention.
    1. # Closed-loop control (illustrative pseudocode)
    2. MAX_STEPS = 30 # maximum steps, to prevent infinite loops
    3. MAX_RETRY = 2 # maximum retries for a single step
    4. def run_agent(user_task, lm, screen, actor, checker):
    5. model = lm.load() # model stays resident; reused by later tasks
    6. history = []
    7. for step in range(1, MAX_STEPS + 1):
    8. state = screen.capture() # perceive: screenshot + UI tree
    9. prompt = build_prompt(user_task, state, history)
    10. parsed = parse_action(model.decide(prompt), state.valid_ids)
    11. if "error" in parsed: # validation failed; retry with the error message
    12. history.append({"step": step, "error": parsed["error"]})
    13. continue
    14. if parsed["action"] == "done":
    15. return parsed["args"]
    16. # High-risk actions require user confirmation first
    17. if checker.is_sensitive(parsed):
    18. if not checker.confirm(parsed):
    19. history.append({"step": step, "action": parsed, "result": "user rejected"})
    20. return {"status": "aborted"}
    21. retries = 0
    22. while retries <= MAX_RETRY:
    23. actor.execute(parsed) # execute: carry out the action
    24. after = screen.capture()
    25. ok = checker.verify(parsed, state, after) # verify: did the state meet expectations
    26. if ok:
    27. break
    28. retries += 1
    29. state = after
    30. history.append({"step": step, "action": parsed, "ok": ok})
    31. if not ok:
    32. # Record the failure in history for the next round's decision
    33. history.append({"step": step, "note": "the previous step failed; try another approach"})
    34. return {"status": "max_steps_reached", "history": history}

    6.3 Task Planning: Combining Global and Local

    There are two typical ways to organize a long-running task:

    • Global planning: first have the model break the task into ordered subtasks — for example, “open photo library → filter screenshots → batch delete” — then execute them step by step;
    • Local decision-making: each round decides the next step based only on the current screen.

    In practice, combining the two is safer: the global level handles “the right direction,” while the local level handles “walking each step.” When local steps fail repeatedly, the agent can return to global planning to re-evaluate. For example, if the target page requires login, it first jumps to the login flow, then continues the original task.

    6.4 Coordinating with the System Lifecycle

    On-device processes may be reclaimed by the system, which needs special attention during long tasks:

    • keep the necessary service state during a foreground task to avoid being silently terminated;
    • persist key progress promptly to support resuming from a checkpoint;
    • separate inference from execution so the inference process does not block the user-interaction thread.

    7. Key Engineering Problems and Practical Recommendations

    7.1 Performance and Resources

    • Resident model: start the inference engine with the service to avoid reloading the model for every task;
    • Prompt trimming: UI node pruning and history compression directly determine decode time;
    • Thermal-aware scheduling: avoid running heavy tasks when the device is hot or low on battery, and prompt the user if necessary;
    • Small-large model collaboration: route simple deterministic operations through a rules path, and call the model only for complex semantic judgments.

    7.2 Device Adaptation and Compatibility

    OEM system customizations differ markedly in accessibility interfaces, background restrictions, and battery policies. Practical deployment requires:

    • building a compatibility matrix covering mainstream devices, with continuous regression testing;
    • designing fallback paths for when interfaces are unavailable — for example, switching to screenshot + OCR;
    • dedicated validation for form-factor changes such as portrait/landscape rotation and foldable expansion.

    7.3 Privacy and Security

    Running on-device inherently reduces the risk of data leaving the device, but “local” does not equal “absolutely secure”:

    • Encrypt local storage: model files and runtime logs may contain user data and should be encrypted with a reasonable retention period;
    • Operation auditing: record each action and its result so users can trace back;
    • Sensitive-action interception: operations such as payment, transfers, deleting data, and sending messages must require second confirmation, or be restricted to a whitelist of allowed actions;
    • Least privilege: request only the permissions needed for the task and provide a one-tap disable option.

    7.4 End-Cloud Collaboration and Cloud Capabilities

    Pure on-device solutions are limited by model capability on complex tasks. For scenarios requiring stronger reasoning, an end-cloud collaborative architecture can be used: simple tasks are handled on-device, while complex tasks or repeated on-device failures are escalated to cloud inference. If building on the cloud side, the architecture can be planned by general capability categories:

    • Model distribution: host model files on object storage and deliver new versions with a content delivery network;
    • Task and data management: store task records and audit logs in databases and object storage;
    • Observability: use log services and monitoring/alerting to track task success rates, failure distributions, and crashes, and to quickly pinpoint version issues;
    • Cloud inference: enhance complex-task capability through cloud-hosted large-model inference services.

    Taking Baidu AI Cloud as an example, its various products can be fit into an end-cloud collaborative architecture under these general categories. Actual selection should be based on a comprehensive evaluation of business needs, rather than assuming on-device or cloud is inherently superior.

    7.5 Evaluation System

    An on-device agent cannot be judged only by whether it “runs one demo,” but should establish a quantitative evaluation:

    Metric Meaning Focus
    Task success rate end-to-end proportion of completing the user’s goal broken down by task type
    Average steps decision rounds needed to complete a single task too many indicate redundant decisions
    Per-step latency time from perception to execution completion pure-CPU decoding is the main bottleneck
    Startup time time from cold start to a usable state resident strategies can greatly reduce it
    Resource usage memory, CPU, battery affects battery life and heat
    Failure recovery rate proportion still completed after an unexpected state reflects closed-loop robustness

    8. Conclusion

    The core value of on-device agents lies in bringing the ability to “understand intent and operate the interface” to the device locally, keeping users’ data in their own hands. In terms of technical composition, they consist of three parts:

    • Model layer: a lightweight language model optimized through quantization and runtime tuning;
    • Perception layer: interface understanding centered on the UI tree, with multimodal support as an aid;
    • Execution layer: a controlled-action system driven by closed-loop verification.

    The difficulty of engineering implementation lies not in “which model was adopted” but in every detail: how a 2.6GB model is compressed to an acceptable memory footprint, how an approximately 45-second cold start is mitigated through residency and warm-up, how hundreds or thousands of interface nodes are pruned into text the model can understand, and how the model’s occasional erroneous actions are caught by verification and retry. Only by polishing these details solidly can on-device agents truly move from demo to everyday usability.