Designing and Implementing Custom AI Agents on Smart Terminals

    This article provides a practical architecture for building custom AI agents on smart terminals such as AR glasses and wearable devices. It addresses three core challenges: preventing sensitive data from leaving the device, adapting to diverse business scenarios without relying on a single fixed model, and enabling agents to execute actions through device capabilities. The proposed three-layer design — model access, privacy control, and skill execution — is explained with concrete implementation guidance, including SSE-based streaming integration, model routing, local privacy safeguards, and function-calling enforcement, along with security checklists and deployment considerations for real-world enterprise, personal, and industrial use cases.

    Introduction

    As AR glasses, smart wearables, and other terminal devices evolve from simple interaction tools into proactive, autonomous agents, developers face three practical problems:

    1. Cloud-based large language model (LLM) calls may expose sensitive data outside the device.
    2. A single embedded model cannot adapt to the wide variety of business scenarios.
    3. Agents often lack the ability to invoke device-level capabilities, making task execution incomplete.

    This article addresses these issues by presenting a practical architecture that can be implemented step by step, with clear boundaries and security requirements for each layer.

    Overall Architecture of a Custom Agent

    An agent system can be divided into three relatively independent parts:

    • The inference layer, powered by LLMs.
    • The local data layer, responsible for memory and privacy.
    • The skill layer, which executes actions.

    From an engineering perspective, a maintainable architecture typically consists of three layers:

    • Model access layer
    • Privacy control layer
    • Skill execution layer

    These layers communicate only through well-defined interfaces, so replacing the implementation of one layer does not require changes in the others.

    • The model access layer abstracts protocol differences between various LLM providers.
    • The privacy control layer determines which data may leave the device.
    • The skill execution layer wraps terminal capabilities into callable functions and performs permission validation before execution.

    The following sections explain the implementation of each layer.

    Model Access Layer: Streaming via SSE

    Server-Sent Events (SSE) is a unidirectional streaming protocol built on HTTP. A server can send text events to the client continuously. Most LLM inference services support SSE for token-by-token output, making it a common choice. Because SSE runs over plain HTTP, it works reliably through proxies and firewalls. On disconnection, browsers and some client libraries can resume using the Last-Event-ID header.

    To connect, the client only needs the endpoint URL and an authentication key for the inference service. Switching models becomes a configuration change, not a code change. For example, complex reasoning tasks can be directed to a large cloud-hosted model, while low-latency or weak-network scenarios can fall back to a smaller local model.

    Below is an example SSE client in Python. It is a teaching example and not production-tested; adjust the field parsing according to the actual service response format before deployment.

    1. import json
    2. import os
    3. import time
    4. import requests
    5. MAX_RETRIES = 3
    6. BASE_BACKOFF_SECONDS = 1.0
    7. RETRYABLE_STATUS = {429, 500, 502, 503}
    8. class RetryableError(Exception):
    9. pass
    10. def stream_llm_sse(endpoint, payload, timeout=(5, 60)):
    11. # Key is read from environment or secret store, never hardcoded
    12. api_key = os.environ.get("LLM_API_KEY")
    13. if not api_key:
    14. raise RuntimeError("LLM_API_KEY is not configured")
    15. if not endpoint.startswith("https://"):
    16. raise ValueError("Model endpoint must use HTTPS")
    17. headers = {
    18. "Authorization": f"Bearer {api_key}",
    19. "Accept": "text/event-stream",
    20. }
    21. for attempt in range(MAX_RETRIES):
    22. has_output = False
    23. try:
    24. with requests.post(endpoint, headers=headers, json=payload,
    25. stream=True, timeout=timeout) as resp:
    26. if resp.status_code in RETRYABLE_STATUS:
    27. raise RetryableError(f"Service unavailable: {resp.status_code}")
    28. if resp.status_code != 200:
    29. raise RuntimeError(f"Request failed: {resp.status_code}")
    30. event_type = "message"
    31. for line in resp.iter_lines(decode_unicode=True):
    32. if not line or line.startswith(":"):
    33. # Empty line ends an event; lines starting with ':' are heartbeat comments
    34. event_type = "message"
    35. continue
    36. field, _, value = line.partition(":")
    37. value = value[1:] if value.startswith(" ") else value
    38. if field == "event":
    39. event_type = value
    40. elif field == "data":
    41. if value == "[DONE]":
    42. return
    43. if event_type == "error":
    44. raise RuntimeError(f"Model service error: {value}")
    45. try:
    46. chunk = json.loads(value)
    47. except json.JSONDecodeError:
    48. raise RuntimeError("Failed to parse data frame")
    49. text = chunk.get("content", "")
    50. if text:
    51. has_output = True
    52. yield text
    53. return
    54. except (RetryableError, requests.exceptions.Timeout):
    55. # Do not retry if partial content has already been sent
    56. if has_output or attempt == MAX_RETRIES - 1:
    57. raise
    58. time.sleep(BASE_BACKOFF_SECONDS * (2 ** attempt))

    Important notes on this code:

    • Connection and read timeouts are set separately.
    • Retries use exponential backoff for status codes 429, 500, 502, and 503.
    • The API key is not embedded in the code.
    • If partial content has already been yielded, the client does not auto-retry to avoid duplicate output; instead, it raises an exception for the upper layer to handle.
    • Real services may send multi-line data fields, custom event types, or different heartbeat formats. Follow the service documentation for those variations.

    Model Routing and Dynamic Switching

    When multiple models coexist, a model registry is needed to record each model’s capabilities and constraints. A routing gateway selects the appropriate model based on the registry and predefined policies. Common policies include privacy-first, cost-first, and quality-first.

    Field Example Value Purpose
    Model ID local-7b-int4 Unique identifier
    Deployment Location On-device / Private cloud / Public cloud Determines whether data leaves the device
    Privacy Level L1 public / L2 internal / L3 confidential Defines which data categories can be processed
    Context Length 8K tokens Maximum context that can be injected
    Average Time to First Token 300 ms Determines real-time suitability
    Per-invocation Cost per-token billing Used for cost-first routing
    Suitable Tasks summarization, Q&A, code review Used for task matching

    The routing rules must be deterministic. For instance, if a task involves L3 confidential data, only models deployed on-device or in a private enterprise network may be selected. When the network is unavailable, fallback to a local model. The policy table should be separated from the code so it can be audited and adjusted independently.

    Privacy Control Layer: Local Closed-Loop and Data Exit Boundaries

    In finance, healthcare, and enterprise office scenarios, the most critical control is data leaving the device. Processing data on-device significantly reduces leakage risk, but this only works when:

    • Local storage has access control.
    • Anonymization rules are validated.
    • Only the minimum required data is transmitted to the cloud.

    The workflow is as follows:

    1. Local intent and sensitive information detection. The agent first determines the request type and marks the sensitivity level of data such as files, chat logs, and browsing history.
    2. Local retrieval. A local vector database stores embeddings and original text for retrieval-augmented generation (RAG). Both the original content and vectors remain on-device under access control.
    3. Pre-exit processing. If a cloud model is required, only the minimum necessary context is sent after anonymization or summarization. Raw private content must never leave the device.
    4. Block on anonymization failure. If the anonymization module cannot confirm whether a piece of content is safe, the system must block the outbound request and prompt the user to switch to a local model or manually confirm. Failed events must be logged and alerted.

    It is worth noting that even when a private model is used, if the inference service runs outside the enterprise network, data still leaves the device. Therefore, the deployment location must be recorded in the model registry, not left to the user’s assumption.

    Skill Execution Layer: From Conversation to Action

    The LLM determines what needs to be done; the terminal actually executes it. Through Function Calling or Tool Use, the model selects a skill based on the conversation context and generates arguments conforming to a JSON Schema. The device receives the arguments, validates them, and then executes the skill.

    Example: “Summarize my local weekly report and send the key points to Zhang San.”

    The complete flow is:

    1. The model parses the intent and identifies two skills: read_file and send_im_message.
    2. The model generates call arguments, e.g., {"skill": "read_file", "params": {"filename": "weekly_report.docx"}}.
    3. The terminal validates the argument and confirms the file is inside an authorized directory, then reads the text.
    4. The model generates a summary from the text.
    5. The model generates send arguments. Sending an IM message is an external operation; the terminal must show the summary and recipient, and wait for user confirmation before sending.
    6. The terminal writes an audit log including call time, skill name, argument summary, result, and confirmation status.

    The execution layer should follow this security checklist:

    • Least privilege allowlist: Only registered skills can be invoked. File skills are limited to specified directories; browser skills are limited to allowed domains.
    • Argument validation: All arguments are validated against their JSON Schema; non‑compliant calls are rejected immediately.
    • Secondary confirmation for sensitive operations: Delete, send, permission changes, etc., require explicit user consent. Model‑generated instructions cannot replace user authorization.
    • Audit logging: Every invocation logs full metadata, but no keys or raw private content.
    • Rollback on failure: For write‑type operations, keep a backup before execution and restore on failure. Operations that cannot be rolled back must warn the user before execution.
    • Result validation: Skill outputs are treated as untrusted data. The model must not execute instructions embedded in web pages or files as commands.

    Choosing the Right Integration Protocol

    SSE, WebSocket, and HTTP polling each have their use cases. Choose based on the interaction pattern.

    • SSE: Suitable for unidirectional server‑to‑client streaming, e.g., token‑by‑token model responses. It runs over HTTP, is easier to deploy through proxies, and has built‑in reconnection mechanisms.
    • WebSocket: Suitable for bidirectional, low‑latency continuous interaction, such as simultaneous voice input, sensor data streaming, and model commands. Connection management and heartbeat must be implemented manually.
    • HTTP polling: Suitable for low‑frequency updates with low real‑time requirements. It wastes requests but is the simplest and works well in networks that restrict long‑lived connections.

    For most text‑generation scenarios, SSE is a good starting point. If the same session requires frequent bidirectional exchange of audio or sensor data, consider WebSocket.

    Typical Application Scenarios and Compliance Checkpoints

    Enterprise Office Assistant

    Employees use AR glasses or enterprise terminals to handle local sensitive documents. Data stays on‑device or inside the corporate network, helping meet compliance audit requirements. Before deployment, complete data classification and grading, define which documents are confidential, and set up alerts for anonymization failures.

    Personal Life Assistant

    Users can connect different open‑source or commercial models, allowing the agent to manage schedules and filter web content. Skill authorization must be granular for each operation type, especially message sending and file modification, and operation logs must be kept for user review.

    Industrial Inspection

    Inspectors wear devices that analyze images with on‑device models and retrieve historical maintenance records. When anomalies are found, the system reports to a monitoring center. The report content must be anonymized; device identifiers and factory location must not be sent without processing. The accuracy of local inference models must be verified with real inspection data, not just model parameter count.

    Before going live, at least check the following:

    • Data classification and grading is complete.
    • Anonymization rules have test cases.
    • The skill allowlist covers all entry points.
    • Sensitive operations require secondary confirmation.
    • Audit logs are queryable.
    • Model deployment locations match the registry.

    Conclusion

    The core of a custom agent comes down to three things: integrating various models through a standard protocol, defining the boundary for data leaving the device, and enforcing skill execution under permission and audit constraints. This architecture suits teams with local computing power and governance capabilities. When selecting a solution, evaluate it based on your specific scenario requirements.