Skip to main content
HB
RAG & AI Agents
Freelance client

Multi-Stage Legal RAG with Azure AI Search

Azure AI Search · Azure AI Foundry · Cosmos DB · FastAPI · Next.js

Hasan Iqbal Butt
By Hasan Iqbal ButtPublished: February 2025
3,145 Docs5-Layer Retrieval Pipeline
01

The Challenge

Standard RAG implementations chunk documents by token count and call it done. For general-purpose question answering, this works. For legal documents, it is a hallucination factory. Legal ordinances have specific structure: preamble, operative sections, definitions, and schedules. Schedules contain country lists, fee tables, and rate tables. These are the most frequently queried content and the most likely to be merged into a blob with surrounding pages by a token-count chunker. When the schedule disappears into the blob, the retrieval system cannot surface it independently. The model, finding no ground truth in the retrieved context, draws on training data and confidently gets it wrong. The client needed accurate answers across 3,145 Hong Kong and Singapore legal ordinances, covering questions about specific contract clauses, regulatory requirements, fee schedules, and country-specific enforcement rules. A question like whether France is on the reciprocating countries list under Cap 188B would consistently produce hallucinated answers because the schedule table was buried inside a larger chunk.

02

The Approach

The solution has three architectural pillars: structure-aware chunking, a five-layer retrieval pipeline, and a corpus audit system. For chunking, every page is classified into one of four semantic types using regex pattern matching: schedule, definition, preamble, or operative. Schedule detection takes highest priority. Chunks are determined by section-type transitions, not token count. When the page type changes, a new chunk begins. This means schedule tables always get their own standalone, independently retrievable chunk. Each chunk carries 15 metadata fields including cap number, section type, section number, and legal category. Chunk IDs are deterministic MD5 hashes, making re-indexing idempotent through mergeOrUpload. The retrieval pipeline has five layers. Layer one detects jurisdiction using weighted regex patterns for Hong Kong and Singapore terminology. Layer two runs pre-agent interceptors that catch security probes and verify deep subsection references in five milliseconds without touching the LLM. Layer three evaluates ten deterministic injection triggers. If a query matches a known pattern like stamp duty rates or annual leave entitlements, the system directly queries Azure AI Search with OData filters and injects the exact chunk as verified ground truth before the agent runs. Layer four runs the Azure AI Foundry agent with BM25 keyword retrieval followed by semantic reranking across the full index. Layer five applies post-generation guardrails that scrub forbidden URLs and parse citation metadata. Conversation memory runs on Cosmos DB with four containers. Azure AI Foundry maintains state through a previous_response_id mechanism, and GPT-4o summarizes every four turns with delayed injection to prevent the model from citing summaries as factual sources. The entire system deploys on Azure App Service with a Next.js frontend that receives responses via SSE streaming. New documents uploaded to Azure Blob Storage automatically trigger the indexing pipeline.

03

System Architecture

Loading architecture diagram...
04

Azure Infrastructure

Azure Infrastructure

Architecture for the Multi-Stage Legal RAG Pipeline. Click a node to view its configuration details.

HTTPS/SSERetrieveGenerateMemoryEmbedTriggerSearchNext.js FrontendSSE StreamingAzure App ServiceFastAPI BackendAzure AI SearchBM25 + Semantic RerankAzure AI FoundryGPT-4o AgentAzure OpenAIEmbeddings 3-largeCosmos DBConversation MemoryAzure BlobPDF StorageMonitoringTelemetry + Audit
Select a node to view infrastructure details
Primary data flow
Observability
05

Interactive Demo

Walk through the system design and data flow for this project step by step.

How the Legal RAG Pipeline Works

PDF3,145filespdfplumberper-page extractText PagesImage-OnlyAzure Blob StorageEvent Grid triggerAuto-pipeline on new upload

Step 1Document Ingestion and PDF Extraction

The system processes 3,145 Hong Kong and Singapore legal ordinances as PDF files. Each PDF is opened with pdfplumber and every page is extracted independently. Pages returning empty text are flagged as image-only content and logged for manual review since they are invisible to the retrieval system. When a new PDF is uploaded to Azure Blob Storage, an Event Grid trigger automatically kicks off the ingestion pipeline without any manual intervention.

Key Insight

Image-only pages are classified as a severity-high issue in the corpus audit system. These pages often contain scanned schedules or fee tables that are critical for answering queries but completely invisible to text-based retrieval. The audit identified and flagged these gaps across all 3,145 documents.

1 of 7

06

Overview

Built a production legal RAG system for 3,145 Hong Kong and Singapore ordinances with a five-layer retrieval pipeline. The system uses structure-aware page classification to chunk documents by semantic type instead of token count, eliminating schedule-merge hallucinations. Ten deterministic injection triggers bypass semantic search for known query patterns and inject verified ground truth. Azure AI Search handles BM25 retrieval with semantic reranking, GPT-4o on Azure AI Foundry generates grounded answers, and Cosmos DB manages multi-turn conversation memory. The 200-question validation suite completed three consecutive clean runs with zero hallucinations.

07

Business Impact

The 200-question test suite passed with zero errors, zero hallucinations, and zero URL leaks across three consecutive identical runs. Structure-aware chunking resolved the core retrieval problem where schedule tables were being merged into surrounding text, causing the model to hallucinate country lists from training data. The corpus audit identified and fixed 173 caps with missing schedule chunks and 171 with incomplete coverage across all 3,145 ordinances. Belgium, Norway, and France were all correctly identified as non-reciprocating countries without any per-country hardcoded logic. Fake sections like Section 999 of Cap 486 were correctly refused instead of fabricated.

08

Technical Highlights

  • Structure-aware page classification into schedule, definition, preamble, and operative types
  • 10 deterministic injection triggers that bypass semantic search for known query patterns
  • BM25 keyword retrieval with Azure AI Search semantic reranking on 8,709+ schedule chunks
  • Jurisdiction detection with weighted regex scoring for Hong Kong and Singapore legal terms
  • Pre-agent interceptors block source disclosure probes and verify deep subsection references
  • Idempotent indexing with MD5-based chunk IDs and mergeOrUpload for safe re-indexing
  • Cosmos DB conversation memory with GPT-4o summarization every 4 turns
  • Corpus audit system detecting 5 classes of retrieval gaps across 3,145 PDFs
  • SSE streaming for real-time response delivery to the Next.js frontend
  • Azure Blob trigger auto-indexes new documents without manual intervention
09

Frequently Asked Questions

Q: What makes this Legal RAG system different from standard RAG implementations?

It uses a multi-stage approach featuring structure-aware page classification (preamble, schedule, operative, definitions) to chunk documents by semantic boundaries rather than token counts. This ensures large schedules and rate tables are kept intact, completely eliminating context-merge hallucinations.

Q: How do the deterministic injection triggers work?

We implemented ten deterministic query triggers that detect search patterns mapping to known legal structures (such as stamp duty rates). These bypass semantic vector search entirely, using OData filters to fetch and inject verified legal tables as context, guaranteeing 100% accurate ground truth for critical numbers.

Q: How was retrieval accuracy validated for the 3,145 Hong Kong and Singapore ordinances?

We created a 200-question automated validation suite covering edge cases (such as Reciprocating Countries lists and non-existent sections). The suite completed three consecutive clean runs with zero errors and zero hallucinations before the system went to production.

Want results like this for your infrastructure?

I specialize in taking complex AI pipelines and cloud setups from concept to high-availability production. Let's discuss how to optimize your workloads, secure your environment, and reduce cloud costs.