Overview
Level 2: Build ยท Module 6: Retrieval Augmented Generation (RAG) ยท 20 min read
Why this matters
The frontend UI is the trust interface between an AI model and the human user. If an assistant delivers an answer with zero visible sources, users have no way to verify whether the output is an authoritative corporate policy or a hallucinated fabrication. Conversely, dumping 10 raw text chunks directly beneath an answer clutters the interface and overwhelms the user. Designing a sleek, accessible, responsive RAG UI with interactive source accordions, semantic confidence badges, side-drawer previewers, and graceful fallback messages establishes user trust and satisfies strict enterprise compliance standards.
Learning objectives
- Build an expandable, accessible Source Accordion component for retrieved chunks.
- Render semantic confidence badges based on reranker similarity scores.
- Implement an interactive side-drawer for deep source passage inspection.
- Design graceful, helpful fallback UI states when zero relevant documents are found.
- Support keyboard navigation and WCAG 2.2 accessibility for citation interactions.
Anatomy of an Enterprise RAG UI Component
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Assistant Response [ 94% Grounded ] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ To invalidate Next.js cache tags in Server Actions, invoke revalidateTag() โ
โ with the specific tag string [1]. Cached data will be cleared across all โ
โ edge nodes on the subsequent request lifecycle [2]. โ
โ โ
โ โผ Sources Used (2 Citations) โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ [1] Next.js Data Cache Documentation (Relevance: 0.94) โ โ
โ โ "revalidateTag(tag) purges the server cache for any fetch tagged..."โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ
โ โ [2] Cache Invalidation & Edge Propagation (Relevance: 0.88) โ โ
โ โ "Edge purge events propagate to CDN pops within 300ms..." โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโgraph TD
A["User clicks citation badge [1]"] --> B{"Is viewport Mobile or Desktop?"}
B -->|Desktop| C["Highlight and auto-expand Source Accordion #1 below message"]
B -->|Mobile / Deep Read| D["Slide out full Source Drawer with original document link"]Implementation: The Complete Grounded RAG Message Component
Here is a full React component featuring expandable source accordions, confidence badges, and citation badges:
// components/RagMessageView.tsx
"use client";
import React, { useState } from "react";
export interface RetrievedSource {
id: number;
title: string;
excerpt: string;
score: number; // 0.0 to 1.0
documentUrl?: string;
}
interface RagMessageViewProps {
answer: string;
sources: RetrievedSource[];
isStreaming?: boolean;
}
export function RagMessageView({ answer, sources, isStreaming = false }: RagMessageViewProps) {
const [isSourcesExpanded, setIsSourcesExpanded] = useState(false);
const [highlightedSourceId, setHighlightedSourceId] = useState<number | null>(null);
// Compute average confidence from sources
const avgConfidence = sources.length > 0
? Math.round((sources.reduce((acc, s) => acc + s.score, 0) / sources.length) * 100)
: 0;
// Split text by bracketed citations: [1], [2]
const parsedParts = answer.split(/(\[\d+\])/g);
return (
<div className="rounded-2xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-950 p-6 shadow-sm space-y-4">
{/* Header Bar: Status & Confidence Badge */}
<div className="flex items-center justify-between pb-3 border-b border-gray-150 dark:border-gray-800">
<span className="text-xs font-bold uppercase tracking-wider text-gray-500 flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-blue-600 animate-pulse" />
Grounded Answer
</span>
{sources.length > 0 && !isStreaming && (
<span
className={`px-2.5 py-1 rounded-full text-xs font-semibold font-mono ${
avgConfidence >= 85
? "bg-emerald-50 text-emerald-700 dark:bg-emerald-950/60 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-800"
: "bg-blue-50 text-blue-700 dark:bg-blue-950/60 dark:text-blue-300 border border-blue-200 dark:border-blue-800"
}`}
>
{avgConfidence}% Grounded
</span>
)}
</div>
{/* Answer Body with Clickable Badges */}
<div className="text-sm leading-relaxed text-gray-900 dark:text-gray-100">
{parsedParts.map((part, idx) => {
const match = part.match(/\[(\d+)\]/);
if (match) {
const sourceId = parseInt(match[1], 10);
return (
<button
key={idx}
onClick={() => {
setIsSourcesExpanded(true);
setHighlightedSourceId(sourceId);
}}
className="inline-flex items-center justify-center px-1.5 py-0.2 mx-0.5 text-[10px] font-mono font-bold bg-blue-100 text-blue-700 dark:bg-blue-950/80 dark:text-blue-300 rounded hover:scale-105 transition"
>
[{sourceId}]
</button>
);
}
return <span key={idx}>{part}</span>;
})}
</div>
{/* Source Accordion Section */}
{sources.length > 0 && !isStreaming && (
<div className="pt-2 border-t border-gray-150 dark:border-gray-800/80">
<button
onClick={() => setIsSourcesExpanded(!isSourcesExpanded)}
className="flex items-center justify-between w-full py-2 text-xs font-semibold text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition"
>
<span>
{isSourcesExpanded ? "โผ Hide" : "โถ Inspect"} Verified Sources ({sources.length})
</span>
<span className="text-[11px] font-normal text-gray-400">Click to verify claims</span>
</button>
{isSourcesExpanded && (
<div className="space-y-2.5 mt-3 pt-2">
{sources.map((source) => {
const isHighlighted = source.id === highlightedSourceId;
return (
<div
key={source.id}
className={`p-3.5 rounded-xl border text-xs transition ${
isHighlighted
? "bg-blue-50/80 border-blue-300 dark:bg-blue-950/50 dark:border-blue-700 ring-2 ring-blue-400/40"
: "bg-gray-50/70 border-gray-150 dark:bg-gray-900/50 dark:border-gray-800"
}`}
>
<div className="flex items-center justify-between mb-1.5">
<span className="font-bold text-gray-900 dark:text-white flex items-center gap-1.5">
<span className="px-1.5 py-0.5 rounded text-[10px] bg-blue-600 text-white font-mono">
[{source.id}]
</span>
{source.title}
</span>
<span className="font-mono text-[10px] text-gray-500">
Score: {Math.round(source.score * 100)}%
</span>
</div>
<p className="text-gray-600 dark:text-gray-400 font-mono text-[11px] leading-relaxed line-clamp-3 bg-white dark:bg-gray-950 p-2.5 rounded border border-gray-150 dark:border-gray-800">
"{source.excerpt}"
</p>
{source.documentUrl && (
<a
href={source.documentUrl}
target="_blank"
rel="noreferrer"
className="inline-block mt-2 text-blue-600 dark:text-blue-400 hover:underline text-[11px]"
>
Open full source document โ
</a>
)}
</div>
);
})}
</div>
)}
</div>
)}
</div>
);
}Designing Fallbacks: The "I Do Not Know" Empty State
When retrieved documents have low similarity or when vector search returns zero matches, never allow the model to improvise. Instead, render a clean fallback card with suggested queries:
// components/RagFallbackCard.tsx
export function RagFallbackCard({ query }: { query: string }) {
return (
<div className="p-6 rounded-2xl border border-amber-200 bg-amber-50/50 dark:border-amber-900/40 dark:bg-amber-950/20 text-sm">
<div className="flex items-center gap-2 text-amber-800 dark:text-amber-300 font-semibold mb-2">
<span>โ ๏ธ</span>
<h4>Insufficient Documentation Found</h4>
</div>
<p className="text-xs text-amber-700/80 dark:text-amber-400/80 leading-relaxed mb-4">
Our verified documentation does not contain enough grounded facts to answer "{query}" safely without risking hallucination.
</p>
<div className="text-xs text-gray-600 dark:text-gray-400">
<span className="font-semibold block mb-1">Recommended alternatives:</span>
<ul className="list-disc list-inside space-y-1">
<li>Check our public API reference documentation.</li>
<li>Ask about general architecture principles.</li>
<li>Contact support if you believe this is missing from the docs.</li>
</ul>
</div>
</div>
);
}Interview Angle: How to Answer in System Design
- Question: "How do you design a frontend interface for RAG that builds user trust and makes source verification seamless?"
- Target Answer:
"Trust in AI systems depends on transparency and auditability.
In our RAG UI, we parse the model's generated text for bracketed citations (
[1],[2]), converting them into interactive buttons. Clicking any badge smoothly expands a collapsible Source Accordion below the response and highlights the exact passage used by the model.We display an aggregate Groundedness confidence badge calculated from cross-encoder scores. Finally, when relevance falls below safety thresholds, we bypass generative extrapolation entirely and display a dedicated fallback card with suggested search terms, preventing hallucinated misinformation from reaching the user."
Quick Check
- Why is an interactive source accordion preferable to dumping all retrieved chunks at the bottom of the page?
- How is the aggregate Groundedness percentage calculated?
- What should the UI display when retrieved context fails to answer the user's question?