Overview

7 Enterprise RAG: Agentic Routing, Semantic Caching, and Query Rewriting

This chapter reframes retrieval-augmented generation for enterprise realities, moving beyond single-pipeline “naive” RAG to adaptive, auditable systems that reason about user intent, data domains, and operational constraints. It outlines how large, heterogeneous organizations face challenges that simple vector search cannot solve alone—strict latency SLAs, cost controls, regulatory and provenance needs, and frequent ambiguity in user queries. Within a broader Enterprise RAG landscape that also includes safety guardrails, memory, access control, and observability, the chapter focuses on three high-impact pillars—agentic routing, semantic caching, and query rewriting—as the fastest path from proof-of-concept to production-grade performance and reliability.

Agentic routing sits at the decision-making core, classifying intent and directing queries to purpose-built knowledge partitions and retrieval strategies rather than a monolithic index. By separating “where to look” (routing) from “what to find” (retrieval), it avoids cross-domain contamination, respects authority and provenance, and preserves precision as domains scale. A minimal three-route example demonstrates the pattern: two internal, domain-specific vector collections for technical documentation and financial filings, plus a live web search fallback for out-of-scope or current-event queries. The router’s structured, justified outputs create an audit trail for transparency, while domain-specific retrieval keeps prompts focused, costs contained, and answers grounded—at the known tradeoff of a small added routing latency.

To meet enterprise cost and latency targets, semantic caching reuses results for semantically similar questions via an embedding-based cache (e.g., FAISS), with a conservative similarity threshold for accuracy and a fast keyword filter to bypass the cache for time-sensitive queries. This cuts LLM calls and vector searches on repeat questions, delivering millisecond responses without sacrificing freshness. Query rewriting and sub-query decomposition improve retrieval quality before it begins: a rewriter expands abbreviations, resolves ambiguity using recent context, and preserves user intent, while a decomposer splits compound prompts into focused, independently retrievable sub-queries. Combined into a unified pipeline—cache check, time-sensitivity detection, routing, rewriting, optional decomposition, targeted retrieval, grounded synthesis, then caching—the three pillars yield a scalable, auditable, and high-precision Enterprise RAG system that aligns with real-world compliance and performance demands.

Enterprise RAG: A modular framework that uses a central decision-making hub to route requests through specialized knowledge repositories and safety guardrails for high-precision results.
Agentic Router: A contrast between two frameworks, one that uses central knowledge retrieval (left) vs. a router-based approach to retrieve data from relevant repositories (right)
Naïve Search: A central unified index raises challenges of pulling data from one source, often leading to irrelevant retrieval
illustrates the complete query flow through the three-route architecture, from the initial user query through routing classification, domain-specific retrieval, and final response generation.
The core concept of semantic caching within an Enterprise RAG system to help reduce processing time to look up time for similar queries previously asked
A detailed, step-by-step pipeline diagram illustrating a query processing system

Summary

  • The first step in building Enterprise RAG is recognizing that naive RAG architectures fail in enterprise environments. These architectures embed all documents into a single index and run every query against the same collection. When document types differ significantly, such as financial filings, technical documentation, and live web content, a shared vector space introduces cross-domain interference that degrades retrieval precision across every query.
  • To direct queries to the right knowledge base, we built an LLM-based agentic router that classifies user intent and sends each query to the most appropriate retrieval backend. Unlike keyword matching or naive semantic search across a unified index, the LLM router reasons about the meaning and category of a query as a whole, correctly classifying questions even when they contain no obvious domain-specific keywords.
  • The three-route architecture we built covers OpenAI documentation, 10-K financial filings, and live web search, and is deliberately minimal. The same routing pattern scales to any number of domain-specific collections. The key design principle is that routes should map to fundamentally different retrieval strategies, not just different topics. Adding a new route requires only a new collection and an updated router prompt.
  • Semantic caching addresses the cost and latency problem that comes up when enterprise users repeatedly ask variations of the same question. By embedding each query and comparing it against previously cached queries using FAISS with an L2 distance threshold, the system can return stored answers for semantically equivalent questions in 10 to 50 milliseconds, which is over 100x faster than running the full routing, retrieval, and generation pipeline.
  • Cache correctness depends heavily on the time-sensitivity filter. We use a keyword-based approach rather than an LLM-based classifier to keep cache lookups fast. Queries containing temporal indicators like "today," "current," or "latest" bypass the cache entirely and always pull fresh results from live search, which prevents the system from returning stale answers to time-sensitive questions.
  • To handle the ambiguity and imprecision of real-world enterprise queries, we added query rewriting and sub-query decomposition as pre-retrieval transformation steps. The single-query rewriter expands abbreviations, resolves vague references using conversation history, and adds domain specificity. The sub-query decomposer breaks compound questions into focused atomic queries that can each be routed and retrieved independently, giving precise retrieval for every distinct information need within a complex question.
  • The complete Enterprise RAG pipeline processes each query through a fixed sequence: semantic cache check, time-sensitivity filtering, LLM-based routing, query rewriting, optional sub-query decomposition, domain-specific retrieval, grounded response generation, and cache storage. Each component targets a specific failure mode of naive RAG, and the most expensive components only run on cache misses, so the system gets faster and cheaper the longer it operates.

