AI Search in the Browser: Architecture and Implementation Practices
This article explains how to build an AI search experience into a browser, covering system architecture, intent detection, query rewriting, hybrid retrieval, reranking, prompt construction, citations, streaming responses, session management, privacy, security, compliance, and performance evaluation. It also provides a reference orchestration flow and practical implementation considerations.
1. Background: From Keyword Search to Semantic Answers
Traditional browser address bars and search boxes send user keywords to a search engine. Users then open multiple result pages and manually filter the information they need. As large language models become better at understanding and generating language, more browser products are beginning to provide answers directly through AI search.
These systems typically have three characteristics:
- They understand natural-language intent.
- They use real-time web content when answering questions.
- They cite the sources used to generate the answer.
For developers, the main challenge is not calling a model. It is organizing retrieval, reasoning, presentation, and compliance into a stable and controllable system. The following sections examine the architecture, core request flow, engineering implementation, user experience, and governance requirements.
2. Layered Architecture
A practical AI search system usually consists of the following layers:
- Interaction layer: Handles input from the address bar or side panel, streaming rendering, and citation cards.
- Orchestration layer: Manages intent detection, query rewriting, retrieval scheduling, context assembly, and model calls.
- Retrieval layer: Includes web indexes, search API wrappers, vector retrieval, and result reranking.
- Model layer: Provides general-purpose large language model services and supports switching between standard answer mode and reasoning mode.
- Governance layer: Covers content safety filtering, audit logging, user privacy, and quality monitoring.
Layering allows each component to be replaced and scaled independently. When the model service is upgraded, the orchestration interface does not need to change. When a new retrieval source is added, the retrieval layer only needs to register a corresponding data adapter.
User input -> Intent detection -> Query rewriting -> Multi-source retrieval -> Reranking and truncation-> Prompt assembly -> Streaming generation -> Citation binding -> UI rendering
3. Core Request Flow
3.1 Intent Detection
Not every query requires web access. Casual conversation, translation, and unit conversion can often be answered directly by the model, which saves time and reduces cost.
A common approach is to use a lightweight classifier or rule-based logic to determine whether a query depends on external knowledge. Queries containing time-sensitive terms such as “today,” “latest,” or “current,” as well as specific entities or explicit factual questions, can trigger retrieval.
The decision threshold should be continuously adjusted based on production logs. For time-sensitive questions, the cost of one additional retrieval request is usually much lower than the cost of providing an outdated answer.
3.2 Query Rewriting
User queries are often conversational and lack sufficient context. Reconstructing the current question with information from the conversation history can significantly improve retrieval quality. For example, “What about its price?” can be rewritten as a complete query that includes the name of the relevant product or entity.
The rewritten query should be retained alongside the original query. Both can be used in parallel during retrieval to reduce the risk that the rewrite changes the user’s actual intent.
3.3 Retrieval and Reranking
Retrieval commonly combines keyword search with vector search.
- Keyword search is more effective for exact names, identifiers, and similar queries.
- Vector search is more robust when the wording differs but the meaning is similar.
After the two result sets are merged, a reranking model or scoring function should sort the candidates. Only the top results should be selected as context.
More context is not always better. Exceeding the model’s effective context window or including irrelevant passages can reduce answer accuracy.
3.4 Prompt Assembly and Citations
The prompt should clearly state three requirements:
- The answer must be based only on the supplied materials.
- Conflicts between sources must be explicitly identified.
- Every important conclusion must include a source number.
This allows users to verify the answer item by item. It also enables the system to trace each source number back to the original web page, creating a complete citation chain.
3.5 Reasoning Mode
Some questions require multiple reasoning steps, such as comparing several options or performing numerical derivations. In these cases, the system can enable a reasoning mode so the model processes the problem before presenting the conclusion.
In the interface, the reasoning process should be collapsed by default. This preserves transparency without interrupting normal reading. Because reasoning mode generally takes longer, it should be enabled only for complex questions, with an option for users to switch it on manually.
4. Engineering Implementation Example
The following code illustrates the main flow in the orchestration layer. Retrieval, reranking, and model calls are placeholder functions and should be replaced with the corresponding interfaces of the services used in production.
def ai_search(query, session):# Rewrite the query using conversation history while retaining the original queryrewritten = rewrite_query(query, session.history)# Retrieve from multiple sources in parallel, then deduplicate the resultscandidates = dedupe(search_keyword(rewritten, top_k=10)+ search_vector(rewritten, top_k=10))# Rerank the candidates and fit the context within the model input budgetcontext = trim_to_budget(rerank(query, candidates), max_tokens=3000)# Assemble the prompt and stream the responseprompt = build_prompt(query, context, instruction=CITATION_RULES)for chunk in stream_llm(prompt):yield chunk# Return the citation list and update the sessionyield render_citations(context)session.append(query, context)
Several implementation details require attention:
- Set timeouts and fallback strategies. Both retrieval and model calls should have time limits. For example, if retrieval fails, the model can answer using its existing knowledge while clearly telling the user that web search was unavailable for this request.
- Deduplicate normalized URLs or content fingerprints. Otherwise, multiple versions of the same page may occupy several context slots.
- Reserve output capacity in the input budget. If the input becomes too long, the generated answer may be truncated.
5. Streaming Output and User Experience
Users often judge an AI search feature primarily by how quickly it responds. Streaming output allows the interface to render the first generated fragment as soon as it becomes available, which significantly reduces perceived waiting time.
The frontend should handle several details:
- Display incomplete Markdown syntax gracefully during generation.
- Bind citation numbers to source cards after generation is complete.
- When the user cancels a request, terminate the backend data stream and release the connection.
In terms of page structure, the answer should appear at the top, followed immediately by the source list. Related follow-up questions can be placed at the bottom. Source cards should show the site name and a short summary so users can quickly assess the credibility and relevance of each result.
6. Session and Context Management
Multi-turn conversations can cause the context to grow continuously. Common strategies include:
- Keep the most recent several turns in full and compress older content into a summary.
- Treat retrieved results as valid only for the current turn instead of storing them permanently in the session state.
- Delete content immediately when the user explicitly asks to remove it.
Session storage should also have an expiration policy and remain decoupled from account information where possible. This reduces the risk of sensitive content being retained for too long.
7. Privacy, Security, and Compliance
AI search naturally involves user queries, browsing context, and third-party web content. This creates significant governance requirements. The following measures can be applied:
- Data minimization: Collect only the fields required to complete the task. For example, do not send the user’s complete browsing history to the model.
- Sensitive-content exclusion: Password fields, private pages, and similar content should be excluded directly on the client and should not enter the retrieval or model pipeline.
- Content safety: Filter retrieved content and generated content separately. Web text should be treated as data rather than instructions. The prompt must explicitly enforce this boundary to prevent malicious text embedded in a web page from changing the model’s behavior.
- Audit logging: Record the request ID, retrieval sources, and model version to support issue investigation and reproduction. User identifiers in logs should be anonymized or otherwise de-identified.
- User controls: Provide options to disable web search, clear the session, and view source material.
8. Quality Evaluation and Monitoring
Before launch, establish an offline evaluation set covering factual questions, time-sensitive questions, multi-hop reasoning, and questions that should be refused.
For each category, track the following metrics:
- Answer accuracy
- Citation accuracy, meaning whether the cited passage actually supports the conclusion
- Hallucination rate
- Time to first token
- Total response time
After launch, continue iterating through sampled logs and user feedback. Pay particular attention to cases where the answer includes citations but the conclusion is unsupported. These cases often indicate defects in reranking rules or prompt constraints.
For latency analysis, measure retrieval, reranking, and generation separately. This makes it easier to identify the stage responsible for performance bottlenecks.
9. Implementation Recommendations and Common Pitfalls
- Pitfall 1: Assuming that connecting a model is enough to build AI search. Retrieval quality determines the upper limit of answer quality.
