Generative Search Architecture and Engineering Practice: From Query Fan-Out to Trustworthy Answers
Generative search moves beyond returning ten ranked links to synthesizing a single cited answer, which changes where the hard problems live. This article breaks down the end-to-end architecture and the engineering decisions behind it: the shift from ranking precision to decomposition quality, query fan-out with intent-typed sub-queries, multi-source retrieval across web, knowledge graph, structured, and private data with reciprocal rank fusion, a rerank-and-synthesize orchestration skeleton, multi-turn state management, high-resolution image generation with multiple reference images, and a latency/cost/availability budget. It also covers offline and online quality evaluation, security and compliance concerns, and a phased rollout plan. Readers will get concrete code sketches, practical constraints, and the tradeoffs that separate "generating fluent text" from "returning a trustworthy answer."
1. The Paradigm Shift: From Retrieving Links to Synthesizing Answers
The core pipeline of a traditional search engine is “query parsing → inverted-index recall → ranking → return ten blue links,” leaving users to read, compare, and summarize on their own. Generative search extends this into “intent understanding → question decomposition → multi-source recall → reranking and fusion → answer synthesis → citation tracing.” The system directly outputs a conclusive piece of text with sources, and the interaction model shifts from a one-shot Q&A to multi-turn follow-up.
This shift brings three fundamental changes:
- The hard problem moves from “ranking precision” to “decomposition quality.” Ranking only operates within an existing candidate set, while decomposition determines whether that candidate set covers all facets of the question. Poor decomposition cannot be salvaged by even the strongest reranker.
- The evaluation target expands from “relevance” to “factuality.” Traditional metrics such as NDCG and MRR are insufficient to characterize the reliability of generated results. You must introduce new dimensions like citation coverage, factual consistency, and harmful-content interception rate.
- The cost structure changes from “milliseconds per query” to “multiple model calls per query.” A single Q&A may sit behind dozens of retrievals and several rounds of reasoning, so latency and cost budgets must be redesigned.
2. Core Mechanisms: Query Fan-Out and Multi-Source Recall
2.1 Why Do Query Fan-Out
A user’s single question is often a compressed expression of composite intent. For example, “Help me evaluate the compliance procedures and rough budget for building a mid-sized data center in a given city” contains at least three kinds of intent: local approval processes (procedural), energy-consumption and environmental metrics (regulatory), and construction and equipment cost ranges (numeric). If you issue only one retrieval, the results will be dominated by whichever intent is most frequent, and the other facets get drowned out.
Query fan-out hands the main question to a model to decompose into several semantically independent, separately retrievable sub-queries, tags each with an intent type and a preferred information source, then executes them concurrently and merges the results.
from dataclasses import dataclassfrom concurrent.futures import ThreadPoolExecutor@dataclassclass SubQuery:text: strintent: str # factual / procedural / comparison / temporal / numericsource: str # web / graph / structured / privateweight: float # weight applied during mergedef fan_out(main_query: str, llm, max_subs: int = 12) -> list[SubQuery]:prompt = f"""Decompose the user question into independent, parallelizable sub-queries, at most {max_subs}.Tag each with an intent and a source, and give a weight between 0 and 1. Output only a JSON array.User question: {main_query}"""raw = llm.chat(prompt, response_format="json")return sanitize(raw) # dedupe, clamp out-of-range values, truncate length, filter prompt injection
A few engineering points are essential:
- The number of sub-queries has an optimal range. Too few leaves gaps in coverage; too many dilutes the recall depth of each sub-query and drags tail latency behind the slowest branch. Keep it around 6–12, and prune low-value branches by weight.
- Decouple decomposition from retrieval. Decomposition results should be persisted as structured objects to support replay and offline evaluation; otherwise online failures cannot be attributed.
- Prompt-injection protection is mandatory. The decomposition model’s input comes entirely from untrusted users, and its output directly drives downstream retrieval, so any privilege-escalating instruction that appears in a sub-query must be filtered.
2.2 Fusing Multiple Sources: Web, Knowledge Graph, and Structured Data
A single text index cannot cover every information shape. In practice you typically build four channels:
| Channel | Content it carries | Typical techniques |
|---|---|---|
| Web text | Long-tail, highly time-sensitive content | Inverted index + dense vectors |
| Knowledge graph | Entities, relations, hierarchies | Graph queries and subgraph extraction |
| Structured data | Numeric values, metrics, catalogs | Table retrieval, metric services |
| Private/enterprise data | Internal documents, tickets | Permission-aware vector retrieval |
There are two mainstream ways to merge results from multiple paths. Weighted summation first normalizes each channel’s scores and is sensitive to distributional differences. Reciprocal Rank Fusion (RRF) relies only on ranks and needs no score calibration, making it simple and robust:
def rrf_fuse(ranked_lists, k=60):scores = {}for ranked in ranked_lists: # one ordered doc_id list per channelfor rank, doc_id in enumerate(ranked, start=1):scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)return sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
After fusion, a rerank is still needed. RRF only guarantees that documents “approved by multiple paths” float to the top; it cannot judge whether a given passage actually answers a specific facet of a sub-query. So in a real system, a lightweight interactive reranker runs over the top 40–60 fused results, scoring them as “sub-query–document” pairs so that every sub-query gets a representative hit and candidates do not concentrate on a single intent.
2.3 The Orchestration Skeleton
def answer(main_query, llm, retriever, reranker, max_workers=8):subs = fan_out(main_query, llm)with ThreadPoolExecutor(max_workers=max_workers) as pool:groups = list(pool.map(lambda s: retrieve(s, retriever), subs))fused = rrf_fuse([g.ids for g in groups])ctx = reranker.rerank(main_query, subs, fused, top_n=40)return llm.synthesize(main_query, ctx, cite=True) # streaming output + citation backfill
The semantics of pool.map are worth emphasizing: it returns results in input order, so the total time equals the time of the slowest sub-query branch. Without timeout circuit-breaking, a single faulty sub-query can push the overall P99 up by an order of magnitude. It is recommended to set an independent 300–500 ms timeout per branch, continue with partial results after a timeout, and flag the answer’s information completeness.
3. State Management for Multi-Turn Dialogue
Multi-turn follow-up requires the system to distinguish a “new topic” from “context continuation.” In practice, a three-layer strategy is used:
- Coreference resolution layer: First use a small model to rewrite “what is its power consumption?” into a self-contained query such as “the power consumption of the accelerator card model mentioned in the previous turn,” then feed it into retrieval. A self-contained query is the basic unit that can be cached and evaluated.
- Session state layer: Maintain the intent tags, cited document IDs, and confirmed constraints (budget, region, time range) from the last few turns to avoid redundant retrieval.
- Progressive retrieval layer: Trigger a new round of fan-out only when a new constraint appears. Without a new constraint, reuse the previous context for local reasoning, which significantly reduces latency and cost.
A common anti-pattern is concatenating the entire conversation history verbatim into the retrieval query, which bloats the query string and dilutes its semantics, actually degrading recall quality. Always send only “the single self-contained question that currently needs retrieval” into the retrieval pipeline.
4. Image Generation Engineering for High Resolution and Multiple Reference Images
The capability upgrade on the generation side is fundamentally a breakthrough along two dimensions: controllability and resolution.
Multiple reference image inputs. When the number of reference images reaches a dozen or more, the key challenge is no longer “can it fit into the model,” but how to maintain subject consistency. A common approach is to extract unified semantic tags (person, material, color scheme, composition constraints), group and encode the reference images by role, and apply attention constraints per group during generation. Conflicting constraints (for example, two reference images specifying different primary colors) should be resolved before generation or handed back to the user for confirmation, rather than letting the model pick randomly.
High-resolution output. Running inference directly at the target canvas size makes memory and attention costs grow quadratically with pixel count, so it usually requires tiled generation followed by stitching:
def generate_hires(prompt, refs, canvas=(3840, 2160), tile=1024, overlap=128):base = model.generate(prompt, refs=refs, size=(1024, 1024)) # first produce a low-res structurefor y in range(0, canvas[1], tile - overlap):for x in range(0, canvas[0], tile - overlap):cond = crop(base, x, y, tile) # use the low-res result as the structural conditionpatch = model.refine(prompt, init=cond, refs=refs)blend(base_canvas, patch, x, y, feather=overlap) # feather-blend the overlap regionreturn model.upsample_2x(base_canvas) # second-stage super-resolution upscaling
Three engineering points: the overlap region must be feather-blended, or the seams become extremely visible in gradient areas; the low-resolution result carries the “global structure” role to avoid style drift across tiles; and the memory peak occurs during the upscaling stage, which should be paired with tiled inference and operator-level memory reuse.
Provenance and compliance. Generated images should carry a source identifier and an invisible watermark in their metadata, and the service layer should perform content-safety checks on both inputs and outputs. For multi-reference scenarios, you also need to verify the usage rights of user-uploaded assets to avoid style- and likeness-related infringement risks.
5. Performance, Cost, and Availability
The following is an illustrative end-to-end latency budget, meant to show the relative weight of each stage; the actual numbers must be based on load-testing your own pipeline:
| Stage | Reference budget | Key optimization levers |
|---|---|---|
| Query understanding and decomposition | 150–300 ms | Small-parameter models, rule-based pre-processing, result caching |
| Parallel multi-path recall | 100–250 ms | Fan-out concurrency, index warm-up, per-path timeout circuit-breaking |
| Fusion and reranking | 80–200 ms | Candidate truncation, lightweight interactive models, batched inference |
| First-token output | < 800 ms | Persistent serving, KV-cache reuse, incremental rendering |
Three principles for cutting cost and boosting efficiency:
- Layered caching. The self-contained query is a natural cache key. Caching decomposition results, retrieval results, and final answers separately yields a hit rate typically much higher than caching only the final answer.
- Difficulty routing. Simple factual questions go through single-path retrieval, and only composite questions trigger fan-out. A lightweight classifier for routing can push average cost very low.
- Graceful degradation. When a dependency service fails, fall back step by step: “reduce the number of sub-queries → skip reranking → return a cited retrieval summary,” ensuring the feature stays usable rather than failing entirely.
In capability systems such as Baidu AI Cloud’s, a container platform hosts inference and retrieval services, a message queue decouples asynchronous tasks, object storage holds sessions and artifacts, a vector retrieval service powers semantic recall, and logging with monitoring and alerting covers full-pipeline observability. These general categories are already enough to support building and operating the architecture above, with no proprietary components required.
6. Quality Evaluation and Security Compliance
The offline evaluation set should cover five types of samples: single-hop factual, multi-hop reasoning, comparison, time-sensitive, and no-answer (used to test refusal). Core metrics include sub-query recall rate, citation coverage, answer factual consistency, refusal accuracy, and human usefulness scores. Online, use gray-release A/B comparison to observe changes in follow-up rate, click-through rate, and complaint rate.
On security, three points deserve attention: treat all retrieved web content as untrusted input to prevent it from carrying instructions that pollute the generation process; in high-risk domains such as medical, legal, and financial, prioritize authoritative sources and explicitly state limitations; and all conclusions must be traceable to specific snippets, avoiding assertions that cannot be sourced.
7. A Phased Implementation Plan
- Phase 1: Establish a minimal closed loop of “retrieve → rerank → generate with citations,” solving factuality and traceability first without introducing complex orchestration.
- Phase 2: Add query fan-out, hybrid retrieval, and fusion ranking, and set up the offline evaluation set and online gray-release mechanism.
- Phase 3: Fill in multi-turn state management, difficulty routing, cost optimization, and generative modalities such as images, and complete provenance marking and security review.
The competitiveness of generative search ultimately does not depend on model size, but on the information coverage of the retrieval pipeline, the robustness of the orchestration layer, and the rigor of the evaluation system. Only by making these three solid can you truly convert “able to generate a fluent piece of text” into “able to give a trustworthy answer.”
