On-Device AI Agents: App Control and Token Cost Management

    AI agents that operate mobile apps require more than accurate language generation: they need reliable perception, constrained actions, safety controls, and measurable task economics. This article outlines a five-layer architecture, explains why token consumption grows in multi-step workflows, and presents practical approaches to model routing, context compression, caching, budgets, device–cloud collaboration, and rollout evaluation.

    1. From Answering Questions to Completing Tasks

    For several years, conversational interfaces have dominated AI interactions on mobile devices: users ask questions, and models return text. More recent development is shifting toward action. A user expresses an intent in natural language, and the system taps, types, and swipes on screen to complete a task across multiple apps.

    The fundamental change is that model outputs are no longer content for people to read. They are executable action sequences. This has three immediate consequences:

    1. Free-form text becomes constrained, structured data that must be parseable, validatable, and support rollback where possible.
    2. A single question-and-answer exchange becomes a repeated perception–decision–execution loop, increasing both model calls and context length.
    3. The cost of an error shifts from a poor answer to an incorrect action. Safety controls become essential rather than optional.

    2. The Technical Architecture

    A practical on-device agent typically consists of five layers.

    Perception

    Screenshots alone are not enough. A more reliable approach combines visual input with an accessibility tree containing the view hierarchy, control types, text, and coordinates of clickable regions.

    Vision-only approaches generalize well but can lack positioning accuracy. Accessibility-tree-only approaches are precise but may not cover every interface element. A common engineering approach combines both: the accessibility tree identifies candidate interactive elements, while a vision model resolves ambiguity and provides a fallback.

    Understanding

    Convert the current screen into a compact textual representation: element ID, type, text, and coordinates. Avoid repeatedly sending the entire original screenshot to the model.

    This is the first major control point for reducing downstream costs.

    Planning

    Use a plan–act loop. The model selects the next action, the system executes it, and the agent observes the updated interface before deciding whether to continue or finish.

    To prevent endless loops, enforce a maximum step count, detect repeated actions, and identify situations where no progress is being made.

    Execution

    Restrict the action space to a finite set of primitives. The model should not have unrestricted execution capabilities; coordinate-based actions, where supported, should remain within the defined schema.

    1. ACTION_SCHEMA = {
    2. "tap": {"element_id": "int", "x": "int?", "y": "int?"},
    3. "input": {"element_id": "int", "text": "str"},
    4. "swipe": {"direction": "up|down|left|right"},
    5. "back": {},
    6. "done": {"summary": "str"},
    7. "ask_user": {"question": "str"},
    8. }

    Safety

    Pause execution and require user confirmation before irreversible or consequential actions, such as payments, deletion, permission grants, or sending messages.

    Sensitive fields, including verification codes and passwords, must stay out of the model context. The system should replace them with placeholders and insert the actual values during execution.

    3. Why Token Consumption Grows So Quickly

    Many teams see rapid growth in model usage but misidentify the cause. Four structural factors drive the increase:

    • Expensive multimodal input: Each round may require the interface to be encoded again. Images can consume substantially more tokens than text conveying equivalent information.
    • Accumulating context: If the full history is appended at every step, the input at step N contains observations from all preceding N−1 steps.
    • Retries and self-correction: Failed actions and replanning can multiply token consumption.
    • Longer tasks: Cross-app workflows can involve a dozen or more steps, making a single task cost tens of times more than a one-turn conversation.

    The primary metrics should therefore shift from daily token volume to cost per task and task success rate, evaluated together. Optimizing usage without accounting for successful completion can lead teams in the wrong direction.

    4. Practical Token Cost Controls

    Tiered Model Routing

    Use smaller models for element localization, screen classification, and completion checks. Reserve larger models for critical planning decisions.

    1. def decide(state, budget):
    2. if budget.remaining_tokens < state.estimate_next_step():
    3. return Action.ask_user("The current budget is insufficient. Continue?")
    4. if is_routine(state):
    5. return small_model(state) # Frequent, low-complexity decisions
    6. return large_model(state) # Infrequent, high-complexity decisions

    Interface Diffs and Screenshot Deduplication

    Compare adjacent frames using pixel or structural differences. When the interface has not changed, reuse the previous observation instead of encoding it again. This can eliminate substantial image-token consumption.

    Context Compression

    Collapse completed steps into a short summary and retain raw observations only for the most recent two or three steps. Truncate element lists by relevance.

    Layered Caching

    Use prefix caching to reuse fixed prompts. Apply result caching to frequently used, predictable paths, such as opening Settings and navigating to Bluetooth.

    Use semantic caching cautiously: a semantically similar request can still require a different action sequence.

    Batching and Asynchronous Processing

    Route offline judgments that can tolerate delays through batch-processing queues. Keep only necessary synchronous calls in the interactive path.

    Budgets and Circuit Breakers

    Set both token and step budgets for each task. When either limit is exceeded, fall back to providing suggested steps rather than continuing execution.

    5. Device–Cloud Trade-offs Under Rising Hardware Costs

    Fluctuations in storage and memory component prices can increase device bill-of-materials costs. They can also constrain the memory and bandwidth available for small on-device models.

    The practical architecture is not a binary choice between device and cloud. It is a division of responsibilities:

    • On the device: Wake-up handling, interface parsing, action execution, and privacy-sensitive judgments.
    • In the cloud: Complex planning and long-context reasoning.

    For this type of architecture, Baidu AI Cloud can provide general infrastructure capabilities such as model services, container platforms, message queues, object storage, logging, monitoring, and alerts. These support elastic inference, asynchronous task processing, and end-to-end observability.

    6. Evaluation and Staged Rollout

    Build a replayable offline evaluation set using fixed tasks and recorded interface sequences. Track:

    • Task success rate
    • Average number of steps
    • Human takeover rate
    • Cost per task

    Use staged rollouts and shadow mode, in which the agent makes decisions without executing them. Compare results against a human baseline before progressively expanding execution permissions.

    7. Implementation Checklist

    1. Minimize the action space and prohibit unrestricted capabilities.
    2. Require confirmation for irreversible actions, and keep sensitive information out of model context.
    3. Convert observations to text and apply diffing and deduplication to control input costs.
    4. Combine tiered model routing with token and step budgets to limit total consumption.
    5. Treat cost per task as a core metric rather than focusing on daily call volume.
    6. Divide responsibilities between device and cloud: use the device for privacy and low latency, and the cloud for more demanding reasoning.

    AI agents that operate apps have crossed the threshold into practical usability. The key differentiators are now reliability and unit economics. Compact perception, constrained actions, and measurable costs are what make this interaction model sustainable.