AI Agent Architecture on Mobile and Desktop: A Technical Guide to On-Device Assistant Integration
This article explains how to build a terminal-side intelligent assistant that connects large language model reasoning with external tool ecosystems. It covers a four-layer architecture (interaction, orchestration, capability, and execution), two-stage tool retrieval and routing for large skill catalogs, layered context engineering, least-privilege sandboxing and auditing, and a state machine design for long-running autonomous tasks. Readers will find tool schema examples, routing and scheduling pseudocode, observability metrics, and practical deployment pitfalls.
1. Background and Problem Definition
On-device intelligent assistants are evolving from question-and-answer interaction into task execution agents. Users no longer settle for a block of text; they expect the assistant to complete multi-step work directly: retrieving information, calling internal systems, generating documents, and triggering long-running tasks. Scenarios such as an out-of-the-box experience on a new device, integration with an external skill ecosystem, one-click linking of common chat applications, and “shrimp farming” all point to the same technical question: how to orchestrate large language model reasoning together with a large number of external tools on mobile and desktop devices in a controlled way.
Setting aside specific product features, this reduces to three general engineering problems:
- Capability integration: how to register, discover, and invoke hundreds or thousands of heterogeneous tools (search, calendar, forms, databases, device control) in a unified way.
- Execution trust: the model produces natural-language intent, while the system executes deterministic actions. A strict layer of validation, mapping, and auditing is required between the two.
- Long-running tasks and state: tasks like “shrimp farming” that require continuous monitoring and parameter tuning over several days cannot be completed in a single session, so a persistent state machine and scheduling are necessary.
2. Overall Architecture: Four Decoupled Layers
A four-layer structure is recommended to avoid coupling the model, tools, and device capabilities together.
- Interaction layer: voice and text input, multi-turn conversation, and card-based result presentation; responsible for completing a user’s vague expression into a structured request.
- Orchestration layer (Agent Runtime): intent recognition, task decomposition, tool selection, loop control, and termination condition evaluation. This is where the “cluster” concept lands—multiple specialized agents (retrieval agent, data agent, device agent, review agent) collaborating in parallel or in sequence.
- Capability layer (Tool/Skill Registry): a unified tool description schema, version management, canary release, and rollback.
- Execution layer (Sandbox & Connector): sandbox containers, least-privilege credentials, network egress control, and audit logs.
An illustrative tool description structure (pseudocode, expressing only the general idea):
{"name": "device.set_threshold","version": "1.3.0","description": "Set a device alert threshold","parameters": {"type": "object","properties": {"device_id": { "type": "string" },"metric": { "type": "string", "enum": ["temp", "ph", "oxygen"] },"value": { "type": "number" }},"required": ["device_id", "metric", "value"]},"risk_level": "medium","requires_approval": true}
The key lies in the two fields risk_level and requires_approval: the model can autonomously invoke low-risk read-only tools, while write operations and tools involving funds or irreversible state changes must go through manual confirmation or policy engine approval.
3. Skill Ecosystem Integration: Registration, Discovery, and Routing
The engineering reality of “one-click access to tens of thousands of skills” is retrieval and routing over a large-scale tool catalog, not stuffing all tool descriptions into the context window. A workable approach has three steps:
- Offline indexing: generate semantic vectors and keyword indexes for each skill, along with metadata such as category, risk level, and invocation frequency.
- Two-stage recall: first use vector search to retrieve Top-N (for example, 50) candidates, then use a lightweight reranking model or rule-based scoring to narrow them down to 5–8 that enter the context. This keeps token cost at a constant level.
- Routing and fallback: when the hit confidence is below the threshold, do not force an invocation; fall back to a clarifying question. If a tool fails repeatedly, trigger a circuit breaker, switch to read-only mode, and inform the user.
def select_tools(query, k_recall=50, k_final=6, threshold=0.62):cands = vector_index.search(query, top_k=k_recall)cands = rerank(query, cands)[:k_final]if not cands or cands[0].score < threshold:return [], "need_clarification"return [c["name"] for c in cands], "ready"
This mechanism also addresses the demand for one-click linking of common chat applications: message channels are abstracted as another kind of tool (send message, fetch conversation) and managed in the same way as business skills, avoiding a dedicated branch for each channel.
4. Context Engineering and Multi-Turn Consistency
Terminal scenarios involve short inputs, high noise, and frequent interruptions, making context management more difficult than on the server side. Recommendations:
- Layered context: system constraints (permissions, compliance, output format) stay resident; task state (completed steps, conclusions reached) is stored in a structured form; the raw conversation keeps only a summary of the most recent turns.
- Externalized state: write task state to external storage (general object storage or a document database) and load it on demand when a session resumes, avoiding unlimited context growth.
- Structured intermediate artifacts: each step produces a result object with a schema, and the next step consumes only the necessary fields, reducing model misreading.
TaskState {goal: stringplan: Step[]artifacts: { name -> uri }constraints: { budget, deadline, approval_policy }cursor: int}
5. Permissions, Sandboxing, and Compliance
The more tools there are, the larger the attack surface. Model output must be untrusted by default:
- Least privilege: each connector uses independent, revocable, short-lived credentials issued on demand; read-only first.
- Sandboxed execution: skills run in isolated containers with limits on the file system, network egress, and resource quotas; external dependencies are whitelisted.
- Policy up front: place a policy engine between the orchestration layer and the execution layer to validate parameter types and ranges and to force secondary confirmation for high-risk actions.
- Full-chain auditing: record “who, in which session, based on what intent, invoked which tool, and received what result.” Logs are sent uniformly to the logging service and the monitoring and alerting system for traceability and anomaly detection.
- Data boundaries: sensitive data is masked before entering the model context, and cross-border or cross-tenant flows require explicit policy constraints.
6. Long-Running Tasks: A State Machine Design Using “Shrimp Farming”
“Shrimp farming” is more of a lighthearted expression in the original material, but its technical form is a typical long-term autonomous task: collect metrics on a time schedule, judge trends, adjust parameters, and notify humans on anomalies. Implementation points:
- Explicit state machine:
initialize → inspect → evaluate → tune → review → suspend on anomaly. Every transition is persisted, so the process can resume after a restart. - Scheduling and idempotency: a scheduler triggers by cron or event, and all write operations carry an idempotency key to avoid duplicate feeding or duplicate tuning.
- Trend judgment rather than single-point judgment: introduce a sliding window and threshold bands so a single fluctuation does not trigger an action, reducing misoperations.
- Human in the loop: on out-of-bounds conditions or consecutive failures, automatically degrade to “report only, do not execute” and push summaries and suggestions through the message channel.
- Cost accounting: set a token and invocation budget for each task; exceeding the budget pauses the task and raises an alert to prevent the autonomous loop from running out of control.
on_tick(now):m = collect_metrics()if not in_range(m): state = ALERT; notify(); returnif trend_stable(m, window=6):act = plan_action(m) # suspend if approval is requiredapply_with_idempotency(act)persist(state)
7. Observability and Evaluation
An autonomous system cannot be judged only by “whether the final answer is correct”; process quality matters too:
- Process metrics: tool recall hit rate, parameter validation failure rate, average number of steps, manual confirmation rate, and number of circuit breaker trips.
- Result metrics: task completion rate, rework rate, and cost per task (tokens and number of invocations).
- Regression evaluation set: turn historical real requests into test cases and run regression after tool descriptions or prompts change, preventing “fix one, break three.”
- Canary strategy: release new skills to a small traffic share first, observe failure modes, then roll out fully.
8. Implementation Advice and Common Pitfalls
- Start with narrow, deep scenarios: get 3–5 high-frequency tasks working end to end, then expand skills horizontally, avoiding a collapse in routing accuracy from integrating tens of thousands of tools at the start.
- Tool description quality sets the ceiling: vague descriptions and overlapping parameter semantics are the primary cause of recall mismatch, so description standards and review are needed.
- Do not give the model direct database or shell access: expose limited actions only through controlled connectors.
- Design cost in, do not optimize it afterward: layered context, recall compression, and budget circuit breaking should be in place in the first version.
- Balance compliance and experience: one extra confirmation for high-risk actions significantly reduces incidents and loss of trust over the long run.
9. Conclusion
The competitiveness of a terminal intelligent assistant lies not in how many skills it integrates, but in whether it can complete tasks reliably under controlled permissions, measurable cost, and auditable processes. Decoupling the four layers of interaction, orchestration, capability, and execution, combined with two-stage tool recall, structured task state, and up-front policy validation, makes it possible to build a solution on top of the general capabilities provided by Baidu AI Cloud—container platform, object storage, message queue, logging service, and monitoring and alerting—that can both answer questions quickly and safely execute long-running autonomous tasks, keeping office work and scenarios like “shrimp farming” on a controllable engineering track.
