Web AppProjects

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

8 min read

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.

React 19ViteTailwind v4SupabaseGPT-4oRAGpgvector

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).

Legal AI home page with a box for asking legal questions in natural language
Home page: a plain-language question box in the middle of the screen, no section numbers needed
84K+
Sections in the database
1,811
Laws (OCS)
5
Law categories
v13
Edge Function version

Design Thinking Process

Why lawyers need a tool like this

New chat screen with example questions grouped by situation
New chat: example questions organized by "situation" so lawyers can start asking right away
01

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.

02

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?

03

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

04

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.

05

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

The 3-part chat page: chat history, an answer with citation cards, and a panel for reading the legal text
The real 3-panel layout: chat history · answer + Citation Cards · Law Viewer showing the section text alongside
LA
Legal AI
N
An employee was dismissed without notice. What compensation are they entitled to?
AI
Under the Labour Protection Act B.E. 2541 (1998), an employee dismissed without notice is entitled to:
1. Severance pay based on length of service (Section 118)
2. Payment in lieu of advance notice (Section 17)
3. Damages for unfair dismissal (Act on the Establishment of Labour Courts, Section 49)
Labour Protection Act B.E. 2541
Section 17 Section 118 Section 119
Act on the Establishment of Labour Courts
Section 49

Key Features

Core features designed for lawyers

Home page on mobile
Home page on mobile
Chat page on mobile
Chat page on mobile

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

The AI answer split across 3 laws, with section numbers and related court decisions
The result of RAG: answers grouped by the laws found, with section links and related court decisions
User Question
Lawyer asks in natural language
→
Hybrid Search
FTS + pgvector over 84K sections
→
GPT-4o + Context
AI answers from the real section text
→
Structured JSON
content + citations + summary
01

Scrape & Store

Pull 1,811 laws and 84,376 sections from the OCS API into Supabase (PostgreSQL), with deduplication

02

Hybrid Search

Full-text search (tsvector) + vector search (pgvector, text-embedding-3-small, 1536 dims) through the Supabase function hybrid_search

03

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.

04

Structured Output

The response is JSON: content (markdown), citations (laws + cited sections), courtDecisions, summary (next steps)


Database Schema

Supabase (PostgreSQL) + pgvector + Row Level Security

Cards for the collected legal data sources, with Active and Planned status
Data sources stored in the database, with Active / Planned status per source
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

The legal citation card and summary box components
Citation Card + Summary Box: why the AI is forced to answer in structured JSON
edge-function/chat/prompt-v13.ts
// Key prompt rules for legal accuracy
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)

CriteriaLegal AIGemini Pro
Structured Citations✓ Card-basedInline text
Source Verification✓ DB-backedGeneral knowledge
Law Viewer✓ Real-time✗ None
Content DepthGood✓ More detailed
Answer Format✓ JSON structuredPlain text

OCS Scraper

Legal data pulled from the Office of the Council of State

A panel for reading the act, with a table of contents and the sections cited in the chat highlighted
Law Viewer: section text pulled from OCS + table of contents + highlights for sections cited in the chat
scripts/scrape-sections.ts
// Scrape 84,376 sections from OCS API
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

Release Notes page showing versions 1.3 and 1.2
The prototype's Release Notes page (the numbers in the image are sample prototype data)
01

Foundation · Database + Scraper + Auth

Scraped 1,811 laws and 84K sections from OCS, built the Supabase schema (5 migrations), Supabase Auth (email + Google OAuth)

02

Landing Page · Hero + Data Sources + Login

Landing page with stats from the database, OCS data sources, a Release Notes section and a login modal

03

Chat System · 3-Panel Layout + RAG + Citations

Full 3-panel chat page: sidebar (history), chat (AI response + Citation Cards), Law Viewer (real legal text)

04

AI Refinement · Prompt v13 + Vector Embeddings

Tuned the prompt to verify sections before citing them, added pgvector + text-embedding-3-small for semantic search

05

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)

The Legal AI component library page
Component Library: the single component reference for the whole project
project-structure
src/
├── 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

Network error, No results and Rate limit states
Error / No results / Rate limit: error states designed from the start

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

React 19ViteTailwind v4SupabasePostgreSQLpgvectorGPT-4oOpenAI EmbeddingsEdge FunctionsPlaywright

Tan · Natpakan Sirirat

Product Designer & AI Builder — designing user experiences and building AI tools that actually work.

0%