Legal AI
A proof of concept for AI-assisted Thai legal research, built to prove that RAG + structured output can make an AI cite real law reliably

A research tool for lawyers covering 84,000+ sections of Thai law. Ask in plain language and get an answer that cites real sections from the database.
Overview
Legal AI is a proof of concept for Thai legal research. It uses RAG (Retrieval-Augmented Generation) to pull the actual text of each section from a database and give it to the AI as context. Answers are not generated from general knowledge; they cite real laws scraped from the Office of the Council of State (OCS).

Design Thinking Process
Why lawyers need a tool like this

Empathize · Lawyers and legal research: the hidden problem
To prepare a single case, a Thai lawyer may need to search 84,000+ sections across many acts. The usual way is keyword search on the OCS website, which only works if you know the exact name of the act or the section number. If you don't, you won't find it.
Insight: lawyers know the "situation" but not which "section" to look up. They need a tool they can ask in plain language.
Define · "If the AI gets the law wrong, you could lose the case"
ChatGPT can answer legal questions, but it often cites the wrong section or hallucinates laws that don't exist, which is dangerous in legal work. The system has to cite real law that can be checked.
HMW: How might we build an AI that answers legal questions accurately, citing only real sections from the database?
Ideate · RAG: make the AI cite from a real database
Use RAG (Retrieval-Augmented Generation) instead of letting the AI answer from general knowledge:
• Scrape 1,811 laws and 84,376 sections from OCS
• Full-text search + vector search (pgvector) to find relevant sections
• Send the actual section text to GPT-4o as context
• Instruct the AI to cite only sections that appear in that context
Prototype · 3-Panel Layout — Chat + Citations + Law Viewer
The chat page has 3 parts: a sidebar (chat history), the chat area (AI answers with Citation Cards) and a Law Viewer panel (the actual legal text). Tapping a Citation Card opens the real text right away without leaving the chat.
Key decision: Citation Cards use 3 colors (green/purple/blue) by the role of each law, so lawyers can grasp the overall picture quickly.
Test · Comparison Testing — Legal AI vs Gemini Pro
I used Playwright to run 5 legal questions through Legal AI and Gemini Pro side by side:
• Legal AI: better structured output (citations + summary), with the cited sections clearly visible
• Gemini: more detailed and more complete content
• Next: add vector search to retrieve relevant sections more precisely
Chat Interface
Ask in plain language, get an answer with Citation Cards that open the real law

Key Features
Core features designed for lawyers


RAG Search
Full-text + vector search across 84K sections. Real legal text becomes the AI's context, so it doesn't hallucinate.
Citation Cards
Cited laws appear as cards in 3 colors. Tap to read the actual text right away.
Law Viewer Panel
Read the real legal text from the database, with the sections the AI cited highlighted, plus a table of contents
Structured Output
The AI answers in structured JSON: content + citations + court decisions + a summary box
Chat History
Chat history grouped by day, searchable and deletable, with auto-generated titles and descriptions
Markdown Rendering
Supports headings, bold, bullets, numbered lists, tables and horizontal rules in AI responses
Auth System
Supabase Auth: email/password + Google OAuth, with RLS so users only see their own data
Landing Page
Hero + stats from the database, data sources, release notes, login modal
RAG Architecture
The Retrieval-Augmented Generation system that makes the AI cite real law

Scrape & Store
Pull 1,811 laws and 84,376 sections from the OCS API into Supabase (PostgreSQL), with deduplication
Hybrid Search
Full-text search (tsvector) + vector search (pgvector, text-embedding-3-small, 1536 dims) through the Supabase function hybrid_search
AI Generation
GPT-4o receives the real section text as context. The prompt says "ONLY cite sections that APPEAR in the context" to prevent hallucination.
Structured Output
The response is JSON: content (markdown), citations (laws + cited sections), courtDecisions, summary (next steps)
Database Schema
Supabase (PostgreSQL) + pgvector + Row Level Security

| Table | Rows | Description |
|---|---|---|
| law_sections | 84,376 | Section-level text (deduplicated) + vector embeddings |
| laws | 1,811 | Laws from OCS, all 5 categories |
| conversations | dynamic | User chats (RLS: user-only) |
| messages | dynamic | User + AI messages + citations (RLS: user-only) |
| releases | 1 | Release notes (public read) |
| system_stats | 4 | Home page stats |
Prompt Engineering
The prompt went through 13 versions to make answers accurate enough for lawyers

