Skip to main content
Glama
README.md
# 법마디(Lawmadi) OS — Korean AI Legal Operating System

> **법마디(Lawmadi)는 대한민국 AI 법률 운영체제(OS)이다.**
> 60명의 분야별 전문 AI 법률 리더가 국가법령정보센터 법령을 실시간 검증하여 법률 분석을 제공한다.

> **Lawmadi is a Korean AI Legal Operating System.**
> 60 domain-specialized AI legal leaders provide statute-verified legal analysis using Korea's official legislative database ([law.go.kr](https://www.law.go.kr)) in real-time.

[![Cloud Run](https://img.shields.io/badge/Cloud%20Run-online-brightgreen)](https://lawmadi.com)
[![Tests](https://img.shields.io/badge/tests-657-brightgreen)]()
[![MCP](https://img.shields.io/badge/MCP-compatible-blue)](https://lawmadi.com/mcp)
[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue)](LICENSE)
[![Glama](https://glama.ai/mcp/servers/peter120525-cmd/lawmadi-os-v60/badges/score.svg)](https://glama.ai/mcp/servers/peter120525-cmd/lawmadi-os-v60)
[![Smithery](https://smithery.ai/badge/lawmadi-os)](https://smithery.ai/server/lawmadi-os)

**[lawmadi.com](https://lawmadi.com)** · [MCP Server](https://lawmadi.com/mcp) · [API Docs](https://lawmadi.com/.well-known/openapi-public.json) · [llms.txt](https://lawmadi.com/llms.txt)

---

## Why Lawmadi Exists

Korean legal questions require answers grounded in actual statutes — not AI hallucinations. Lawmadi OS ensures every legal citation is verified against Korea's National Law Information Center (law.go.kr) in real-time. If verification fails, the system blocks the answer rather than providing unverified information (**fail-closed** principle).

### Grand Thesis — LLM-Independent by Design (왜 "OS"인가)

Lawmadi is an **OS**, not an LLM wrapper. Answer quality is guaranteed by the **verified-asset layer (SSOT) + grounding + fail-closed verification** — *not* by which LLM happens to generate the text. Today Gemini powers responses, but the goal is that **any LLM can be swapped in and produce the same quality of answer.** The LLM is a replaceable component; the moat is the asset & verification layer. The verification pipeline sits *after* generation and rejects unverified citations regardless of the model that produced them.

> 법마디를 "OS"라 부르는 이유: 답변 품질은 *어떤 LLM을 쓰는가*가 아니라 *검증 자산(SSOT) + 그라운딩 + fail-closed 검증 계층*이 보장합니다. 지금은 Gemini가 응답하지만, **어떤 LLM으로 교체해도 동일 품질**을 내는 것이 궁극 목표입니다. LLM은 교체 가능한 부품이고, 시스템의 해자는 자산·검증 레이어입니다.

## What Lawmadi Does

- **60 Legal Domains** — Labor, housing, divorce, criminal, tax, corporate, IP, immigration, and 52 more specialized areas
- **Real-time Statute Verification** — Every cited law article is cross-checked against law.go.kr DRF API. Zero hallucination policy
- **Multi-Agent Architecture** — NLU routes each question to the most relevant specialist among 60 AI legal leaders
- **Bilingual** — Full Korean & English support (`lang: ko` / `lang: en`)
- **MCP Compatible** — Works with Claude Desktop, Cursor, and any MCP client (6 tools available)
- **Free Credits** — 3 free credits granted one time on login (non-recurring). Purchased credits never expire — use anytime

## Bar Exam Answers (변호사시험 답안)

A dedicated study hub organizes Korean Bar Exam (변호사시험) answers by **format × subject × round**, so candidates can review everything in one place ([lawmadi.com/exam-essays](https://lawmadi.com/exam-essays)).

- **선택형 (MCQ)** — All 15 exams to date (제1회~제15회, 2012–2026). Official Ministry of Justice question stems and choices are shown verbatim alongside the answer, per-option ○/× explanations, and the supporting statute/precedent for each item. Readable for direct study.
- **금답안 (Gold-Standard Answers)** — 제6~15회 (2017–2026) 선택형 1,500문항: every option carries an inline citation (statute name + article, or the exact Supreme Court / Constitutional Court docket) with a working law.go.kr deep link (`precSc.do` / `detcSc.do`). Each docket is fail-closed verified against law.go.kr before publishing. **Only gold-verified rounds are published** — non-gold rounds (currently 제1~5회) are withheld from every published surface until they pass the gold gate.
- **판례번호·조문 검색 (Case-Number / Statute Search)** — [lawmadi.com/exam-search](https://lawmadi.com/exam-search): a client-side search index over the published gold rounds (제6~15회 선택형 전과목 1,500문항·판례 2,312종). Look up any question by Supreme Court / Constitutional Court docket (e.g. `2014도6992`), statute article (e.g. 형법 제310조), or keyword, with each docket linking to its law.go.kr source.
- **사례형 · 기록형 (Essay / Record)** — Per-leader worked solution examples, organized by 공법 · 민사법 · 형사법 · 선택과목.
- **Exam-faithful structure** — Scoring metadata follows the official 변호사시험법 시행령 layout (공법·형사법 선택형 40문항/100점, 민사법 70문항/175점; 총점 1,660점).

### Citation Verification Gate (fail-closed)

Every cited statute and precedent in a published answer is cross-checked against law.go.kr. A CI **hard gate** blocks publishing on any hallucinated citation. To stay independent of law.go.kr outages, cited statutes (361 laws cached) and precedents (10,777 cases cached) are pre-fetched, so verification runs offline and a transient network failure never publishes unverified content. The gate distinguishes infrastructure failures (re-run) from genuine hallucinations (block), and re-verifies only the items that changed via an incremental OK-set cache.

### Search Indexing (SEO)

Because the answer pages render client-side, the build injects static `ItemList` JSON-LD (선택형 entries carry the official question stems) and registers every answer deep-link (`view=choice` / `view=essay`) in `sitemap.xml`, making each round/subject answer discoverable in search. The build also emits `exam-search-index.json` (published gold rounds only, with each question's docket/statute list) powering the `/exam-search` page, which exposes a `WebSite` + `SearchAction` schema so search engines surface the case-number search box directly. A **gold publish gate** (`gold_rounds()`, keyed on `_lint_gold_format`) excludes any non-gold round (currently 제1~5회) from every published artifact — exam-detail, exam-essays JSON-LD, the search index, and sitemap answer links — so only verified gold answers ever go live.

## Study Tools (수험 학습 도구)

Two analytical tools complement the gold-standard answers:

- **출제·인용 히트맵 (Exam & Citation Heatmap)** — [lawmadi.com/heatmap](https://lawmadi.com/heatmap): for every article across the 7 core laws, a dual bar compares **bar-exam frequency** (gold, confirmed exam appearances) against **precedent-citation frequency** (blue), so high-yield articles surface even when one signal alone would bury them. Supports citation-order / exam-order sorting and links each article to its representative precedent's law.go.kr source.
- **판례 생존율 (Precedent Survival)** — [lawmadi.com/case-survival](https://lawmadi.com/case-survival): tracks whether a key precedent was later upheld, modified, or overruled, so you can tell whether a holding is still good law.

### Bilingual Leader Profiles

Each of the 60 legal leaders has a prerendered profile in both Korean (`/leader-profile/L01`) and English (`/leader-profile-en/L01`) at clean, crawlable URLs with per-leader metadata and `hreflang` alternates — no `?id=` query parameters.

## How It Works

```
User Query → NLU Router (selects 1 of 60 specialists)
    │
    ├─ Stage 0: Query Classification (intent + domain detection)
    ├─ Stage 1: RAG Statute Search (Vertex AI Search, 44,085+ docs)  ← parallel
    ├─ Stage 2: Gemini 3.5 Flash Analysis (leader persona + 5-step legal framework)
    └─ Stage 3: DRF Verification (real-time, exhaustive law.go.kr article + precedent check)
    │
    ▼
Verified Legal Response (with statute citations + enforcement dates)
```

### Verification Pipeline

Every response passes through a 4-stage pipeline. Stage 3 (DRF Verification) cross-references all cited statutes against the official Korean legislative database. If any citation cannot be verified, the system regenerates or blocks the response — never passes unverified legal information to the user.

## Quick Start

### MCP Server (Recommended for AI Agents)

Add to your MCP client configuration:

```json
{
  "mcpServers": {
    "lawmadi": {
      "url": "https://lawmadi.com/mcp"
    }
  }
}
```

6 tools available: `ask`, `ask_expert`, `search`, `get_leaders`, `chat_leader`, `suggest_questions`

### REST API

```bash
# Korean legal question
curl -X POST https://lawmadi.com/ask \
  -H "Content-Type: application/json" \
  -d '{"query": "부당해고를 당했는데 어떻게 해야 하나요?", "lang": "ko"}'

# English
curl -X POST https://lawmadi.com/ask \
  -H "Content-Type: application/json" \
  -d '{"query": "My landlord won't return my deposit", "lang": "en"}'
```

### Self-Hosting

```bash
git clone https://github.com/peter120525-cmd/lawmadi-os-v60.git
cd lawmadi-os-v60
cp .env.example .env  # Fill in your API keys
pip install -r requirements.txt
python main.py
```

Required: `GEMINI_KEY`, `LAWGO_DRF_OC` (law.go.kr API key), PostgreSQL

## Architecture

| Layer | Component | Technology |
|-------|-----------|-----------|
| Backend | FastAPI + Uvicorn | Python 3.10, Cloud Run (Seoul) |
| LLM | Gemini 3.5 Flash (`gemini-3.5-flash`) | Single model, automatic 429 exponential backoff + fallback |
| RAG | Vertex AI Search | 44,085+ legal documents indexed (30,995 statutes · 10,840 precedents · 2,250 exam Q&A) |
| Verification | DRF API (law.go.kr) | Real-time, exhaustive statute + precedent cross-check (361 laws / 10,777 cases cached offline) |
| Database | Cloud SQL | PostgreSQL, encrypted connections |
| Frontend | Firebase Hosting | Static HTML/CSS/JS (CSR), Korean + English |
| MCP | custom JSON-RPC (`mcp_simple`) | HTTP/SSE transport, 6 tools |
| Payments | Paddle | Credit packs: ₩2,100 / ₩7,000 / ₩13,800 |

## API Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/ask` | POST | Legal question → verified analysis |
| `/ask-stream` | POST | Same, SSE streaming |
| `/ask-expert` | POST | Expert mode (full pipeline) |
| `/api/leaders` | GET | List all 60 specialist agents |
| `/api/chat-leader` | POST | 1:1 chat with a specific agent |
| `/search` | GET | Search Korean legal topics |
| `/suggest-questions` | POST | AI-generated follow-up questions |
| `/mcp` | SSE | MCP protocol endpoint |
| `/health` | GET | Service health check |

## 60 Legal Domains

<details>
<summary>View all domains</summary>

Civil Law · Real Estate · Construction · Urban Redevelopment · Medical Law · Damages · Traffic Accidents · Lease & Housing · Government Contracts · Civil Enforcement · Debt Collection · Registry & Auction · Commercial Law · Corporate & M&A · Startup & Venture · Insurance · International Trade · Energy & Resources · Maritime & Aviation · Tax & Finance · IT & Cybersecurity · Criminal Law · Entertainment · Tax Appeals · Military Law · Intellectual Property · Environmental Law · Trade & Customs · Gaming & Content · Labor & Employment · Administrative Law · Fair Trade · Space & Aerospace · Privacy & Data Protection · Constitutional Law · Cultural Heritage · Juvenile Law · Consumer Protection · Telecommunications · Human Rights · Family & Divorce · Copyright · Industrial Accidents · Social Welfare · Education & Youth · Pension & Insurance · Venture & New Industries · Arts & Culture · Food & Health Safety · Multicultural & Immigration · Religion & Tradition · Media & Press · Agriculture & Livestock · Marine & Fisheries · Science & Technology · Disability Rights · Inheritance & Trust · Sports & Leisure · Data & AI Ethics · General Legal

</details>

## Tests

```bash
pytest tests/ -v  # 657 tests
```

## License

Lawmadi OS uses a **dual-licensing model** — the software and the legal content are licensed separately.

**Software / code — [AGPL-3.0](LICENSE):** You may use, modify, and distribute this software. If you run a modified version as a network service, you must release your source code under the same license. Software copyright (c) 2025-2026 Choe Jainam (최재남).

**Legal content / data — Proprietary, All Rights Reserved:** AGPL-3.0 covers the software, not the data or content. The bar-exam gold-standard answers (변호사시험 금답안 — 선택형·사례형·기록형 and their explanations/citation indexes), AI-generated legal analyses and leader-persona outputs, verified legal-asset compilations (SSOT statute & precedent datasets), and daily legal content are proprietary and are **NOT** licensed under AGPL-3.0. Content copyright (c) 2026 Choe Jainam (최재남). Scraping, bulk extraction, redistribution, AI/ML training, fine-tuning, embeddings, RAG ingestion, or creating derivative/competing products from this content requires prior written permission (peter120525@gmail.com).

TDQS

B3/5.0

Scored across 7 tools

Disambiguation4/5

The tools are mostly distinct in purpose (basic query, expert mode, streaming, chat with leader, list leaders, search, suggest questions), though some overlap exists between the various 'ask' tools. Descriptions help differentiate but an agent might still be confused about which to use.

Naming Consistency2/5

Tool names are inconsistent and awkward, often duplicating segments (e.g., 'ask_ask_post', 'ask_expert_ask_expert_post') and mixing path components. This auto-generated style lacks a clear, user-friendly pattern.

Tool Count5/5

With 7 tools, the server is well-scoped for a legal Q&A system. Each tool serves a distinct function without being too few or too many.

Completeness4/5

The tool set covers core interactions: asking questions (multiple modes), listing specialists, searching, and suggesting follow-ups. Minor gaps exist (e.g., no history or feedback), but the main workflow is supported.

Maintenance

ActivityActive
ResponsivenessSyncing