Architecting Hybrid RAG Agents
Deterministic multi-agent supervisor routing queries across structured SQL warehouses (GA4) and unstructured vector stores with early ambiguity detection and token distillation.
Context: Delivered in collaboration with Battlefield Capital, architecting an enterprise data intelligence platform that unifies structured data warehouses (Google Analytics 4, SQL) and unstructured document repositories (PDFs, Excel workbooks, contracts) behind a single query interface.
Bridging Structured and Unstructured Silos
Standard retrieval systems operate on a single modality: either vector similarity over chunked documents or text-to-SQL over relational tables. Enterprise decision-making rarely fits inside one boundary.
Consider a typical cross-domain query:
"How did the Q3 Marketing Campaign (defined in a strategy PDF) affect our lead generation trend in Google Analytics (stored in a SQL warehouse) last month?"
Answering this accurately requires three distinct operations:
- Vector Retrieval: Extract the campaign scope, dates, and target channels from unstructured PDF documents.
- Constrained SQL Execution: Query the Google Analytics 4 (
GA4) relational warehouse for lead conversion time series over those dates and channels. - Cross-Modal Synthesis: Reconcile the qualitative campaign definitions with the quantitative SQL output into a verifiable response.
A standard RAG pipeline fails because it cannot execute relational aggregations. A standalone SQL agent fails because the database has no knowledge of internal campaign nomenclature.
Router-Based Multi-Agent Architecture
Rather than relying on a single monolithic prompt with dozens of bound tools, we implemented a hierarchical Multi-Agent Supervisor in LangGraph. Specialized sub-agents own isolated domains, and a central supervisor coordinates routing and state aggregation.
1. Deterministic Source Dispatching
Letting an LLM dynamically improvise execution plans across multiple data sources introduces non-deterministic routing failures. Once the classifier identifies the required data modalities, MultiAgentSupervisor dispatches execution through a strict Python lookup table keyed by frozenset[DataSourceType].
Using frozenset guarantees order-invariant dispatch for multi-modal queries (for example, GA4 + Vector Store vs. Vector Store + GA4):
# backend-ai-api/src/domain/agents/qna/qna_multi_agent_system/qna_multi_agent_system.py
# Order-invariant dispatch table for data source combinations
self._combination_handlers: dict[
frozenset[DataSourceType], CombinationHandler
] = {
frozenset(
{DataSourceType.GOOGLE_ANALYTICS, DataSourceType.FILE_UPLOADED}
): self._handle_ga_and_file,
frozenset(
{DataSourceType.GOOGLE_ANALYTICS, DataSourceType.VECTORSTORE}
): self._handle_ga_and_vectorstore,
# ... other combinations
frozenset({DataSourceType.GOOGLE_ANALYTICS}): self._handle_ga_only,
frozenset({DataSourceType.VECTORSTORE}): self._handle_vectorstore_only,
}2. Inter-Agent State Compression
A common failure mode in multi-agent graphs is context window pollution. If the SQL sub-agent returns a 500-row result set and passes the raw payload into the downstream synthesis node, token costs spike and retrieval recall degrades across the middle of the context window.
We introduced an intermediate Distiller Node between execution and synthesis. Whenever a sub-agent's output exceeds a configured token budget, the distiller extracts only the fields and aggregates requested by the supervisor schema before merging into the shared graph state.
3. Constrained SQL Generation & Driver-Level Isolation
Exposing a production database to LLM-generated queries requires both prompt-level schema boundaries and database-level isolation in GA4SQLAgentFactory:
- Schema Whitelisting: The agent is restricted to tables with the
ga4_prefix. - Canonical Identifiers: Queries must filter on immutable
property_idkeys rather than mutabledisplay_namestrings.
Why We Replaced LangChain's Default create_sql_agent
Off-the-shelf SQL agents operate as unconstrained ReAct loops that repeatedly query information_schema, inspect sample rows, and retry malformed joins—adding seconds of latency and risking hallucinated table names. We replaced the generic agent with a constrained classification pipeline where the schema definition is injected statically and validated via Pydantic before execution.
Read-Only Materialized Views & PII Sanitization
Prompt constraints alone are never a security boundary. At the PostgreSQL driver layer, the agent authenticates using a read-only database role restricted to pre-aggregated materialized views. Raw user-level PII columns are excluded from the view definitions entirely, ensuring sensitive records cannot enter the LLM context window.
4. Real-Time Execution Telemetry via SSE
Multi-step queries across SQL and vector stores take 10 to 25 seconds to resolve. To prevent the UI from appearing frozen, we implemented a typed Server-Sent Events (SSE) protocol that streams intermediate state transitions (event: step) separately from the final payload (event: final).
// frontend-app/src/hooks/chat/useChatSubmission.ts
while (reading) {
const { done, value } = await reader.read();
// ... stream decoding ...
if (eventType === 'step') {
// Updates the live execution stage indicator in the UI
onStreamingStep(eventData);
} else if (eventType === 'final') {
// Renders the synthesized markdown response and citations
const finalResult = JSON.parse(eventData);
handleApiResponseWithSuggestions(finalResult);
break;
}
}As each node in the LangGraph state machine completes, the client renders the active execution stage ("Analyzing query clarity...", "Selecting data sources...", "Executing GA4 SQL query..."), keeping perceived latency low during multi-hop execution.
5. Pre-Routing Ambiguity Gate
Before invoking the supervisor or spawning database queries, incoming requests pass through a lightweight AmbiguityDetectionAgent.
If a query lacks required temporal bounds or metric definitions (for example, "How are conversions doing?" without a date range or channel), the gate short-circuits the graph and returns a targeted clarification prompt. Intercepting underspecified queries at the edge reduced downstream token consumption by roughly 40%.
# backend-ai-api/src/domain/agents/aux/ambiguity_detection/ambiguity_detection_agent.py
if is_ambiguous and system_with_max_confidence:
reason = specialized_responses[system_with_max_confidence]["decision_reason"]
clarification_message = f"Your query needs clarification: {reason}"
# Short-circuit graph execution before invoking the Supervisor
yield f"event: final\ndata: {json.dumps(ambiguity_result)}\n\n"Summary
Reliable multi-agent engineering depends on bounding non-determinism: using a lightweight ambiguity gate at the ingress, frozenset dispatch tables for routing, read-only materialized views for SQL execution, and state distillation between nodes.
— Pedro
Founder & Principal Engineer