FAQ

What problems with naive RAG show up in enterprise settings?Naive, single-pipeline RAG struggles with cross-domain noise, lack of source authority/freshness awareness, and brittle behavior under varied intents. At scale, you must also hit strict latency SLAs, control costs, respect compliance and access controls, and provide auditable decisions. Enterprise RAG addresses this with adaptive routing, semantic caching, and query rewriting.
What is agentic routing and why isn’t pure semantic similarity enough?Agentic routing is an LLM-powered intent classifier that decides where a query should go before retrieval. Semantic similarity tells “what is close,” but not “what is appropriate.” Typical failure modes of single-index semantic search include: cross-domain contamination, authority/provenance blindness, and degraded precision as more domains are added. Routing answers “where to look”; retrieval answers “what to find.”
Why partition the knowledge base instead of using one large vector index?Merging very different document types into one index dilutes precision. Partitioning by domain/type (for example, API docs vs. 10-K filings) keeps each vector space semantically coherent, improves top-k quality, and avoids cross-domain interference. Adding a new domain becomes a new collection plus a router update, without harming existing domains.
How does the three-route architecture in this chapter work?The router sends each query to one of three destinations: OPENAI_QUERY (OpenAI docs in Qdrant), 10K_DOCUMENT_QUERY (Uber/Lyft 10-Ks in Qdrant), or WEB_SEARCH (live web via SerpApi). Internal routes use domain-specific vector collections; the web route “escapes” when content is out-of-scope or time-sensitive.
How is the router implemented and audited?An LLM (e.g., GPT-4o) is prompted to return structured JSON: {action, reason, answer}. The “reason” gives a human-readable audit trail for compliance and debugging. If parsing fails, it safely falls back to WEB_SEARCH. For trivially obvious queries, the router may return a short direct answer to skip retrieval.
What is semantic caching and how is it implemented here?Semantic caching reuses prior answers based on meaning, not exact strings. Queries are embedded and stored in a FAISS IndexFlatL2; a conservative L2 threshold (~0.2, ~0.98 cosine) returns hits only for near-identical paraphrases. Hits typically take 10–50 ms and avoid both LLM calls and vector DB queries, cutting latency and cost substantially.
Why isn’t exact-match caching sufficient for natural language queries?People rarely type the same words twice. Paraphrases like “What was Uber’s revenue in 2021?” vs. “How much did Uber make in 2021?” should map to the same answer. String equality misses these; semantic similarity finds them and yields high-precision cache hits.
How do you prevent stale answers for time-sensitive queries in the cache?A lightweight keyword-based time-sensitivity filter (e.g., “today,” “this week,” “outage,” “stock price”) bypasses the cache and routes to live web search; such answers are not cached. Using keywords keeps lookup ultra-fast and avoids paying an LLM latency/cost just to decide whether to check the cache.
What is query rewriting and sub-query decomposition, and where do they fit?Query rewriting clarifies intent by expanding acronyms, resolving vague references using recent history, and adding obvious domain specifics without inventing constraints. Sub-query decomposition splits compound questions into atomic, independently answerable queries. Both run after routing and before retrieval, improving recall/precision with modest overhead.
What is the end-to-end pipeline flow, and how does it reduce hallucinations and aid compliance?- Check semantic cache; return if hit. - If time-sensitive, bypass cache and use live web search. - Route with an LLM and capture a reason. - Rewrite and, if needed, decompose into sub-queries. - Retrieve from the routed collection(s) or web. - Synthesize a response with required citations to provided context. - Cache the result. Citations and domain-appropriate routing ground answers, while the router’s reason and end-to-end metadata create an auditable trail.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build an Advanced RAG Application (From Scratch) ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build an Advanced RAG Application (From Scratch) ebook for free