AI Search Architecture: A Technical and Engineering Guide
This article presents a vendor-neutral technical architecture for AI search systems and the engineering practices needed to build them. It breaks a production system into six layers, explains common failure modes at each layer, and shows how to iterate using measurable metrics. Topics include offline indexing, query understanding, hybrid retrieval and reranking, evidence-grounded generation, layered evaluation, latency and cost control, and security compliance. Readers will find practical code examples and a deployment checklist for balancing answer accuracy, latency, and cost.
1. Introduction: From Keyword Matching to Answer Generation
Once major internet service providers began entering the AI search space, the shape of search systems changed fundamentally. Previously, a system returned a list of links ranked by relevance, and users had to read, compare, and summarize the results themselves. Today, systems are expected to return a verifiable conclusion directly, along with the evidence behind it. This shift is not simply a matter of bolting a generation model onto an existing pipeline. It introduces a new set of engineering constraints around retrieval quality, context organization, factual consistency, latency budgets, and cost structure.
This article discusses the general technical architecture and implementation methods of AI search from a neutral perspective. It does not cover any specific vendor’s product implementation. It focuses on three questions: what layers make up a usable AI search system; what the common failure modes are at each layer; and how to iterate continuously in a quantifiable way.
2. Layered Architecture
A mature AI search system can usually be split into six layers, with clear data contracts decoupling each layer from the next.
- Data ingestion and governance layer: responsible for collecting, deduplicating, cleaning, annotating permissions on, and incrementally syncing multi-source data.
- Offline indexing layer: builds inverted indexes and vector indexes, producing the physical structures used for online retrieval.
- Query understanding layer: handles rewriting, correction, intent recognition, entity linking, and multi-turn context completion.
- Retrieval layer: runs keyword retrieval, semantic retrieval, and structured retrieval in parallel to form a candidate set.
- Ranking and generation layer: performs coarse ranking, fine ranking, and reranking, then organizes context and passes it to a generation model to produce the answer.
- Serving and governance layer: caching, rate limiting, degradation, observability, evaluation, and cost control.
It is important to emphasize that the generation layer should never be treated as a “catch-all, do-everything module.” When retrieval is missing key evidence, the generation model can only produce text that looks plausible. This is one of the primary sources of hallucination.
3. Offline Indexing: The Foundation of AI Search
Index design must serve two retrieval paradigms at once. Inverted indexes excel at exact matching, long-tail entities, and ID-style queries. Vector indexes excel at semantic similarity and colloquial expressions. In practice, a common strategy is to maintain both indexes and fuse them at query time.
Key engineering points include:
- Chunking strategy. Split on semantic boundaries rather than a fixed character count, and retain the heading hierarchy as a context prefix. This can significantly improve the usability of retrieved fragments.
- Metadata design. Attach source, timestamp, permission tags, and version number to each chunk to support filtering and auditing.
- Incremental updates. Publish indexes using versioned writes plus atomic swaps to avoid retrieving half-built data.
- Permission enforcement up front. Annotate access control at index time and enforce filtering at retrieval time to prevent unauthorized content from entering the context.
Illustrative chunking and metadata construction logic:
def build_chunks(doc, max_tokens=512, overlap=64):sections = split_by_semantic_boundary(doc.body) # Split on heading/paragraph boundarieschunks, buf = [], []for sec in sections:buf.append(sec)if count_tokens(buf) >= max_tokens:chunks.append(merge_with_overlap(buf, overlap))buf = buf[-1:]if buf:chunks.append(buf)return [{"text": c,"source": doc.uri,"updated_at": doc.updated_at,"acl": doc.acl_tags, # Permission tags, enforced at retrieval time"version": doc.version,}for c in chunks]
4. Query Understanding: Translating User Input into Retrieval Intent
User input is often short, ambiguous, and full of references. The goal of the query understanding layer is to turn a sentence of natural language into a structured retrieval request.
- Normalization and correction: unify full-width and half-width characters, letter case, units, and common spelling deviations.
- Intent classification: distinguish factual, comparative, operational, and exploratory queries, and route different intents to different retrieval and generation templates.
- Query rewriting: generate several synonymous and decomposed variants to improve retrieval coverage; for multi-hop questions, decompose into sub-questions first.
- Multi-turn completion: fill in omitted elements using conversation history, but set a rewriting confidence threshold and skip rewriting when confidence is low.
Rewriting must run in parallel with retrieval on the original query, not replace the original query. Otherwise, a rewrite that “looks smarter” can easily lose the user’s true intent.
5. Hybrid Retrieval and Reranking
A single retrieval channel has a clear ceiling on recall, so engineering practice commonly uses multiple channels in parallel:
- Lexical channel: handles exact terms, error codes, and proper entities.
- Semantic channel: handles colloquial expressions, synonymous phrasing, and cross-language scenarios.
- Structured channel: handles questions that require range filtering or aggregate statistics.
During fusion, weighted summation or rank-based methods (such as reciprocal rank fusion) are commonly used to eliminate the inconsistent score scales across channels. Reranking comes next: first use a lightweight model for coarse ranking to shrink the candidate set, then use a cross-encoder-style model for fine ranking to output the evidence fragments used for generation.
def hybrid_search(q, top_k=8):lexical = inverted_index.search(q.queries, limit=50)semantic = vector_index.search(embed(q.text), limit=50)fused = reciprocal_rank_fusion([lexical, semantic], k=60)filtered = [c for c in fused if acl_ok(c, q.user)] # Permission filteringreranked = cross_encoder.rerank(q.text, filtered)[:top_k]return reranked
Reranking output should carry scores and sources. Evidence with scores below the threshold should not enter the context. It is better to answer “insufficient evidence” than to let the model improvise.
6. Generation and Factual Consistency
The core of the generation stage is not eloquence but verifiability. Practical constraints include:
- Structured prompting: state rules explicitly, such as “answer only based on the evidence below,” “cite the reference number for each point,” and “present conflicting evidence side by side.”
- Citation alignment: every conclusion in the answer points back to a specific fragment number, making it easy for the frontend to display sources.
- Conflict handling: when multiple sources disagree, output an explanation of the differences with timestamps rather than forcing an average.
- Refusal mechanism: when evidence coverage is insufficient, return a clarifying question or a clear statement of the information gap.
- Output validation: apply rule-based checks on numbers, dates, and units, and query structured data sources again when necessary.
A minimal example of evidence organization:
PROMPT = """Answer the question based only on the [Evidence] below; do not introduce external knowledge.Requirements: 1) Mark the source with [number] after each conclusion; 2) explain conflicting evidence separately;3) clearly state the gap when evidence is insufficient.[Question] {question}[Evidence]{evidence}"""def answer(q, evidence):if coverage(q, evidence) < 0.6:return {"text": "The available material is insufficient to answer. Please provide: " + missing_slots(q)}ctx = "\n".join(f"[{i}] {e.text}" for i, e in enumerate(evidence, 1))return {"text": llm(PROMPT.format(question=q.text, evidence=ctx))}
7. Evaluation: No Measurement, No Iteration
Evaluation for AI search must be layered. A single “answer satisfaction” metric cannot be allowed to mask problems:
- Retrieval layer: recall, hit rate, mean reciprocal rank, and context coverage.
- Generation layer: factual accuracy, citation correctness, refusal appropriateness, and answer completeness.
- Experience layer: time to first token, end-to-end latency, session resolution rate, and follow-up rate.
- Safety layer: unauthorized content leakage rate and prompt injection interception rate.
It is recommended to build a regression set with standard answers, bucket statistics by intent type, and run automated batches after every index or model change to form a trend dashboard. Human evaluation is used to calibrate automatic metrics; the two cannot replace each other.
8. Performance, Cost, and Stability
Generative pipelines have high latency and high cost, so budget management is essential:
- Tiered caching: query-level caching, retrieval-result caching, and answer caching, with cache keys isolated by permission dimension.
- Adaptive compute: route simple queries to lightweight models or smaller parameter configurations, and escalate only complex multi-hop queries.
- Streaming output: return the first token and the citation skeleton first to reduce perceived latency.
- Degradation path: when generation is unavailable, fall back to a list of highly relevant fragments to preserve availability.
- Observability: full-chain tracing that records the time spent and hit status of rewriting, retrieval, reranking, and generation.
The key to cost control is changing “unrestricted calls to large models” into “allocating budget by query complexity,” and setting a hard limit on overly long contexts.
9. Security and Compliance Essentials
- Permission consistency: permission checks at indexing, retrieval, generation, and caching must all come from the same source.
- Prompt injection protection: label external content as untrusted data and prohibit it from carrying instructions.
- Audit trail: retain the question, evidence numbers, and model version to support after-the-fact tracing.
- Data minimization: keep only the necessary fragments in the context, and desensitize sensitive fields before indexing.
10. Implementation Checklist
- Does the index support incremental updates and atomic swaps?
- Is permission filtering enforced at retrieval time?
- Are multiple retrieval channels used with scale-normalized fusion?
- Are the reranking threshold and refusal policy clearly defined?
- Does the answer enforce citation numbers with clickable source tracing?
- Is layered evaluation automated and included in the release process?
- Are caching, degradation, and streaming output in place?
- Are full-chain tracing and auditing complete?
The engineering difficulty of AI search centers on one basic fact: evidence quality determines answer quality. Only by turning indexing, retrieval, reranking, constrained generation, and layered evaluation into a closed loop can a system achieve a sustainable balance among accuracy, latency, and cost. If you already have general cloud infrastructure such as a container platform, object storage, a message queue, logging services, and monitoring and alerting, you can further standardize the indexing and evaluation pipelines. For example, you can use the relevant general capabilities of Baidu AI Cloud to handle batch processing and observability needs, allowing engineering effort to focus on retrieval and generation quality itself.