const promptRules = {
verification: "ONLY cite sections that APPEAR in DB context",
lawNames: "Use EXACT law name from database",
audience: "User is a lawyer - don't suggest 'consult a lawyer'",
format: "400-600 words, ## headings, warnings, follow-up",
model: "GPT-4o primary, GPT-4o-mini fallback",
};
Comparison: Legal AI vs Gemini Pro (5 Questions)
| Criteria | Legal AI | Gemini Pro |
|---|---|---|
| Structured Citations | ✓ Card-based | Inline text |
| Source Verification | ✓ DB-backed | General knowledge |
| Law Viewer | ✓ Real-time | ✗ None |
| Content Depth | Good | ✓ More detailed |
| Answer Format | ✓ JSON structured | Plain text |
OCS Scraper
Legal data pulled from the Office of the Council of State

for (const law of laws) {
const doc = await fetch(`OCS_API/getLawDoc?id=${law.id}`);
const sections = parseSections(doc);
await supabase.from('law_sections')
.upsert(sections, { onConflict: 'law_id,section_number' });
}
// Result: 1,811 laws, 84,376 sections (deduplicated)
Development Timeline
From zero to a production-ready POC

Foundation · Database + Scraper + Auth
Scraped 1,811 laws and 84K sections from OCS, built the Supabase schema (5 migrations), Supabase Auth (email + Google OAuth)
Landing Page · Hero + Data Sources + Login
Landing page with stats from the database, OCS data sources, a Release Notes section and a login modal
Chat System · 3-Panel Layout + RAG + Citations
Full 3-panel chat page: sidebar (history), chat (AI response + Citation Cards), Law Viewer (real legal text)
AI Refinement · Prompt v13 + Vector Embeddings
Tuned the prompt to verify sections before citing them, added pgvector + text-embedding-3-small for semantic search
Testing · Comparison Testing + UI Polish
Playwright comparison against Gemini Pro on 5 questions, tuned Law Viewer highlight colors, Markdown rendering and auto-scroll
Project Structure
Frontend (React 19 + Vite) + Backend (Supabase Edge Functions)

├── App.tsx // Routes + ProtectedRoute
├── pages/
│ ├── LandingPage.tsx // Hero + stats + login
│ ├── ChatPage.tsx // 3-panel chat interface
│ └── ReleasesPage.tsx // Release notes
├── components/
│ ├── chat/
│ │ ├── ChatSidebar.tsx // History grouped by date
│ │ ├── ChatMessage.tsx // Markdown + citations
│ │ ├── CitationCard.tsx // Color-coded law refs
│ │ └── LawViewer.tsx // Real law content panel
│ └── landing/ // Landing page sections
├── lib/
│ ├── supabase.ts // Client init
│ └── api.ts // All CRUD functions
supabase/
├── migrations/001-006 // Schema + pgvector
└── functions/chat/ // Edge Function v13
scripts/
├── scrape-ocs.ts // Law list from OCS API
├── scrape-sections.ts // 84K sections via getLawDoc
└── generate-embeddings.ts // pgvector embeddings
Lessons Learned
What I learned building Legal AI

RAG beats fine-tuning for domain-specific data. Fine-tuning a model is expensive and hard to maintain. Scraping the real data into a database and using RAG so the AI cites it gives results that are far easier to verify.
Prompt engineering matters a lot. From v1, where the AI hallucinated sections, to v13, which says "ONLY cite sections that APPEAR in the context", hallucination dropped significantly.
Hybrid search (FTS + vector) beats FTS alone. Full-text search only finds keyword matches, while vector search picks up meaning. For example, a question about "dismissal" also finds sections on "severance pay".
Structured output helps UX a lot. Having the AI return JSON (content + citations + summary) instead of plain text makes it possible to build an orderly, interactive UI (tap a citation to read the real law).
Color-coded citations reduce cognitive load. Three colors (green/purple/blue) by the role of each law let lawyers see the big picture without reading every line.
Full tech stack
