AI Search Architecture and Engineering Practices: A Practical Guide

    This guide explains how search systems evolve from keyword ranking into generative question answering, and how to engineer that shift. It covers a five-layer pipeline (query understanding, hybrid retrieval, reranking and context assembly, generation, and credibility post-processing), three parameterized response modes that trade latency for depth, performance and cost controls such as layered caching and per-layer timeouts, an evaluation framework, common anti-patterns, and how to combine these components with general-purpose cloud capabilities. Readers will come away with a maintainable blueprint for balancing answer quality, latency, and cost.

    1. From Keyword Retrieval to “Thinking” Question Answering

    Traditional search rests on one assumption: users know what they are looking for, and the system’s job is to rank the most relevant documents first. In generative question answering, user intent is often much fuzzier, and what people expect is a conclusion they can use directly, not ten links. Search therefore stops being a ranking problem and becomes a composite problem of understanding + retrieval + reasoning + expression.

    From an engineering perspective, this shift brings three structural changes:

    1. The output moves from a list to prose, which raises the bar for factual consistency considerably.
    2. The latency budget gets squeezed by the generation step, so the pipeline must be layered and parallelized.
    3. Errors are no longer just “ranked poorly” but potentially “stated incorrectly,” which requires credibility governance.

    A common industry approach is to split capabilities into two tiers: a “fast answer” tier that targets extremely low latency for factual and short-answer queries, and a “deep thinking” tier that lets the model reason over multiple steps and decompose sub-questions, trading longer latency for more complete conclusions. In practice, teams usually keep a middle tier as well, balancing cost and experience between the two extremes. These three tiers are not three separate products but parameterized configurations of the same pipeline.

    2. Target Scenarios and Requirement Breakdown

    Before designing anything, break requirements into measurable goals. Otherwise every later optimization lacks a basis for judgment:

    • Query intent diversity: factual lookups, how-to guidance, comparison and selection, long-document summarization, and time-sensitive queries each call for a different optimal strategy.
    • Freshness and authority: content involving prices, versions, or policies must prioritize recent and trustworthy sources.
    • Explainability: conclusions need attached source snippets so users can verify them.
    • Cost constraints: the per-unit cost of generation is far higher than retrieval, so it needs strict trigger conditions.
    • Safety and compliance: filter both input and output, and for sensitive domains state boundaries rather than definitive conclusions.

    3. Reference Architecture: A Five-Layer Pipeline

    A maintainable implementation is usually split into five layers, decoupled through explicit data contracts between them.

    3.1 Query Understanding Layer

    Responsible for rewriting, expansion, and intent classification. Typical actions include spelling correction, coreference resolution, merging multi-turn context, query decomposition (splitting one compound question into several sub-queries), and deciding whether to enter deep mode.

    1. def analyze(query, history):
    2. q = normalize(query) # normalization, spelling correction
    3. ctx = merge_context(q, history) # merge multi-turn context
    4. intent = classify_intent(ctx) # factual / how-to / compare / time-sensitive
    5. sub_queries = decompose(ctx) if intent in ("compare", "multi") else [ctx]
    6. mode = "deep" if (intent in ("compare", "multi") or len(ctx) > 120) else "fast"
    7. return sub_queries, intent, mode

    The key point: intent classification should not rely on text length alone. It also needs to check for time-sensitivity trigger words, whether a comparison is requested, and whether step-by-step output is expected.

    3.2 Hybrid Retrieval Layer

    Any single retrieval method has blind spots. The common approach is a hybrid “sparse + dense” strategy: sparse retrieval excels at exact terms, identifiers, and proper nouns, while dense vector retrieval excels at semantic similarity and paraphrasing. Results from both paths are merged and then handed to reranking.

    1. candidates = merge(
    2. sparse_index.search(sub_q, top_k=50), # keyword / inverted index
    3. dense_index.search(embed(sub_q), top_k=50) # semantic vectors
    4. )

    Engineering details: retrieve independently for each sub-query, then deduplicate across the combined set; boost recent documents for time-sensitive queries; apply a baseline boost to authoritative sources, but keep those weights configurable and auditable to avoid an unexplainable black-box bias.

    3.3 Reranking and Context Assembly Layer

    Retrieval aims for “don’t miss anything”; reranking aims for “order it correctly.” A common approach is a cross-encoder that scores each query-snippet pair individually, keeping the top few snippets. Next comes context assembly, the step most often overlooked yet most influential on cost:

    • Budget control: set an upper bound on total snippet length and assemble greedily by score and source authority.
    • Redundancy removal: when adjacent snippets are semantically duplicative, keep only the one with higher information content.
    • Structure annotation: retain a source identifier and position information for each snippet so citations can be produced later.

    3.4 Generation Layer

    The input to the generation layer is “assembled context + user question + output constraints.” Constraints should be explicit, for example: answer only from the provided material, state clearly when the material is insufficient, and append citation numbers after conclusions.

    1. System constraint: answer using only the information in [Material]; if the material is insufficient, state what is missing.
    2. Output format: first the conclusion (no more than three sentences), then a bullet list of key points, then the citation numbers.
    3. [Material] [1] ... [2] ...
    4. [Question] ...

    Deep mode adds planning on top of this: first output the solution steps, then retrieve additional evidence step by step, and finally aggregate. In engineering terms, cap the maximum number of iterations and the total duration so latency stays controllable.

    3.5 Credibility and Post-Processing Layer

    This includes citation alignment checks (can every assertion in the conclusion be traced back to the material), numeric and unit consistency checks, sensitive content filtering, and a fallback strategy for low confidence: degrade to “show the source list” instead of forcing a conclusion.

    4. Design Trade-offs Across the Three Response Modes

    Mode Trigger conditions Pipeline differences Latency profile Typical scenarios
    Fast answer Factual, short queries Single retrieval + single generation Low Definitions, numbers, single-point facts
    Middle mode Moderate complexity Query rewriting + light iteration Medium Step-by-step guidance, key-point summaries
    Deep thinking Comparison, multiple constraints, long documents Multiple rounds of decomposition and supplementary retrieval High Selection comparisons, solution evaluation

    Mode selection should be decided centrally by a policy layer and delivered as configuration, so it can be rolled out gradually and rolled back per business scenario.

    5. Performance, Cost, and Stability

    • Layered caching: query-level cache (identical requests), snippet-level cache (retrieval results), and answer-level cache (conclusion + citations). Hit rates across the three layers usually differ significantly and should be monitored separately.
    • Parallelization: retrieval and reranking for multiple sub-queries run in parallel; the generation stage runs serially.
    • Timeouts and degradation: set an independent timeout for each layer, and degrade that layer on failure rather than failing the whole request.
    • Cost control: set quotas and trigger thresholds for deep mode so the expensive path is not triggered en masse by ordinary queries.
    • Observability: log the query before and after rewriting, which sources retrieval hit, the distribution of snippet scores, generation time, and citation coverage, forming a traceable pipeline snapshot.

    6. Evaluation Framework

    Search optimization without evaluation is blind tuning. Cover at least four categories of metrics:

    1. Retrieval quality: recall, top-k hit rate, and information coverage after deduplication.
    2. Generation quality: factual consistency, citation coverage, answer completeness, and format compliance rate.
    3. Experience metrics: time to first token, end-to-end latency, and degradation rate.
    4. Safety metrics: filter block rate, false-block rate, and the reasonableness of refusals in sensitive domains.

    The evaluation set should include sampled real queries with human-annotated gold answers, with time-sensitive queries in a separate set, and regression runs on a regular schedule.

    7. Common Anti-Patterns

    • Stuffing all retrieval results into the context, which spikes cost and dilutes key information.
    • Missing the “state when material is insufficient” constraint in generation, producing plausible but wrong conclusions.
    • Citations that do not align with conclusions, leaving users unable to verify.
    • Deep mode with no iteration cap, where long-tail queries drag down overall latency.
    • Running offline evaluation only, with no online pipeline snapshots, so issues cannot be reproduced.

    8. Combining with General-Purpose Cloud Capabilities

    In practice, you rarely need to build every component from scratch. General-purpose capability categories can be combined: object storage for raw documents and snapshots, a message queue for peak shaving and driving asynchronous index building, a container platform for elastic scaling of retrieval and generation services, and logging plus monitoring and alerting for pipeline tracing and metrics dashboards. Baidu AI Cloud offers corresponding foundational capabilities in these general categories and can serve as one reference for architecture selection; refer to the official documentation for specific configurations and specifications.

    9. Summary

    The engineering focus of intelligent search has moved from “rank more accurately” to “gather evidence more completely, express more reliably, and keep the pipeline controllable.” Splitting the system into five layers (query understanding, hybrid retrieval, reranking and assembly, generation, and credibility governance), combined with three response modes and layered caching, yields an operable balance among experience, latency, and cost. A solid evaluation framework and pipeline snapshots are the prerequisite for continuous iteration.