Technical Architecture and Implementation Path for Mobile AI Assistants

    This article breaks down the technical architecture of a mobile AI assistant, covering a four-layer design, dual-mode inference (fast and deep thinking), retrieval-augmented generation for up-to-date answers, and document and image understanding pipelines. It also outlines practical guidance on performance, cost control, observability, security, and a phased rollout plan for building a stable, scalable assistant on a mobile client.

    1. From Product Form to Technical Problems

    The core of a mobile AI assistant is compressing large language model capabilities into a client that runs reliably on weak networks, low battery, and small screens. The original requirements can be abstracted into three technical problems:

    1. How to offer a switchable two-tier experience between “instant response” and “complex reasoning.”
    2. How to let model answers go beyond the time boundary of training data.
    3. How to turn files and images on the user’s phone into context the model can read.

    These three problems map to inference mode orchestration, retrieval-augmented generation (RAG), and on-device document parsing with optical character recognition (OCR). Each is expanded below.

    2. Layered Architecture

    A maintainable implementation is usually divided into four layers:

    1. Interaction layer: chat interface, mode switch controls, file and image entry points, streaming rendering.
    2. Orchestration layer: intent detection, mode routing, retrieval triggering, context assembly, timeout and fallback.
    3. Capability layer: model inference service, vector retrieval service, file parsing service, OCR service.
    4. Infrastructure layer: object storage, message queue, logging service, monitoring and alerting, key and quota management.

    The key benefit of layering: the model is replaceable, retrieval is pluggable, on-device parsing failures can fall back to asynchronous cloud processing, and the interaction layer does not need to be aware of backend topology changes.

    3. Dual-Mode Design: Fast Mode and Deep Thinking

    “Fast mode” targets time-to-first-byte, typically using an inference configuration with a smaller parameter scale or a shorter reasoning budget, and streams output directly. “Deep thinking mode” allows the model to perform internal reasoning before giving a conclusion, at the cost of significantly higher latency and compute.

    From an engineering standpoint, it is not advisable to hardcode two separate pipelines in the client. Instead, use a unified entry with parameterized policies:

    1. MODE_POLICY = {
    2. "fast": {"max_tokens": 1024, "reasoning": False, "timeout_ms": 8000},
    3. "deep": {"max_tokens": 4096, "reasoning": True, "timeout_ms": 60000},
    4. }
    5. def route(query: str, mode: str, ctx: dict):
    6. policy = MODE_POLICY[mode]
    7. if mode == "deep" and len(query) < 20:
    8. # Short questions do not need deep reasoning; downgrade automatically to save resources
    9. policy = MODE_POLICY["fast"]
    10. return stream_generate(query, ctx, **policy)

    Three points need attention. First, mode switching must preserve session context; otherwise the user experience breaks. Second, deep mode needs queuing and a concurrency cap to avoid long tasks dragging down overall availability. Third, streaming output should support a “thinking” status indicator so users understand why they are waiting.

    4. Web Search: Making Answers Time-Sensitive

    The standard approach to online retrieval is “retrieve first, then constrain generation.” The flow is: query rewriting → multi-path recall → deduplication and relevance ranking → snippet trimming → insertion into the prompt → generation with source attribution.

    1. User question
    2. → Query rewriting (fill in omissions, split multiple intents)
    3. → Retrieval (web / knowledge base / document store in parallel)
    4. → Reranking (relevance + freshness + source credibility)
    5. → Context window trimming (by token budget)
    6. → Model generation (require source citations)
    7. → Post-processing (sensitive information filtering, formatting)

    The most error-prone part here is the context budget: too many retrieved snippets squeeze out generation space and amplify hallucination, while too few lose key information. In practice, a “question type determines snippet count” strategy is more stable: give factual questions a small number of highly relevant snippets, and give survey-style questions more but shorter snippets.

    5. File and Image Understanding Pipeline

    Solving problems from photos, uploading files, and reading scanned text all come down to converting unstructured input into structured text.

    • Image path: on-device preprocessing (compression, dewarping, enhancement) → OCR → layout reconstruction (titles, paragraphs, formulas, tables) → structured text.
    • Document path: format detection → text extraction (preserving hierarchy) → table-to-structure conversion → chunking and summary indexing for long documents.
    • Hybrid path: extract first, then hand off to the model for summarization, avoiding forcing an entire document into the context.

    An illustrative chunking strategy:

    1. def chunk_text(text, size=800, overlap=120):
    2. chunks, start = [], 0
    3. while start < len(text):
    4. chunks.append(text[start:start + size])
    5. start += size - overlap
    6. return chunks

    Chunk overlap prevents semantics from being cut off at boundaries; tables and code blocks should be handled separately and must not be hard-split by character count.

    6. Performance, Cost, and Stability

    The bottleneck of the mobile experience is usually the network and time-to-first-byte, not the model itself. Common measures include: request coalescing and connection pre-warming, on-device caching of high-frequency Q&A, streaming result rendering, automatic retries on failure with idempotent design, and per-tenant and per-user quotas and rate limiting.

    For cost control, it is recommended to set differentiated budgets for different modes and to cap the number of retrieval snippets and the maximum generation length. For observability, cover at least five metrics: time-to-first-byte, end-to-end duration, retrieval hit rate, parsing failure rate, and fallback trigger count, forming a closed loop with logging and monitoring/alerting.

    7. Security and Compliance

    • Encrypt data in transit and at rest; keys are issued by unified credential management and never written into the client.
    • Set type and size whitelists for uploaded files, and execute parsing in an isolated environment.
    • Perform sensitive information detection and warnings on the output side, and clearly label content as model-generated.
    • Retain traceable request identifiers for auditing and troubleshooting.

    8. Implementation Recommendations

    If an enterprise wants to build similar capabilities quickly, it can build the foundation on general capabilities such as object storage, message queue, container platform, logging service, and monitoring/alerting from Baidu AI Cloud, while keeping the model and retrieval components replaceable. The recommended implementation order is: first get single-turn Q&A and streaming output working, then integrate retrieval and file parsing, and finally complete quotas, auditing, and fallback policies. Following this path yields a stable, scalable mobile AI assistant experience at a controllable cost.